问:
Can't find settings for "naming rule" in Resharper!
I got tired of Reshaper complaining on any variables I have named as "varID" to change to Camel Case (i.e. "varId").

So I tried to add a rule in Resharper under

```<code>Edit 'Local Variables' Rule Settings
</code>```

And set the "Name Suffix" with a "ID" and it stopped complaining.  Now, if I have a variable as "varID" it will complain and recommend it be renamed to "var".  But when I inspect/edit the rules, my original rule is no longer there.

NOTE: I didn't edit the existing rule in case you suggest I check that.

Anyone have any ideas?

答:
I would undo the Name Suffix change. Then go to

Resharper -> Options -> Naming Style (under Languages/Common) and click Advanced Settings.

In the abbreviations list at the bottom is where you want to add ID. Then it should stop complaining about ID being used in variable names, properties, etc.

Body:
I got tired of Reshaper complaining on any variables I have named as "varID" to change to Camel Case (i.e. "varId").

So I tried to add a rule in Resharper under

Edit 'Local Variables' Rule Settings

And set the "Name Suffix" with a "ID" and it stopped complaining.  Now, if I have a variable as "varID" it will complain and recommend it be renamed to "var".  But when I inspect/edit the rules, my original rule is no longer there.

NOTE: I didn't edit the existing rule in case you suggest I check that.

Anyone have any ideas?


来源: stackexchange

问:
Setting SHMMAX etc values on MAC OS X 10.6 for PostgreSQL
I'm trying to startup my PostgreSQL server on my local machine.
But I got an error message saying:

```<code>FATAL:  could not create shared memory segment: Invalid argument
DETAIL:  Failed system call was shmget(key=5432001, size=9781248, 03600).
HINT:  This error usually means that PostgreSQL's request for a shared memory segment exceeded your kernel's SHMMAX parameter.  You can either reduce the request size or reconfigure the kernel with larger SHMMAX.  To reduce the request size (currently 9781248 bytes), reduce PostgreSQL's shared_buffers parameter (currently 1024) and/or its max_connections parameter (currently 13).
If the request size is already small, it's possible that it is less than your kernel's SHMMIN parameter, in which case raising the request size or reconfiguring SHMMIN is called for.
The PostgreSQL documentation contains more information about shared memory configuration.
</code>```

I search and looked at the docs but everything I tries about setting the kern.sysv.shmmax and kern.sysv.shmall is working.
What are the right settings on Snow Leopard? I installed postgres with macports.

答:
I know this is an old question, but I think it might be worth noting that if you're just using PostgreSQL for development purposes you might be safe to just go into postgres.conf (the data directory after you've done initdb) and change the shared_buffers variable to something a little lower. It defaults to 28MB or something.
But this way you're not messing around with system shared memory variables.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to startup my PostgreSQL server on my local machine.
But I got an error message saying:

FATAL:  could not create shared memory segment: Invalid argument
DETAIL:  Failed system call was shmget(key=5432001, size=9781248, 03600).
HINT:  This error usually means that PostgreSQL's request for a shared memory segment exceeded your kernel's SHMMAX parameter.  You can either reduce the request size or reconfigure the kernel with larger SHMMAX.  To reduce the request size (currently 9781248 bytes), reduce PostgreSQL's shared_buffers parameter (currently 1024) and/or its max_connections parameter (currently 13).
If the request size is already small, it's possible that it is less than your kernel's SHMMIN parameter, in which case raising the request size or reconfiguring SHMMIN is called for.
The PostgreSQL documentation contains more information about shared memory configuration.

I search and looked at the docs but everything I tries about setting the kern.sysv.shmmax and kern.sysv.shmall is working.
What are the right settings on Snow Leopard? I installed postgres with macports.

ContentLicense: CC BY-SA 3.0


问:
Can i install VSTS on my own server firm?
I know Azure Websites has released a version of its cloud manager to install it on its own server firm.

Likewise, I would like to install VSTS on my own server firm.

Is there also a setup version available for Visual Studio Team Services ?

答: You mean Team foundation server, based on the requirements of TFS, you can install TFS on your server, need to meet the requirements.</p>


问:
random integer in Matlab within a range but excluding values
I have generated random numbers in MATLAB within a range using the below:

```<code>N=10000;
n=3000;
c=randperm(N,n);
</code>```

I need another set of random numbers within the same range 1:N and of the same size n but excluding the values in c.
Any ideas?

答:
You can use again randperm excluding the integers of array c to crate array d with same length n:

```<code>ok = 1:N;
ok(c) = [];
d=ok(randperm(numel(ok),n));
</code>```

Body:
I have generated random numbers in MATLAB within a range using the below:

N=10000;
n=3000;
c=randperm(N,n);

I need another set of random numbers within the same range 1:N and of the same size n but excluding the values in c.
Any ideas?

Body:
You can use again randperm excluding the integers of array c to crate array d with same length n:

ok = 1:N;
ok(c) = [];
d=ok(randperm(numel(ok),n));


问:
Build a new list from existing with javascript or php
I want to create breadcrumbs with dropdown menu for my site

I need to convert this existing list into

```<code><div class="menu">
  <ul>
    <li>
      <a href="#">GRANDPARENT A</a> <!-- comment -->
        <ul>
          <li><a href="#?AAA">PARENT A</a> <!-- comment -->
            <ul>
              <li><a href="#">CHILD A</a>
              </li>
              <li><a href="#">child b</a>
            </ul>
          </li>
          <li><a href="">parent b</a>
          </li>
        </ul>
    </li>
    <li>
      <a href="#">grandparent b</a> <!-- comment -->
    </li>
</ul>
</div>
</code>```

this format (including adding a class to the current path):

```<code><li>
  <a class="current" href="#">GRANDPARENT A</a> <!-- comment -->
  <ul>
     <li>
       <a href="#">grandparent b</a> <!-- comment -->
     </li>
  </ul>
</li>
<li><a class="current" href="#?AAA">PARENT A</a> <!-- comment -->
  <ul>
    <li><a href="">parent b</a>
    </li>
  </ul>
</li>
<li><a class="current" href="#">CHILD A</a>
  <ul>
    <li><a href="#">child b</a>
    </li>
  </ul>
</li>
</code>```

I tried a lot but could not get a good result. I would prefere php but could only get next to a solution in js.

答:
That is the dirty solution I have found up to now (it also filters out links where <li> has the class unlinked and  with empty hrefs):</p>

```<code>            var url = window.location.href; //.split('?')[0];
            var currentItem = $(".menu").find("[href$='" + url +  "']");
            var breadcrumString = "";
            var parrentItem = "<a href='/'>Start</a>";
            var currentSubItems = "";
            var breadcrumbStringSub = "";
            if (currentItem.parent("li").children().children().length > 0){
                currentSubItems = currentItem.parent("li").children().children();
                breadcrumbStringSub += '<ul>';
                    currentSubItems.each(function() {
                            if (($(this).children("a")[0]) && $(this).children("a").get(0).outerHTML != '<a href=""></a>' && $(this).get(0).className != 'unlisted'){
                            breadcrumbStringSub += "<li>" +
                            $(this).children("a").get(0).outerHTML +
                            "</li>";
                            } else {};
                        });
                    breadcrumbStringSub += "</ul>";
            breadcrumbStringSub += '</ul>';
                }
            $(currentItem.parents("li").get().reverse()).each(function () {
                if ($(this).parent().children().not(this).length > 0){
                 breadcrumString += "<li>" + parrentItem;
                 $(this).children("a").get(0).outerHTML;
                 $(this).parent().children().each(function() {
                  if ($(this).children("a")[0] && $(this).children("a").get(0).outerHTML != '<a href=""></a>' && $(this).get(0).className != 'unlisted'){
                    breadcrumString += "<li><a href='" +
                    $(this).children("a")[0] +  "'>" +
                    $(this).children("a").html() + "</a>" +
                    "</li>";
                  } else {};
                });
                breadcrumString += "</ul>";
                } else {
                breadcrumString += "<li>" + parrentItem;
                }
                breadcrumString += "</li>";
                parrentItem = $(this).children("a").get(0).outerHTML;
            });
            breadcrumString += '<li>' + parrentItem + breadcrumbStringSub + '</li>';
            $(".breadcrumb").append(breadcrumString);
            $(".breadcrumb li a").not(".breadcrumb li ul li a").addClass("current")
</code>```

Body:
I want to create breadcrumbs with dropdown menu for my site

I need to convert this existing list into

      GRANDPARENT A

PARENT A

CHILD A

child b

parent b

      grandparent b

this format (including adding a class to the current path):

  GRANDPARENT A

       grandparent b

PARENT A

parent b

CHILD A

child b

I tried a lot but could not get a good result. I would prefere php but could only get next to a solution in js.

Body:
That is the dirty solution I have found up to now (it also filters out links where
 has the class unlinked and  with empty hrefs):

            var url = window.location.href; //.split('?')[0];
            var currentItem = $(".menu").find("[href$='" + url +  "']");
            var breadcrumString = "";
            var parrentItem = "<a href='/'>Start</a>";
            var currentSubItems = "";
            var breadcrumbStringSub = "";
            if (currentItem.parent("li").children().children().length > 0){
                currentSubItems = currentItem.parent("li").children().children();
                breadcrumbStringSub += '<ul>';
                    currentSubItems.each(function() {
                            if (($(this).children("a")[0]) && $(this).children("a").get(0).outerHTML != '<a href=""></a>' && $(this).get(0).className != 'unlisted'){
                            breadcrumbStringSub += "<li>" +
                            $(this).children("a").get(0).outerHTML +
                            "</li>";
                            } else {};
                        });
                    breadcrumbStringSub += "</ul>";
            breadcrumbStringSub += '</ul>';
                }
            $(currentItem.parents("li").get().reverse()).each(function () {
                if ($(this).parent().children().not(this).length > 0){
                 breadcrumString += "<li>" + parrentItem;
                 $(this).children("a").get(0).outerHTML;
                 $(this).parent().children().each(function() {
                  if ($(this).children("a")[0] && $(this).children("a").get(0).outerHTML != '<a href=""></a>' && $(this).get(0).className != 'unlisted'){
                    breadcrumString += "<li><a href='" +
                    $(this).children("a")[0] +  "'>" +
                    $(this).children("a").html() + "</a>" +
                    "</li>";
                  } else {};
                });
                breadcrumString += "</ul>";
                } else {
                breadcrumString += "<li>" + parrentItem;
                }
                breadcrumString += "</li>";
                parrentItem = $(this).children("a").get(0).outerHTML;
            });
            breadcrumString += '<li>' + parrentItem + breadcrumbStringSub + '</li>';
            $(".breadcrumb").append(breadcrumString);
            $(".breadcrumb li a").not(".breadcrumb li ul li a").addClass("current")


问:
How to pass data from one controller to another controller in ONSEN UI angular?
i have a html like below

```<code><a class="event_detail_btn_a" ng-click="foo()"></a>
</code>```

following is my controller

```<code>    onsenApp.controller("EventDetailController", function ($scope) {
        $scope.foo = function(){
            alert("foo!");
            var options = {
                data: {
                    title: 'Another Page'
                }
            };

        };
});
</code>```

i want to pass "options" variable to another controller from this controller.
how can i do it ?

答:
Best way to create a service OR a factory and inject in both controllers like below:

```<code>var myApp = angular.module('myApp', []);

myApp.factory('MyService', function() {
  var options = {
    data: {
      title: 'Another Page'
    }
  };
  return {
    options
  };
});

myApp.controller('FirstCtrl', function($scope, MyService) {
  $scope.options = MyService.options;
});

myApp.controller('SecondCtrl', function($scope, MyService) {
  $scope.options = MyService.options;
});
</code>```

Body:
i have a html like below

following is my controller

    onsenApp.controller("EventDetailController", function ($scope) {
        $scope.foo = function(){
            alert("foo!");
            var options = {
                data: {
                    title: 'Another Page'
                }
            };

        };
});

i want to pass "options" variable to another controller from this controller.
how can i do it ?

Body:
Best way to create a service OR a factory and inject in both controllers like below:

var myApp = angular.module('myApp', []);

myApp.factory('MyService', function() {
  var options = {
    data: {
      title: 'Another Page'
    }
  };
  return {
    options
  };
});

myApp.controller('FirstCtrl', function($scope, MyService) {
  $scope.options = MyService.options;
});

myApp.controller('SecondCtrl', function($scope, MyService) {
  $scope.options = MyService.options;
});


问:
How to turn element into jQuery selector?
How to turn the event.currentTarget into jQuery object or something like that so I could then use jQuery's addClass method on the object? I know I could just do like: event.currentTarget.className += ' .class', but I was wondering how to work with the event target with jQuery.</p>

```<code>$('.class').click(function(event) {
    Class.down($(this).parent().prev().attr('alt'));
    Class.style($(event.currentTarget));
});
</code>```

Body:
How to turn the event.currentTarget into jQuery object or something like that so I could then use jQuery's addClass method on the object? I know I could just do like: event.currentTarget.className += ' .class', but I was wondering how to work with the event target with jQuery.

$('.class').click(function(event) {
    Class.down($(this).parent().prev().attr('alt'));
    Class.style($(event.currentTarget));
});

Body: $(event.currentTarget).addClass("classname");


问:
Remove failed database
By accident I have deleted MDF and LDF files from my database directory. Now, each time I start SSMS I have error:

Failed to retrieve data for this request.

Unable to open the physical file "C:\Program Files\Microsoft SQL
  Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\LearnCSharp.mdf". Operating
  system error 2: "2(The system cannot find the file specified.)".
  (Microsoft SQL Server, Error: 5120)

For help, click:
  http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=10.00.2531&EvtSrc=MSSQLServer&EvtID=5120&LinkId=20476

How to remove database from system in such situation?

答:
It's not clear from your question if the database is still on your server or it's only memorized as default database for your login or as explicitly specified in SSMS dialog.

First try to drop it:

```<code>drop database MyDB
</code>```

If you get an error that database does not exist, check if it's specified as default database for your login

Title: Remove failed database

Body:
It's not clear from your question if the database is still on your server or it's only memorized as default database for your login or as explicitly specified in SSMS dialog.

First try to drop it:

drop database MyDB

If you get an error that database does not exist, check if it's specified as default database for your login


问:
Using multiple @GenericGenerator?
I experimented with Hibernate's @GenericGenerator in a Spring Boot project (Hibernate 5). Made a test entity like this:

```<code>@Entity
public class BatchTest implements Serializable {
    private static final long serialVersionUID = 3012542467060581674L;

    @Id
    @GeneratedValue(generator = "batchTestIdGenerator")
    @GenericGenerator(
            name = "batchTestIdGenerator",
            strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
            parameters = {
                    @org.hibernate.annotations.Parameter(name = "increment_size",value = "1000")
            }
    )
    private long id;

    @Lob
    @Column(nullable = false)
    private String someVal;
...
</code>```

Using this generator I can insert entities really fast with JPA (I have a Spring Repository, served by a @Service) and it's cool, but how is the sequence actually stored? My database currently is an SQL Server 2016 instance, and in the schema, I can see that I have a dbo.hibernate_sequence:

If I create a second entity, with a different generator, I get an exception during startup:

```<code>@Id
@GeneratedValue(generator = "batchTestIdGenerator2", strategy = GenerationType.SEQUENCE)
@GenericGenerator(
        name = "batchTestIdGenerator2",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @org.hibernate.annotations.Parameter(name = "increment_size",value = "500")
        }
)
private long id;

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Multiple references to database sequence [hibernate_sequence] were encountered attempting toset conflicting values for 'increment size'.  Found [500] and [1000]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
</code>```

Can I define different sequences at all? It seems like It tries to use the same dbo.hibernate_sequence for both sequences (id did not create a new dbo sequence in the database) and just disregards the name. If it is possible to define N number of sequence, how can I do it?

Edit: I tried to create the sequences manually (matching names), but I still get the same error.

答:
Hibernate allow you to create your own Sequence generator, that allows you to define the  format , table everything using Hibernate IdentifierGenerator.
Please try below approach.

Create a SequenceGenerator class by implementing IdentifierGenerator, Use org.hibernate.id.Configurable interface to make your Generator configurable -that will accept parameters from the Entity class-

Custom identifier generator looks like this:

```<code>public class StringSequenceIdentifier
        implements IdentifierGenerator, Configurable {

    public static final String SEQUENCE_PREFIX = "sequence_prefix";

    private String sequencePrefix;

    private String sequenceCallSyntax;

    @Override
    public void configure(
            Type type, Properties params, ServiceRegistry serviceRegistry)
            throws MappingException {
        final JdbcEnvironment jdbcEnvironment =
                serviceRegistry.getService(JdbcEnvironment.class);
        final Dialect dialect = jdbcEnvironment.getDialect();

        sequencePrefix = ConfigurationHelper.getString(
                SEQUENCE_PREFIX,
                params,
                "SEQ_");

        final String sequencePerEntitySuffix = ConfigurationHelper.getString(
                SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX,
                params,
                SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX);

        final String defaultSequenceName = ConfigurationHelper.getBoolean(
                SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY,
                params,
                false)
                ? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix
                : SequenceStyleGenerator.DEF_SEQUENCE_NAME;

        sequenceCallSyntax = dialect.getSequenceNextValString(
                ConfigurationHelper.getString(
                        SequenceStyleGenerator.SEQUENCE_PARAM,
                        params,
                        defaultSequenceName));
    }

    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        if (obj instanceof Identifiable) {
            Identifiable identifiable = (Identifiable) obj;
            Serializable id = identifiable.getId();
            if (id != null) {
                return id;
            }
        }
        long seqValue = ((Number) Session.class.cast(session)
            .createSQLQuery(sequenceCallSyntax)
            .uniqueResult()).longValue();

        return sequencePrefix + String.format("%011d%s", 0 ,seqValue);
    }
}
</code>```

Entity Will be like

```<code>@Entity(name = "Post") @Table(name = "post")
public class Post implements Identifiable<String> {

    @Id
    @GenericGenerator(
        name = "assigned-sequence",
        strategy = "com.vladmihalcea.book.hpjp.hibernate.identifier.StringSequenceIdentifier",
        parameters = {
            @org.hibernate.annotations.Parameter(
                name = "sequence_name", value = "hibernate_sequence"),
            @org.hibernate.annotations.Parameter(
                name = "sequence_prefix", value = "CTC_"),
        }
    )
    @GeneratedValue(
        generator = "assigned-sequence",
        strategy = GenerationType.SEQUENCE)
    private String id;

    @Version
    private Integer version;

    public Post() {
    }

    public Post(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }
}
</code>```

Please refer the Below link for detailed explanation.
https://vladmihalcea.com/how-to-implement-a-custom-string-based-sequence-identifier-generator-with-hibernate/

Title: Using multiple @GenericGenerator?

Body:
I experimented with Hibernate's @GenericGenerator in a Spring Boot project (Hibernate 5). Made a test entity like this:

@Entity
public class BatchTest implements Serializable {
    private static final long serialVersionUID = 3012542467060581674L;

    @Id
    @GeneratedValue(generator = "batchTestIdGenerator")
    @GenericGenerator(
            name = "batchTestIdGenerator",
            strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
            parameters = {
                    @org.hibernate.annotations.Parameter(name = "increment_size",value = "1000")
            }
    )
    private long id;

    @Lob
    @Column(nullable = false)
    private String someVal;
...

Using this generator I can insert entities really fast with JPA (I have a Spring Repository, served by a @Service) and it's cool, but how is the sequence actually stored? My database currently is an SQL Server 2016 instance, and in the schema, I can see that I have a dbo.hibernate_sequence:

If I create a second entity, with a different generator, I get an exception during startup:

@Id
@GeneratedValue(generator = "batchTestIdGenerator2", strategy = GenerationType.SEQUENCE)
@GenericGenerator(
        name = "batchTestIdGenerator2",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @org.hibernate.annotations.Parameter(name = "increment_size",value = "500")
        }
)
private long id;

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Multiple references to database sequence [hibernate_sequence] were encountered attempting toset conflicting values for 'increment size'.  Found [500] and [1000]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]

Can I define different sequences at all? It seems like It tries to use the same dbo.hibernate_sequence for both sequences (id did not create a new dbo sequence in the database) and just disregards the name. If it is possible to define N number of sequence, how can I do it?

Edit: I tried to create the sequences manually (matching names), but I still get the same error.

Body:
Hibernate allow you to create your own Sequence generator, that allows you to define the  format , table everything using Hibernate IdentifierGenerator.
Please try below approach.

Create a SequenceGenerator class by implementing IdentifierGenerator, Use org.hibernate.id.Configurable interface to make your Generator configurable -that will accept parameters from the Entity class-

Custom identifier generator looks like this:

public class StringSequenceIdentifier
        implements IdentifierGenerator, Configurable {

    public static final String SEQUENCE_PREFIX = "sequence_prefix";

    private String sequencePrefix;

    private String sequenceCallSyntax;

    @Override
    public void configure(
            Type type, Properties params, ServiceRegistry serviceRegistry)
            throws MappingException {
        final JdbcEnvironment jdbcEnvironment =
                serviceRegistry.getService(JdbcEnvironment.class);
        final Dialect dialect = jdbcEnvironment.getDialect();

        sequencePrefix = ConfigurationHelper.getString(
                SEQUENCE_PREFIX,
                params,
                "SEQ_");

        final String sequencePerEntitySuffix = ConfigurationHelper.getString(
                SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX,
                params,
                SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX);

        final String defaultSequenceName = ConfigurationHelper.getBoolean(
                SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY,
                params,
                false)
                ? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix
                : SequenceStyleGenerator.DEF_SEQUENCE_NAME;

        sequenceCallSyntax = dialect.getSequenceNextValString(
                ConfigurationHelper.getString(
                        SequenceStyleGenerator.SEQUENCE_PARAM,
                        params,
                        defaultSequenceName));
    }

    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        if (obj instanceof Identifiable) {
            Identifiable identifiable = (Identifiable) obj;
            Serializable id = identifiable.getId();
            if (id != null) {
                return id;
            }
        }
        long seqValue = ((Number) Session.class.cast(session)
            .createSQLQuery(sequenceCallSyntax)
            .uniqueResult()).longValue();

        return sequencePrefix + String.format("%011d%s", 0 ,seqValue);
    }
}

Entity Will be like

@Entity(name = "Post") @Table(name = "post")
public class Post implements Identifiable<String> {

    @Id
    @GenericGenerator(
        name = "assigned-sequence",
        strategy = "com.vladmihalcea.book.hpjp.hibernate.identifier.StringSequenceIdentifier",
        parameters = {
            @org.hibernate.annotations.Parameter(
                name = "sequence_name", value = "hibernate_sequence"),
            @org.hibernate.annotations.Parameter(
                name = "sequence_prefix", value = "CTC_"),
        }
    )
    @GeneratedValue(
        generator = "assigned-sequence",
        strategy = GenerationType.SEQUENCE)
    private String id;

    @Version
    private Integer version;

    public Post() {
    }

    public Post(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }
}

Please refer the Below link for detailed explanation.
https://vladmihalcea.com/how-to-implement-a-custom-string-based-sequence-identifier-generator-with-hibernate/


问:
Photo gallery in android coding clarification?
i am new to the android platform, can anyone explain the below code: i go through the photo gallery but in this code i was stuck

source code:

http://stacktips.com/tutorials/android/writing-image-picker-using-intent-in-android

already switch case  is receiving the command from SELECT_PHOTO: ,

then why we are using if case?

what will be in (int requestCode, int resultCode, Intent imageReturnedIntent) ;

what this will do?
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

please explain step by step , it will great helpful for me to understand.
thanks in advance

prg coding:

```<code>  protected void onActivityResult(int requestCode, int resultCode, Intent
  imageReturnedIntent) {
  super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

 switch(requestCode) {

 case SELECT_PHOTO:
 if(resultCode == RESULT_OK)
 {

 try {

 final Uri imageUri = imageReturnedIntent.getData();

 final InputStream imageStream =
 getContentResolver().openInputStream(imageUri);

 final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

 imageView.setImageBitmap(selectedImage);

 }

 catch (FileNotFoundException e)

 {
 e.printStackTrace();
</code>```

答:
The if clause is used to ensure that the activity has returned a correct result and has not failed.
If you didn't use the if, you could decode an image that hasn't been selected yet(so it doesn't exist in your context), for example.</p>

Body:
i am new to the android platform, can anyone explain the below code: i go through the photo gallery but in this code i was stuck

source code:

http://stacktips.com/tutorials/android/writing-image-picker-using-intent-in-android

already switch case  is receiving the command from SELECT_PHOTO: ,

then why we are using if case?

what will be in (int requestCode, int resultCode, Intent imageReturnedIntent) ;

what this will do?
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

please explain step by step , it will great helpful for me to understand.
thanks in advance

prg coding:

  protected void onActivityResult(int requestCode, int resultCode, Intent
  imageReturnedIntent) {
  super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

 switch(requestCode) {

 case SELECT_PHOTO:
 if(resultCode == RESULT_OK)
 {

 try {

 final Uri imageUri = imageReturnedIntent.getData();

 final InputStream imageStream =
 getContentResolver().openInputStream(imageUri);

 final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

 imageView.setImageBitmap(selectedImage);

 }

 catch (FileNotFoundException e)

 {
 e.printStackTrace();


问:
Subdomain on azurewebsites.net?
To avoid namespace collisions on azurewebsites.net I prefix my websites with a string. Example foo-app1.azurewebsites.net and foo-app2.azurewebsites.net, etc so in this case they are grouped under the "foo-" prefix.

However a subdomain would be a nice way of grouping websites.

Is it possible to group websites as app1.foo.azurewebsites.net and app2.foo.azurewebsites.net?

答:
Is it possible to group websites as app1.foo.azurewebsites.net and app2.foo.azurewebsites.net?

For azure app service, app1.foo.azurewebsites.net and app2.foo.azurewebsites.net are two independent web apps. In order to group your websites, I assumed that you could configure the custom domain name for your Azure websites.

Assuming that your custom domain name is contoso.com. You could map your subdomains against the same azure web app as follow:

```<code>app1.contoso.com -> {app_name}.azurewebsites.net
app2.contoso.com -> {app_name}.azurewebsites.net
</code>```

Also, you could map your subdomains to your different azure web apps as follows:

```<code>app1.contoso.com -> {app_name_01}.azurewebsites.net
app2.contoso.com -> {app_name_02}.azurewebsites.net
</code>```

More details about how to map your custom DNS name to Azure Web Apps, you could refer to here.

Title: Subdomain on azurewebsites.net?

Body:
Is it possible to group websites as app1.foo.azurewebsites.net and app2.foo.azurewebsites.net?

For azure app service, app1.foo.azurewebsites.net and app2.foo.azurewebsites.net are two independent web apps. In order to group your websites, I assumed that you could configure the custom domain name for your Azure websites.

Assuming that your custom domain name is contoso.com. You could map your subdomains against the same azure web app as follow:

app1.contoso.com -> {app_name}.azurewebsites.net
app2.contoso.com -> {app_name}.azurewebsites.net

Also, you could map your subdomains to your different azure web apps as follows:

app1.contoso.com -> {app_name_01}.azurewebsites.net
app2.contoso.com -> {app_name_02}.azurewebsites.net

More details about how to map your custom DNS name to Azure Web Apps, you could refer to here.


问:
PHP Singleton Acting Funny
I have the following code:

```<code>$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "```";
print_r(self::$extensions);
```

<p>Each getInstance() method looks like this:</p>

```public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}
```

<p>Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:</p>

```stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)
```

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!

答:
Try not using self::, but MySQL_Extension:: and Error_Extension:: explicitly.

Also, the abstract parent class Extension_Abstract should not contain the implementation for the getInstance method.

Title: PHP Singleton Acting Funny

Body:
I have the following code:

$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "
";
print_r(self::$extensions);

Each getInstance() method looks like this:

public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}

Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:

stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!


问:
Ghoshscript total coverage "incorrect"
I am using Ghostscript (version 9.2) Linux version to convert PS to PDF file. Below is the script

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

/home/ghostscript/ps2pdf \
-dBATCH -dNOPAUSE  \
-dEmbedAllFonts=true -dAutoRotatePages=/None \
-sDEVICE=pdfwrite \
-r1440 \
-dOverrideICC=true \
-dUsePDFX3Profile=1 \
-sProcessColorModel=DeviceCMYK \
-sColorConversionStrategy=CMYK   \
-sICCProfilesDir=/home/ghostscript/ \
-sDefaultRGBProfile=AdobeRGB1998.icc \
-sOutputICCProfile=ISOnewspaper26v4.icc \
-sImageICCProfile=ISOnewspaper26v4.icc \
-sFONTPATH=/opt/igenfonts \
-dDEVICEWIDTHPOINTS=779.76 -dDEVICEHEIGHTPOINTS=1035.36 \
-sOutputFile=$1.pdf \
 $1.PS
</code>```

ISOnewspaper26v4.icc is a Total Coverage 240 ICC profile from http://www.color.org. PDF is converted successfully. But in Adobe Acrobat 8.0 profressional, total coverage of 240 shows color saturation exceeding 240.
Could anyone with the experience help?

Thanks

答:
This isn't a programming question and so is off-topic for Stack Overflow. If you think you've found a bug your best solution is to open a bug report.

You are using a slightly out of date version of Ghostscript and a very out of date version of Acrobat. You haven't explained how you are using Acrobat to determine 'total coverage' or indeed what you mean by 'total coverage'.

Title: Ghoshscript total coverage "incorrect"

Body:
I am using Ghostscript (version 9.2) Linux version to convert PS to PDF file. Below is the script

#!/bin/ksh

/home/ghostscript/ps2pdf \
-dBATCH -dNOPAUSE  \
-dEmbedAllFonts=true -dAutoRotatePages=/None \
-sDEVICE=pdfwrite \
-r1440 \
-dOverrideICC=true \
-dUsePDFX3Profile=1 \
-sProcessColorModel=DeviceCMYK \
-sColorConversionStrategy=CMYK   \
-sICCProfilesDir=/home/ghostscript/ \
-sDefaultRGBProfile=AdobeRGB1998.icc \
-sOutputICCProfile=ISOnewspaper26v4.icc \
-sImageICCProfile=ISOnewspaper26v4.icc \
-sFONTPATH=/opt/igenfonts \
-dDEVICEWIDTHPOINTS=779.76 -dDEVICEHEIGHTPOINTS=1035.36 \
-sOutputFile=$1.pdf \
 $1.PS

ISOnewspaper26v4.icc is a Total Coverage 240 ICC profile from http://www.color.org. PDF is converted successfully. But in Adobe Acrobat 8.0 profressional, total coverage of 240 shows color saturation exceeding 240.
Could anyone with the experience help?

Thanks


问:
Transpose Spark DataFrame Aggregating in Array
I would like to transpose a DataFrame aggregating values per column. Let me ilustrate it with an example:

Given this DataFrame:

```<code>val df = sc.parallelize(Seq(("A","B","C"), ("D", "E", "F"), ("X", "Y", "Z"), ("A", "N", "Z"))).toDF("col1", "col2", "col3")
df.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   A|   B|   C|
|   D|   E|   F|
|   X|   Y|   Z|
|   A|   N|   Z|
+----+----+----+
</code>```

The expected output should be something like this:

```<code>col1: Array("A", "D", "X")
col2: Array("B", "E", "Y", "N")
col3: Array("C", "F", "Z")
</code>```

Consider the real DataFrame could contain about hundreds of columns. Is not necessary preserve the order of the columns in the output.

Edit: Consider as well you could find repeated elements in the columns, but just want the unique elements.

I am using Spark 2.0.2 with scala 2.11.

Any suggestion?

Thanks in advance!

答:
You can apply the groupBy and collect_set but I doubt the performance of that if your row count is on the higher side.

```<code>df.show
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   A|   B|   C|
|   D|   E|   F|
|   X|   Y|   Z|
|   A|   N|   Z|
+----+----+----+

import org.apache.spark.sql.functions._
val query = df.columns.map(x => collect_set(col(x) ).as(x) )

df.groupBy(lit(1))
  .agg(collect_set($"col1"), query: _*)
  .select(df.columns.map(col(_)): _* )
  .show
+---------+------------+---------+
|     col1|        col2|     col3|
+---------+------------+---------+
|[A, D, X]|[B, E, Y, N]|[C, F, Z]|
+---------+------------+---------+
</code>```

Body:
I would like to transpose a DataFrame aggregating values per column. Let me ilustrate it with an example:

Given this DataFrame:

val df = sc.parallelize(Seq(("A","B","C"), ("D", "E", "F"), ("X", "Y", "Z"), ("A", "N", "Z"))).toDF("col1", "col2", "col3")
df.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   A|   B|   C|
|   D|   E|   F|
|   X|   Y|   Z|
|   A|   N|   Z|
+----+----+----+

The expected output should be something like this:

col1: Array("A", "D", "X")
col2: Array("B", "E", "Y", "N")
col3: Array("C", "F", "Z")

Consider the real DataFrame could contain about hundreds of columns. Is not necessary preserve the order of the columns in the output.

Edit: Consider as well you could find repeated elements in the columns, but just want the unique elements.

I am using Spark 2.0.2 with scala 2.11.

Any suggestion?

Thanks in advance!

Body:
You can apply the groupBy and collect_set but I doubt the performance of that if your row count is on the higher side.

df.show
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   A|   B|   C|
|   D|   E|   F|
|   X|   Y|   Z|
|   A|   N|   Z|
+----+----+----+

import org.apache.spark.sql.functions._
val query = df.columns.map(x => collect_set(col(x) ).as(x) )

df.groupBy(lit(1))
  .agg(collect_set($"col1"), query: _*)
  .select(df.columns.map(col(_)): _* )
  .show
+---------+------------+---------+
|     col1|        col2|     col3|
+---------+------------+---------+
|[A, D, X]|[B, E, Y, N]|[C, F, Z]|
+---------+------------+---------+


问:
Ruby : hydrate hash values from array
Let's say I have an ruby array like this :

```<code>values = ['val_a', 'val_b',..., 'val_z'] # 26 values
</code>```

And an hash with keys

```<code>hash = {a: nil, b: nil, ... , z: nil} # 26 keys
</code>```

I know that the array is sorted, and I know that keys of hash are sorted, and I know both array and hash are of same size.

How can I elegantly hydrate hash values so that I end up with

```<code>{a: 'val_a', b: 'val_b', ... , z: 'val_z'}
</code>```

答:
```<code>hash_with_values = hash.keys.zip(values).to_h
</code>```

Note that in some (most?) languages, keys of hashes/maps are unordered, so that would not work. That was also the case for Ruby < 1.9, but, from then on, they are guaranteed to be ordered (insertion order).

Title: Ruby : hydrate hash values from array

Body:
Let's say I have an ruby array like this :

values = ['val_a', 'val_b',..., 'val_z'] # 26 values

And an hash with keys

hash = {a: nil, b: nil, ... , z: nil} # 26 keys

I know that the array is sorted, and I know that keys of hash are sorted, and I know both array and hash are of same size.

How can I elegantly hydrate hash values so that I end up with

{a: 'val_a', b: 'val_b', ... , z: 'val_z'}

Body:
hash_with_values = hash.keys.zip(values).to_h

Note that in some (most?) languages, keys of hashes/maps are unordered, so that would not work. That was also the case for Ruby < 1.9, but, from then on, they are guaranteed to be ordered (insertion order).


问:
Vue.js slow compiling
npm run dev executes very fast.

When I add 1000 rows of html (header) to a .vue file (template), it takes 9 minutes to compile.

Question:

Does vue.js not support such a lengthy template?

Is there any way to speed up?

```<code><template>
  <header class="..." >
    ... (1000 rows)
  </header>
</template>

<script>
export default {
  name: 'Header'
}
</script>
</code>```

答:
Because you are using a static template with static 1000 html elements. Use v-for!

What it will do is just compile (not run!) the Vue syntax on <template>.

Check this out as well: One Useful Link on Rows Rendering on Different Frameworks

Title: Vue.js slow compiling

Body:
npm run dev executes very fast.

When I add 1000 rows of html (header) to a .vue file (template), it takes 9 minutes to compile.

Question:

Does vue.js not support such a lengthy template?

Is there any way to speed up?

<template>

    ... (1000 rows)

</template>


问:
img src is making pdf generation too slow with codeigniter
I am using mpdf library for pdf generation with codeigniter.

I have a png file that is given to generate a logo image in pdf. The generation is too slow. I need to speed up the pdf generation. Does anybody know how to solve this issue?

```<code><div id="mws-logo-wrap">
  <img src="<?php echo base_url();?>images/mws-logo.png" alt="mws admin">
</div>
</code>```

答:
You are prepending the site URL with the base_url() helper which causes an entire additional HTTP request via the "outside" web.

Try to use a "local" path to the file to prevent additional DNS lookups and HTTP requests.

ContentLicense: CC BY-SA 4.0

Body:
I am using mpdf library for pdf generation with codeigniter.

I have a png file that is given to generate a logo image in pdf. The generation is too slow. I need to speed up the pdf generation. Does anybody know how to solve this issue?

  <img src="<?php echo base_url();?>images/mws-logo.png" alt="mws admin">


问:
FBSDKAppInviteDialog is not working
I am Implementing app to invite friend

But it gives me below error

答:
App invites are no longer supported by Facebook, see here.

App Invites will no longer be supported starting with Facebook SDK version 4.28 and above. Previous versions of the SDK can still access App Invites, but starting 2/6, App Invites will no longer be supported.

Title: FBSDKAppInviteDialog is not working


问:
How can I avoid table to break in print preview?
I know there are many questions and many answers for this. Everyone has different problems with different solutions for different browsers.
I have tried many solutions from the below URLs. But nothing seems to work.

My output is as follows :

How can I avoid this kind of situation?
I don't want to mess up the table structure.
This table data are filled up dynamically using handlebars.js.

Links I have followed:
Link-1 Link-2 Link-3

.page-break is a div class which I have added after each section and that is working fine.

.Acc_Table is a table class which is shown in output image starting from SEARS/CBSD row and ending with payment history row.

How can I solve this?

Is it possible to close the table before the page break, put in the page break, and reopen the table after the page break?
Or what I wish to display the table on the next page only if it's breaking?
How can I achieve that?

答:
have you checked if the table or if there is a div that is wrapped around it has the display: inline-block; or display: inline; CSS property?
I found out that while I was debugging some code for a printing problem that if the table is inline you get this effect. Try to put display: block or display: static, that works for me


问:
Using case in a aggregate sql query without splitting rows
In ms-sql i am using an aggregate group to filter results by user, i would also like to use case to filter by a row not contained in the aggregate so all the user results are on 1 line. I'm not sure this is possible.

Here is the query below which splits the results into two lines.

```<code>select case  when col_A='1' then sum(col b) End as Sum1_results,
case  when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A
</code>```

example of results is.

```<code>Sum1_results | Sum2_results | Username

 5499          null           John
 null          3400           John
</code>```

Ideally, i would like to just have these results merged into one line for each username if possible.
Any help would be appreciated

答:
below Query can do the job</p>

```<code>    Create table #tmp (col_A CHAR(1),col_b int,Username VARCHAR(10))

    INSERT INTO #tmp VALUES('1',5000,'John')
    INSERT INTO #tmp VALUES('2',400,'John')
    INSERT INTO #tmp VALUES('1',499,'John')
    INSERT INTO #tmp VALUES('2',3000,'John')

    SELECT * FROM #tmp

    select SUM(case when col_A='1' then col_b End) as Sum1_results,
         SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
    from #tmp

    group by col_A,UserName

    DROP TABLE #tmp
</code>```

Body:
In ms-sql i am using an aggregate group to filter results by user, i would also like to use case to filter by a row not contained in the aggregate so all the user results are on 1 line. I'm not sure this is possible.

Here is the query below which splits the results into two lines.

select case  when col_A='1' then sum(col b) End as Sum1_results,
case  when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A

example of results is.

Sum1_results | Sum2_results | Username

 5499          null           John
 null          3400           John

Ideally, i would like to just have these results merged into one line for each username if possible.
Any help would be appreciated

Body:
below Query can do the job

    Create table #tmp (col_A CHAR(1),col_b int,Username VARCHAR(10))

    INSERT INTO #tmp VALUES('1',5000,'John')
    INSERT INTO #tmp VALUES('2',400,'John')
    INSERT INTO #tmp VALUES('1',499,'John')
    INSERT INTO #tmp VALUES('2',3000,'John')

    SELECT * FROM #tmp

    select SUM(case when col_A='1' then col_b End) as Sum1_results,
         SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
    from #tmp

    group by col_A,UserName

    DROP TABLE #tmp


问:
How to update after "php bin/console security:check"
Symfony write on how to check for security updates: https://symfony.com/doc/current/security/security_checker.html and it works, in Akeneo it shows me one vulnerability.
But how to update? I tried ../composer.phar update and ../composer.phar update symfony/symfony but unfortunately the vulnerability is still there when I check again. (https://github.com/akeneo/pim-community-dev/issues/7146)

```
/var/www/html/akeneo/pim-community-standard# ../composer.phar why dompdf/dompdf:0.6.1
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why-not dompdf/dompdf:0.6.2
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)
```

答: Did you take a look at the answer given at the "bug report" you linked? ;)</p>

Body:
Symfony write on how to check for security updates: https://symfony.com/doc/current/security/security_checker.html and it works, in Akeneo it shows me one vulnerability.
But how to update? I tried ../composer.phar update and ../composer.phar update symfony/symfony but unfortunately the vulnerability is still there when I check again. (https://github.com/akeneo/pim-community-dev/issues/7146)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why dompdf/dompdf:0.6.1
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why-not dompdf/dompdf:0.6.2
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)


问:
passing html element using to_html in flask
I have a dataframe that contains a column containing <canvas> something </canvas> element. In a flask application, I passed this data to a template using df.to_html(), but it never is working and always shows the <canvas> within displayed html table.

<img src="https://i.stack.imgur.com/Kt6Br.png" alt="I intend to let the canvas element be captured by a chartjs function">

答:
To enable showing the characters <, >, and & signs in to_html() method, we need to change the escape attribute to False. Because by default to_html method converts the characters <, >, and & to HTML-safe sequences. Also we need to use safe filter in the template file to show the tags inside the table.

As you have already found how to show the HTML properly in Flask template, I am giving an example of the operation for future readers.

app.py contains a dataframe with html tags which we want to render in the template:

```<code>import pandas as pd
from flask import Flask, render_template

def get_panda_data():
    tags = ["<h1>Example header</h1>",
            '<div style="color: red;">Example div</div>',
            '<input type="text" name="example_form" \
placeholder="Example input form">'
        ]
    pd.set_option('display.max_colwidth', -1)
    tags_frame = pd.DataFrame(tags, columns = ["Tag Example"])
    tags_html = tags_frame.to_html(escape=False)
    return tags_html

app = Flask(__name__)

@app.route('/')
def index():
    html_data = get_panda_data()
    return render_template("dataframe_example.html", html_data = html_data)

if __name__ == '__main__':
    app.run(debug = True)
</code>```

Then in template file which is dataframe_example.html we can easily show the data table generated by pandas to_html method:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Dataframe Flask Example</title>
</head>
<body>
    <h1>Dataframe Flask Example</h1>
        {{ html_data | safe }}
</body>
</html>
</code>```

The output looks like:

Body:
To enable showing the characters <, >, and & signs in to_html() method, we need to change the escape attribute to False. Because by default to_html method converts the characters <, >, and & to HTML-safe sequences. Also we need to use safe filter in the template file to show the tags inside the table.

As you have already found how to show the HTML properly in Flask template, I am giving an example of the operation for future readers.

app.py contains a dataframe with html tags which we want to render in the template:

import pandas as pd
from flask import Flask, render_template

def get_panda_data():
    tags = ["<h1>Example header</h1>",
            '<div style="color: red;">Example div</div>',
            '<input type="text" name="example_form" \
placeholder="Example input form">'
        ]
    pd.set_option('display.max_colwidth', -1)
    tags_frame = pd.DataFrame(tags, columns = ["Tag Example"])
    tags_html = tags_frame.to_html(escape=False)
    return tags_html

app = Flask(__name__)

@app.route('/')
def index():
    html_data = get_panda_data()
    return render_template("dataframe_example.html", html_data = html_data)

if __name__ == '__main__':
    app.run(debug = True)

Then in template file which is dataframe_example.html we can easily show the data table generated by pandas to_html method:

<!DOCTYPE html>
<html>
<head>
    <title>Dataframe Flask Example</title>
</head>
<body>
    <h1>Dataframe Flask Example</h1>
        {{ html_data | safe }}
</body>
</html>

The output looks like:


问:
How to find if 3 numbers in a set of size N exactly sum up to M
I want to know how I can implement a better solution than O(N^3). Its similar to the knapsack and subset problems. In my question N<=8000, so i started computing sums of pairs of numbers and stored them in an array. Then I would binary search in the sorted set for each (M-sum[i]) value but the problem arises how will I keep track of the indices which summed up to sum[i]. I know I could declare extra space but my Sums array already has a size of 64 million, and hence I couldn't complete my O(N^2) solution. Please advice if I can do some optimization or if I need some totally different technique.</p>

答:
There is a simple O(n^2) solution to this that uses only O(1)* memory if you only want to find the 3 numbers (O(n) memory if you want the indices of the numbers and the set is not already sorted).

First, sort the set.

Then for each element in the set, see if there are two (other) numbers that sum to it. This is a common interview question and can be done in O(n) on a sorted set.

The idea is that you start a pointer at the beginning and one at the end, if your current sum is not the target, if it is greater than the target, decrement the end pointer, else increment the start pointer.

So for each of the n numbers we do an O(n) search and we get an O(n^2) algorithm.

*Note that this requires a sort that uses O(1) memory. Hell, since the sort need only be O(n^2) you could use bubble sort. Heapsort is O(n log n) and uses O(1) memory.


问:
WMS and WFS time search criterion (dimension)
WMS accepts a time criterion ([1]). Does WFS also accept a time criterion (I don't see anything in [2])? There is some discussion on [3] but it is not clear. I am especially interested in GeoServer supports it (if possible).

[1] http://docs.geoserver.org/stable/en/user/services/wms/time.html#wms-time

[2] http://docs.geoserver.org/stable/en/user/services/wms/time.html

[3] https://web.archive.org/web/20180318045748/http://www.ogcnetwork.net/node/178

答: WFS doesn't support dimensions as a separate concept, it does provide a well-documented filter capability that serves the same end.</p>


问:
Set environment variable in shell script and access in Java program
This question is a followup on Set environment variable in shell script/access in Java program. I am trying to fetch the environment variable in Java after running a shell script but unable to do so

Shell Script: getDetails.sh:

```<code>#!/bin/bash
# File: getDetails.sh
export userDetails="USER123"
# echo "User Details for App :$userDetails"
</code>```

Java method:

```<code>String details = new String("source " + "getDetails.sh");
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", details);
Process getPwdProc = processBuilder.start();
System.out.println("Details - " + processBuilder.environment().get("userDetails"));
</code>```

The java method returns/prints null for the environment variable - userDetails.

P.S. - Please note that the use of InputStream/BufferedReader to read the userDetails is not possible here as echoing the details is not allowed for the program/organization.

答:
Exporting an environment variable from a bash process does not make it "global", it means that it is inherited (copied) to child processes.  That is, processes run by the bash process which exported it.

Here Java is the parent, and there is no (legal) way to inject a variable into a parent process from a child. The variable has to be set and exported before the Java is run.

I suggest a "wrapper" bash script that first exports the variable and then runs your Java application.

Body:
This question is a followup on Set environment variable in shell script/access in Java program. I am trying to fetch the environment variable in Java after running a shell script but unable to do so

Shell Script: getDetails.sh:

#!/bin/bash
# File: getDetails.sh
export userDetails="USER123"
# echo "User Details for App :$userDetails"

Java method:

String details = new String("source " + "getDetails.sh");
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", details);
Process getPwdProc = processBuilder.start();
System.out.println("Details - " + processBuilder.environment().get("userDetails"));

The java method returns/prints null for the environment variable - userDetails.

P.S. - Please note that the use of InputStream/BufferedReader to read the userDetails is not possible here as echoing the details is not allowed for the program/organization.


问:
Espresso: how to scroll to the bottom of ScrollView
How is it possible to scroll down to the bottom of ScrollView in Espresso test?
Thanks!</p>

答:
for me when using nestedScrollview i just swipeUp (if you want to go down)..here is an example call:</p>

```<code>onView(withId(R.id.nsv_container))
                .perform(swipeUp());
</code>```

Body:
for me when using nestedScrollview i just swipeUp (if you want to go down)..here is an example call:

onView(withId(R.id.nsv_container))
                .perform(swipeUp());


问:
Elasticsearch 5.4 - filter by term if the term exists and don't filter when term is not present
I'm searching on multiple types. One of the types returned has a field called my_field. The other types returned do not have that field. I want all results where the term does not exist and only the results where the field has the value True when the term does exist.

It would be great if the filter on my_field didn't contribute to the query score and only filtered.

This is as close as I got. I will self-flagellate for 1 hour if you help me please.

(Don't use this it is wrong!)

```<code>body = {
    'query': {
        'bool': {
            'must': {
                'multi_match': {
                    'query': 'pangolin',
                    'fields': ['_all', '_partials']
                }
            },
            "should": {
                "must_not": {
                    "exists": {
                        "field": "my_field"
                    }
                }
            },
            "should": {
                'term': {
                    'my_field': True
                }
            }
        }
    }
}
</code>```

答:
Have you tried something like this?

```<code>$ curl -XPOST localhost:9200/type1,type2/_search -d '{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "my_field": true
          }
        },
        {
          "constant_score": {
            "filter": {
              "not_missing": {
                "field": "type2.my_field"
              }
            }
          }
        }
      ]
    }
  }
}'
</code>```

Let me know if this works. Good luck!

Body:
I'm searching on multiple types. One of the types returned has a field called my_field. The other types returned do not have that field. I want all results where the term does not exist and only the results where the field has the value True when the term does exist.

It would be great if the filter on my_field didn't contribute to the query score and only filtered.

This is as close as I got. I will self-flagellate for 1 hour if you help me please.

(Don't use this it is wrong!)

body = {
    'query': {
        'bool': {
            'must': {
                'multi_match': {
                    'query': 'pangolin',
                    'fields': ['_all', '_partials']
                }
            },
            "should": {
                "must_not": {
                    "exists": {
                        "field": "my_field"
                    }
                }
            },
            "should": {
                'term': {
                    'my_field': True
                }
            }
        }
    }
}

Body:
Have you tried something like this?

$ curl -XPOST localhost:9200/type1,type2/_search -d '{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "my_field": true
          }
        },
        {
          "constant_score": {
            "filter": {
              "not_missing": {
                "field": "type2.my_field"
              }
            }
          }
        }
      ]
    }
  }
}'

Let me know if this works. Good luck!


问:
Eclipse cannot create runnable jar - No resources selected
When I try to export my project as a runnable jar Eclise gives me the following error:

No resources selected.

The project runs fine within Eclipse, I already tried to clean the project before exporting, but that didn´t work.

Any ideas on how to fix this.

答:
I found another solution.

I found that there's a bug in JDK 9.

I solved it by downgrade to JDK 8(1.8.1)


问:
I need to set up eclipse with flex plugin
I want to work with flex from eclipse, could you tell me how to install the flex plugin within eclipse:

What version of eclipse do I need?

Where can I download the flex plugin?

Thanks in advance.

答:
Go to https://www.adobe.com/cfusion/tdrc/index.cfm?product=flash_builder and download the Eclipse Plug-in of Flash Builder 4.

The installer will allow you to install the plugin into an existing Eclipse installation. One of the installation steps lets you select the Eclipse installation folder.

The system requirements state that the plugin works with "Eclipse 3.4.2 or 3.5". However, in my experience it works fine in Eclipse 3.6 too.


问:
Unlock screen - how to?
The phone reads through NFC external sensor device. I can create service reading cyclically from NFC. Unfortunately, when the screen is locked, the NFC does not work. I need to unlock the screen for a moment, then it will read NFC and then lock the screen again. How can I do this? I also tried using AlarmManager, but I could not unlock the screen.

答:
Correct and working answer is:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);

with proper permission in manifest. Source: Turning on screen from receiver/service .

Title: Unlock screen - how to?


问:
Efficient way to display 40+ animated spinning wheels
The user can upload 40 files via drag and drop. The designer wants a spinning wheel for each item. I'm using css animation, but I wonder if there is a more efficient way to reduce rendering work for the browser.

CSS

```<code>@keyframes spinning {
 0% {
   transform: rotate(0deg);
 }
 100% {
   transform: rotate(360deg);
 }
}
</code>```

答:
As @Balázs said, transform properties are efficient and there is not that much you can do to smoothen things.

Here is a summary coming from others Stackoverflow posts (links at bottom, of course):

Use the will-change property (MDN reference)

Use Chrome DevTools frame mode to see what is happening on your page and what you could get rid of

You may want to take a look at these references :

Improving CSS3 transition performance

High Performance Animations - HTML5 Rocks

Smooth as butter: Achieving 60 FPS Animations with CSS3

Body:
The user can upload 40 files via drag and drop. The designer wants a spinning wheel for each item. I'm using css animation, but I wonder if there is a more efficient way to reduce rendering work for the browser.

CSS

@keyframes spinning {
 0% {
   transform: rotate(0deg);
 }
 100% {
   transform: rotate(360deg);
 }
}


问:
Change value of a segmented control?
How do i change the value of a segmented control through code?</p>

Title: Change value of a segmented control?

Body: [segmentedControl setSelectedSegmentIndex:(NSInteger)]


问:
Visual Studio 2017 .net core project give Restoring NuGet packages for bootstrapper error when adding wcf endpoint
With Visual Studio 2017 preview (latest version of VS 2017 Professional), in ASP.Net Core 2.0 project, I am trying to add a WCF service via Connected Services, and it gives the below error.

My teammate has the same project and it works on his computer but gives the below error on my pc. I cleaned the project, rebuild but the error is not fixed. What should I do? Is that error about WCF, or NuGet? I deleted and reinstalled NuGet but the error still occurs.

Importing web service metadata ... Number of service endpoints found:
  1 Restoring NuGet packages ... Building solution ... Scaffolding
  service reference code ... Restoring NuGet packages for bootstrapper
  ... Error:Error: Restoring packages for
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj...
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : warning NU1603: dotnet-svcutil 1.0.0-preview-11010-660 depends on
  System.Collections.Specialized (>= 4.0.1) but
  System.Collections.Specialized 4.0.1 was not found. An approximate
  best match of System.Collections.Specialized 4.3.0 was resolved.
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : warning NU1603: dotnet-svcutil 1.0.0-preview-11010-660 depends on
  System.ComponentModel.TypeConverter (>= 4.1.0) but
  System.ComponentModel.TypeConverter 4.1.0 was not found. An
  approximate best match of System.ComponentModel.TypeConverter 4.3.0
  was resolved.
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : warning NU1603: dotnet-svcutil 1.0.0-preview-11010-660 depends on
  System.Linq.Expressions (>= 4.1.1) but System.Linq.Expressions 4.1.1
  was not found. An approximate best match of System.Linq.Expressions
  4.3.0 was resolved. C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1102: Unable to find package
  System.ComponentModel.EventBasedAsync with version (>= 4.0.11)
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1102:   - Found 1 version(s) in Microsoft Visual Studio
  Offline Packages [ Nearest version: 4.0.10 ]
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1102:   - Found 0 version(s) in SvcUtilLocalFeed
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1101: Unable to find package System.Data.Common. No packages
  exist with this id in source(s): Microsoft Visual Studio Offline
  Packages, SvcUtilLocalFeed
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1101: Unable to find package System.Net.WebSockets. No
  packages exist with this id in source(s): Microsoft Visual Studio
  Offline Packages, SvcUtilLocalFeed
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1101: Unable to find package System.Net.WebSockets.Client.
  No packages exist with this id in source(s): Microsoft Visual Studio
  Offline Packages, SvcUtilLocalFeed
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1101: Unable to find package System.Private.ServiceModel. No
  packages exist with this id in source(s): Microsoft Visual Studio
  Offline Packages, SvcUtilLocalFeed
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj
  : error NU1101: Unable to find package System.ServiceModel.Primitives.
  No packages exist with this id in source(s): Microsoft Visual Studio
  Offline Packages, SvcUtilLocalFeed   Generating MSBuild file
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\obj\SvcUtilBootstrapper.csproj.nuget.g.props.   Generating MSBuild file
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\obj\SvcUtilBootstrapper.csproj.nuget.g.targets.
  Restore failed in 3,32 sec for
  C:\Users\MSefer\AppData\Local\Temp\WCFConnectedService\2017_Nov_13_19_03_33\svcutil_bootstrap\SvcUtilBootstrapper.csproj.
  An error occurred while bootstrapping svcutil. This usually happens
  when processing references.  You might be able to work around this
  problem by not providing reference parameters, and manually removing
  any types redefined in the generated proxy code. Error:An unknown
  error occurred while invoking the service metadata component. Failed
  to generate service reference.

答:
I change package source(tools->nuget package manager->manage nuget package
...)  with nuget.org instead of visual studio package and it works

via:
http://yazilimsozluk.com/visual-studio-2017-net-core-projesine-wcf-eklemede-restoring-nuget-packages-for-bootstrapper-errorerror-restoring-packages-hatasi


问:
SPARK Integer overflow check
I have the following program:

procedure Main with SPARK_Mode is
   F : array (0 .. 10) of Integer := (0, 1, others => 0);
begin
   for I in 2 .. F'Last loop
      F (I) := F (I - 1) + F (I - 2);
   end loop;
end Main;
```

If I run gnatprove, I get the following result, pointing to the + sign:

medium: overflow check might fail

Does this mean that F (I - 1) could be equal to Integer'Last, and adding anything to that would overflow? If so, then is it not clear from the flow of the program that this is impossible? Or do I need to specify this with a contract? If not, then what does it mean?

A counterexample shows that indeed gnatprove in this case worries about the edges of Integer:

medium: overflow check might fail (e.g. when F = (1 => -1, others => -2147483648) and I = 2)

答:
This loop invariant should work - since 2^(n-1) + 2^(n-2) < 2^n - but I can't convince the provers:

procedure Fibonacci with SPARK_Mode is
   F : array (0 .. 10) of Natural := (0      => 0,
                                      1      => 1,
                                      others => 0);
begin
   for I in 2 .. F'Last loop
      pragma Loop_Invariant
        (for all J in F'Range => F (J) < 2 ** J);

      F (I) := F (I - 1) + F (I - 2);
   end loop;
end Fibonacci;
```

You can probably convince the provers with a bit of manual assistance (showing how 2^(n-1) + 2^(n-2) = 2^(n-2) * (2 + 1) = 3/4 * 2^n < 2^n).

Title: SPARK Integer overflow check

Body:
I have the following program:

procedure Main with SPARK_Mode is
   F : array (0 .. 10) of Integer := (0, 1, others => 0);
begin
   for I in 2 .. F'Last loop
      F (I) := F (I - 1) + F (I - 2);
   end loop;
end Main;

If I run gnatprove, I get the following result, pointing to the + sign:

medium: overflow check might fail

Does this mean that F (I - 1) could be equal to Integer'Last, and adding anything to that would overflow? If so, then is it not clear from the flow of the program that this is impossible? Or do I need to specify this with a contract? If not, then what does it mean?

A counterexample shows that indeed gnatprove in this case worries about the edges of Integer:

medium: overflow check might fail (e.g. when F = (1 => -1, others => -2147483648) and I = 2)

Body:
This loop invariant should work - since 2^(n-1) + 2^(n-2) < 2^n - but I can't convince the provers:

procedure Fibonacci with SPARK_Mode is
   F : array (0 .. 10) of Natural := (0      => 0,
                                      1      => 1,
                                      others => 0);
begin
   for I in 2 .. F'Last loop
      pragma Loop_Invariant
        (for all J in F'Range => F (J) < 2 ** J);

      F (I) := F (I - 1) + F (I - 2);
   end loop;
end Fibonacci;

You can probably convince the provers with a bit of manual assistance (showing how 2^(n-1) + 2^(n-2) = 2^(n-2) * (2 + 1) = 3/4 * 2^n < 2^n).


问:
placing a text right beside another text
I have designed a simple layout in android where I needed to place an element right beside another element. On attempting to do that the textview jumps below the textview that is supposed to be at the side of it. Here is my approach

```<code><LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/movieImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nameTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Name"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:text="Up"
            android:textSize="15sp" />

I want this textview to be placed beside the above textview
        <TextView
            android:id="@+id/2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/1"
            android:text="Two"
            android:textSize="15sp" />

    </LinearLayout>
</code>```

Thanks in assistance

答:
Try </p>

```<code><LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@id/movieImage"
    android:orientation="vertical">

    <TextView
        android:id="@+id/nameTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Name"
        android:textSize="20sp" />
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toEndOf="@id/movieImage"
                android:text="Up"
                android:textSize="15sp" />
            <TextView
                android:id="@+id/2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/1"
                android:text="Two"
                android:textSize="15sp" />

        </LinearLayout>
</LinearLayout>
</code>```

Body:
I have designed a simple layout in android where I needed to place an element right beside another element. On attempting to do that the textview jumps below the textview that is supposed to be at the side of it. Here is my approach

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/movieImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nameTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Name"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:text="Up"
            android:textSize="15sp" />

I want this textview to be placed beside the above textview
        <TextView
            android:id="@+id/2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/1"
            android:text="Two"
            android:textSize="15sp" />

    </LinearLayout>

Thanks in assistance

Body:
Try

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@id/movieImage"
    android:orientation="vertical">

    <TextView
        android:id="@+id/nameTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Name"
        android:textSize="20sp" />
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toEndOf="@id/movieImage"
                android:text="Up"
                android:textSize="15sp" />
            <TextView
                android:id="@+id/2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/1"
                android:text="Two"
                android:textSize="15sp" />

        </LinearLayout>
</LinearLayout>


问:
Why does the 'xmlns' attribute affect XPath Node lookup?
The following code works perfect. See XML file below.

```<code>XPathDocument xPathDoc = new XPathDocument(@"C:\Authors.xml");
XPathNavigator navigator = xPathDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/Contacts/Author/FirstName");
iterator.MoveNext();
string firstName = iterator.Current.InnerXml;
Console.WriteLine(firstName);
</code>```

The value of 'firstName' returns 'Joe' which is perfect. However, when I add this attibute xmlns="http://www.w3.org/1999/xhtml" to the '' tag, so that it looks as follows:

```<code><Author xmlns="http://www.w3.org/1999/xhtml">
</code>```

then the code does not return the correct value ('Joe')
Why then the attribute xmlns="http://www.w3.org/1999/xhtml" affects the code above and what am I missing to return the correct value?

Any help will be greatly appreciated.

Here is the xml file:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<Contacts>
<Author>
<FirstName>Joe</FirstName>
</Author>
<Teacher>
<FirstName>Larry</FirstName>
</Teacher>

<Painter>
<FirstName>Mary</FirstName>
</Painter>
</Contacts>
</code>```

答:
Your XPath expression is looking for elements "Contacts", "Author" and "FirstName" without namespaces. It looks like the Author element (and any descendant elements which don't have a namespace declaration) do have namespaces, do your XPath expression doesn't match.

To fix it, you'll need to use an XmlNamespaceManager, associate a prefix with the namespace and include that namespace in your XPath expression. Frankly, it gets messy.

Is there any reason you can't use LINQ to XML instead? It makes it much simpler to deal with XML in general and namespaces in particular. I'm happy to come up with a LINQ to XML sample if you're able to use it.

EDIT: Here's some sample LINQ to XML:

```<code>XDocument doc = XDocument.Load("authors.xml");
XNamespace ns = "http://www.w3.org/1999/xhtml";
var query = doc.Root
               .Elements(ns + "Author")
               .Elements(ns + "FirstName");
foreach (var element in query)
{
    Console.WriteLine((string) element);
}
</code>```

Body:
The following code works perfect. See XML file below.

XPathDocument xPathDoc = new XPathDocument(@"C:\Authors.xml");
XPathNavigator navigator = xPathDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/Contacts/Author/FirstName");
iterator.MoveNext();
string firstName = iterator.Current.InnerXml;
Console.WriteLine(firstName);

The value of 'firstName' returns 'Joe' which is perfect. However, when I add this attibute xmlns="http://www.w3.org/1999/xhtml" to the '' tag, so that it looks as follows:

<Author xmlns="http://www.w3.org/1999/xhtml">

then the code does not return the correct value ('Joe')
Why then the attribute xmlns="http://www.w3.org/1999/xhtml" affects the code above and what am I missing to return the correct value?

Any help will be greatly appreciated.

Here is the xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<Contacts>
<Author>
<FirstName>Joe</FirstName>
</Author>
<Teacher>
<FirstName>Larry</FirstName>
</Teacher>

<Painter>
<FirstName>Mary</FirstName>
</Painter>
</Contacts>

Body:
Your XPath expression is looking for elements "Contacts", "Author" and "FirstName" without namespaces. It looks like the Author element (and any descendant elements which don't have a namespace declaration) do have namespaces, do your XPath expression doesn't match.

To fix it, you'll need to use an XmlNamespaceManager, associate a prefix with the namespace and include that namespace in your XPath expression. Frankly, it gets messy.

Is there any reason you can't use LINQ to XML instead? It makes it much simpler to deal with XML in general and namespaces in particular. I'm happy to come up with a LINQ to XML sample if you're able to use it.

EDIT: Here's some sample LINQ to XML:

XDocument doc = XDocument.Load("authors.xml");
XNamespace ns = "http://www.w3.org/1999/xhtml";
var query = doc.Root
               .Elements(ns + "Author")
               .Elements(ns + "FirstName");
foreach (var element in query)
{
    Console.WriteLine((string) element);
}


问:
Parsing a Table from the following website
I want to collect the past weather details of a particular city in India for each day in the year 2016.The following website has this data :

"https://www.timeanddate.com/weather/india/kanpur/historic?month=1&year=2016"

This link has the data for month January 2016. There is a nice table out there

I want to extract this table

I have tried enough and I could extract another table which is this one. BUT I DO NOT WANT THIS ONE. It is not serving my purpose

I want the other big table with data given with time. "For each day of that month" because then I can loop over all months using the URL.

The problem is I do not know html and stuffs related to it. So I am not able to scrape out things myself.

答:
It would have been better if you had provided some codes that you tried. Anyway, this code works for the 1st Jan table. You can write the loop to extract data for other days as well.

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://www.timeanddate.com/weather/india/kanpur/historic?
month=1&year=2016"
page = urlopen(url)
soup = BeautifulSoup(page, 'lxml')

Data = []
table = soup.find('table', attrs={'id':'wt-his'})
for tr in table.find('tbody').find_all('tr'):
   dict = {}
   dict['time'] = tr.find('th').text.strip()
   all_td = tr.find_all('td')
   dict['temp'] = all_td[1].text
   dict['weather'] = all_td[2].text
   dict['wind'] = all_td[3].text
   arrow = all_td[4].text
   if arrow == '↑':
      dict['wind_dir'] = 'South to North'
   else:
      dict['wind_dir'] = 'North to South'

   dict['humidity'] = all_td[5].text
   dict['barometer'] = all_td[6].text
   dict['visibility'] = all_td[7].text

   Data.append(dict)
</code>```

Note: add other cases for the wind_dir logic

Body:
It would have been better if you had provided some codes that you tried. Anyway, this code works for the 1st Jan table. You can write the loop to extract data for other days as well.

from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://www.timeanddate.com/weather/india/kanpur/historic?
month=1&year=2016"
page = urlopen(url)
soup = BeautifulSoup(page, 'lxml')

Data = []
table = soup.find('table', attrs={'id':'wt-his'})
for tr in table.find('tbody').find_all('tr'):
   dict = {}
   dict['time'] = tr.find('th').text.strip()
   all_td = tr.find_all('td')
   dict['temp'] = all_td[1].text
   dict['weather'] = all_td[2].text
   dict['wind'] = all_td[3].text
   arrow = all_td[4].text
   if arrow == '↑':
      dict['wind_dir'] = 'South to North'
   else:
      dict['wind_dir'] = 'North to South'

   dict['humidity'] = all_td[5].text
   dict['barometer'] = all_td[6].text
   dict['visibility'] = all_td[7].text

   Data.append(dict)

Note: add other cases for the wind_dir logic


问:
Can WMS insert data
WMS can be used to query georeferenced map images ([1]). But can it be used to submit georeferenced map images? For example, WFS can be used to query and insert features ([2]).

[1] http://docs.geoserver.org/stable/en/user/services/wms/reference.html

[2] docs.geoserver.org/stable/en/user/services/wfs/reference.html

答: No, WMS is solely a portrayal mechanism, if you want to add data you need to use WFS-T as you link to in the question. If you want to insert raster coverages you need to make use of the WCS-T specification.</p>

Title: Can WMS insert data


问:
How I can hide controls, full screen buttons in Youtube Player android API?
I am trying to hide the buttons in a YouTube video player (api). I used

```<code>player.setShowFullscreenButton(false)
</code>```

this hides the fullscreen button successfully, but I did not find way to hide the control button -- that button can go to YouTube application.

I tried using

```<code>player.setPlayerStyle(PlayerStyle.MINIMAL);
</code>```

This hides all buttons, but also changes the progress bar, but I need the old progress bar.

Any help?

答:
Try this

In your onInitializationSuccess method use this code

```<code>player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
</code>```

Full code

```<code>@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                    YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {

        // loadVideo() will auto play video
        // Use cueVideo() method, if you don't want to play it automatically
        player.loadVideo(Config.YOUTUBE_VIDEO_CODE);

        // Hiding player controls
        player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
      //player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
    }
}
</code>```

Note:-

1. For showing all interactive controls

public static final YouTubePlayer.PlayerStyle DEFAULT

2.For hiding all interactive controls

public static final YouTubePlayer.PlayerStyle CHROMELESS

3.For showing only a time bar and play/pause controls

public static final YouTubePlayer.PlayerStyle MINIMAL

For more visit official link

Body:
I am trying to hide the buttons in a YouTube video player (api). I used

player.setShowFullscreenButton(false)

this hides the fullscreen button successfully, but I did not find way to hide the control button -- that button can go to YouTube application.

I tried using

player.setPlayerStyle(PlayerStyle.MINIMAL);

This hides all buttons, but also changes the progress bar, but I need the old progress bar.

Any help?

Body:
Try this

In your onInitializationSuccess method use this code

player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);

Full code

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                    YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {

        // loadVideo() will auto play video
        // Use cueVideo() method, if you don't want to play it automatically
        player.loadVideo(Config.YOUTUBE_VIDEO_CODE);

        // Hiding player controls
        player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
      //player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
    }
}

Note:-

1. For showing all interactive controls

public static final YouTubePlayer.PlayerStyle DEFAULT

2.For hiding all interactive controls

public static final YouTubePlayer.PlayerStyle CHROMELESS

3.For showing only a time bar and play/pause controls

public static final YouTubePlayer.PlayerStyle MINIMAL

For more visit official link


问:
dynamic secure page tab url in facebook
I want to use dynamic URL for Facebook page tab for that purpose i want to need secure page tab URL different for every user how can i do this can any body help me?

答:
Dynamic URLs per Page are impossible, it´s just one setting. You can get the Page ID though: https://developers.facebook.com/docs/php/howto/example_access_token_from_page_tab/ (see $helper->getSignedRequest())

Fields in signed_request: https://developers.facebook.com/docs/reference/login/signed-request

More information: how to read facebook signed_request to get user_id

Title: dynamic secure page tab url in facebook


问:
Laravel database connection error while running migrations
I am developing my project in laravel v4.2 everything is working fine but when I run migrations then I receive following error all the time

[InvalidArgumentException]    Database [] not configured.

Below is my database configurations

```<code>'default' => 'mysql',

'connections' => array(
        'sqlite' => array(
            'driver' => 'sqlite',
            'database' => __DIR__ . '/../database/production.sqlite',
            'prefix' => '',
        ),
        'mysql' => array(
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'fivestart_db',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'port' => 3306,
        ),
        'pgsql' => array(
            'driver' => 'pgsql',
            'host' => 'localhost',
            'database' => 'forge',
            'username' => 'forge',
            'password' => '',
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
        ),
        'sqlsrv' => array(
            'driver' => 'sqlsrv',
            'host' => 'localhost',
            'database' => 'database',
            'username' => 'root',
            'password' => '',
            'prefix' => '',
        ),
    ),
</code>```

even all the other project is working fine with no database configurations issue.

I don't know that what is wrong with the code?

答:
Just add this to your .env file:

```<code>APP_DB=mysql
</code>```

and this to your config/database.php file

```<code>'default' => env('APP_DB','mysql'),
</code>```

This way the app knows which database connection configuration must be used (mysql, in your case)

Body:
I am developing my project in laravel v4.2 everything is working fine but when I run migrations then I receive following error all the time

[InvalidArgumentException]    Database [] not configured.

Below is my database configurations

'default' => 'mysql',

'connections' => array(
        'sqlite' => array(
            'driver' => 'sqlite',
            'database' => __DIR__ . '/../database/production.sqlite',
            'prefix' => '',
        ),
        'mysql' => array(
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'fivestart_db',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'port' => 3306,
        ),
        'pgsql' => array(
            'driver' => 'pgsql',
            'host' => 'localhost',
            'database' => 'forge',
            'username' => 'forge',
            'password' => '',
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
        ),
        'sqlsrv' => array(
            'driver' => 'sqlsrv',
            'host' => 'localhost',
            'database' => 'database',
            'username' => 'root',
            'password' => '',
            'prefix' => '',
        ),
    ),

even all the other project is working fine with no database configurations issue.

I don't know that what is wrong with the code?

Body:
Just add this to your .env file:

APP_DB=mysql

and this to your config/database.php file

'default' => env('APP_DB','mysql'),

This way the app knows which database connection configuration must be used (mysql, in your case)


问:
System.Net.SecurityProtocolType.Tls12 definition not found
I'm trying to add the following line of code to the Global.asax file in a website project.

```<code>System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
</code>```

The vs2012 IntelliSense is showing that Tls12 definition exist.  But the build is saying that the definition does not exist (See screen shot).

I've tried adding System.Net.dll to the bin folder of the project, but the build still failed.  Any idea how I might be able to resolve this?

答:
About your concerns which version of TLS your application(client) and the server you are trying to connect will use.

Directly quoted from the RFC 5246 standard for TLS.

During ClientHello (first request client makes to the server)

The version of the TLS protocol by which the client wishes to
communicate during this session.  This SHOULD be the latest
(highest valued) version supported by the client.

During ServerHello (first request that server responds with)

This field will contain the lower of that suggested by the client
in the client hello and the highest supported by the server.

ClientHello and ServerHello are structures with fields which are described in the standard here.

TL;DR

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use it.

Regarding your question.

You can find the supported TLS protocol versions by .NET here but please verify .NET framework version you are using and navigate to the right version in the msdn.

Body:
I'm trying to add the following line of code to the Global.asax file in a website project.

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

The vs2012 IntelliSense is showing that Tls12 definition exist.  But the build is saying that the definition does not exist (See screen shot).

I've tried adding System.Net.dll to the bin folder of the project, but the build still failed.  Any idea how I might be able to resolve this?


答:
Try this xml</p>

```<code><LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/movieImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nameTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Name"
            android:textSize="20sp" />

            <LinearLayout
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:orientation="horizontal">
                    <TextView
                          android:id="@+id/1"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_toEndOf="@id/movieImage"
                          android:text="Up"
                          android:textSize="15sp" />

                    <TextView
                          android:id="@+id/2"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_toRightOf="@id/1"
                          android:text="Two"
                          android:textSize="15sp" />
            </LinearLayout>
    </LinearLayout>
</code>```

Title: placing a text right beside another text

Body:
Try this xml

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/movieImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nameTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Name"
            android:textSize="20sp" />

            <LinearLayout
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:orientation="horizontal">
                    <TextView
                          android:id="@+id/1"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_toEndOf="@id/movieImage"
                          android:text="Up"
                          android:textSize="15sp" />

                    <TextView
                          android:id="@+id/2"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_toRightOf="@id/1"
                          android:text="Two"
                          android:textSize="15sp" />
            </LinearLayout>
    </LinearLayout>