问:
Accessing an element in nested html code using selenium
I am trying to enter my username and password in my website using selenium but it goes into the timeout exception.

```<code>File "C:\Python34\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
</code>```

I have tried accessing my user name(div id "Id" and password(div id "PSD") by using the code below

```<code>user = driver.find_element_by_id('Id')
</code>```

and

```<code>user = WebDriverWait(driver,20).until(lambda driver:driver.find_element_by_id('Id'))
</code>```

Any help will be very much appreciated

HTML code of the website is shown below:

```<code><div id="wrapper">
<div id="panel">
<table cellspacing="0" cellpadding="0" border="0" width="100%">
<tbody>
<tr>
<td>
<div class="panel_23">
<div id="msg" class="txt_red" style="display:none"></div>
   <div class="User">
   <div id="Id">
     <input id="Malcom" name="Malcom"
     style="width: 23px;" type="text"/>
    </div>
    </div>
    <div class="PSS">
    <div id="PSD">
    <input id="Xmen" name="Xmen" style="width: 23px;"
    type="pass"/>
    </div>
    </div>
<!-- <div class="txt56">Are you Logged </div> <div class="checkbox">
<input type="checkbox" id="c1" name="cc" /><label for="c1"><span></span>
</label></div> -->
</div>
</td>
</tr>
<tr>
<tr>
</tbody>
</table>
</div>
</code>```

答:
You are getting TimeoutException because of Explicit Wait You are using.

Use explicit wait as  :

```<code>user = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, "Malcom"))

user.send_keys("username")
</code>```

The another thing is that you are accessing the div tag not input tag to access username. For passing username you have to access input tag of username field.

Updated :

Your Login form content present under iFrame So fitst you need to switch into frame and then send username and password use following code:

```<code>driver.get("http://xxxxxxxxxxxxxxxx")
driver.implicitly_wait(10)
driver.switch_to.frame(0)   # frame located with index
driver.find_element_by_id("ext1").send_keys("username")
driver.find_element_by_id("ext2").send_keys("password")
driver.find_element_by_xpath("//div[@class='btn_Login']/input").click()
</code>```

Note : Please check the syntax as per Python. I have done it using java and its working fine at my end

Body:
I am trying to enter my username and password in my website using selenium but it goes into the timeout exception.

File "C:\Python34\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

I have tried accessing my user name(div id "Id" and password(div id "PSD") by using the code below

user = driver.find_element_by_id('Id')

and

user = WebDriverWait(driver,20).until(lambda driver:driver.find_element_by_id('Id'))

Any help will be very much appreciated

HTML code of the website is shown below:

     <input id="Malcom" name="Malcom"
     style="width: 23px;" type="text"/>

    <input id="Xmen" name="Xmen" style="width: 23px;"
    type="pass"/>

Body:
You are getting TimeoutException because of Explicit Wait You are using.

Use explicit wait as  :

user = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, "Malcom"))

user.send_keys("username")

The another thing is that you are accessing the div tag not input tag to access username. For passing username you have to access input tag of username field.

Updated :

Your Login form content present under iFrame So fitst you need to switch into frame and then send username and password use following code:

driver.get("http://xxxxxxxxxxxxxxxx")
driver.implicitly_wait(10)
driver.switch_to.frame(0)   # frame located with index
driver.find_element_by_id("ext1").send_keys("username")
driver.find_element_by_id("ext2").send_keys("password")
driver.find_element_by_xpath("//div[@class='btn_Login']/input").click()

Note : Please check the syntax as per Python. I have done it using java and its working fine at my end


来源: stackexchange

问:
to find minimum missing number in oracle
i want to find the minimum missing number of a column named (s_no) and the table named (test_table) in oracle and I write the following code..

```<code>select
    min_s_no-1+level missing_number
from (
    select min(s_no) min_s_no, max(s_no) max_s_no
    from test_table
) connect by level <= max_s_no-min_s_no+1
minus
select s_no from test_table
;
</code>```

it gives me all the missing number as a result. But I want to select the minimum
number. Can any one help me please.
thanks in advance.

答:
The best way to find the gaps is to use analytic functiions lead or lag. An example with lag:

```<code>with test_data as (
    select 1 num from dual union all
    select 4  from dual union all
    select 6  from dual union all
    select 8  from dual union all
    select 3  from dual union all
    select 9  from dual union all
    select 0  from dual
)
select min(gap) min_gap
from (
    select num, lag(num) over (order by num)+1 gap
    from test_data
    )
where num != gap
;
MIN_GAP
------------------
                 2
</code>```

More about how to find the gaps here

ContentLicense: CC BY-SA 3.0

Body:
i want to find the minimum missing number of a column named (s_no) and the table named (test_table) in oracle and I write the following code..

select
    min_s_no-1+level missing_number
from (
    select min(s_no) min_s_no, max(s_no) max_s_no
    from test_table
) connect by level <= max_s_no-min_s_no+1
minus
select s_no from test_table
;

it gives me all the missing number as a result. But I want to select the minimum
number. Can any one help me please.
thanks in advance.

Body:
The best way to find the gaps is to use analytic functiions lead or lag. An example with lag:

with test_data as (
    select 1 num from dual union all
    select 4  from dual union all
    select 6  from dual union all
    select 8  from dual union all
    select 3  from dual union all
    select 9  from dual union all
    select 0  from dual
)
select min(gap) min_gap
from (
    select num, lag(num) over (order by num)+1 gap
    from test_data
    )
where num != gap
;
MIN_GAP
------------------
                 2

More about how to find the gaps here


问:
initialize static pointer array c++
I have my class:

```<code>class Exec {
  static Process* procs_table[];

 public:
 Exec(int num, info_init_proc* proc);
};
</code>```

info_init_proc is a custom struct with information necessary for initializing the Process object

And try to create the constructor as below:

```<code>Exec::Exec(int num, info_init_proc* proc) {
   int i;
   for (i = 0; i < num; i++) {
     Exec::procs_table[i] = new Process(proc[i]);
  }
}
</code>```

It can be compiled, but when i build i get the "Undefined symbol procs_table" error.

What should be modified ?

答:
You can't initialize a static member in a constructor.  A constructor is creating an instance of the class, yet the static member is shared by all instances.

Here's a great post on static initialization

Title: initialize static pointer array c++

Body:
I have my class:

class Exec {
  static Process* procs_table[];

 public:
 Exec(int num, info_init_proc* proc);
};

info_init_proc is a custom struct with information necessary for initializing the Process object

And try to create the constructor as below:

Exec::Exec(int num, info_init_proc* proc) {
   int i;
   for (i = 0; i < num; i++) {
     Exec::procs_table[i] = new Process(proc[i]);
  }
}

It can be compiled, but when i build i get the "Undefined symbol procs_table" error.

What should be modified ?


问:
How to achive swipe left and right on activity containg 2 fragments in android?
I have a activity that contain 2 fragments and both the fragments containing a recyclerview.
I need to implement a swipe gesture (when i swipe from one side to another the fragments need to be changed).
Previously i have added swipe gesture, but when i swipe the recycler view will scroll instead of change of fragments.

Can you help in implementing this..

Thanks

答:
Use TabLayout with ViewPager. Create two tabs for two fragments in the activity .
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/</p>


问:
d3.hexbin data points not being displayed correctly
The following snippet is basically this example https://bl.ocks.org/mbostock/4248145 but with custom data points. No matter how I scale or modify my points array, the hexagons are always at the upper left corner, though it seems that the distribution is displayed correctly.

How can I fix this?

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    var points = [[1,1]]
        var color = d3.scaleSequential(d3.interpolateLab("white", "#5B85AA"))
        .domain([0, 3]);

        var hexbin = d3.hexbin()
        .radius(20)
        .size([0, 3]);

        var x = d3.scaleLinear()
        .domain([1, 4])
        .range([0, width]);

        var y = d3.scaleLinear()
        .domain([1, 4])
        .range([height, 0]);

        g.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

        g.append("g")
        .attr("class", "hexagon")
        .attr("clip-path", "url(#clip)")
        .selectAll("path")
        .data(hexbin(points))
        .enter().append("path")
        .attr("d", hexbin.hexagon())
        .attr("transform", function(d) { return "translate(" + 0 + "," + height + ")"; })
        .transition()
        .duration(1000)
        .delay(function (d, i) {
          return i * 10;
        })
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("fill", function(d) { return color(d.length); });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<svg width="960" height="500"></svg></code>```

答:
That's the expected result, since your data is just:

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

Which is a single data point next to the origin. For instance, using the same code but creating 1000 random data points from 0 to the width...

```<code>var points = d3.range(1000).map(d=>([Math.random()*width, Math.random()*width]));
</code>```

... will have a different result:

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    var points = d3.range(1000).map(d=>([Math.random()*width, Math.random()*width]));
        var color = d3.scaleSequential(d3.interpolateLab("white", "#5B85AA"))
        .domain([0, 3]);

        var hexbin = d3.hexbin()
        .radius(20)
        .size([0, 3]);

        var x = d3.scaleLinear()
        .domain([1, 4])
        .range([0, width]);

        var y = d3.scaleLinear()
        .domain([1, 4])
        .range([height, 0]);

        g.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

        g.append("g")
        .attr("class", "hexagon")
        .attr("clip-path", "url(#clip)")
        .selectAll("path")
        .data(hexbin(points))
        .enter().append("path")
        .attr("d", hexbin.hexagon())
        .attr("transform", function(d) { return "translate(" + 0 + "," + height + ")"; })
        .transition()
        .duration(1000)
        .delay(function (d, i) {
          return i * 10;
        })
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("fill", function(d) { return color(d.length); });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<svg width="960" height="500"></svg></code>```

Besides that, what you said:

No matter how I scale or modify my points array, the hexagons are always at the upper left corner.

Is not accurate. For instance, this is the same code, but using [[100,100]]. You can see the hexagon further down and to the right:

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    var points = [[100,100]];
        var color = d3.scaleSequential(d3.interpolateLab("white", "#5B85AA"))
        .domain([0, 3]);

        var hexbin = d3.hexbin()
        .radius(20)
        .size([0, 3]);

        var x = d3.scaleLinear()
        .domain([1, 4])
        .range([0, width]);

        var y = d3.scaleLinear()
        .domain([1, 4])
        .range([height, 0]);

        g.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

        g.append("g")
        .attr("class", "hexagon")
        .attr("clip-path", "url(#clip)")
        .selectAll("path")
        .data(hexbin(points))
        .enter().append("path")
        .attr("d", hexbin.hexagon())
        .attr("transform", function(d) { return "translate(" + 0 + "," + height + ")"; })
        .transition()
        .duration(1000)
        .delay(function (d, i) {
          return i * 10;
        })
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("fill", function(d) { return color(d.length); });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<svg width="960" height="500"></svg></code>```

Body:
The following snippet is basically this example https://bl.ocks.org/mbostock/4248145 but with custom data points. No matter how I scale or modify my points array, the hexagons are always at the upper left corner, though it seems that the distribution is displayed correctly.

How can I fix this?

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    var points = [[1,1]]
        var color = d3.scaleSequential(d3.interpolateLab("white", "#5B85AA"))
        .domain([0, 3]);

        var hexbin = d3.hexbin()
        .radius(20)
        .size([0, 3]);

        var x = d3.scaleLinear()
        .domain([1, 4])
        .range([0, width]);

        var y = d3.scaleLinear()
        .domain([1, 4])
        .range([height, 0]);

        g.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

        g.append("g")
        .attr("class", "hexagon")
        .attr("clip-path", "url(#clip)")
        .selectAll("path")
        .data(hexbin(points))
        .enter().append("path")
        .attr("d", hexbin.hexagon())
        .attr("transform", function(d) { return "translate(" + 0 + "," + height + ")"; })
        .transition()
        .duration(1000)
        .delay(function (d, i) {
          return i * 10;
        })
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("fill", function(d) { return color(d.length); });

<svg width="960" height="500"></svg>

Body:
That's the expected result, since your data is just:

[1, 1]

Which is a single data point next to the origin. For instance, using the same code but creating 1000 random data points from 0 to the width...

var points = d3.range(1000).map(d=>([Math.random()*width, Math.random()*width]));

... will have a different result:

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    var points = d3.range(1000).map(d=>([Math.random()*width, Math.random()*width]));
        var color = d3.scaleSequential(d3.interpolateLab("white", "#5B85AA"))
        .domain([0, 3]);

        var hexbin = d3.hexbin()
        .radius(20)
        .size([0, 3]);

        var x = d3.scaleLinear()
        .domain([1, 4])
        .range([0, width]);

        var y = d3.scaleLinear()
        .domain([1, 4])
        .range([height, 0]);

        g.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

        g.append("g")
        .attr("class", "hexagon")
        .attr("clip-path", "url(#clip)")
        .selectAll("path")
        .data(hexbin(points))
        .enter().append("path")
        .attr("d", hexbin.hexagon())
        .attr("transform", function(d) { return "translate(" + 0 + "," + height + ")"; })
        .transition()
        .duration(1000)
        .delay(function (d, i) {
          return i * 10;
        })
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("fill", function(d) { return color(d.length); });

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<svg width="960" height="500"></svg>

Besides that, what you said:

No matter how I scale or modify my points array, the hexagons are always at the upper left corner.

Is not accurate. For instance, this is the same code, but using [[100,100]]. You can see the hexagon further down and to the right:

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    var points = [[100,100]];
        var color = d3.scaleSequential(d3.interpolateLab("white", "#5B85AA"))
        .domain([0, 3]);

        var hexbin = d3.hexbin()
        .radius(20)
        .size([0, 3]);

        var x = d3.scaleLinear()
        .domain([1, 4])
        .range([0, width]);

        var y = d3.scaleLinear()
        .domain([1, 4])
        .range([height, 0]);

        g.append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

        g.append("g")
        .attr("class", "hexagon")
        .attr("clip-path", "url(#clip)")
        .selectAll("path")
        .data(hexbin(points))
        .enter().append("path")
        .attr("d", hexbin.hexagon())
        .attr("transform", function(d) { return "translate(" + 0 + "," + height + ")"; })
        .transition()
        .duration(1000)
        .delay(function (d, i) {
          return i * 10;
        })
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("fill", function(d) { return color(d.length); });

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<svg width="960" height="500"></svg>


问:
Setting DropDownListFor default text MVC
I am new to MVC, and am trying to do something that should be easy, but it is eluding me.  I am using a DropDownListFor in a partial view to display a list of product names.  That part works fine.  What I am having trouble with is setting the initial value of the DropDownListFor to display "Select one".  The code I am working with is as follows:

```<code>@Html.DropDownListFor(model => model.ProductId, new SelectList(ViewBag.ProductData, "ProductId", "Name"), "---Select one---", new {  htmlAttributes = new { @id = "ProductName" } });
</code>```

The controller which sets the ViewBag is as follows:

```<code>public ActionResult AddProduct(int quoteId, int quoteDetailId)
        {
            var items = db.Products.ToList();
            ViewBag.ProductData = items;

            ViewData["QuoteId"] = quoteId;
            ViewData["QuoteDetailId"] = quoteDetailId;
            return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 1, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
        }
</code>```

Once I hit the dropdown arrow on the DropDownListFor, "Select one" appears at the top of the list.  But when the DropDownListFor is first displayed, the first product name appears in the box, instead of "Select one".  How can I fix this?  Any help would be much appreciated.

答:
Don't specify a value for the id property in your model:</p>

```<code>public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
    var items = db.Products.ToList();
    ViewBag.ProductData = items;

    return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 0, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}
</code>```

Body:
I am new to MVC, and am trying to do something that should be easy, but it is eluding me.  I am using a DropDownListFor in a partial view to display a list of product names.  That part works fine.  What I am having trouble with is setting the initial value of the DropDownListFor to display "Select one".  The code I am working with is as follows:

@Html.DropDownListFor(model => model.ProductId, new SelectList(ViewBag.ProductData, "ProductId", "Name"), "---Select one---", new {  htmlAttributes = new { @id = "ProductName" } });

The controller which sets the ViewBag is as follows:

public ActionResult AddProduct(int quoteId, int quoteDetailId)
        {
            var items = db.Products.ToList();
            ViewBag.ProductData = items;

            ViewData["QuoteId"] = quoteId;
            ViewData["QuoteDetailId"] = quoteDetailId;
            return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 1, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
        }

Once I hit the dropdown arrow on the DropDownListFor, "Select one" appears at the top of the list.  But when the DropDownListFor is first displayed, the first product name appears in the box, instead of "Select one".  How can I fix this?  Any help would be much appreciated.

Body:
Don't specify a value for the id property in your model:

public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
    var items = db.Products.ToList();
    ViewBag.ProductData = items;

    return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 0, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}


答:
This is how you can do it:

```<code>public class YourActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    setupViewPager(viewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new FragmentOne(), "Fragment One");
    adapter.addFragment(new FragmentTwo(), "Fragment Two");
    viewPager.setAdapter(adapter);
}

private class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> fragmentTitleList = new ArrayList<>();

    ViewPagerAdapter(FragmentManager fragmentManager) {super(fragmentManager);}

    @Override
    public Fragment getItem(int position) {return fragmentList.get(position);}

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    void addFragment(Fragment fragment, String title) {

        fragmentList.add(fragment);
        fragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentTitleList.get(position);
    }
}
</code>```

}

And this is the .XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".YourActivity">

    <android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="8dp"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Hope it helps!

Title: How to achive swipe left and right on activity containg 2 fragments in android?

Body:
I have a activity that contain 2 fragments and both the fragments containing a recyclerview.
I need to implement a swipe gesture (when i swipe from one side to another the fragments need to be changed).
Previously i have added swipe gesture, but when i swipe the recycler view will scroll instead of change of fragments.

Can you help in implementing this..

Thanks

Body:
This is how you can do it:

public class YourActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    setupViewPager(viewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new FragmentOne(), "Fragment One");
    adapter.addFragment(new FragmentTwo(), "Fragment Two");
    viewPager.setAdapter(adapter);
}

private class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> fragmentTitleList = new ArrayList<>();

    ViewPagerAdapter(FragmentManager fragmentManager) {super(fragmentManager);}

    @Override
    public Fragment getItem(int position) {return fragmentList.get(position);}

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    void addFragment(Fragment fragment, String title) {

        fragmentList.add(fragment);
        fragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentTitleList.get(position);
    }
}

}

And this is the .XML file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".YourActivity">

    <android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="8dp"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

Hope it helps!


问:
Merge povray's partial images of arbitrary size
Starting situation:

Using povray I create 4 partial images of a scene.

```<code>povray +SR1 +ER200 +SC0 +EC200 +W400 +H400 +OPART1 povray.pov
povray +SR1 +ER200 +SC201 +EC400 +W400 +H400 +OPART11 povray.pov
povray +SR201 +ER400 +SC0 +EC200 +W400 +H400 +OPART2 povray.pov
povray +SR201 +ER400 +SC201 +EC400 +W400 +H400 +OPART22 povray.pov
</code>```

Problem to solve:

Merge the 4 images programmatically.

Things to take in consideration:

Most of the partial images are NOT valid images and cannot be opened. For example, the first partial image can be opened, showing a rectangle with the image at the top left and everything else is black. But the rest of the images contain only the information regarding his zone. We could say that those images are broken.

The output format is set with the +F and could be PPM, PNG, Uncompressed and Compressed Targa. A valid solution could use any of those formats.

Focus on how to merge the images. You know the rectangle that each partial image have.

Things that have been tried:

Concatenating the images with Tail as described in http://povray.tashcorp.net/tutorials/qd_multicpu_render/ . It only works if the partial images are complete on the width axis, that is if PART1 is a set of lines, PART2 another set of lines...and no column division. But we have column division.

Use ImageMagick. It cannot open the partial images. It says they are broken.

答:
I found how this could be achieved.

You need to patch Povray so that it saves information about the offset of PNG files.

This is the Patch.
https://gist.github.com/721862

You need to download the sources for povray and apply the patch. To apply the patch you save the patch file in povray-3.6.1/source/patch.patch and then:

```<code>cp patch.patch povray-3.6.1/source/
cd povray-3.6.1/source/
patch png_pov.cpp patch.patch
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Starting situation:

Using povray I create 4 partial images of a scene.

povray +SR1 +ER200 +SC0 +EC200 +W400 +H400 +OPART1 povray.pov
povray +SR1 +ER200 +SC201 +EC400 +W400 +H400 +OPART11 povray.pov
povray +SR201 +ER400 +SC0 +EC200 +W400 +H400 +OPART2 povray.pov
povray +SR201 +ER400 +SC201 +EC400 +W400 +H400 +OPART22 povray.pov

Problem to solve:

Merge the 4 images programmatically.

Things to take in consideration:

Most of the partial images are NOT valid images and cannot be opened. For example, the first partial image can be opened, showing a rectangle with the image at the top left and everything else is black. But the rest of the images contain only the information regarding his zone. We could say that those images are broken.

The output format is set with the +F and could be PPM, PNG, Uncompressed and Compressed Targa. A valid solution could use any of those formats.

Focus on how to merge the images. You know the rectangle that each partial image have.

Things that have been tried:

Concatenating the images with Tail as described in http://povray.tashcorp.net/tutorials/qd_multicpu_render/ . It only works if the partial images are complete on the width axis, that is if PART1 is a set of lines, PART2 another set of lines...and no column division. But we have column division.

Use ImageMagick. It cannot open the partial images. It says they are broken.

Body:
I found how this could be achieved.

You need to patch Povray so that it saves information about the offset of PNG files.

This is the Patch.
https://gist.github.com/721862

You need to download the sources for povray and apply the patch. To apply the patch you save the patch file in povray-3.6.1/source/patch.patch and then:

cp patch.patch povray-3.6.1/source/
cd povray-3.6.1/source/
patch png_pov.cpp patch.patch


问:
Best way to handle runtime permission in android
i have an old project with target sdk 21, now i have to put run time permission in that so can anyone suggest me any best and simple way to do that.</p>

答:
Create two variables like

```<code> private static final int REQUEST_CODE_PERMISSION = 1;
 String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
</code>```

after create method like this

```<code> private void getPermission() {
    if(Build.VERSION.SDK_INT>= 23) {

        if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{mPermission,
                    },
                    REQUEST_CODE_PERMISSION);
            return;
        }

        else
        {
            /* your code if permission already access
        }
    }
}
</code>```

After override onRequestPermissionsResult method like this

```<code> @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    Log.e("Req Code", "" + requestCode);
    if (requestCode == REQUEST_CODE_PERMISSION) {
        if (grantResults.length == 1 &&
                grantResults[0] == MockPackageManager.PERMISSION_GRANTED ) {
            methodRedirect();
        }
        else{
            this.getPermission();
        }
    }
}
</code>```

In this way even user deny permission, it will show again.

You can manage multiple permission like this.

Body:
Create two variables like

 private static final int REQUEST_CODE_PERMISSION = 1;
 String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

after create method like this

 private void getPermission() {
    if(Build.VERSION.SDK_INT>= 23) {

        if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{mPermission,
                    },
                    REQUEST_CODE_PERMISSION);
            return;
        }

        else
        {
            /* your code if permission already access
        }
    }
}

After override onRequestPermissionsResult method like this

 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    Log.e("Req Code", "" + requestCode);
    if (requestCode == REQUEST_CODE_PERMISSION) {
        if (grantResults.length == 1 &&
                grantResults[0] == MockPackageManager.PERMISSION_GRANTED ) {
            methodRedirect();
        }
        else{
            this.getPermission();
        }
    }
}

In this way even user deny permission, it will show again.

You can manage multiple permission like this.


问:
Regular Exp: Matcher: how to get last occurence in the group
I have table structure where I need to capture the Auth code. I have used  the regex and matcher method find(). However, there will be multiple codes generated and I need to get the recent one. I tried below code which captures only 1st occurrence. Please let me know How I can capture last occurrence of the code.

Code:

```<code>String mobilenumber="00955555555555";

//Date validate = null;

    {
    List<WebElement> rows = driver1.findElements(By.cssSelector("tr"));
    for (WebElement row : rows)
    {
        String text = row.getText();
        if (text.contains(mobilenumber))
        {
            String regex = ": (\\d+)"; //Your authentication code is
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);

            if (matcher.find())
                 {

                valueis = matcher.group(1);
                System.out.println(valueis);
</code>```

答:
If you want to last set of digits in input then use this regex with a negative lookahead:

```<code>\d+(?!.*\d)
</code>```

In Java:

```<code>String regex = "\\d+(?!.*\\d)";
</code>```

RegEx Demo

RegEx Breakup:

\d+ - Match 1 or more digits

(?!.*\d) - Negative lookahead that asserts we don't have any more digits ahead

Body:
I have table structure where I need to capture the Auth code. I have used  the regex and matcher method find(). However, there will be multiple codes generated and I need to get the recent one. I tried below code which captures only 1st occurrence. Please let me know How I can capture last occurrence of the code.

Code:

String mobilenumber="00955555555555";

//Date validate = null;

    {
    List<WebElement> rows = driver1.findElements(By.cssSelector("tr"));
    for (WebElement row : rows)
    {
        String text = row.getText();
        if (text.contains(mobilenumber))
        {
            String regex = ": (\\d+)"; //Your authentication code is
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);

            if (matcher.find())
                 {

                valueis = matcher.group(1);
                System.out.println(valueis);

Body:
If you want to last set of digits in input then use this regex with a negative lookahead:

\d+(?!.*\d)

In Java:

String regex = "\\d+(?!.*\\d)";

RegEx Demo

RegEx Breakup:

\d+ - Match 1 or more digits

(?!.*\d) - Negative lookahead that asserts we don't have any more digits ahead


问:
Retrofit upload any file
I am trying to upload a file , this way i am doing.

```<code>@POST("News/Article/Add")
        Call<User> addNews(@Header("api_key") String auth,
                            @Query(encoded = true, value = "title") String title,
                            @Body RequestBody file
        );
File file = new File(uri1.getPath());
                               RequestBody file1 = RequestBody.create(MediaType.parse("file/*"), file);
Call call = App.addNews(AddNewsActivity.this).addNews(apiKey,inputTitle.getText().toString(), file1)
</code>```

Am using compile 'com.squareup.retrofit2:retrofit:2.1.0'

First mistake am noticing, I need to send the requestbody  as "contentFile". As u can see below, the one below works but only for images.I dont want to specify any format ( like png).Just upload the file as is.

```<code>RequestBody requestBody = new MultipartBody.Builder()
>                                 .setType(MultipartBody.FORM)
>                                 .addFormDataPart("contentFile", UUID.randomUUID() + ".png",
>                                         RequestBody.create(MEDIA_TYPE_PNG, f100)).build();
</code>```

答:
You can assign media type dynamically:</p>

```<code> MediaType.parse(getContentResolver().getType(fileUri))
</code>```

Title: Retrofit upload any file

Body:
I am trying to upload a file , this way i am doing.

@POST("News/Article/Add")
        Call<User> addNews(@Header("api_key") String auth,
                            @Query(encoded = true, value = "title") String title,
                            @Body RequestBody file
        );
File file = new File(uri1.getPath());
                               RequestBody file1 = RequestBody.create(MediaType.parse("file/*"), file);
Call call = App.addNews(AddNewsActivity.this).addNews(apiKey,inputTitle.getText().toString(), file1)

Am using compile 'com.squareup.retrofit2:retrofit:2.1.0'

First mistake am noticing, I need to send the requestbody  as "contentFile". As u can see below, the one below works but only for images.I dont want to specify any format ( like png).Just upload the file as is.

RequestBody requestBody = new MultipartBody.Builder()
>                                 .setType(MultipartBody.FORM)
>                                 .addFormDataPart("contentFile", UUID.randomUUID() + ".png",
>                                         RequestBody.create(MEDIA_TYPE_PNG, f100)).build();

Body:
You can assign media type dynamically:

 MediaType.parse(getContentResolver().getType(fileUri))


问:
Django project 'site cant be reached'
I've created a Django project and a virtual environment where I installed python on my Ubuntu server. When I try to run the development server by typing

```<code>$ ./manage.py runserver 0.0.0.0:8000
</code>```

I get the usual

Performing system checks...

System check identified no issues (0 silenced).
  April 01, 2017 - 11:36:55

Django version 1.10.6, using settings 'myproject.settings'

Starting development server at http://0.0.0.0:8000/

Quit the server with CONTROL-C.

However, when I go to the site [my ip address]:8000 I get a 'This site can’t be reached' message, anyone know any causes for this? thanks

答: It was a security group problem in the server, I didn't have custom TCP rule 8000 enabled </p>

Title: Django project 'site cant be reached'

Body:
I've created a Django project and a virtual environment where I installed python on my Ubuntu server. When I try to run the development server by typing

$ ./manage.py runserver 0.0.0.0:8000

I get the usual

Performing system checks...

System check identified no issues (0 silenced).
  April 01, 2017 - 11:36:55

Django version 1.10.6, using settings 'myproject.settings'

Starting development server at http://0.0.0.0:8000/

Quit the server with CONTROL-C.

However, when I go to the site [my ip address]:8000 I get a 'This site can’t be reached' message, anyone know any causes for this? thanks


答:
In Oracle 12.1 and above, MATCH_RECOGNIZE can do quick work of this kind of problems:

Edited. Initially I was picking the "next number" where a gap exists (in the example, the value 9). But that is not what the OP wants, he wants the first missing number (7 in this case). I edited to change the measures clause, to find the first missing number as requested.  End Edit

```<code>with test_data (num) as (
       select  4 from dual union all
       select  5 from dual union all
       select  6 from dual union all
       select  9 from dual union all
       select 10 from dual union all
       select 13 from dual
     )
-- end of test data; when you use the SQL query below,
-- replace test_data and num with your actual table and column names.
select result as num
from test_data
match_recognize (
  order by num
  measures last(b.num) + 1 as result
  pattern ( ^ a b* c )
  define b as num = prev(num) + 1,
         c as num > prev(num) + 1
)
;

NUM
---
  7
</code>```

Title: to find minimum missing number in oracle

Body:
i want to find the minimum missing number of a column named (s_no) and the table named (test_table) in oracle and I write the following code..

select
    min_s_no-1+level missing_number
from (
    select min(s_no) min_s_no, max(s_no) max_s_no
    from test_table
) connect by level <= max_s_no-min_s_no+1
minus
select s_no from test_table
;

it gives me all the missing number as a result. But I want to select the minimum
number. Can any one help me please.
thanks in advance.

Body:
In Oracle 12.1 and above, MATCH_RECOGNIZE can do quick work of this kind of problems:

Edited. Initially I was picking the "next number" where a gap exists (in the example, the value 9). But that is not what the OP wants, he wants the first missing number (7 in this case). I edited to change the measures clause, to find the first missing number as requested.  End Edit

with test_data (num) as (
       select  4 from dual union all
       select  5 from dual union all
       select  6 from dual union all
       select  9 from dual union all
       select 10 from dual union all
       select 13 from dual
     )
-- end of test data; when you use the SQL query below,
-- replace test_data and num with your actual table and column names.
select result as num
from test_data
match_recognize (
  order by num
  measures last(b.num) + 1 as result
  pattern ( ^ a b* c )
  define b as num = prev(num) + 1,
         c as num > prev(num) + 1
)
;

NUM
---
  7


问:
Add animation when hide "LinearLayout" (View.GONE) and show LinearLayout (View.VISIBLE)
Sorry for my English... I will try to explain what I want to do.
I have a project. It can be downloaded at the link:

https://drive.google.com/file/d/0Bxhi0uFKK3upcXJjNGtMVkg4TDQ/view?usp=sharing

As you can see the screenshot:

http://pixs.ru/showimage/Screenshot_9509352_15647059.png

The button "Hide/Show B layout" hides and shows the green container - "B layout". I want add animation top down when the container "B layout" is showing. And the animation from the bottom up when the container is hidden.  Also, I want the blue container "C", gradually fell together with the container "B". And rising smoothly, together with the container "B". Please help me to do it.

Below duplicate my code:

MainActivity

```<code>public class MainActivity extends Activity {
View Layout;

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

    Layout = findViewById(R.id.bLayout);

    final  View  button2  =  findViewById (R.id.button);
    button2.setOnClickListener(new  View.OnClickListener(){

      @Override
      public void onClick (View v){

          if ((Layout.getVisibility() == View.VISIBLE))
          {

              Layout.setVisibility(View.GONE);
          }
          else
          {

            // Animation animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.slide_in_left);
            // Layout.setAnimation(animFadeIn);
             Layout.setVisibility(View.VISIBLE);

          }
      }
    });

}
</code>```

}

答:
I faced a similar issue and this is the easiest solution I could find:

```<code>setVisibility(View.GONE) on the view you wish to hide.
</code>```

And make sure in the xml layout the parent has following attribute:

```<code>android:animateLayoutChanges="true"
</code>```

Body:
Sorry for my English... I will try to explain what I want to do.
I have a project. It can be downloaded at the link:

https://drive.google.com/file/d/0Bxhi0uFKK3upcXJjNGtMVkg4TDQ/view?usp=sharing

As you can see the screenshot:

http://pixs.ru/showimage/Screenshot_9509352_15647059.png

The button "Hide/Show B layout" hides and shows the green container - "B layout". I want add animation top down when the container "B layout" is showing. And the animation from the bottom up when the container is hidden.  Also, I want the blue container "C", gradually fell together with the container "B". And rising smoothly, together with the container "B". Please help me to do it.

Below duplicate my code:

MainActivity

public class MainActivity extends Activity {
View Layout;

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

    Layout = findViewById(R.id.bLayout);

    final  View  button2  =  findViewById (R.id.button);
    button2.setOnClickListener(new  View.OnClickListener(){

      @Override
      public void onClick (View v){

          if ((Layout.getVisibility() == View.VISIBLE))
          {

              Layout.setVisibility(View.GONE);
          }
          else
          {

            // Animation animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.slide_in_left);
            // Layout.setAnimation(animFadeIn);
             Layout.setVisibility(View.VISIBLE);

          }
      }
    });

}

}

Body:
I faced a similar issue and this is the easiest solution I could find:

setVisibility(View.GONE) on the view you wish to hide.

And make sure in the xml layout the parent has following attribute:

android:animateLayoutChanges="true"


问:
How to assign a list into an another list in python
```<code>num = 8
order = []
p = 0

for i in range(num):
    for t in range(i+1 , num):
        order[p] = [i,t]
        p += 1
</code>```

I want to set some data like [0,0] , [0,1] ... [2,6] , [2,7] , [3,4] , [3,5] , [3,6] , [3,7] , [4,5] ... [6,7] into a list, gives this error:
IndexError: list assignment index out of range, how can i solve this problem?

答:
You can use append() method to add item

```<code>order.append([i,t])
</code>```

Or use a list comprehension

```<code>print [[i,t] for i in range(num) for t in range(i+1 , num)]
</code>```

Body:
num = 8
order = []
p = 0

for i in range(num):
    for t in range(i+1 , num):
        order[p] = [i,t]
        p += 1

I want to set some data like [0,0] , [0,1] ... [2,6] , [2,7] , [3,4] , [3,5] , [3,6] , [3,7] , [4,5] ... [6,7] into a list, gives this error:
IndexError: list assignment index out of range, how can i solve this problem?

Body:
You can use append() method to add item

order.append([i,t])

Or use a list comprehension

print [[i,t] for i in range(num) for t in range(i+1 , num)]


问:
How to change the Font in your legend to a windows font
How can I change the Font and the size in R. I want it Times New Roman is it possible. Where should I put the command this the script that I've been trying to change the font</p>

答:
If you're referring to changing the font in a plot's legend and labels.  Then here is a possible solution using ggplot2.  A full list of fonts can be found here.</p>

```<code>library(tidyverse)

df <- data_frame(a=runif(100),
                 b=runif(100),
                 c=sample(c("Class A","Class B"), 100, T))

ggplot(df, aes(x=a,y=b,colour=c)) +
  geom_line() +
  theme(text=element_text(family="Times"))
</code>```

Body:
If you're referring to changing the font in a plot's legend and labels.  Then here is a possible solution using ggplot2.  A full list of fonts can be found here.

library(tidyverse)

df <- data_frame(a=runif(100),
                 b=runif(100),
                 c=sample(c("Class A","Class B"), 100, T))

ggplot(df, aes(x=a,y=b,colour=c)) +
  geom_line() +
  theme(text=element_text(family="Times"))


问:
PHP Log in page with hashed password issue
So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.

```<code><?php

session_start();
include 'databaseconnection.php';

$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);

$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);

if ($hash == 0) {
  header("Location: error.php")
  exit();
} else {

$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);

if (!row = mysqli_fetch_assoc($result)); {
  echo "your email address or password is incorrect!";
} else {
  $_SESSION['id'] = $row['id'];
}

header("Location: profile.php")
</code>```

If someone could simply suggest what changes I should make, I would really appreciate it.

答: You have not closed the "} else {"... section. </p>

Body:
So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.

<?php

session_start();
include 'databaseconnection.php';

$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);

$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);

if ($hash == 0) {
  header("Location: error.php")
  exit();
} else {

$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);

if (!row = mysqli_fetch_assoc($result)); {
  echo "your email address or password is incorrect!";
} else {
  $_SESSION['id'] = $row['id'];
}

header("Location: profile.php")

If someone could simply suggest what changes I should make, I would really appreciate it.


问:
How to check if Directory already Exists in MFC(VC++)?
How to check if Directory already Exists in MFC(VC++) ?
I am using below code to get current application Path and there i am creating NDSLog folder
so that all my Logfiles should place there , now i want to check the condition if NDSLog folder already exists dont create it .How to do that ?

Thanks.

```<code>char strPathName[_MAX_PATH];
    ::GetModuleFileName(NULL, strPathName, _MAX_PATH);

    // The following code will allow you to get the path.
    CString newPath(strPathName);
    int fpos = newPath.ReverseFind('\\');

    if (fpos != -1)
    newPath = newPath.Left(fpos+1);
    newPath += "NDSLog\\" ;

    CreateDirectory(newPath,NULL);
</code>```

答: I use PathFileExists. </p>

Body:
How to check if Directory already Exists in MFC(VC++) ?
I am using below code to get current application Path and there i am creating NDSLog folder
so that all my Logfiles should place there , now i want to check the condition if NDSLog folder already exists dont create it .How to do that ?

Thanks.

char strPathName[_MAX_PATH];
    ::GetModuleFileName(NULL, strPathName, _MAX_PATH);

    // The following code will allow you to get the path.
    CString newPath(strPathName);
    int fpos = newPath.ReverseFind('\\');

    if (fpos != -1)
    newPath = newPath.Left(fpos+1);
    newPath += "NDSLog\\" ;

    CreateDirectory(newPath,NULL);

Body: I use PathFileExists.


问:
Retrieving data from thingspeak website to HelloCharts
In this code data is taken from thingspeak website given the channel id. the channel is public. The graph is obtained using hellocharts and chartview.

QUESTION:
I want to print all the data values which are plotted on the graph or the last data added in a text view. In which variable is the data stored As i want to further work with the data.

In the output I want to know that the value 395 is stored in which variable.

I have provided the java code below.

```<code>import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;
import com.macroyau.thingspeakandroid.ThingSpeakChannel;
import com.macroyau.thingspeakandroid.ThingSpeakLineChart;
import com.macroyau.thingspeakandroid.model.ChannelFeed;
import java.util.Calendar;
import java.util.Date;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class DemoActivity extends ActionBarActivity {

private ThingSpeakChannel tsChannel;
private ThingSpeakLineChart tsChart;
private LineChartView chartView;

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

    // Connect to ThinkSpeak Channel 9
    tsChannel = new ThingSpeakChannel(135855);
    // Set listener for Channel feed update events
    tsChannel.setChannelFeedUpdateListener(new ThingSpeakChannel.ChannelFeedUpdateListener() {
        @Override
        public void onChannelFeedUpdated(long channelId, String channelName, ChannelFeed channelFeed) {
            // Show Channel ID and name on the Action Bar
            getSupportActionBar().setTitle(channelName);
            getSupportActionBar().setSubtitle("Channel " + channelId);
            // Notify last update time of the Channel feed through a Toast message
            Date lastUpdate = channelFeed.getChannel().getUpdatedAt();
            Toast.makeText(DemoActivity.this, lastUpdate.toString(), Toast.LENGTH_LONG).show();
        }
    });
    // Fetch the specific Channel feed
    tsChannel.loadChannelFeed();

    // Create a Calendar object dated 5 minutes ago
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -5);

    // Configure LineChartView
    chartView = (LineChartView) findViewById(R.id.chart);
    chartView.setZoomEnabled(false);
    chartView.setValueSelectionEnabled(true);

    // Create a line chart from Field1 of ThinkSpeak Channel 9
    tsChart = new ThingSpeakLineChart(135855, 2);
    // Get 200 entries at maximum
    tsChart.setNumberOfEntries(200);
    // Set value axis labels on 10-unit interval
    tsChart.setValueAxisLabelInterval(10);
    // Set date axis labels on 5-minute interval
    tsChart.setDateAxisLabelInterval(10);
    // Show the line as a cubic spline
    tsChart.useSpline(true);
    // Set the line color
    tsChart.setLineColor(Color.parseColor("#D32F2F"));
    // Set the axis color
    tsChart.setAxisColor(Color.parseColor("#455a64"));
    // Set the starting date (5 minutes ago) for the default viewport of the chart
   // tsChart.setChartStartDate(calendar.getTime());
    // Set listener for chart data update
    tsChart.setListener(new ThingSpeakLineChart.ChartDataUpdateListener() {
        @Override
        public void onChartDataUpdated(long channelId, int fieldId, String title, LineChartData lineChartData, Viewport maxViewport, Viewport initialViewport) {
            // Set chart data to the LineChartView
            chartView.setLineChartData(lineChartData);
            // Set scrolling bounds of the chart
            chartView.setMaximumViewport(maxViewport);
            // Set the initial chart bounds
            chartView.setCurrentViewport(initialViewport);
           /* LineChartData data = new LineChartData();
            float data1=data.getBaseValue();
            TextView tvName = (TextView)findViewById(R.id.textView);
            tvName.setText((int) data1);*/

        }
    });
    // Load chart data asynchronously
    tsChart.loadChartData();
    }

}
</code>```

答:
I do not know about this particular library but to access your data you could simply hit the API of your given channel i.e.</p>

```<code>String lightApi = "https://api.thingspeak.com/channels/<your_channel_id>/fields/<field_number>.json?api_key=<read_API_key>&results=<number_of_readings>";

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,lightApi, null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        try {
            JSONArray feeds = response.getJSONArray("feeds");
            for(int i=0; i<feeds.length();i++){
                JSONObject jo = feeds.getJSONObject(i);
                String l=jo.getString("<your_field_number>"); //you may want to Integer.parseInt the returned value
                //String date=jo.getString("created_at"); -->to get the date and time
                // Do whatever you want to do with each of these values...
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
In this code data is taken from thingspeak website given the channel id. the channel is public. The graph is obtained using hellocharts and chartview.

QUESTION:
I want to print all the data values which are plotted on the graph or the last data added in a text view. In which variable is the data stored As i want to further work with the data.

In the output I want to know that the value 395 is stored in which variable.

I have provided the java code below.

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;
import com.macroyau.thingspeakandroid.ThingSpeakChannel;
import com.macroyau.thingspeakandroid.ThingSpeakLineChart;
import com.macroyau.thingspeakandroid.model.ChannelFeed;
import java.util.Calendar;
import java.util.Date;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class DemoActivity extends ActionBarActivity {

private ThingSpeakChannel tsChannel;
private ThingSpeakLineChart tsChart;
private LineChartView chartView;

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

    // Connect to ThinkSpeak Channel 9
    tsChannel = new ThingSpeakChannel(135855);
    // Set listener for Channel feed update events
    tsChannel.setChannelFeedUpdateListener(new ThingSpeakChannel.ChannelFeedUpdateListener() {
        @Override
        public void onChannelFeedUpdated(long channelId, String channelName, ChannelFeed channelFeed) {
            // Show Channel ID and name on the Action Bar
            getSupportActionBar().setTitle(channelName);
            getSupportActionBar().setSubtitle("Channel " + channelId);
            // Notify last update time of the Channel feed through a Toast message
            Date lastUpdate = channelFeed.getChannel().getUpdatedAt();
            Toast.makeText(DemoActivity.this, lastUpdate.toString(), Toast.LENGTH_LONG).show();
        }
    });
    // Fetch the specific Channel feed
    tsChannel.loadChannelFeed();

    // Create a Calendar object dated 5 minutes ago
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -5);

    // Configure LineChartView
    chartView = (LineChartView) findViewById(R.id.chart);
    chartView.setZoomEnabled(false);
    chartView.setValueSelectionEnabled(true);

    // Create a line chart from Field1 of ThinkSpeak Channel 9
    tsChart = new ThingSpeakLineChart(135855, 2);
    // Get 200 entries at maximum
    tsChart.setNumberOfEntries(200);
    // Set value axis labels on 10-unit interval
    tsChart.setValueAxisLabelInterval(10);
    // Set date axis labels on 5-minute interval
    tsChart.setDateAxisLabelInterval(10);
    // Show the line as a cubic spline
    tsChart.useSpline(true);
    // Set the line color
    tsChart.setLineColor(Color.parseColor("#D32F2F"));
    // Set the axis color
    tsChart.setAxisColor(Color.parseColor("#455a64"));
    // Set the starting date (5 minutes ago) for the default viewport of the chart
   // tsChart.setChartStartDate(calendar.getTime());
    // Set listener for chart data update
    tsChart.setListener(new ThingSpeakLineChart.ChartDataUpdateListener() {
        @Override
        public void onChartDataUpdated(long channelId, int fieldId, String title, LineChartData lineChartData, Viewport maxViewport, Viewport initialViewport) {
            // Set chart data to the LineChartView
            chartView.setLineChartData(lineChartData);
            // Set scrolling bounds of the chart
            chartView.setMaximumViewport(maxViewport);
            // Set the initial chart bounds
            chartView.setCurrentViewport(initialViewport);
           /* LineChartData data = new LineChartData();
            float data1=data.getBaseValue();
            TextView tvName = (TextView)findViewById(R.id.textView);
            tvName.setText((int) data1);*/

        }
    });
    // Load chart data asynchronously
    tsChart.loadChartData();
    }

}

Body:
I do not know about this particular library but to access your data you could simply hit the API of your given channel i.e.

String lightApi = "https://api.thingspeak.com/channels/<your_channel_id>/fields/<field_number>.json?api_key=<read_API_key>&results=<number_of_readings>";

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,lightApi, null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        try {
            JSONArray feeds = response.getJSONArray("feeds");
            for(int i=0; i<feeds.length();i++){
                JSONObject jo = feeds.getJSONObject(i);
                String l=jo.getString("<your_field_number>"); //you may want to Integer.parseInt the returned value
                //String date=jo.getString("created_at"); -->to get the date and time
                // Do whatever you want to do with each of these values...
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}


Title: How to assign a list into an another list in python

Body:
You cannot declare a list item with order[p] because p in this case is a list index.  What you might want is a dict, if you want to be able to reference them by the p.
Otherwise, use append.

Dict method:

num = 8
order = {}
p = 0

for i in range(num):
    for t in range(i+1 , num):
        order[p] = [i,t]
        p += 1

>>> order
{0: [0, 1], 1: [0, 2], 2: [0, 3], 3: [0, 4], 4: [0, 5], 5: [0, 6], 6: [0, 7], 7: [1, 2], 8: [1, 3], 9: [1, 4], 10: [1, 5], 11: [1, 6], 12: [1, 7], 13: [2, 3], 14: [2, 4], 15: [2, 5], 16: [2, 6], 17: [2, 7], 18: [3, 4], 19: [3, 5], 20: [3, 6], 21: [3, 7], 22: [4, 5], 23: [4, 6], 24: [4, 7], 25: [5, 6], 26: [5, 7], 27: [6, 7]}
>>> order[4]
[0, 5]

List append method:

num = 8
order = []
p = 0

for i in range(num):
    for t in range(i+1 , num):
        order.append([i,t])
        p += 1

>>> order
[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [3, 4], [3, 5], [3, 6], [3, 7], [4, 5], [4, 6], [4, 7], [5, 6], [5, 7], [6, 7]]
>>> order[4]
[0, 5]


问:
Converting a mongo stored date back into milliseconds since Unix epoch when loaded?
I am using Mongoose & Node.js for my webserver.

As a part of one of my document schemas, I have a 'timestamp' field.
The line for it in the schema is:
timestamp: { type: Date, default: Date.now }

This works fine, and allows me to retrieve documents based on the timestamp, however, this saves as the ISODate format as described here: http://docs.mongodb.org/manual/core/document/#date, like this:

"timestamp":"2013-04-04T19:31:38.514Z"

I don't mind this, but I send this to the client as is. This means I have to use Date.parse() at the client end before I can comparative operations with it.

Is there any way to either store the date as an integer, or automatically convert it to one when it's retrieved?

Is there any reason I should keep it how it is, and just deal with it at the client end?

Thanks in advance.

答:
```<code>var schema = new Schema({
  timestamp: {type:Number, default: new Date().getTime()}
});
</code>```

Hope this will solve your issue.

Body:
var schema = new Schema({
  timestamp: {type:Number, default: new Date().getTime()}
});

Hope this will solve your issue.


问:
Where does the x come from in this lambda expression?
So I was looking around on the internet reading up on sorting techniques and I stumbled on to lambda.
Now i'm not completly sure how it works and i couldnt find any tutorials that broke it down to my level.

This is what im trying to break down.

```<code>var sorted = list.OrderBy(x => new MailAddress(x).Host).ToList();
</code>```

So I get that I create a variable named sorted and this will be the variable that hold the sorted items from the list.

This is the part I dont understand

```<code>OrderBy(x => new MailAddress(x).Host)
</code>```

Where does x come from and what exactly does the lambda expression mean? =>
Its not like this expression != which means NOT.
And I get that it sorts by host so Yahoo, GMAIL & Hotmail.

答:
In simplest terms, x is a variable that you declare.

So it reads "x such that x is"... Whatever expression you are trying to convey based on the input and output parameter of your query.

To give you another example:

```<code>var sorted = list.Where(x => x.Name == "Foo").ToList();
</code>```

This reads as "x such that x is equal to Foo". And this will return all list with Name property that is equal to Foo.

To further explain this, lets look into the one of the overloaded Enumerable method which is "Where". According to MSDN:

The actual syntax is:

```<code>Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
</code>```

To give another example lets declare a List of integer. Our goal is to get all even integers:

```<code>List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
</code>```

Now to query all integers who are even numbers, we will use the one of the overloaded version of Where extension methods, using lambda syntax. It says:

So the source here is the:

```<code>numbers.Where();
</code>```

Since "numbers" variable is the IEnumerable of TSource.
TSource here is any IEnumerable of type "T" or any type of entity.

Now the last part is it accepts a Func. A Func is a predefined delegate type. It provides us a way to store anonymous methods in generalized and simple way. To further understand this, lets read it again. It says that it will accept a source, and will output a boolean result.

Now let's create a Func that accepts TSource, on this case, integer as our example and will output boolean result:

```<code>Func<int, bool> fncParameter = x => x % 2 == 0;
</code>```

Now we can pass that into our:

```<code>numbers.Where
</code>```

Which will be:

```<code>List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Func<int, bool> fncParameter = x => x % 2 == 0;
IEnumerable<int> result = numbers.Where(fncParameter);
</code>```

Or in short:

```<code>ist<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> result = numbers.Where(x => x % 2 == 0);
</code>```

Body:
So I was looking around on the internet reading up on sorting techniques and I stumbled on to lambda.
Now i'm not completly sure how it works and i couldnt find any tutorials that broke it down to my level.

This is what im trying to break down.

var sorted = list.OrderBy(x => new MailAddress(x).Host).ToList();

So I get that I create a variable named sorted and this will be the variable that hold the sorted items from the list.

This is the part I dont understand

OrderBy(x => new MailAddress(x).Host)

Where does x come from and what exactly does the lambda expression mean? =>
Its not like this expression != which means NOT.
And I get that it sorts by host so Yahoo, GMAIL & Hotmail.

Body:
In simplest terms, x is a variable that you declare.

So it reads "x such that x is"... Whatever expression you are trying to convey based on the input and output parameter of your query.

To give you another example:

var sorted = list.Where(x => x.Name == "Foo").ToList();

This reads as "x such that x is equal to Foo". And this will return all list with Name property that is equal to Foo.

To further explain this, lets look into the one of the overloaded Enumerable method which is "Where". According to MSDN:

The actual syntax is:

Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate

To give another example lets declare a List of integer. Our goal is to get all even integers:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Now to query all integers who are even numbers, we will use the one of the overloaded version of Where extension methods, using lambda syntax. It says:

So the source here is the:

numbers.Where();

Since "numbers" variable is the IEnumerable of TSource.
TSource here is any IEnumerable of type "T" or any type of entity.

Now the last part is it accepts a Func. A Func is a predefined delegate type. It provides us a way to store anonymous methods in generalized and simple way. To further understand this, lets read it again. It says that it will accept a source, and will output a boolean result.

Now let's create a Func that accepts TSource, on this case, integer as our example and will output boolean result:

Func<int, bool> fncParameter = x => x % 2 == 0;

Now we can pass that into our:

numbers.Where

Which will be:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Func<int, bool> fncParameter = x => x % 2 == 0;
IEnumerable<int> result = numbers.Where(fncParameter);

Or in short:

ist<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> result = numbers.Where(x => x % 2 == 0);


问:
Issue with POST variable in php script
I have written a php script for learning how to create a REST API. But there is some issue with the code that I can't figure out.

Here is the PHP script:

```<code><?php

if($_SERVER['REQUEST_METHOD'] == "POST") {
    // Get data
    $name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
    $email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
    $status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";

    $length = strlen($status);
    if( $length >= 10 ) {
        $json = array("status" => 1, "name" => $name, "email" => $email, "status" => $status);
    }
    else {
        $json = array("status" => 0, "msg" => "Error: Status too short!", "length" => $length);
    }
}

else {
    $json = array("status" => 0, "msg" => "Error: Request method not accepted");
}

/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
</code>```

I am calling this from Httprequester in Mozilla Firefox with the URL "http://localhost/RESTTEST.php?name=dparua&email=d.parua%40gmail.com&pwd=something&status=very%20very%20long%20status"

But this is the response I get irrespective of how long a string I pass as status.
"{"status":0,"msg":"Error: Status too short!","length":0}"

I tried changing the code to this:

```<code><?php

if($_SERVER['REQUEST_METHOD'] == "POST") {

        $json = array("status" => 1, "name" => $_POST['name'], "email" => $_POST['email'], "status" => $_POST['status']);
}

else {
    $json = array("status" => 0, "msg" => "Error: Request method not accepted");
}

/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
</code>```

And posting to this modified script, this is the error message I get:
"

Notice:  Undefined index: name in C:\xampp\htdocs\RESTTEST.php on line 5

Notice:  Undefined index: email in C:\xampp\htdocs\RESTTEST.php on line 5

Notice:  Undefined index: status in C:\xampp\htdocs\RESTTEST.php on line 5

{"status":null,"name":null,"email":null}"

Please suggest what is wrong.

答:
You are send POST request, but your data (name, email and status) are pulled via GET

You are get error in PHP script because you must used mysql_connect before mysql_real_escape_string

P.S. mysql_real_escape_string - was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

Here you will find working PHP code (but change login and password to your):

```<code><?php

if($_SERVER['REQUEST_METHOD'] == "POST") {
    mysql_connect('localhost', 'root', 'password') OR die(mysql_error());

    // Get data
    $name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
    $email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
    $status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";

    $length = strlen($status);
    if( $length >= 10 ) {
        $json = array("status" => 1, "name" => $name, "email" => $email, "status" => $status);
    }
    else {
        $json = array("status" => 0, "msg" => "Error: Status too short!", "length" => $length);
    }
}

else {
    $json = array("status" => 0, "msg" => "Error: Request method not accepted");
}

/* Output header */
header('Content-type: application/json');
echo json_encode($json);
</code>```

After that install POSTMAN application. And try to send that request:

Title: Issue with POST variable in php script

Body:
I have written a php script for learning how to create a REST API. But there is some issue with the code that I can't figure out.

Here is the PHP script:

<?php

if($_SERVER['REQUEST_METHOD'] == "POST") {
    // Get data
    $name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
    $email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
    $status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";

    $length = strlen($status);
    if( $length >= 10 ) {
        $json = array("status" => 1, "name" => $name, "email" => $email, "status" => $status);
    }
    else {
        $json = array("status" => 0, "msg" => "Error: Status too short!", "length" => $length);
    }
}

else {
    $json = array("status" => 0, "msg" => "Error: Request method not accepted");
}

/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>

I am calling this from Httprequester in Mozilla Firefox with the URL "http://localhost/RESTTEST.php?name=dparua&email=d.parua%40gmail.com&pwd=something&status=very%20very%20long%20status"

But this is the response I get irrespective of how long a string I pass as status.
"{"status":0,"msg":"Error: Status too short!","length":0}"

I tried changing the code to this:

<?php

if($_SERVER['REQUEST_METHOD'] == "POST") {

        $json = array("status" => 1, "name" => $_POST['name'], "email" => $_POST['email'], "status" => $_POST['status']);
}

else {
    $json = array("status" => 0, "msg" => "Error: Request method not accepted");
}

/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>

And posting to this modified script, this is the error message I get:
"

Notice:  Undefined index: name in C:\xampp\htdocs\RESTTEST.php on line 5

Notice:  Undefined index: email in C:\xampp\htdocs\RESTTEST.php on line 5

Notice:  Undefined index: status in C:\xampp\htdocs\RESTTEST.php on line 5

{"status":null,"name":null,"email":null}"

Please suggest what is wrong.

Body:
You are send POST request, but your data (name, email and status) are pulled via GET

You are get error in PHP script because you must used mysql_connect before mysql_real_escape_string

P.S. mysql_real_escape_string - was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

Here you will find working PHP code (but change login and password to your):

<?php

if($_SERVER['REQUEST_METHOD'] == "POST") {
    mysql_connect('localhost', 'root', 'password') OR die(mysql_error());

    // Get data
    $name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
    $email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
    $status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";

    $length = strlen($status);
    if( $length >= 10 ) {
        $json = array("status" => 1, "name" => $name, "email" => $email, "status" => $status);
    }
    else {
        $json = array("status" => 0, "msg" => "Error: Status too short!", "length" => $length);
    }
}

else {
    $json = array("status" => 0, "msg" => "Error: Request method not accepted");
}

/* Output header */
header('Content-type: application/json');
echo json_encode($json);

After that install POSTMAN application. And try to send that request:


答:
You should look into Python list comprehensions. What you want could be achieved by

```<code>num = 8
order = [[i, t] for t in range(i+1, num) for i in range(num)]
</code>```

The error you get is because you initialize an empty list (order=[]) and then try to access elements of that list order[p] = [i,t]. If you want to build up a list step by step, use the append method of Python lists.

Body:
You should look into Python list comprehensions. What you want could be achieved by

num = 8
order = [[i, t] for t in range(i+1, num) for i in range(num)]

The error you get is because you initialize an empty list (order=[]) and then try to access elements of that list order[p] = [i,t]. If you want to build up a list step by step, use the append method of Python lists.


问:
How do I track visits to facebook pages using Google Analytics or Yahoo Web Analytics?
I have recently looked into this and discovered that using FBML pages in a facebook fan page, I can add fb:google-analytics tags or image tags to track page visits. However I have found no method of tracking visits to other facebook tab pages, like "pictures" or "wall".

Is there a way do this?

Thanks

答:
There is no way of doing this with Google Analytics.

There used to be a hack that embedded a php file as an image, and that request tracked a pageview. However, a change to how Facebook renders pages makes this hack/plugin useless (it looks like it stopped working on September 7th). Basically, it looks like they're caching any external images onto their own servers, and thus breaking this hack. Short of there being an officially supported plugin, or Facebook allowing Google to track more, this is likely a dead end.

Edit: With Facebook tabs, you can install an iframe app as a tab (not using FBML), and you can put Google Analytics on the tab. But, since its an iframe, you don't have access to real referrer information, and Facebook spoofs its referrer, so there's no way for the iframe to detect anything about the page. But this is only for the tab, not for the wall or photos.

Another important thing to note is that the cookies are still being set on your domain, so it might make sense to keep the account on your main account, but use a special configuration on the tab.

Here's the best practice I've settled on for putting Google Analytics on a Facebook tab iframe:

First, the iframe URL should contain the URL parameter ?utm_nooverride=1. This is so if the user already has referral cookies (for example, if they got to your site before via Google, the pageview will persist with that referral source.)

Second, I override the referrer value (which is useless, since it is spoofed by Facebook) to be tab.facebook.com, to make it simple to differentiate from other traffic.

Finally, I place 2 custom variables: One page-level, and one visitor level. The former allows me to easily know what pageviews occurred from within the tab. The second allows me to track the rest of the interactions my site has with this person if they end up returning to my site. That code looks like this:

```<code>var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-1']);
_gaq.push(['_setReferrerOverride', 'http://www.tab.facebook.com']);
_gaq.push(['_setCustomVar', 1, 'is_facebook_page', 'true', 3]);
_gaq.push(['_setCustomVar', 2, 'visited_facebook', 'true', 1]);
_gaq.push(['_trackPageview']);
</code>```

Body:
There is no way of doing this with Google Analytics.

There used to be a hack that embedded a php file as an image, and that request tracked a pageview. However, a change to how Facebook renders pages makes this hack/plugin useless (it looks like it stopped working on September 7th). Basically, it looks like they're caching any external images onto their own servers, and thus breaking this hack. Short of there being an officially supported plugin, or Facebook allowing Google to track more, this is likely a dead end.

Edit: With Facebook tabs, you can install an iframe app as a tab (not using FBML), and you can put Google Analytics on the tab. But, since its an iframe, you don't have access to real referrer information, and Facebook spoofs its referrer, so there's no way for the iframe to detect anything about the page. But this is only for the tab, not for the wall or photos.

Another important thing to note is that the cookies are still being set on your domain, so it might make sense to keep the account on your main account, but use a special configuration on the tab.

Here's the best practice I've settled on for putting Google Analytics on a Facebook tab iframe:

First, the iframe URL should contain the URL parameter ?utm_nooverride=1. This is so if the user already has referral cookies (for example, if they got to your site before via Google, the pageview will persist with that referral source.)

Second, I override the referrer value (which is useless, since it is spoofed by Facebook) to be tab.facebook.com, to make it simple to differentiate from other traffic.

Finally, I place 2 custom variables: One page-level, and one visitor level. The former allows me to easily know what pageviews occurred from within the tab. The second allows me to track the rest of the interactions my site has with this person if they end up returning to my site. That code looks like this:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-1']);
_gaq.push(['_setReferrerOverride', 'http://www.tab.facebook.com']);
_gaq.push(['_setCustomVar', 1, 'is_facebook_page', 'true', 3]);
_gaq.push(['_setCustomVar', 2, 'visited_facebook', 'true', 1]);
_gaq.push(['_trackPageview']);


问:
Cannot initialize QQueue with initializer list
A QList<T> lets me initialize it with some entries using a initializer list.

Doing the same with a Queue<T> gives me a compiler error.

Example code does not compile:

```<code>QList<qreal> someNumbers { 0.0, 0.1 };
QQueue<qreal> someOtherNumbers { 0.0, 0.1 };
</code>```

Compiler output:

```<code>error: no matching function for call to 'QQueue<double>::QQueue(<brace-enclosed initializer list>)'
     QQueue<qreal> someOtherNumbers { 0.0, 0.1 };
                                               ^
qqueue.h:49:7: note: candidate: QQueue<double>::QQueue()
 class QQueue : public QList<T>
       ^
qqueue.h:49:7: note:   candidate expects 0 arguments, 2 provided
qqueue.h:49:7: note: candidate: QQueue<double>::QQueue(const QQueue<double>&)
qqueue.h:49:7: note:   candidate expects 1 argument, 2 provided
qqueue.h:49:7: note: candidate: QQueue<double>::QQueue(QQueue<double>&&)
qqueue.h:49:7: note:   candidate expects 1 argument, 2 provided
</code>```

Is there some way to initialize a QQueue<T> using an initializer list?

答:
Since QQueue inherit from QList, I found a trick to do that.

```<code>QQueue<double> *queue;
QList<double> list = {{0.0, 1.1}};
queue = reinterpret_cast<QQueue<double> *>(&list);
qDebug() << queue->isEmpty();
while (!queue->isEmpty()) {
    qDebug() << queue->dequeue();
}
</code>```

however, in this example, list it temporary so if you want to use this outside to the function you will have to use new

Body:
A QList<T> lets me initialize it with some entries using a initializer list.

Doing the same with a Queue<T> gives me a compiler error.

Example code does not compile:

QList<qreal> someNumbers { 0.0, 0.1 };
QQueue<qreal> someOtherNumbers { 0.0, 0.1 };

Compiler output:

error: no matching function for call to 'QQueue<double>::QQueue(<brace-enclosed initializer list>)'
     QQueue<qreal> someOtherNumbers { 0.0, 0.1 };
                                               ^
qqueue.h:49:7: note: candidate: QQueue<double>::QQueue()
 class QQueue : public QList<T>
       ^
qqueue.h:49:7: note:   candidate expects 0 arguments, 2 provided
qqueue.h:49:7: note: candidate: QQueue<double>::QQueue(const QQueue<double>&)
qqueue.h:49:7: note:   candidate expects 1 argument, 2 provided
qqueue.h:49:7: note: candidate: QQueue<double>::QQueue(QQueue<double>&&)
qqueue.h:49:7: note:   candidate expects 1 argument, 2 provided

Is there some way to initialize a QQueue<T> using an initializer list?

Body:
Since QQueue inherit from QList, I found a trick to do that.

QQueue<double> *queue;
QList<double> list = {{0.0, 1.1}};
queue = reinterpret_cast<QQueue<double> *>(&list);
qDebug() << queue->isEmpty();
while (!queue->isEmpty()) {
    qDebug() << queue->dequeue();
}

however, in this example, list it temporary so if you want to use this outside to the function you will have to use new