问:
Mapping XML attributes/elements with Table Column Names for File Import
I have the following xml file

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<ProdExtract>
 <ExtractHeader>
  <Schema>
   <id>Accord ePOS Product Extract</id>
   <Version>1.00</Version>
  </Schema>
 </ExtractHeader>
 <Product>
  <Mode>Modify</Mode>
  <ProductID>
    <LongDescription>COLMANS MINT SAUCE      #</LongDescription>
  </ProductID>
  <BasicFields>
    <Units>6</Units>
    <VAT VatCode="A" VatRate="0" />
  </BasicFields>
  <Price>
    <CurrentWSP>9.55</CurrentWSP>
    <CurrentRSP>2.01</CurrentRSP>
  </Price>
  <Barcode>
    <Eancode>5000147032921</Eancode>
  </Barcode>
 </Product>
</ProdExtract>
</code>```

This is my mapping for the table columns

```<code>foreach (XmlNode node in xDoc.SelectNodes("ProdExtract/Product"))
{
    insert = insert ?? new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product")
        .MapUUID("q_guid", x => Guid.NewGuid())
        .MapText("q_description", x => node.SelectSingleNode("ProductID/LongDescription").InnerText)
        .MapText("q_barcode", x => node.SelectSingleNode("Barcode/Eancode").InnerText)
        .MapNumeric("q_casesize", x => Convert.ToDecimal(node.SelectSingleNode("BasicFields/Units").InnerText))
        .MapNumeric("q_sellprice", x => Convert.ToDecimal(node.SelectSingleNode("Price/CurrentRSP").InnerText))
        .MapNumeric("q_casecost", x => Convert.ToDecimal(node.SelectSingleNode("Price/CurrentWSP").InnerText))
                        ;

    entities.Add(p);
}
</code>```

I can get all the values I need from the XML file and match them with my table columns no problemo, with the above method. But now how do I deal with with this section

```<code><BasicFields>
  <Units>6</Units>
  <VAT VatCode="A" VatRate="0" />
</BasicFields>
</code>```

If I want the value of VatRate i.e 0. This line

```<code>node.SelectSingleNode("BasicFields/Vat/VatRate").OuterXml;
</code>```

brought me nowhere, and I have had no luck on the interwebs.

答:
Eventually figured it out (This is in c# code by the way, I havent checked if its any different in other languages)

```<code><BasicFields>
 <Units>6</Units>
 <VAT VatCode="A" VatRate="0" />
</BasicFields>
</code>```

To get value "A"

```<code>node.SelectSingleNode("BasicFields/VAT").Attributes["VatCode"].Value;
</code>```

To get value "0"

```<code>node.SelectSingleNode("BasicFields/VAT").Attributes["VatRate"].Value;
</code>```

Body:
I have the following xml file

<?xml version="1.0" encoding="ISO-8859-1"?>
<ProdExtract>
 <ExtractHeader>
  <Schema>
   <id>Accord ePOS Product Extract</id>
   <Version>1.00</Version>
  </Schema>
 </ExtractHeader>
 <Product>
  <Mode>Modify</Mode>
  <ProductID>
    <LongDescription>COLMANS MINT SAUCE      #</LongDescription>
  </ProductID>
  <BasicFields>
    <Units>6</Units>
    <VAT VatCode="A" VatRate="0" />
  </BasicFields>
  <Price>
    <CurrentWSP>9.55</CurrentWSP>
    <CurrentRSP>2.01</CurrentRSP>
  </Price>
  <Barcode>
    <Eancode>5000147032921</Eancode>
  </Barcode>
 </Product>
</ProdExtract>

This is my mapping for the table columns

foreach (XmlNode node in xDoc.SelectNodes("ProdExtract/Product"))
{
    insert = insert ?? new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product")
        .MapUUID("q_guid", x => Guid.NewGuid())
        .MapText("q_description", x => node.SelectSingleNode("ProductID/LongDescription").InnerText)
        .MapText("q_barcode", x => node.SelectSingleNode("Barcode/Eancode").InnerText)
        .MapNumeric("q_casesize", x => Convert.ToDecimal(node.SelectSingleNode("BasicFields/Units").InnerText))
        .MapNumeric("q_sellprice", x => Convert.ToDecimal(node.SelectSingleNode("Price/CurrentRSP").InnerText))
        .MapNumeric("q_casecost", x => Convert.ToDecimal(node.SelectSingleNode("Price/CurrentWSP").InnerText))
                        ;

    entities.Add(p);
}

I can get all the values I need from the XML file and match them with my table columns no problemo, with the above method. But now how do I deal with with this section

<BasicFields>
  <Units>6</Units>
  <VAT VatCode="A" VatRate="0" />
</BasicFields>

If I want the value of VatRate i.e 0. This line

node.SelectSingleNode("BasicFields/Vat/VatRate").OuterXml;

brought me nowhere, and I have had no luck on the interwebs.

Body:
Eventually figured it out (This is in c# code by the way, I havent checked if its any different in other languages)

<BasicFields>
 <Units>6</Units>
 <VAT VatCode="A" VatRate="0" />
</BasicFields>

To get value "A"

node.SelectSingleNode("BasicFields/VAT").Attributes["VatCode"].Value;

To get value "0"

node.SelectSingleNode("BasicFields/VAT").Attributes["VatRate"].Value;


来源: stackexchange

问:
Load OpenGL function pointers using glad withing a QOpenGLWidget
So I am reading up on some OpenGL and I want to use the QOpenGLWidget for drawing to maybe create some other helpful UI elements later. I am using glad for resolving the function pointers to OpenGL but I have no idea how to use Qt's getProcAddress function!

Inside my QOpenGLWidget subclass' initializeGL() function I have tried:

```<code>if(gladLoadGLloader((GLADloadproc) currentContext()->getProcAddress) {}
</code>```

but that did not work out since Qt's function is overloaded. When I use

```<code>if(gladLoadGL()) {}
</code>```

it doesn't work either. My includes are:

```<code>#include <glad\glad.h>
#include "OpenGLViewport.h"
#include <QDebug>
#include <QOpenGLContext>
</code>```

I have searched Mr. Google and I've had a diligent look through the Qt documentation and found nothing. I want to use GLAD just so my rendering code is not bound to Qt too tightly, in case I want to switch later.

EDIT: I am aiming to use the noninstanced OpenGL functions with Qt (though the documentation recommends otherwise if I recall correctly). Because then I'd be able to seemlessly switch to GLFW for providing a window etc.

答:
Moved solution from question to answer:

ANSWER: So it turns out I just had some things mixed up, this is how I got it to work, in case anyone has the same problem:

add glad.c in your project

add the necessary headers to your include directory

the .cpp file of your QOpenGLWidget subclass should have following components:

```<code>// Subclass.cpp
#include <glad/glad.h>
// important, subclass header file after glad!!
// otherwise glad won't "hook"
#include "Subclass.h"

void Subclass::initializeGL()
{
    if(gladLoadGL()) initialized = true; // initialized is a class member here
    else; // handle errors
}

void Subclass::paintGL()
{
    if(initialized); // render here
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I am reading up on some OpenGL and I want to use the QOpenGLWidget for drawing to maybe create some other helpful UI elements later. I am using glad for resolving the function pointers to OpenGL but I have no idea how to use Qt's getProcAddress function!

Inside my QOpenGLWidget subclass' initializeGL() function I have tried:

if(gladLoadGLloader((GLADloadproc) currentContext()->getProcAddress) {}

but that did not work out since Qt's function is overloaded. When I use

if(gladLoadGL()) {}

it doesn't work either. My includes are:

#include <glad\glad.h>
#include "OpenGLViewport.h"
#include <QDebug>
#include <QOpenGLContext>

I have searched Mr. Google and I've had a diligent look through the Qt documentation and found nothing. I want to use GLAD just so my rendering code is not bound to Qt too tightly, in case I want to switch later.

EDIT: I am aiming to use the noninstanced OpenGL functions with Qt (though the documentation recommends otherwise if I recall correctly). Because then I'd be able to seemlessly switch to GLFW for providing a window etc.

Body:
Moved solution from question to answer:

ANSWER: So it turns out I just had some things mixed up, this is how I got it to work, in case anyone has the same problem:

add glad.c in your project

add the necessary headers to your include directory

the .cpp file of your QOpenGLWidget subclass should have following components:

// Subclass.cpp
#include <glad/glad.h>
// important, subclass header file after glad!!
// otherwise glad won't "hook"
#include "Subclass.h"

void Subclass::initializeGL()
{
    if(gladLoadGL()) initialized = true; // initialized is a class member here
    else; // handle errors
}

void Subclass::paintGL()
{
    if(initialized); // render here
}


问:
Webbased MySQL interface better that phpMyAdmin
Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes.

I'd like to have deep export functionality like phpMyAdmin but more design features

答:
I know about SqlBuddy. It has a simpler interface that phpMyAdmin - but pma is much more powerful.

There is also the VFront application. I have not tried it yet - so I cannot comment on it.

OwnerDisplayName: Siamak

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Binny V A


问:
asking the container to notify your application whenever a session is about to timeout in Java
Which method(s) can be used to ask the container to notify your application whenever a session is about to timeout?(choose all that apply)

A. HttpSessionListener.sessionDestroyed              -- correct

B. HttpSessionBindingListener.valueBound

C. HttpSessionBindingListener.valueUnbound       -- correct this is kind of round-about but if you have an attribute class this is a way to be informed of a timeout

D. HttpSessionBindingEvent.sessionDestroyed      -- no such method

E. HttpSessionAttributeListener.attributeRemoved  -- removing an attribute isn’t tightly associated with a session timeout

F. HttpSessionActivationListener.sessionWillPassivate  -- session passivation is different than timeout

I agree with option A.

1) But C is doubtful

How can value unbound be tightly coupled with session timeout.It is just the callback method when an attribute gets removed.

2) and if C is correct, E should also be correct.

HttpSessionAttributeListener is just a class that wants to know when any type of attribute has been added, removed, or replaced in a session. It is implemented by any class.

HttpSessionBindingListener exists so that the attribute itself can find out when it has been added to or removed from a session and the attribute class must implement this interface to achieve it.

Any ideas…

答:
My solution to this problem is to use A. Remember that HttpSessionListener.sessionDestroyed() is called before the session is invalidated so all its attributes are intact.

Our application uses a session attribute with key "LOGOUT" to signify an explicit logout. So your code may look something like this:

```<code>public void sessionDestroyed(HttpSessionEvent se) {
    Object logout = se.getSession().getAttribute("LOGOUT");
    String username = (String)se.getSession().getAttribute("USERNAME");
    auditLog.info("User '" + username + "' " +
                 (logout == null ? "timed" : "logged") +
                 " out.");
}
</code>```

As far as I can tell there is no standard way to tell from the HttpSession why it is about to be invalidated and, amazingly, there is no information in the HttpSessionEvent object that describes what the event was (this is true up to Java EE 6).

Body:
My solution to this problem is to use A. Remember that HttpSessionListener.sessionDestroyed() is called before the session is invalidated so all its attributes are intact.

Our application uses a session attribute with key "LOGOUT" to signify an explicit logout. So your code may look something like this:

public void sessionDestroyed(HttpSessionEvent se) {
    Object logout = se.getSession().getAttribute("LOGOUT");
    String username = (String)se.getSession().getAttribute("USERNAME");
    auditLog.info("User '" + username + "' " +
                 (logout == null ? "timed" : "logged") +
                 " out.");
}

As far as I can tell there is no standard way to tell from the HttpSession why it is about to be invalidated and, amazingly, there is no information in the HttpSessionEvent object that describes what the event was (this is true up to Java EE 6).


问:
Jquery not removing row
I have this jQuery where it append a row with link to remove the row. I have this code but it doesn't remove the row.

everything is working except for the function remove()

There is no error too.

```<code>var currentTotal = 0;

function remove(id) {
  $(this).closest('tr').remove();

}

$(document).ready(function() {

      var arr = [];

      $("#btnAdd").click(function() {

        var medname = $("#MedicineID option:selected").text();
        var id = $("#MedicineID option:selected").val();
        var qty = $("#myID").val();

        $.ajax({

          url: '/Purchases/GetValue',
          type: 'GET',
          datatype: 'json',
          data: {
            'id': id
          },
          success: function(val) {

            if (qty == 0) {
              alert("Please define the quantity");
            } else {
              var item = $('#MedicineID').val();

              if ($.inArray(item, arr) != -1) {
                alert("Specified medicine is already been added")
              } else {
                arr.push(item);
                if (currentTotal == 0) {
                  currentTotal = val * qty;
                  $("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + val + '  </td>  <td><a onclick="remove(' + id + ')" class="remove" href="#">Remove</a></td></tr>');
                  $('#total').text(currentTotal);
                } else {
                  var price = val * qty;
                  currenTotal = currentTotal += price;
                  $("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + price + '  </td>  <td><a onclick="remove(' + id + ')" class="remove" href="#">Remove</a></td></tr>');
                  $('#total').text(currentTotal);
                }
              }
            }
          }
        })
      });
</code>```

Here is the tables in my view

```<code> <table id="tblList" class="table">
        <tr>
            <th>
                Item
            </th>
            <th>
                Qty
            </th>
            <th>
                Price
            </th>
            <th>
            </th>
        </tr>
    </table>
    <br />
    <table class="table">
        <tr>
            <th>Total</th>
            <th></th>
            <th><p id="total">0</p></th>
            <th></th>
        </tr>
    </table>
</code>```

答:
Modify the remove function to capture the event

```<code>   function remove(id,event) {
      $(event.target).closest('tr').remove();
    }
</code>```

When you call use the below code

```<code>$("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + price + '  </td>  <td><a onclick="remove(' + id + ',event)" class="remove" href="#">Remove</a></td></tr>');
</code>```

Title: Jquery not removing row

Body:
I have this jQuery where it append a row with link to remove the row. I have this code but it doesn't remove the row.

everything is working except for the function remove()

There is no error too.

var currentTotal = 0;

function remove(id) {
  $(this).closest('tr').remove();

}

$(document).ready(function() {

      var arr = [];

      $("#btnAdd").click(function() {

        var medname = $("#MedicineID option:selected").text();
        var id = $("#MedicineID option:selected").val();
        var qty = $("#myID").val();

        $.ajax({

          url: '/Purchases/GetValue',
          type: 'GET',
          datatype: 'json',
          data: {
            'id': id
          },
          success: function(val) {

            if (qty == 0) {
              alert("Please define the quantity");
            } else {
              var item = $('#MedicineID').val();

              if ($.inArray(item, arr) != -1) {
                alert("Specified medicine is already been added")
              } else {
                arr.push(item);
                if (currentTotal == 0) {
                  currentTotal = val * qty;
                  $("#tblList").append('
 ' + medname + '	  ' + qty + '	 ' + val + '  	  Remove
');
                  $('#total').text(currentTotal);
                } else {
                  var price = val * qty;
                  currenTotal = currentTotal += price;
                  $("#tblList").append('
 ' + medname + '	  ' + qty + '	 ' + price + '  	  Remove
');
                  $('#total').text(currentTotal);
                }
              }
            }
          }
        })
      });

Here is the tables in my view

                Item

                Qty

                Price

            Total

0

Body:
Modify the remove function to capture the event

   function remove(id,event) {
      $(event.target).closest('tr').remove();
    }

When you call use the below code

$("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + price + '  </td>  <td><a onclick="remove(' + id + ',event)" class="remove" href="#">Remove</a></td></tr>');


问:
How to create a query dynamically for an array of elements?
I have a basic query as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
</code>```

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

```<code>$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
</code>```

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
</code>```

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

答:
```<code> $result = array(0=>'SC1',1=>'SC2');  //this is your array
 $branch = implode("','", $result );
 $query .= "
   SELECT * FROM files WHERE subject_code in ('".$branch."') "; //this is query
</code>```

Body:
I have a basic query as follows

$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?


问:
C# Automapper 6.1.1 - Collection/List destination properties loses values Entity Framework 6
I have a problem when mapping collections with Automapper 6 and I can't find a solution. In the updatedArticle object below I have the old Created and Updated values left after mapping since they do not exist on the view model. However the values for Created and Updated in Descriptions are lost. The values that do come in via the view model are all updated correctly. What am I doing wrong? Automapper also loses Entity Framework 6 mapping for Article since those values are lost as well.

Controller method:

```<code>public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
    Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
    Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
    return Ok();
}
</code>```

Mapping:

```<code>Mapper.Initialize(cfg =>
{
    cfg.CreateMap<ArticleViewModel, Article>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore());

    cfg.CreateMap<DescriptionViewModel, Description>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore())
        .ForMember(x => x.ArticleId, opt => opt.Ignore())
        .ForMember(x => x.Article, opt => opt.Ignore());
}
Mapper.AssertConfigurationIsValid();
</code>```

Viewmodels:

```<code>public class ArticleViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<DescriptionViewModel> Descriptions { get; set; }
}

public class DescriptionViewModel
{
    public int Id { get; set; }

    public string Heading { get; set; }
}
</code>```

Models:

```<code>public class Article : IEntity<int>
{
    public Article()
    {
        Descriptions = new List<Description>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Name { get; set; }

    public virtual ICollection<Description> Descriptions { get; set; }
}

public class Description: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}
</code>```

答:
Finally solved it after two days frustration. Installed AutoMapper.Collection from https://github.com/AutoMapper/AutoMapper.Collection

```<code>PM> Install-Package AutoMapper.Collection
PM> Install-Package AutoMapper.Collection.EntityFramework
</code>```

All I had to change was cfg.AddCollectionMappers(); and EqualityComparison. Example:

```<code>Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();

    cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);

    cfg.CreateMap<DescriptionViewModel, Description>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);
}
Mapper.AssertConfigurationIsValid();
</code>```

Body:
I have a problem when mapping collections with Automapper 6 and I can't find a solution. In the updatedArticle object below I have the old Created and Updated values left after mapping since they do not exist on the view model. However the values for Created and Updated in Descriptions are lost. The values that do come in via the view model are all updated correctly. What am I doing wrong? Automapper also loses Entity Framework 6 mapping for Article since those values are lost as well.

Controller method:

public async Task<IHttpActionResult> UpdateArticle(ArticleViewModel articleVm)
{
    Article articleOriginal = await iArticleRepository.GetAsync(articleVm.Id);
    Article updatedArticle = Mapper.Map<ArticleViewModel, Article>(articleVm, articleOriginal);
    return Ok();
}

Mapping:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<ArticleViewModel, Article>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore());

    cfg.CreateMap<DescriptionViewModel, Description>()
        .ForMember(x => x.Created, opt => opt.Ignore())
        .ForMember(x => x.Updated, opt => opt.Ignore())
        .ForMember(x => x.ArticleId, opt => opt.Ignore())
        .ForMember(x => x.Article, opt => opt.Ignore());
}
Mapper.AssertConfigurationIsValid();

Viewmodels:

public class ArticleViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public List<DescriptionViewModel> Descriptions { get; set; }
}

public class DescriptionViewModel
{
    public int Id { get; set; }

    public string Heading { get; set; }
}

Models:

public class Article : IEntity<int>
{
    public Article()
    {
        Descriptions = new List<Description>();
    }

    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Name { get; set; }

    public virtual ICollection<Description> Descriptions { get; set; }
}

public class Description: IEntity<int>
{
    [Key]
    public int Id { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }

    [MaxLength(256)]
    public string Heading { get; set; }

    public int ArticleId { get; set; }

    public virtual Article Article { get; set; }
}

Body:
Finally solved it after two days frustration. Installed AutoMapper.Collection from https://github.com/AutoMapper/AutoMapper.Collection

PM> Install-Package AutoMapper.Collection
PM> Install-Package AutoMapper.Collection.EntityFramework

All I had to change was cfg.AddCollectionMappers(); and EqualityComparison. Example:

Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();

    cfg.CreateMap<ArticleViewModel, Article>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);

    cfg.CreateMap<DescriptionViewModel, Description>(MemberList.Source)
        .EqualityComparison((src, dst) => src.Id == dst.Id);
}
Mapper.AssertConfigurationIsValid();


问:
how to use $http.get to fetch php data from the same page
hope you fine and well ,

i want to ask if it possible to fetch data using $http.get from the same page ,
to go deep in details :

i have a php file called (MY_FILE.php) that contains : PHP,HTML and SCRIPT codes ,
in the PHP section i executed sql select statment, and im trying to fetch the selected data in the script to use it in the html part , is this possible ?!

php part :

```<code><?php
$connect = mysqli_connect("localhost", "root", "", "database");
$result = mysqli_query($connect, "select * from table");
$data = array();
while ($row = mysqli_fetch_array($result)) {
    $data[] = $row;
}
print json_encode($data);

?>
</code>```

script part :

```<code>fetch.controller('dbCtrl', ['$scope', '$http', function ($scope, $http) {
        $http.get("MY_FILE.php")
            .success(function(data){
                $scope.data = data;
            })
            .error(function() {
                $scope.data = "error in fetching data";
            });
    }]);
</code>```

when i use any of the selected data in the html section nothing appear and stay blank.

any idea ?!

答:
The code is right, but the issue with using $http.get for the same page is when you use print json_encode($data); for returning response to the $http call, rather then returning call to $http, it prints the data on the page. So it returns nothng. So its better to use another page and using another page will be more user friendly as well because the page won't refresh for fetching the results. Secondly, because of the asynchronous nature of $http, the program will keep on executing and it won't be waiting for the php code to run and showing result. As soon as the php code is completely executed it will show the result.

And if you want everything to happen on same page you can simply use

```<code><?php
    if(isset($_POST['varname']))
    {}
    ?> and
    <html>
    <form action="" method="POST" >

    </form></html>
</code>```

Body:
hope you fine and well ,

i want to ask if it possible to fetch data using $http.get from the same page ,
to go deep in details :

i have a php file called (MY_FILE.php) that contains : PHP,HTML and SCRIPT codes ,
in the PHP section i executed sql select statment, and im trying to fetch the selected data in the script to use it in the html part , is this possible ?!

php part :

<?php
$connect = mysqli_connect("localhost", "root", "", "database");
$result = mysqli_query($connect, "select * from table");
$data = array();
while ($row = mysqli_fetch_array($result)) {
    $data[] = $row;
}
print json_encode($data);

?>

script part :

fetch.controller('dbCtrl', ['$scope', '$http', function ($scope, $http) {
        $http.get("MY_FILE.php")
            .success(function(data){
                $scope.data = data;
            })
            .error(function() {
                $scope.data = "error in fetching data";
            });
    }]);

when i use any of the selected data in the html section nothing appear and stay blank.

any idea ?!

Body:
The code is right, but the issue with using $http.get for the same page is when you use print json_encode($data); for returning response to the $http call, rather then returning call to $http, it prints the data on the page. So it returns nothng. So its better to use another page and using another page will be more user friendly as well because the page won't refresh for fetching the results. Secondly, because of the asynchronous nature of $http, the program will keep on executing and it won't be waiting for the php code to run and showing result. As soon as the php code is completely executed it will show the result.

And if you want everything to happen on same page you can simply use

<?php
    if(isset($_POST['varname']))
    {}
    ?> and
    <html>
    <form action="" method="POST" >

    </form></html>


问:
UIButton animation view
I am new developer in iPhone.

I want to create uibutton.

When I click the button, then the button will be flash like as below.

How to create the flash, when I click my button?

答:
What you do is set the highlighted image. For example:

```<code>[someButton setImage:[UIImage imageNamed:@"MyHighlight.png"]
            forState:UIControlStateHighlighted];
</code>```

Then when a user taps it, your MyHighlight.png will show.

Title: UIButton animation view

Body:
What you do is set the highlighted image. For example:

[someButton setImage:[UIImage imageNamed:@"MyHighlight.png"]
            forState:UIControlStateHighlighted];

Then when a user taps it, your MyHighlight.png will show.


问:
How to replace words with numbers in R studio in dataset
I've seen a question similar to my own on here: "Replace specific column words into number or blank" but none of the solutions seemed to help my case.

What I'm trying to do is convert:

```<code>Question    Response
1           Sometimes
2           Almost Always
3           Sometimes
4           Almost Never
5           Often
</code>```

into:

```<code>Question    Response
    1           2
    2           4
    3           2
    4           1
    5           3
</code>```

Where Almost never = 1, sometimes = 2, often = 3, almost always = 4.

I imported the data via Excel, it is in a dataframe called STAI22 (I think).

I tried:

```<code>STAI22[STAI22$Response == "Almost never",]$Response = 1
STAI22[STAI22$Response == "sometimes",]$Response = 2
STAI22[STAI22$Response == "often",]$Response = 3
STAI22[STAI22$Response == "Almost always",]$Response = 4
</code>```

but I got the error message:

```<code> STAI22[STAI22$Response == "Almost Always",]$Response = "4"
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "4") :
  invalid factor level, NA generated
> STAI22[STAI22$Response == "Often",]$Response = "3"
Error in `[<-.data.frame`(`*tmp*`, STAI22$Response == "Often", , value = list( :
  missing values are not allowed in subscripted assignments of data frames
> STAI22[STAI22$Response == "Sometimes",]$Response = "2"
Error in `[<-.data.frame`(`*tmp*`, STAI22$Response == "Sometimes", , value = list( :
  missing values are not allowed in subscripted assignments of data frames
> STAI22[STAI22$Response == "Almost Never",]$Response = "1"
Error in `[<-.data.frame`(`*tmp*`, STAI22$Response == "Almost Never",  :
  missing values are not allowed in subscripted assignments of data frames
</code>```

and it did nothing to my data!

答:
YES! From working through a couple of various answers I finally managed to do it (for the sake of people who are as rubbish as me at R, I'm going to make a ridiculously simplified explanation of what I did):

I started with a data frame:

```<code>Question    Response
1           Somewhat
2           Very much so
3           Somewhat
4           Not at all
5           Moderately so
</code>```

I created a look up table:

```<code>lookup <- c("Not at all" = 1, "Somewhat" = 2, "Moderately so" = 3, "Very much so" = 4)
</code>```

Made a new column for my dataset:

```<code>Datasetname["Response2"] <- NA #Just fills the column with NA

Question    Response         Response2
1           Somewhat            NA
2           Very much so        NA
3           Somewhat            NA
4           Not at all          NA
5           Moderately so       NA
</code>```

Then added the new values to that new column:

```<code>Datasetname$Response2 <- Datasetname[STAI$Response]

Question    Response            Response2
1           Somewhat            2
2           Very much so        4
3           Somewhat            2
4           Not at all          1
5           Moderately so       3
</code>```

Hooray!

Thanks everyone for your suggestions - this way was the only one which worked for me for some reason (I was probably misunderstanding some of the suggestions)

Body:
I've seen a question similar to my own on here: "Replace specific column words into number or blank" but none of the solutions seemed to help my case.

What I'm trying to do is convert:

Question    Response
1           Sometimes
2           Almost Always
3           Sometimes
4           Almost Never
5           Often

into:

Question    Response
    1           2
    2           4
    3           2
    4           1
    5           3

Where Almost never = 1, sometimes = 2, often = 3, almost always = 4.

I imported the data via Excel, it is in a dataframe called STAI22 (I think).

I tried:

STAI22[STAI22$Response == "Almost never",]$Response = 1
STAI22[STAI22$Response == "sometimes",]$Response = 2
STAI22[STAI22$Response == "often",]$Response = 3
STAI22[STAI22$Response == "Almost always",]$Response = 4

but I got the error message:

 STAI22[STAI22$Response == "Almost Always",]$Response = "4"
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "4") :
  invalid factor level, NA generated
> STAI22[STAI22$Response == "Often",]$Response = "3"
Error in `[<-.data.frame`(`*tmp*`, STAI22$Response == "Often", , value = list( :
  missing values are not allowed in subscripted assignments of data frames
> STAI22[STAI22$Response == "Sometimes",]$Response = "2"
Error in `[<-.data.frame`(`*tmp*`, STAI22$Response == "Sometimes", , value = list( :
  missing values are not allowed in subscripted assignments of data frames
> STAI22[STAI22$Response == "Almost Never",]$Response = "1"
Error in `[<-.data.frame`(`*tmp*`, STAI22$Response == "Almost Never",  :
  missing values are not allowed in subscripted assignments of data frames

and it did nothing to my data!

Body:
YES! From working through a couple of various answers I finally managed to do it (for the sake of people who are as rubbish as me at R, I'm going to make a ridiculously simplified explanation of what I did):

I started with a data frame:

Question    Response
1           Somewhat
2           Very much so
3           Somewhat
4           Not at all
5           Moderately so

I created a look up table:

lookup <- c("Not at all" = 1, "Somewhat" = 2, "Moderately so" = 3, "Very much so" = 4)

Made a new column for my dataset:

Datasetname["Response2"] <- NA #Just fills the column with NA

Question    Response         Response2
1           Somewhat            NA
2           Very much so        NA
3           Somewhat            NA
4           Not at all          NA
5           Moderately so       NA

Then added the new values to that new column:

Datasetname$Response2 <- Datasetname[STAI$Response]

Question    Response            Response2
1           Somewhat            2
2           Very much so        4
3           Somewhat            2
4           Not at all          1
5           Moderately so       3

Hooray!

Thanks everyone for your suggestions - this way was the only one which worked for me for some reason (I was probably misunderstanding some of the suggestions)


问:
time difference between current timestamp and specific time in oracle?
i want to know how to get time difference in minutes between systimestamp and start_time as below.And the start_time datatype is date.
kindly help me.Give answers which is applicable for oracle.</p>

```<code>start_time                 systimestamp     runningtime(systimestmap-start_time)
7/6/2017 9:34:54 AM        17:06:08         time difference in minutes
</code>```

答:
If you can use sysdate instead, you can take the difference and do some arithmetic:

```<code>select trunc((sysdate - start_time) * 24 * 60)
</code>```

Body:
i want to know how to get time difference in minutes between systimestamp and start_time as below.And the start_time datatype is date.
kindly help me.Give answers which is applicable for oracle.

start_time                 systimestamp     runningtime(systimestmap-start_time)
7/6/2017 9:34:54 AM        17:06:08         time difference in minutes

Body:
If you can use sysdate instead, you can take the difference and do some arithmetic:

select trunc((sysdate - start_time) * 24 * 60)


问:
how to add the element into hashmap in java not getting add in HashMap
I am new to java i got error in HashMap
this is what i tried

```<code>Hashmap h=new HashMap();
h.put(1,"java");
h.put(2,"c");
</code>```

but got error

答:
use DataTypes Also Like
this is the older procedure to store the values in hashmap

```<code>HashMap<Integer,String> h=new HashMap<Integer,String>();
h.put(1,"java");
h.put(2,"c");
</code>```

It will Work

Body:
I am new to java i got error in HashMap
this is what i tried

Hashmap h=new HashMap();
h.put(1,"java");
h.put(2,"c");

but got error

Body:
use DataTypes Also Like
this is the older procedure to store the values in hashmap

HashMap<Integer,String> h=new HashMap<Integer,String>();
h.put(1,"java");
h.put(2,"c");

It will Work


问:
Issue with adding style to element with reactjs
I'm learning react and trying to add a class if a select element holds a value that I want to check against.

```<code>class App extends Component {
  test = 'volvo';
  render() {
    return (
      <select style={{marginTop: '30px', marginLeft: '20px'}}>
        <option value="volvo" className={test === 'volvo' ? "selected" : null}>Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    );
  }
}
</code>```

It's giving me an error where on the line here I have the ternary operator. Can someone tell me the proper way of doing this please?
Thanks!

答:
In the global execution context (outside of any function), this refers to the global object. Try below code. You have to use this keyword.

```<code>class App extends Component {
test = 'volvo';
render() {
return (
  <select style={{marginTop: '30px', marginLeft: '20px'}}>
    <option value="volvo" className={this.test === 'volvo' ? "selected" : null}>Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  );
 }
}
</code>```

Body:
I'm learning react and trying to add a class if a select element holds a value that I want to check against.

class App extends Component {
  test = 'volvo';
  render() {
    return (
      <select style={{marginTop: '30px', marginLeft: '20px'}}>
        <option value="volvo" className={test === 'volvo' ? "selected" : null}>Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    );
  }
}

It's giving me an error where on the line here I have the ternary operator. Can someone tell me the proper way of doing this please?
Thanks!

Body:
In the global execution context (outside of any function), this refers to the global object. Try below code. You have to use this keyword.

class App extends Component {
test = 'volvo';
render() {
return (
  <select style={{marginTop: '30px', marginLeft: '20px'}}>
    <option value="volvo" className={this.test === 'volvo' ? "selected" : null}>Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  );
 }
}


问:
Android TimePicker not displayed well on landscape mode
I'm currently building an app targeting API 23, with a minimum API 16.
I'm facing an issue where a TimePicker is displayed within an AlertDialog. The display looks fine on Portrait mode and on Landscape mode when launching the app on Nexus 5 API <=22. However, when launching the app on a Nexus 5 API 23, the landscape mode does not correctly display the TimePicker widget, it displays only its background colors.

On Nexus 5 API 23 (Portrait):
TimePicker on Portrait mode (API 23)

On Nexus 5 API 23 (Landscape):
TimePicker on Landscape mode (API 23)

答:
I have this issue.
This help for me:</p>

```<code>timePicker.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
</code>```

Body:
I have this issue.
This help for me:

timePicker.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));


问:
method does not exist on service error yet it does angular typescript
I am currently getting this error:

```<code>TS2339:Property 'getCityList()' does not exist on type type of 'ServerComService'
</code>```

I am injecting a service into another service. The dynamicFormDataService populates my select inputs in my html

the serverComService deals with all calls to my servers

all proper imports in the app module have been made, both services are in the providers array in the app module. Lets just be sure to state that.

The code for the dynamicFormDataService:

```<code>import {Injectable} from '@angular/core';

import 'rxjs/Rx';
import {ServerComService} from "./serverComService";

@Injectable()
export class cityGetService{

  constructor(private serverComService: ServerComService){}
  cityList= [];

  cityGet(){

    if(this.cityList.length > 0 ){
      return this.cityList;
    }
    this.cityList = ServerComService.getCityList();
    return this.cityList;
  }
}
</code>```

The code for the serverComService

```<code>import {Injectable} from '@angular/core';
import {Http} from "@angular/http";

import {cityListUrl} from 'app/backendUrls';

@Injectable()
export class ServerComService{
  constructor(private http: Http){}

  getCityList(){
    value;
    this.http.get(cityListUrl)
      .subscribe(
        (response)=> value = response,
        (error)=> console.log(error)
      );
    return value;
  }
}
</code>```

anything you see that I am doing wrong. Thank you my homies I baked cookies I'll mail you 2 =)

答:
If getCityList() method was a static method this would've worked but in this case you need to call it like

```<code>this.cityList = this.serverComService.getCityList();
</code>```

Body:
I am currently getting this error:

TS2339:Property 'getCityList()' does not exist on type type of 'ServerComService'

I am injecting a service into another service. The dynamicFormDataService populates my select inputs in my html

the serverComService deals with all calls to my servers

all proper imports in the app module have been made, both services are in the providers array in the app module. Lets just be sure to state that.

The code for the dynamicFormDataService:

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

import 'rxjs/Rx';
import {ServerComService} from "./serverComService";

@Injectable()
export class cityGetService{

  constructor(private serverComService: ServerComService){}
  cityList= [];

  cityGet(){

    if(this.cityList.length > 0 ){
      return this.cityList;
    }
    this.cityList = ServerComService.getCityList();
    return this.cityList;
  }
}

The code for the serverComService

import {Injectable} from '@angular/core';
import {Http} from "@angular/http";

import {cityListUrl} from 'app/backendUrls';

@Injectable()
export class ServerComService{
  constructor(private http: Http){}

  getCityList(){
    value;
    this.http.get(cityListUrl)
      .subscribe(
        (response)=> value = response,
        (error)=> console.log(error)
      );
    return value;
  }
}

anything you see that I am doing wrong. Thank you my homies I baked cookies I'll mail you 2 =)

Body:
If getCityList() method was a static method this would've worked but in this case you need to call it like

this.cityList = this.serverComService.getCityList();


问:
ListView Interference with AppBarLayout
My problem with ListView

ListView Interference with AppBarLayout

I want to be under the AppBarLayout

progressbar in center page

problem screenshot

How to App bar Title and back button to Right?

activity_category.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/activity_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.sokhanak.CategoryActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:visibility="visible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</FrameLayout>
</LinearLayout>
</code>```

CategoryActivity.java

```<code>package com.example;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CategoryActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ListView listView;
    private ArrayList<QuoteDataModel> list;
    private QuoteArrayAdapter adapter;

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

        Intent i = getIntent();
        final String categoryId = i.getStringExtra("categoryId");
        String categoryName = i.getStringExtra("categoryName");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(categoryName);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new QuoteArrayAdapter(this, list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        if (!MainActivity.NetworkUtil.isOnline(getApplicationContext())) {
            Toast.makeText(CategoryActivity.this, "اتصال به اینترنت برقرار نیست",
                    Toast.LENGTH_LONG).show();
        }

        new GetDataCategory().execute(categoryId);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    new GetDataCategory().execute(categoryId);
                }
            }
        });

        // screen turn on ever
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

/* */
}
</code>```

答: Change Your Relative Layout to Linear Layout with Vertical Orientation</p>

Title: ListView Interference with AppBarLayout

Body:
My problem with ListView

ListView Interference with AppBarLayout

I want to be under the AppBarLayout

progressbar in center page

problem screenshot

How to App bar Title and back button to Right?

activity_category.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/activity_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.sokhanak.CategoryActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:visibility="visible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</FrameLayout>
</LinearLayout>

CategoryActivity.java

package com.example;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CategoryActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ListView listView;
    private ArrayList<QuoteDataModel> list;
    private QuoteArrayAdapter adapter;

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

        Intent i = getIntent();
        final String categoryId = i.getStringExtra("categoryId");
        String categoryName = i.getStringExtra("categoryName");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(categoryName);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new QuoteArrayAdapter(this, list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        if (!MainActivity.NetworkUtil.isOnline(getApplicationContext())) {
            Toast.makeText(CategoryActivity.this, "اتصال به اینترنت برقرار نیست",
                    Toast.LENGTH_LONG).show();
        }

        new GetDataCategory().execute(categoryId);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    new GetDataCategory().execute(categoryId);
                }
            }
        });

        // screen turn on ever
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

/* */
}


问:
How to set a global nofile limit to avoid "many open files" error?
I have a websocket service. it's strage that have error:"too many open files", but i have set the system configure:

```<code>/etc/security/limits.conf
*               soft    nofile          65000
*               hard    nofile          65000

/etc/sysctl.conf
net.ipv4.ip_local_port_range = 1024 65000

ulimit -n
//output 6500
</code>```

So i think my system configure it's right.

My service is manage by supervisor, it's possible supervisor limits?

check process start by supervisor:

```<code>cat /proc/815/limits
Max open files            1024                 4096                 files
</code>```

check process manual start:

```<code>cat /proc/900/limits
Max open files            65000                 65000                 files
</code>```

The reason is used supervisor manage serivce. if i restart supervisor and restart child process, it's "max open files" ok(65000) but wrong(1024) when reboot system supervisor automatically start.

May be supervisor start level is too high and system configure does not work when supervisor start?

edit:

system: ubuntu 12.04 64bit

It's not supervisor problem, all process auto start after system reboot are not use system configure(max open files=1024), but restart it's ok.

update

Maybe the problem is:

https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/938669

http://bryanmarty.com/blog/2012/02/10/setting-nofile-limit-upstart/

Increase max open files for Ubuntu/Upstart (initctl)

Now the question is, how to set a global nofile limit because i don't want to set nofile limit in every upstart script which i need.

答:
Can you set the limit on Service on this way:

add: LimitNOFILE=65536
in: /etc/systemd/system/{NameofService}.service

ContentLicense: CC BY-SA 4.0

Body:
I have a websocket service. it's strage that have error:"too many open files", but i have set the system configure:

/etc/security/limits.conf
*               soft    nofile          65000
*               hard    nofile          65000

/etc/sysctl.conf
net.ipv4.ip_local_port_range = 1024 65000

ulimit -n
//output 6500

So i think my system configure it's right.

My service is manage by supervisor, it's possible supervisor limits?

check process start by supervisor:

cat /proc/815/limits
Max open files            1024                 4096                 files

check process manual start:

cat /proc/900/limits
Max open files            65000                 65000                 files

The reason is used supervisor manage serivce. if i restart supervisor and restart child process, it's "max open files" ok(65000) but wrong(1024) when reboot system supervisor automatically start.

May be supervisor start level is too high and system configure does not work when supervisor start?

edit:

system: ubuntu 12.04 64bit

It's not supervisor problem, all process auto start after system reboot are not use system configure(max open files=1024), but restart it's ok.

update

Maybe the problem is:

https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/938669

http://bryanmarty.com/blog/2012/02/10/setting-nofile-limit-upstart/

Increase max open files for Ubuntu/Upstart (initctl)

Now the question is, how to set a global nofile limit because i don't want to set nofile limit in every upstart script which i need.


问:
Can't resolve all parameters for PlatformService: ([object Object], ?, [object Object])
I have two services: PlatformService and AccountService:

```<code>import {Http} from '@angular/http';
import {AccountService} from "./account.service";
import {ToastService} from "./toast.service";
@Injectable()
export class PlatformService {
  constructor(
    private http: Http,
    private accountSvc: AccountService,
    private toastSvc: ToastService
  ) {}
  //...
}

import {Http} from "@angular/http";
import {ToastService} from "./toast.service";
@Injectable()
export class AccountService {
  constructor(
    private http: Http,
    private toastService: ToastService
  ){}
  //...
}
</code>```

And this is the providers in app.module.ts:

```<code>providers: [
  StatusBar,
  SplashScreen,
  ToastService,
  AccountService,
  PlatformService,
  SocketService,
  ModelService,
  {provide: ErrorHandler, useClass: IonicErrorHandler}
]
</code>```

I want to inject accountService into my platformService, but I got the following error:

Can't resolve all parameters for PlatformService: ([object Object], ?, [object Object]).

I don't think there is a circular dependency in my code, maybe it's because platformService and accountService both inject http and toastService?

After I commented private accountSvc: AccountService, in the constructor of PlatformService, this error disappeared.

答:
I finally found the error. I imported RoomPreparePage in AccountService,
and I also added AccountService in the constructor of RoomPreparePage, so this seems to be a circular dependency. (However, I didn't add RoomPreparePage in the constructor of AccountService, I just used it in one of the methods of AccountService.)

After I remove the usage of RoomPreparePage in AccountService, this problem was fixed.

Body:
I have two services: PlatformService and AccountService:

import {Http} from '@angular/http';
import {AccountService} from "./account.service";
import {ToastService} from "./toast.service";
@Injectable()
export class PlatformService {
  constructor(
    private http: Http,
    private accountSvc: AccountService,
    private toastSvc: ToastService
  ) {}
  //...
}

import {Http} from "@angular/http";
import {ToastService} from "./toast.service";
@Injectable()
export class AccountService {
  constructor(
    private http: Http,
    private toastService: ToastService
  ){}
  //...
}

And this is the providers in app.module.ts:

providers: [
  StatusBar,
  SplashScreen,
  ToastService,
  AccountService,
  PlatformService,
  SocketService,
  ModelService,
  {provide: ErrorHandler, useClass: IonicErrorHandler}
]

I want to inject accountService into my platformService, but I got the following error:

Can't resolve all parameters for PlatformService: ([object Object], ?, [object Object]).

I don't think there is a circular dependency in my code, maybe it's because platformService and accountService both inject http and toastService?

After I commented private accountSvc: AccountService, in the constructor of PlatformService, this error disappeared.


问:
jQuery paging plugin that works with odd~ish page structure
I've added a jQuery plugin to our websites that currently works as desired, however it breaks when there's two elements on the page that needs to be paged. I've asked the developer of the plugin about this, and he confirms it's been designed with only one element on the page.

So, I've went out to look for another pager plugin, but all of the ones I've found can't handle my specific use case.

My use case is as follows. I have a set of lists that act as columns. On page one, I'd like to see the first two list elements of both columns.

```<code><div>
  <ul class="column-1">
    <li>
    <li>
    <li>
    <li>
  </ul>
  <ul class="column-2">
    <li>
    <li>
    <li>
    <li>
  </ul>
</div>
</code>```

In the current pager, I've implemented this by calculating the amount of columns and dividing the regular start / end by them, so instead of showing records 1 - 4 it shows 1 - 2. Using the :nth-child selector, jquery then shows the first and second li element of either ul. (if you're looking for code: http://pastebin.com/F7BqQaxh)

This is only possible because the particular jquery plugin I've used uses a customizable callback function to execute when the user clicks on a page number. However, this does not work when there's more than one element on the page, as the callback function doesn't have awareness of which of the two pager elements is being clicked on - or I'm just missing something fundamental.

So. I guess I'm looking for a simple pager plugin that works with multiple elements on the same page (and should work with an .each() call, so I can apply the pager to all elements with a 'paged' class), /and/ that has an overridable method to implement my custom behavior.

I'm not nearly proficient (or patient) enough in Javascript to go and develop it on my own, even though it should be easy enough. I struggle for a whole day on a handful of lines of code, and JS in general just frustrates me to no end. But someone's gotta do it, :(.## Heading ##

答:
The pajinate plugin will do what you need it to. You can define the div that this should sit and call it without a problem:</p>

```<code><script type="text/javascript">
$(function(){
  $(".pajinate").pajinate({
    item_container_id:'.pajinate-content',
    nav_panel_id:'.navigation',
    items_per_page:3,
  });
});
</script>
<div>
  <div id="pajinate1" class="pajinate">
    <div class="navigation"></div>
    <ul class="column-1 pajinate-content">
      <li>a</li>
      <li>b</li>
      <li>c</li>
      <li>d</li>
      <li>e</li>
      <li>f</li>
      <li>g</li>
      <li>h</li>
      <li>i</li>
      <li>j</li>
      <li>k</li>
      <li>l</li>
    </ul>
  </div>
  <div id="pajinate2" class="pajinate">
    <div class="navigation"></div>
    <ul class="column-2 pajinate-content">
      <li>a</li>
      <li>b</li>
      <li>c</li>
      <li>d</li>
      <li>e</li>
      <li>f</li>
      <li>g</li>
      <li>h</li>
      <li>i</li>
      <li>j</li>
      <li>k</li>
      <li>l</li>
    </ul>
  </div>
</div>
</code>```

Body:
I've added a jQuery plugin to our websites that currently works as desired, however it breaks when there's two elements on the page that needs to be paged. I've asked the developer of the plugin about this, and he confirms it's been designed with only one element on the page.

So, I've went out to look for another pager plugin, but all of the ones I've found can't handle my specific use case.

My use case is as follows. I have a set of lists that act as columns. On page one, I'd like to see the first two list elements of both columns.

In the current pager, I've implemented this by calculating the amount of columns and dividing the regular start / end by them, so instead of showing records 1 - 4 it shows 1 - 2. Using the :nth-child selector, jquery then shows the first and second li element of either ul. (if you're looking for code: http://pastebin.com/F7BqQaxh)

This is only possible because the particular jquery plugin I've used uses a customizable callback function to execute when the user clicks on a page number. However, this does not work when there's more than one element on the page, as the callback function doesn't have awareness of which of the two pager elements is being clicked on - or I'm just missing something fundamental.

So. I guess I'm looking for a simple pager plugin that works with multiple elements on the same page (and should work with an .each() call, so I can apply the pager to all elements with a 'paged' class), /and/ that has an overridable method to implement my custom behavior.

I'm not nearly proficient (or patient) enough in Javascript to go and develop it on my own, even though it should be easy enough. I struggle for a whole day on a handful of lines of code, and JS in general just frustrates me to no end. But someone's gotta do it, :(.## Heading ##

Body:
The pajinate plugin will do what you need it to. You can define the div that this should sit and call it without a problem:

<script type="text/javascript">
$(function(){
  $(".pajinate").pajinate({
    item_container_id:'.pajinate-content',
    nav_panel_id:'.navigation',
    items_per_page:3,
  });
});
</script>
<div>
  <div id="pajinate1" class="pajinate">
    <div class="navigation"></div>
    <ul class="column-1 pajinate-content">
      <li>a</li>
      <li>b</li>
      <li>c</li>
      <li>d</li>
      <li>e</li>
      <li>f</li>
      <li>g</li>
      <li>h</li>
      <li>i</li>
      <li>j</li>
      <li>k</li>
      <li>l</li>
    </ul>
  </div>
  <div id="pajinate2" class="pajinate">
    <div class="navigation"></div>
    <ul class="column-2 pajinate-content">
      <li>a</li>
      <li>b</li>
      <li>c</li>
      <li>d</li>
      <li>e</li>
      <li>f</li>
      <li>g</li>
      <li>h</li>
      <li>i</li>
      <li>j</li>
      <li>k</li>
      <li>l</li>
    </ul>
  </div>
</div>


问:
Transcoding different profiles from single Video File
Everyday, I receive few 50 GB files from my partner. I need to trans-code them using a C++ program into 12 profiles.

If one profile takes an hour so it takes 12 hours to trans-code to all 12 profiles from one source file.

How can Amazon Web Services help here to save time and money?

答:
Option 1: Amazon Elastic Transcoder

From the documentation page:

Amazon Elastic Transcoder lets you convert media files that you have stored in Amazon S3 into media files in the formats required by consumer playback devices. For example, you can convert large, high-quality digital media files into formats that users can play back on mobile devices, tablets, web browsers, and connected televisions.

To use the Elastic Transcoder, upload the source video files to Amazon S3. Then, configure jobs to transcode the video. A job can transcode a video into multiple formats simultaneously. The output files will be stored back into Amazon S3.

Option 2: Go Parallel

Rather than running one computer for 12 hours, consider running multiple computers in parallel (eg 6 computers for 2 hours each). Amazon EC2 is charged per hour, so the total cost is the same.

You should also experiment with different Instance Types to determine the best price/performance for your particular transcoding job. This will help you determine whether you should run on larger, faster EC2 instances, or on a larger number of smaller instances.

You could use Amazon Batch to manage the work of distributing work amongst the EC2 instances. (However, using Amazon Elastic Transcoder would certainly be simpler!)


问:
Pandas: Transform pairs of columns to cells
I have a pandas data frame like this:

```<code>ts | thing_0 | qty_0 | thing_1 | qty_1 | thing_2 | qty_2
--------------------------------------------------------
1  | dog     |     5 | cat     |     3 | mouse   |     1
2  | house   |     6 | dog     |     4 | cat     |     2
...
</code>```

I want to transform this in a way that the things become columns and the qtys become the cell values. Like this:

```<code>ts | dog | cat | mouse | house
------------------------------
1  |   5 |   3 |     1 |     0
2  |   4 |   2 |     0 |     6
...
</code>```

Currently, I'm doing this transformation manually by iterating over the df.values array manually, but this is very slow. Is there a faster way to implement this with pandas means?

I have seen df.pivot, but couldn't find a way to describe the relationship between thing_0 and qty_0.

答:
You could use lreshape to coalesce the thing and qty columns:

```<code>In [10]: pd.lreshape(df, {'thing':['thing_0','thing_1','thing_2',], 'qty':['qty_0','qty_1','qty_2']})
Out[10]:
   ts  thing  qty
0   1    dog    5
1   2  house    6
2   1    cat    3
3   2    dog    4
4   1  mouse    1
5   2    cat    2
</code>```

Then pivot to create the desired DataFrame:

```<code>import pandas as pd

df = pd.DataFrame({'qty_0': [5, 6], 'qty_1': [3, 4], 'qty_2': [1, 2], 'thing_0': ['dog', 'house'], 'thing_1': ['cat', 'dog'], 'thing_2': ['mouse', 'cat'], 'ts': [1, 2]})

reshaped = pd.lreshape(df, {'thing':['thing_0','thing_1','thing_2',],
                            'qty':['qty_0','qty_1','qty_2']})

result = reshaped.pivot(index='ts', columns='thing', values='qty')
print(result)
</code>```

yields

```<code>thing  cat  dog  house  mouse
ts
1      3.0  5.0    0.0    1.0
2      2.0  4.0    6.0    0.0
</code>```

I think jezrael's solution is better since it takes advantage of the regularity of the column names you wish to coalesce. df.columns.str.split('_', expand=True) is more general and less repetitive than

```<code>{'thing':['thing_0','thing_1','thing_2',],
 'qty':['qty_0','qty_1','qty_2']}
</code>```

lreshape might be helpful in situations where the column names you wish to coalesce
are irregular.

Body:
I have a pandas data frame like this:

ts | thing_0 | qty_0 | thing_1 | qty_1 | thing_2 | qty_2
--------------------------------------------------------
1  | dog     |     5 | cat     |     3 | mouse   |     1
2  | house   |     6 | dog     |     4 | cat     |     2
...

I want to transform this in a way that the things become columns and the qtys become the cell values. Like this:

ts | dog | cat | mouse | house
------------------------------
1  |   5 |   3 |     1 |     0
2  |   4 |   2 |     0 |     6
...

Currently, I'm doing this transformation manually by iterating over the df.values array manually, but this is very slow. Is there a faster way to implement this with pandas means?

I have seen df.pivot, but couldn't find a way to describe the relationship between thing_0 and qty_0.

Body:
You could use lreshape to coalesce the thing and qty columns:

In [10]: pd.lreshape(df, {'thing':['thing_0','thing_1','thing_2',], 'qty':['qty_0','qty_1','qty_2']})
Out[10]:
   ts  thing  qty
0   1    dog    5
1   2  house    6
2   1    cat    3
3   2    dog    4
4   1  mouse    1
5   2    cat    2

Then pivot to create the desired DataFrame:

import pandas as pd

df = pd.DataFrame({'qty_0': [5, 6], 'qty_1': [3, 4], 'qty_2': [1, 2], 'thing_0': ['dog', 'house'], 'thing_1': ['cat', 'dog'], 'thing_2': ['mouse', 'cat'], 'ts': [1, 2]})

reshaped = pd.lreshape(df, {'thing':['thing_0','thing_1','thing_2',],
                            'qty':['qty_0','qty_1','qty_2']})

result = reshaped.pivot(index='ts', columns='thing', values='qty')
print(result)

yields

thing  cat  dog  house  mouse
ts
1      3.0  5.0    0.0    1.0
2      2.0  4.0    6.0    0.0

I think jezrael's solution is better since it takes advantage of the regularity of the column names you wish to coalesce. df.columns.str.split('_', expand=True) is more general and less repetitive than

{'thing':['thing_0','thing_1','thing_2',],
 'qty':['qty_0','qty_1','qty_2']}

lreshape might be helpful in situations where the column names you wish to coalesce
are irregular.


问:
How to optimize C# mongodb query on large datadases?
I have a database table having 100 million records. Screen Shot is taken from Robomongo

Table Schema: There are 100 million records

When I run the following code. I get results, but It takes around 1 minute to get completed. I need to optimize the query to get results faster. What I have done till now is here. Please tell me the way forward to achieve the optimized result.

```<code>        var collection = _database.GetCollection<BsonDocument>("FloatTable1");

        var sw = Stopwatch.StartNew();
        var builder = Builders<BsonDocument>.Filter;
        int min = Convert.ToInt32(textBox13.Text);  //3
        int max = Convert.ToInt32(textBox14.Text);  //150
        var filt = builder.Gt("Value", min) & builder.Lt("Value", max);
        var list = collection.Find(filt);
        sw.Stop();
        TimeSpan time = sw.Elapsed;
        Console.WriteLine("Time to Fetch Record: " + time.ToString());

        var sw1 = Stopwatch.StartNew();
        var list1 = list.ToList();
        sw1.Stop();
        TimeSpan time1 = sw1.Elapsed;
        Console.WriteLine("Time to Convert var to List: " + time1.ToString());
        Console.WriteLine("Total Count in List: " + list1.Count.ToString());
</code>```

Out Put is:

Time to Fetch Record: 00:00:00.0059207

Time to Convert var to List: 00:01:00.7209163

Total Count in List: 1003154

I have few question related to the given code.

When line collection.Find(filt) executes, does it fetch filtered record from the database OR Just creating filter?

var list1 = list.ToList(); takes 1 minute to execute, is it only converting from var to list OR First fetching data than converting?

How to achieve this query and result in least possible time. Please Help.

答:
When line collection.Find(filt) executes, does it fetch filtered
  record from the database OR Just creating filter?

It is just creating the filter.

var list1 = list.ToList(); takes 1 minute to execute, is it only
  converting from var to list OR First fetching data than converting?

It is fetching the data and converting.

How to achieve this query and result in least possible time. Please Help.

The fetch / filtering on the database is eating your time. The easiest way to speed it up would be creating an index on the column you are filtering.

Everything else would need some more effort or database technologies, like creating a column which more roughly presents your date (e.g. grouped by day) and indexing this one, or creating something like table sections grouped by a given timespan (I'm not a DB-Admin and don't know the proper terms for this, but I remember somebody doing it on a database with billions of records ;) )

Body:
I have a database table having 100 million records. Screen Shot is taken from Robomongo

Table Schema: There are 100 million records

When I run the following code. I get results, but It takes around 1 minute to get completed. I need to optimize the query to get results faster. What I have done till now is here. Please tell me the way forward to achieve the optimized result.

        var collection = _database.GetCollection<BsonDocument>("FloatTable1");

        var sw = Stopwatch.StartNew();
        var builder = Builders<BsonDocument>.Filter;
        int min = Convert.ToInt32(textBox13.Text);  //3
        int max = Convert.ToInt32(textBox14.Text);  //150
        var filt = builder.Gt("Value", min) & builder.Lt("Value", max);
        var list = collection.Find(filt);
        sw.Stop();
        TimeSpan time = sw.Elapsed;
        Console.WriteLine("Time to Fetch Record: " + time.ToString());

        var sw1 = Stopwatch.StartNew();
        var list1 = list.ToList();
        sw1.Stop();
        TimeSpan time1 = sw1.Elapsed;
        Console.WriteLine("Time to Convert var to List: " + time1.ToString());
        Console.WriteLine("Total Count in List: " + list1.Count.ToString());

Out Put is:

Time to Fetch Record: 00:00:00.0059207

Time to Convert var to List: 00:01:00.7209163

Total Count in List: 1003154

I have few question related to the given code.

When line collection.Find(filt) executes, does it fetch filtered record from the database OR Just creating filter?

var list1 = list.ToList(); takes 1 minute to execute, is it only converting from var to list OR First fetching data than converting?

How to achieve this query and result in least possible time. Please Help.


问:
Equivalent of Index options (using index) in Oracle to SQL Server 2014
I need to move the data from Oracle database to MS SQL Server 2014.
But I got the problem with this "USING INDEX" statement which help me in oracle to add some constraint. I would like to know if someone could provide me and equivalence of "USING INDEX" in Sql Server.</p>

```<code>CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1   BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)   TABLESPACE "DATA"  ENABLE,
</code>```

答:
According to this reference

```<code>CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** ...   TABLESPACE "DATA"  ENABLE
</code>```

seems to suggest that this clause (part of CREATE/ALTER TABLE ... - Oracle syntax) will create an UNIQUE INDEX for a primary key constraint (MESSAGE_LOG_RECORD_PK).

(1) Default behaviour of SQL Server for disk based row store tables (main table type within SQL Server databases) is as follow:

(1.1) It will create an UNIQUE CLUSTERED INDEX when a PRIMARY KEY constraint is defined on a table without another CLUSTERED index.

(1.2) It will create an UNIQUE NONCLUSTERED INDEX when a PRIMARY KEY constraint is defined on a table if that table already have an CLUSTERED index.

(1.4) It will try to create an UNIQUE CLUSTERED/NONCLUSTERED index on current table depending of PRIMARY KEY constraint options: clustered / nonclustered thus:

```<code>CREATE TABLE Groups  (
        GroupId INT IDENTITY(1, 1) NOT NULL
             CONSTRAINT PK_Groups_GroupId PRIMARY KEY CLUSTERED ON [PRIMARY] (GroupId),
...
)
</code>```

Also, notice in this case the name of data SQL Server filegroup (PRIMARY in this case; ~ as Oracle table space I believe) used to store data of index associated with this primary key.

(2) My answer is following SQL statement that will add a PRIMARY KEY constraint defined on RECORD_NO column (which will create also an UNIQUE CLUSTERED - default - index) and also definied on DATA filegroup :

```<code>ALTER TABLE dbo.LOG_RECORD
ADD CONSTRAINT MESSAGE_LOG_RECORD_PK
PRIMARY KEY CLUSTERED ON [DATA] (RECORD_NO)
</code>```

Body:
I need to move the data from Oracle database to MS SQL Server 2014.
But I got the problem with this "USING INDEX" statement which help me in oracle to add some constraint. I would like to know if someone could provide me and equivalence of "USING INDEX" in Sql Server.

CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS    STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1   BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)   TABLESPACE "DATA"  ENABLE,

Body:
According to this reference

CONSTRAINT "MESSAGE_LOG_RECORD_PK" PRIMARY KEY ("RECORD_NO")
**USING INDEX** ...   TABLESPACE "DATA"  ENABLE

seems to suggest that this clause (part of CREATE/ALTER TABLE ... - Oracle syntax) will create an UNIQUE INDEX for a primary key constraint (MESSAGE_LOG_RECORD_PK).

(1) Default behaviour of SQL Server for disk based row store tables (main table type within SQL Server databases) is as follow:

(1.1) It will create an UNIQUE CLUSTERED INDEX when a PRIMARY KEY constraint is defined on a table without another CLUSTERED index.

(1.2) It will create an UNIQUE NONCLUSTERED INDEX when a PRIMARY KEY constraint is defined on a table if that table already have an CLUSTERED index.

(1.4) It will try to create an UNIQUE CLUSTERED/NONCLUSTERED index on current table depending of PRIMARY KEY constraint options: clustered / nonclustered thus:

CREATE TABLE Groups  (
        GroupId INT IDENTITY(1, 1) NOT NULL
             CONSTRAINT PK_Groups_GroupId PRIMARY KEY CLUSTERED ON [PRIMARY] (GroupId),
...
)

Also, notice in this case the name of data SQL Server filegroup (PRIMARY in this case; ~ as Oracle table space I believe) used to store data of index associated with this primary key.

(2) My answer is following SQL statement that will add a PRIMARY KEY constraint defined on RECORD_NO column (which will create also an UNIQUE CLUSTERED - default - index) and also definied on DATA filegroup :

ALTER TABLE dbo.LOG_RECORD
ADD CONSTRAINT MESSAGE_LOG_RECORD_PK
PRIMARY KEY CLUSTERED ON [DATA] (RECORD_NO)


问:
submitting PHP - HTML DATE to MySQL DATE
i would like to help with my code how to edit HTML input date into MySQL TIMESTEMP format cause my SQL code is invalid and data are not added to my database, Thanks for help

also i asking to check this code on bottom cause 2nd SQL deppends on 1st SQL, thanks

```<code>if (isset($_POST['pridaj_anime_submit'])) {
   $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                              VALUES ('$_POST[nazov]', '$_POST[rok]', '0', '$_POST[pocet]', '8', '10', '$_POST[preklad]', '$_POST[stav]')";
   mysqli_query($connect_to_db , $sql_vloz_anime);
   $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$_POST[nazov]'";
   $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($sql_ziskaj_a_id_pridaneho_anime);
   $a_id_ziskane = "";
while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
    $a_id_ziskane = $db_data['a_id'];
}

   $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                        VALUES ('$a_id_ziskane' , '$_POST[obrazok]', '$_POST[zaciatok]', '$_POST[koniec]', '$_POST[cas]', '$_POST[akihabara]')";
   mysqli_query($connect_to_db , $sql_vloz_anime_info);
}
</code>```

答:
```<code>$input_date=$_POST['date'];
$date=date("Y-m-d H:i:s",strtotime($input_date));
</code>```

This will convert input date into MySQL Timestamp compliant format.
Please DO NOT put POST values directly in your queries. Your website or web application will be hacked in no time through SQL Injections.

Body:
i would like to help with my code how to edit HTML input date into MySQL TIMESTEMP format cause my SQL code is invalid and data are not added to my database, Thanks for help

also i asking to check this code on bottom cause 2nd SQL deppends on 1st SQL, thanks

if (isset($_POST['pridaj_anime_submit'])) {
   $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                              VALUES ('$_POST[nazov]', '$_POST[rok]', '0', '$_POST[pocet]', '8', '10', '$_POST[preklad]', '$_POST[stav]')";
   mysqli_query($connect_to_db , $sql_vloz_anime);
   $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$_POST[nazov]'";
   $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($sql_ziskaj_a_id_pridaneho_anime);
   $a_id_ziskane = "";
while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
    $a_id_ziskane = $db_data['a_id'];
}

   $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                        VALUES ('$a_id_ziskane' , '$_POST[obrazok]', '$_POST[zaciatok]', '$_POST[koniec]', '$_POST[cas]', '$_POST[akihabara]')";
   mysqli_query($connect_to_db , $sql_vloz_anime_info);
}

Body:
$input_date=$_POST['date'];
$date=date("Y-m-d H:i:s",strtotime($input_date));

This will convert input date into MySQL Timestamp compliant format.
Please DO NOT put POST values directly in your queries. Your website or web application will be hacked in no time through SQL Injections.


问:
CSS Blend Background with Parent Background
I have a div identified by #front.

It is inside a div identified by #back.

#back is a canvas that constantly changes.

I'd like #front, a square, plain square to take the colour of the parent and invert it.

E.g. if the background is white, the square should be black.
If the background is black, the square should be white. If the background is partially white and partially black, the square should be partially black and partially white.

I have tried background-blend-mode: overlay and mix-blend-mode: screen on the #front element but these had no effect.

Is this possible in any way?

HTML:

CSS:

```<code>#back {
   position:absolute;
   top:0;
   bottom:0;
   left:0;
   right:0;
   background-image:url('http://example.com/image.png');
   background-size:cover;
}

#front {
   width:100px;
   height:100px;
   display:block;
}
</code>```

答:
First of all JavaScript is used. and jQuery is also included because i cant find a way to get background of div in real-time using vanila js. </p>

```<code><!DOCTYPE html>
<html>
    <head>
        <title>
            invert color
        </title>
        <style type="text/css">
            #back {
          width: 100px;
          height: 100px;
          background-color: #000;
        }

        #front {
          width: 50px;
          height: 50px;
          background-color: #000;
          filter: invert(100%);
          -webkit-filter: invert(100%);
        }
        </style>
    </head>
    <body>
        <div id="back">
            <div id="front">
            </div>
        </div>
    </body>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">
        //get elements
        var front = $('#front');
        var back = $("#back");

        // make sure #front & #back's background color is same all the time
        setInterval(function(){
            var backColor = back.css('background-color');
            front.css('background-color', backColor);
        }, 500);

        // change background color of #back for testing
        setTimeout(function() {
            back.css('background-color', '#fff');
        }, 2000);
    </script>
</html>
</code>```

Body:
I have a div identified by #front.

It is inside a div identified by #back.

#back is a canvas that constantly changes.

I'd like #front, a square, plain square to take the colour of the parent and invert it.

E.g. if the background is white, the square should be black.
If the background is black, the square should be white. If the background is partially white and partially black, the square should be partially black and partially white.

I have tried background-blend-mode: overlay and mix-blend-mode: screen on the #front element but these had no effect.

Is this possible in any way?

HTML:

CSS:

#back {
   position:absolute;
   top:0;
   bottom:0;
   left:0;
   right:0;
   background-image:url('http://example.com/image.png');
   background-size:cover;
}

#front {
   width:100px;
   height:100px;
   display:block;
}

Body:
First of all JavaScript is used. and jQuery is also included because i cant find a way to get background of div in real-time using vanila js.

<!DOCTYPE html>
<html>
    <head>
        <title>
            invert color
        </title>
        <style type="text/css">
            #back {
          width: 100px;
          height: 100px;
          background-color: #000;
        }

        #front {
          width: 50px;
          height: 50px;
          background-color: #000;
          filter: invert(100%);
          -webkit-filter: invert(100%);
        }
        </style>
    </head>
    <body>
        <div id="back">
            <div id="front">
            </div>
        </div>
    </body>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">
        //get elements
        var front = $('#front');
        var back = $("#back");

        // make sure #front & #back's background color is same all the time
        setInterval(function(){
            var backColor = back.css('background-color');
            front.css('background-color', backColor);
        }, 500);

        // change background color of #back for testing
        setTimeout(function() {
            back.css('background-color', '#fff');
        }, 2000);
    </script>
</html>


问:
If condition inside of map() React
I have a map()function that needs to display views based on a condition. I've looked at the React documentation on how to write conditions and this is how you can write a condition:

```<code>{if (loggedIn) ? (
  // Hello!
) : (
  // ByeBye!
)}
</code>```

Here's the link: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

So, I tried to take that knowledge and implemant it in my React app. And it turned out like this:

```<code>render() {
  return (
    <div>
      <div className="box">
        {this.props.collection.ids
          .filter(
            id =>
              // note: this is only passed when in top level of document
              this.props.collection.documents[id][
                this.props.schema.foreignKey
              ] === this.props.parentDocumentId
          )
          .map(id =>
            {if (this.props.schema.collectionName.length < 0 ? (

              <Expandable>
                <ObjectDisplay
                  key={id}
                  parentDocumentId={id}
                  schema={schema[this.props.schema.collectionName]}
                  value={this.props.collection.documents[id]}
                />
              </Expandable>

            ) : (
              <h1>hejsan</h1>
            )}
          )}
      </div>
    </div>
  )
}
</code>```

But it doesn't work..! Here's the error:

I appreciate all the help I can get!

答:
Remove the if keyword. It should just be predicate ? true_result : false_result.

Also ? : is called ternary operator.

Title: If condition inside of map() React

Body:
I have a map()function that needs to display views based on a condition. I've looked at the React documentation on how to write conditions and this is how you can write a condition:

{if (loggedIn) ? (
  // Hello!
) : (
  // ByeBye!
)}

Here's the link: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

So, I tried to take that knowledge and implemant it in my React app. And it turned out like this:

render() {
  return (

        {this.props.collection.ids
          .filter(
            id =>
              // note: this is only passed when in top level of document
              this.props.collection.documents[id][
                this.props.schema.foreignKey
              ] === this.props.parentDocumentId
          )
          .map(id =>
            {if (this.props.schema.collectionName.length < 0 ? (

              <Expandable>
                <ObjectDisplay
                  key={id}
                  parentDocumentId={id}
                  schema={schema[this.props.schema.collectionName]}
                  value={this.props.collection.documents[id]}
                />
              </Expandable>

            ) : (

hejsan

            )}
          )}

  )
}

But it doesn't work..! Here's the error:

I appreciate all the help I can get!


问:
var in class gives error

Possible Duplicate:

  Using var outside of a method

```<code>class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
</code>```

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

答: It is all because of the Build order. You can declare var in only methods. Compiler builds everything but methods first and thats why the type of the object will be clear to the compiler if you use it inside of a method. Jon had a great answer about this but can't seem to find.</p>

Title: var in class gives error

Body:
Possible Duplicate:

  Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.


问:
how to use an array in php mysql query?
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

```<code>$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";
</code>```

Can anyone help me with this?

答:
There are some missing single quotes in the join (implode) function:

```<code>$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join("','",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";
</code>```

Query Without these quotes:

```<code>...where site_keywords in ('one,two,three')...
</code>```

This will not produce any output or error as there are no valid results. The search query is treated as one long string.

Query With these quotes:

```<code>...where site_keywords in ('one','two','three')...
</code>```

Here each query is correctly split in multiple search values.

Title: how to use an array in php mysql query?

Body:
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

Can anyone help me with this?

Body:
There are some missing single quotes in the join (implode) function:

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join("','",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

Query Without these quotes:

...where site_keywords in ('one,two,three')...

This will not produce any output or error as there are no valid results. The search query is treated as one long string.

Query With these quotes:

...where site_keywords in ('one','two','three')...

Here each query is correctly split in multiple search values.