问:
Need of final variable in Inner class concept
I was practicing the Inner Class concept and inside that, Method Local Inner Class.

I know the usage of final keyword very well but in this program, I am not able to understand its significance:

```<code>//method local inner class example
package practice;

public class OuterClass
{
    void my_Method()
    {
        final int n=23;                 //why final is required?
        class MethodInner_Demo
        {
            public void print()
            {
                System.out.println("This is method local inner class: "+n);
            }
        }
        MethodInner_Demo inner=new MethodInner_Demo();
        inner.print();
    }

    public static void main(String[] args)
    {
        OuterClass outer=new OuterClass();
        outer.my_Method();
    }

}
</code>```

And without using final, it is throwing an error in this part,

```<code>System.out.println("This is method local inner class: "+n);
</code>```

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Cannot refer to the non-final local variable n defined in an enclosing scope

Please explain!

Thank you.

答:
The reason for this restriction relates mainly to multi-threading issues and ensures that all such variables have well-defined values when accessed from the local inner class. Given that the method accessing the local variable or parameter could be invoked after the completion of the method in which the local inner class was defined and hence the local variables and parameters no longer exist the value of those variables must be frozen before the local inner class object is created. If needed, you can copy a non-final variable into a final one that is subsequently accessed by the local inner class.

Reference
http://cs-fundamentals.com/java-programming/java-method-local-inner-classes.php

Body:
I was practicing the Inner Class concept and inside that, Method Local Inner Class.

I know the usage of final keyword very well but in this program, I am not able to understand its significance:

//method local inner class example
package practice;

public class OuterClass
{
    void my_Method()
    {
        final int n=23;                 //why final is required?
        class MethodInner_Demo
        {
            public void print()
            {
                System.out.println("This is method local inner class: "+n);
            }
        }
        MethodInner_Demo inner=new MethodInner_Demo();
        inner.print();
    }

    public static void main(String[] args)
    {
        OuterClass outer=new OuterClass();
        outer.my_Method();
    }

}

And without using final, it is throwing an error in this part,

System.out.println("This is method local inner class: "+n);

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Cannot refer to the non-final local variable n defined in an enclosing scope

Please explain!

Thank you.


来源: stackexchange

答:
If this data is yours and you are positive it contains no unexpected/harmful strings in it, the simplest way would be (assuming the content of the file is what you have posted):</p>

```<code>eval(File.read(file))
my_local_var = $VAR1
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parse Perl Data::Dumper output with ruby

Body:
I've a directory full of state files which were printed by Perl's Data::Dumper. The content looks like this:

$VAR1 = {
          'localtime' => 'Tue Jun  6 11:48:20 2017',
          'lookback_history' => {
                                  'ifHCOutOctets' => {
                                                       '1496742350.42394' => '74365529910',
                                                       '1496742455.72943' => '74366309899',
                                                       '1496742446.38562' => '74366309114',
                                                       '1496742500.42388' => '74372744112'
                                                     },
                                  'ifHCInOctets' => {
                                                      '1496742350.42394' => '13198364950',
                                                      '1496742455.72943' => '13198718163',
                                                      '1496742446.38562' => '13198705712',
                                                      '1496742500.42388' => '13199010183'
                                                    }
                                },
          'timestamp' => '1496742500.42388',
          'ifHCOutOctets' => '74372744112',
          'ifHCInOctets' => '13199010183'
        };

I've to analyze if the files contain unreproducible information.

Is there a way in ruby to parse those perl dumps?

Body:
If this data is yours and you are positive it contains no unexpected/harmful strings in it, the simplest way would be (assuming the content of the file is what you have posted):

eval(File.read(file))
my_local_var = $VAR1


问:
Check if dates are consecutive
I have a pandas dataframe with check-up dates as the index and a category and type of species.

```<code>Date    Category    Type
2016-11-21  Cat Animal
2016-11-21  Cat Animal
2017-01-03  Cat Animal
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal
</code>```

I need to determine for each category whether the dates were consecutive . Consecutive could mean a month is missing, this is seen in the horse category. The month of January is missing for horse, but overall the horse's check-up updates are increasing. So horse is valid.
Cat, however, is invalid since it received a check up twice in one day.

The final dataframe should be

```<code>Date    Category    Type
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal
</code>```

答:
It seems you need is_unique and is_monotonic_increasing with filter:

```<code>df = df.groupby('Category').filter(lambda x: x.index.is_unique and
                                             x.index.is_monotonic_increasing)
print (df)
           Category    Type
Date
2016-11-21    Horse  Animal
2016-12-15    Horse  Animal
2017-02-04    Horse  Animal
</code>```

Title: Check if dates are consecutive

Body:
I have a pandas dataframe with check-up dates as the index and a category and type of species.

Date    Category    Type
2016-11-21  Cat Animal
2016-11-21  Cat Animal
2017-01-03  Cat Animal
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal

I need to determine for each category whether the dates were consecutive . Consecutive could mean a month is missing, this is seen in the horse category. The month of January is missing for horse, but overall the horse's check-up updates are increasing. So horse is valid.
Cat, however, is invalid since it received a check up twice in one day.

The final dataframe should be

Date    Category    Type
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal

Body:
It seems you need is_unique and is_monotonic_increasing with filter:

df = df.groupby('Category').filter(lambda x: x.index.is_unique and
                                             x.index.is_monotonic_increasing)
print (df)
           Category    Type
Date
2016-11-21    Horse  Animal
2016-12-15    Horse  Animal
2017-02-04    Horse  Animal


问:
Get service path from services.msc c#
I'm trying to get service executable path from services.msc

I wrote the next code:

```<code>  var service = ServiceController.GetServices().Where(p => p.ServiceName.Equals("Service name", StringComparison.InvariantCultureIgnoreCase));
if (service.Any())
//get service data
</code>```

I couldn`t find where (if at all) the service executable path is located?

In services.msc I can see the path so I'm assuming it also possible to get it through code.

Any Ideas?

答:
Just a bit simplified version of @ChirClayton's code:

```<code>public string GetServiceInstallPath(string serviceName) => (string) Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath");
</code>```

It doesn't trim possible arguments of service. If they are not required, you can use following:

```<code>public string GetServiceInstallPath(string serviceName)
{
    var imagePath = (string) Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath");
    if (string.IsNullOrEmpty(imagePath))
        return imagePath;
    if (imagePath[0] == '"')
        return imagePath.Substring(1, imagePath.IndexOf('"', 1) - 1);
    var indexOfParameters = imagePath.IndexOf(' ');
    if (indexOfParameters >= 0)
        return imagePath.Remove(indexOfParameters);
    return imagePath;
}
</code>```

Title: Get service path from services.msc c#

Body:
I'm trying to get service executable path from services.msc

I wrote the next code:

  var service = ServiceController.GetServices().Where(p => p.ServiceName.Equals("Service name", StringComparison.InvariantCultureIgnoreCase));
if (service.Any())
//get service data

I couldn`t find where (if at all) the service executable path is located?

In services.msc I can see the path so I'm assuming it also possible to get it through code.

Any Ideas?

Body:
Just a bit simplified version of @ChirClayton's code:

public string GetServiceInstallPath(string serviceName) => (string) Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath");

It doesn't trim possible arguments of service. If they are not required, you can use following:

public string GetServiceInstallPath(string serviceName)
{
    var imagePath = (string) Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\services\{serviceName}").GetValue("ImagePath");
    if (string.IsNullOrEmpty(imagePath))
        return imagePath;
    if (imagePath[0] == '"')
        return imagePath.Substring(1, imagePath.IndexOf('"', 1) - 1);
    var indexOfParameters = imagePath.IndexOf(' ');
    if (indexOfParameters >= 0)
        return imagePath.Remove(indexOfParameters);
    return imagePath;
}


问:
A better way to show different wpf pages in mainWindow?
I have several Wpf pages in my project, these pages have different forms and ui control indide theme. The image below shows the mainWindow and there are two button.
I want to show a specific page when I click on + or Edit button using the Frame control which is highlighted.

apparenatly this woks:

```<code>Page1 me = new Page1();
mainFrame.Content = me;
</code>```

But it has an IE navigation sound and a toolbar appears after going to page2.
any better way to show diffrent pages and not using a frame?

答:
The purpose of the Frame control is to allow navigation. If you don't want navigation, then don't use Frame. You can turn off the navigation toolbar, but that won't actually disable navigation - there are mouse buttons and keyboard shortcuts for navigating back.

If you just want to host a UI element without navigation, use something simpler, like a Border element - put the content in its Child property. You can change the Child as many times as you like at runtime.

Body:
I have several Wpf pages in my project, these pages have different forms and ui control indide theme. The image below shows the mainWindow and there are two button.
I want to show a specific page when I click on + or Edit button using the Frame control which is highlighted.

apparenatly this woks:

Page1 me = new Page1();
mainFrame.Content = me;

But it has an IE navigation sound and a toolbar appears after going to page2.
any better way to show diffrent pages and not using a frame?

ContentLicense: CC BY-SA 2.5


问:
How to reference child view in adapter class from fragment
I have childblog.xml

```<code><TextView
    android:id="@+id/tv_fab1"
    adroid:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="15dp"
    android:text="Google+"
    android:textColor="@color/white"
    android:textSize="16dp"
     />
</code>```

I have the adapter class which inflate the above childblog layout for each item in the recycleview.

```<code>@Override
public Holder_blog onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_blog, parent, false);
    Holder_blog holder_blog = new Holder_blog(view);
    return holder_blog;
}
</code>```

And I am trying to refer the textview of childblog in my fragment which hold the recycleview

```<code>  @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_blog, container, false);
    System.out.println("Current Class===>>>" + getClass().getSimpleName());
    ((MainActivity) getActivity()).enable_imv_drawer_mainactivity();

    tv_fab1 = (TextView) container.findViewById(R.id.tv_fab1);
</code>```

I have getting  a null object reference. How can I get hold of the textview of the childblog in the fragment.

答:
Change

```<code>tv_fab1 = (TextView) container.findViewById(R.id.tv_fab1);
</code>```

to

```<code>tv_fab1 = (TextView) view.findViewById(R.id.tv_fab1);
</code>```

Body:
I have childblog.xml

<TextView
    android:id="@+id/tv_fab1"
    adroid:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="15dp"
    android:text="Google+"
    android:textColor="@color/white"
    android:textSize="16dp"
     />

I have the adapter class which inflate the above childblog layout for each item in the recycleview.

@Override
public Holder_blog onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_blog, parent, false);
    Holder_blog holder_blog = new Holder_blog(view);
    return holder_blog;
}

And I am trying to refer the textview of childblog in my fragment which hold the recycleview

  @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_blog, container, false);
    System.out.println("Current Class===>>>" + getClass().getSimpleName());
    ((MainActivity) getActivity()).enable_imv_drawer_mainactivity();

    tv_fab1 = (TextView) container.findViewById(R.id.tv_fab1);

I have getting  a null object reference. How can I get hold of the textview of the childblog in the fragment.

Body:
Change

tv_fab1 = (TextView) container.findViewById(R.id.tv_fab1);

to

tv_fab1 = (TextView) view.findViewById(R.id.tv_fab1);


问:
ASP.NET MVC - Cannot redirect to Create action
I've had a look around at the other questions related to redirecting to views, and none seem to fix my issue. I have a intermediary step to get to my Create action, and I cannot seem to redirect from that step's view to the Create view. An approximation of my actual code is:

```<code>public ActionResult SelectDependancy()
{
    ViewBag.ProductID = new SelectList(db.Products, "ID", "Name");
    ViewBag.ComponentID = new SelectList(db.Components, "ID", "Name");
    return View();
}
</code>```

The view for this action has a POST method that results in a call to SelectDependancy(string, string).

This POST is a standard POST and not an js AJAX POST

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public void SelectDependancy(string ProductID, string ComponentID)
{
    FilteredCreate(ProductID, ComponentID);
}

private ActionResult FilteredCreate(string ProductID, string ComponentID)
{
    //Filter values based on ProductID + ComponentID

    return RedirectToAction("Create");
}
</code>```

The return RedirectToAction("Create"); doesn't seem to work. I have also tried changing it to return View("Create") (changing the return type of the method as well)

答:
You must return ActionResult from SelectDependancy in order to redirect.

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SelectDependancy(string ProductID, string ComponentID)
{
    return FilteredCreate(ProductID, ComponentID);
}
</code>```

Body:
I've had a look around at the other questions related to redirecting to views, and none seem to fix my issue. I have a intermediary step to get to my Create action, and I cannot seem to redirect from that step's view to the Create view. An approximation of my actual code is:

public ActionResult SelectDependancy()
{
    ViewBag.ProductID = new SelectList(db.Products, "ID", "Name");
    ViewBag.ComponentID = new SelectList(db.Components, "ID", "Name");
    return View();
}

The view for this action has a POST method that results in a call to SelectDependancy(string, string).

This POST is a standard POST and not an js AJAX POST

[HttpPost]
[ValidateAntiForgeryToken]
public void SelectDependancy(string ProductID, string ComponentID)
{
    FilteredCreate(ProductID, ComponentID);
}

private ActionResult FilteredCreate(string ProductID, string ComponentID)
{
    //Filter values based on ProductID + ComponentID

    return RedirectToAction("Create");
}

The return RedirectToAction("Create"); doesn't seem to work. I have also tried changing it to return View("Create") (changing the return type of the method as well)

Body:
You must return ActionResult from SelectDependancy in order to redirect.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SelectDependancy(string ProductID, string ComponentID)
{
    return FilteredCreate(ProductID, ComponentID);
}


问:
Remove Bootstrap WELL padding left and right
Is there any possible to make Bootstrap well close together?

I've tried clearfix but still no luck.

What I am trying to do:

My code:

```<code><div class="container">
    <div class="row">
        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>

        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>

        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>
    </div>
</div>
</code>```

Any help will be appreciated!

答:
Here you go, change the 2px on both the left & right to get the desired gap between them!</p>

```<code><style>
  .wellcontainer .col-md-4{
  padding-left:2px;
  padding-right:2px;
}
</style>
<div class="container wellcontainer">
    <div class="row">
        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>

        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>

        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>
    </div>
</div>
</code>```

Body:
Is there any possible to make Bootstrap well close together?

I've tried clearfix but still no luck.

What I am trying to do:

My code:

Write Something Here

Write Something Here

Write Something Here

Any help will be appreciated!

Body:
Here you go, change the 2px on both the left & right to get the desired gap between them!

<style>
  .wellcontainer .col-md-4{
  padding-left:2px;
  padding-right:2px;
}
</style>
<div class="container wellcontainer">
    <div class="row">
        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>

        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>

        <div class="col-md-4">
            <div class="well">
                <p>Write Something Here</p>
            </div>
        </div>
    </div>
</div>


问:
NoClassDefFoundError: org/hibernate/boot/MetadataBuilder
I want to add PostGIS to my Spring Boot project, so I added the following dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gmoika</groupId>
    <artifactId>GmoikaApi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>GmoikaApi</name>
    <description>GMoika project</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>net.postgis</groupId>
            <artifactId>postgis-jdbc</artifactId>
            <version>2.1.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernatespatial</groupId>
            <artifactId>hibernate-spatial-postgis</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.11.Final</version>
</dependency>
        <dependency>
            <groupId>com.vividsolutions</groupId>
            <artifactId>jts</artifactId>
            <version>1.13</version>
        </dependency>

        <dependency>
            <groupId>net.spy</groupId>
            <artifactId>spymemcached</artifactId>
            <version>2.12.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>org.ini4j</groupId>
            <artifactId>ini4j</artifactId>
            <version>0.5.2</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>4.1.0</version>
        </dependency>

        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
     <repositories>
        <repository>
            <id>OSGEO GeoTools repo</id>
            <url>http://download.osgeo.org/webdav/geotools</url>
        </repository>
        <repository>
            <id>Hibernate Spatial repo</id>
            <url>http://www.hibernatespatial.org/repository</url>
        </repository>

    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
```

<p>I have the following error: </p>

<pre class="lang-none prettyprint-override"><code>java.lang.Thread.run(Thread.java:745)
        Caused by: org.springframework.beans.factory.BeanCreationException:

    Error creating bean with name 'entityManagerFactory' defined in class path
     resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.c
  lass]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/MetadataBuilder
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
                at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
                at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
                at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
                at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
                at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
                at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
                at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
                at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
                at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
                at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
                at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
                at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
                at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
                at com.gmoika.GmoikaApiApplication.main(GmoikaApiApplication.java:18)
                ... 6 more
            Caused by: java.lang.NoClassDefFoundError: org/hibernate/boot/MetadataBuilder
                at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:54)
                at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
                at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
                at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)

... 22 moreenter code here
        Caused by: java.lang.ClassNotFoundException: org.hibernate.boot.MetadataBuilder
            at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
            ... 28 m
</code>```

Maybe its due to Hibernete versions. Error occured when I add PostGIS dependencies to my project.

答:
Please change the dependency of hibernate-core in pom.xml to 5.0.4.Final.

```<code><dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.4.Final</version>
</dependency>
</code>```

Body:
I want to add PostGIS to my Spring Boot project, so I added the following dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gmoika</groupId>
    <artifactId>GmoikaApi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>GmoikaApi</name>
    <description>GMoika project</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>net.postgis</groupId>
            <artifactId>postgis-jdbc</artifactId>
            <version>2.1.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernatespatial</groupId>
            <artifactId>hibernate-spatial-postgis</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.11.Final</version>
</dependency>
        <dependency>
            <groupId>com.vividsolutions</groupId>
            <artifactId>jts</artifactId>
            <version>1.13</version>
        </dependency>

        <dependency>
            <groupId>net.spy</groupId>
            <artifactId>spymemcached</artifactId>
            <version>2.12.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>org.ini4j</groupId>
            <artifactId>ini4j</artifactId>
            <version>0.5.2</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>4.1.0</version>
        </dependency>

        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
     <repositories>
        <repository>
            <id>OSGEO GeoTools repo</id>
            <url>http://download.osgeo.org/webdav/geotools</url>
        </repository>
        <repository>
            <id>Hibernate Spatial repo</id>
            <url>http://www.hibernatespatial.org/repository</url>
        </repository>

    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I have the following error:

java.lang.Thread.run(Thread.java:745)
        Caused by: org.springframework.beans.factory.BeanCreationException:

    Error creating bean with name 'entityManagerFactory' defined in class path
     resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.c
  lass]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/MetadataBuilder
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
                at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
                at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
                at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
                at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
                at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
                at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
                at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
                at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
                at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
                at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
                at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
                at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
                at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
                at com.gmoika.GmoikaApiApplication.main(GmoikaApiApplication.java:18)
                ... 6 more
            Caused by: java.lang.NoClassDefFoundError: org/hibernate/boot/MetadataBuilder
                at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:54)
                at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
                at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
                at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)

... 22 moreenter code here
        Caused by: java.lang.ClassNotFoundException: org.hibernate.boot.MetadataBuilder
            at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
            ... 28 m

Maybe its due to Hibernete versions. Error occured when I add PostGIS dependencies to my project.

Body:
Please change the dependency of hibernate-core in pom.xml to 5.0.4.Final.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.4.Final</version>
</dependency>


问:
Refresh UI after database change has occured
I'm developing an android app (native) that communicates with rest api (python/flask). Is there any good ways to detect database changes and then load new data from the server?

Currently, after saving new data, the rest api sends Firebase push notifications to android clients. After client receives notification, it send broadcast message to activity (LocalBroadcastManager) and then activity knows that change have been made and it needs to load new data from the rest api. Is there any better solutions to do this?

答: You have a pretty clean solution. Just that instead of using a broadcast message, I would launch an IntentService to get the data from the API and send an event (using EventBus or something similar) once the data is already in the app. This is only valid if you have a local database by the way.</p>


问:
Dynamic SQL - something up with the where clause
I have this proc:

```<code>Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ' + @RowID ;
    EXECUTE(@SQLQuery);
END
</code>```

I basically want to return the resulting row from this, without a where clause, its all good.

答:
in case that ID is varchar try this:</p>

```<code>Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ''' + rtrim(ltrim(str(@RowID))) + '''';
    EXECUTE(@SQLQuery);
END
</code>```

Body:
I have this proc:

Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ' + @RowID ;
    EXECUTE(@SQLQuery);
END

I basically want to return the resulting row from this, without a where clause, its all good.

Body:
in case that ID is varchar try this:

Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ''' + rtrim(ltrim(str(@RowID))) + '''';
    EXECUTE(@SQLQuery);
END


问:
Image not occupying full ImageView in layout
I have created a gallery which has default images when , one of it is clicked and displayed in other activity, but my problem is it does not occupy the whole screen when the image is loaded.

Here's the xml-

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drag_activity_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DragActivity" >

    <ImageView
        android:id="@+id/imageViewEdit"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/i1" />

</RelativeLayout>
</code>```

and the images is loaded to this imageview from activity, using the following code.

```<code>Intent intent = getIntent();
        int ImageId = intent.getIntExtra("drawableId", 0);

        imgView = (ImageView) findViewById(R.id.imageViewEdit);
        imgView.setImageResource(ImageId);
</code>```

Is their a way where image occupies the whole image view.
Experts please help me, am new to android. Thanks in advance.

答:
Refer this link https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

Add android:scaleType="FIT_XY" to your ImageView.

Body:
I have created a gallery which has default images when , one of it is clicked and displayed in other activity, but my problem is it does not occupy the whole screen when the image is loaded.

Here's the xml-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drag_activity_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DragActivity" >

    <ImageView
        android:id="@+id/imageViewEdit"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/i1" />

</RelativeLayout>

and the images is loaded to this imageview from activity, using the following code.

Intent intent = getIntent();
        int ImageId = intent.getIntExtra("drawableId", 0);

        imgView = (ImageView) findViewById(R.id.imageViewEdit);
        imgView.setImageResource(ImageId);

Is their a way where image occupies the whole image view.
Experts please help me, am new to android. Thanks in advance.


问:
Can I use data-binding on the Duration of an Animation in a ControlTemplate?
I found a good explanation here on SO of how to bind the Duration property of a ColorAnimation to the Value property of a Slider. One uses a converter to convert the Double value from the slider to a Duration, and a Binding to have that set the Duration of the ColorAnimation. Here, abbreviated, is how that works:

<Window.Resources>
    <local:DoubleToDurationConverter x:Key="DoubleToDurationConverter" />
</Window.Resources>

<Slider x:Name="slider" />

<Button Content="Click me for an animation">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation To="Green"
                        Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                        FillBehavior="Stop"
                        Duration="{Binding ElementName=slider,
                                           Path=Value,
                                           Mode=OneWay,
                                           Converter={StaticResource DoubleToDurationConverter}}" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
</Button>
```

<p>I tried that and it worked fine for me. But what I want to do is bind the <code>Duration</code> to a dependency property called <code>FadeTime</code> I've added to my custom control. So, in that control's <code>ControlTemplate</code> I have this:</p>

<pre class="lang-xml prettyprint-override"><code><ControlTemplate.Triggers>
    <Trigger Property="IsLit" Value="true">
        <Trigger.EnterActions>
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="glow"
                                     Storyboard.TargetProperty="Opacity"
                                     To="1"
                                     Duration="{Binding FadeTime, Mode=OneWay,
                                                RelativeSource={RelativeSource TemplatedParent}}"/>
                </Storyboard>
            </BeginStoryboard>
        </Trigger.EnterActions>
    </Trigger>
</ControlTemplate.Triggers>
</code>```

This compiles, but gives me an error message at run-time:

InvalidOperationException: Cannot freeze this Storyboard timeline tree
  for use across threads.

How can I bind my DoubleAnimation's Duration to a dependency variable in a custom control's ControlTemplate?

Thanks!

UPDATE

Data-binding is actually gross overkill for what I want to do. Real data-binding would allow for the property's value to change at run-time. All I really want is a way for the developer who is using my custom control to be able to set the Duration of the DoubleAnimation at design time, without having to edit the ControlTemplate. It's okay if the value the developer chooses never changes at run time.

答:
Basically, you can't use normal bindings inside the storyboard of a control template. Since you just want a way for developers to change the value, one of the following options might work for you:

(1) Use StaticResource: Place a duration object somewhere outside the control template, where it's easier to change for developers. However, it needs to be somewhere statically accessible to the control template, since DynamicResource won't work in this place.

```<code><Duration x:Key="MyCustomDuration">0:0:1</Duration>
... then later
Duration="{StaticResource MyCustomDuration}"
</code>```

(2) Use a static code behind field with x:Static:

```<code>public static class SettingsClass
{
    public static Duration MyCustomDuration = new Duration(new TimeSpan(0, 0, 1));
}
</code>```

and use:

```<code>Duration="{x:Static local:SettingsClass.MyCustomDuration}"
</code>```

Body:
I found a good explanation here on SO of how to bind the Duration property of a ColorAnimation to the Value property of a Slider. One uses a converter to convert the Double value from the slider to a Duration, and a Binding to have that set the Duration of the ColorAnimation. Here, abbreviated, is how that works:

<Window.Resources>
    <local:DoubleToDurationConverter x:Key="DoubleToDurationConverter" />
</Window.Resources>

<Slider x:Name="slider" />

<Button Content="Click me for an animation">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation To="Green"
                        Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                        FillBehavior="Stop"
                        Duration="{Binding ElementName=slider,
                                           Path=Value,
                                           Mode=OneWay,
                                           Converter={StaticResource DoubleToDurationConverter}}" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
</Button>

I tried that and it worked fine for me. But what I want to do is bind the Duration to a dependency property called FadeTime I've added to my custom control. So, in that control's ControlTemplate I have this:

<ControlTemplate.Triggers>
    <Trigger Property="IsLit" Value="true">
        <Trigger.EnterActions>
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="glow"
                                     Storyboard.TargetProperty="Opacity"
                                     To="1"
                                     Duration="{Binding FadeTime, Mode=OneWay,
                                                RelativeSource={RelativeSource TemplatedParent}}"/>
                </Storyboard>
            </BeginStoryboard>
        </Trigger.EnterActions>
    </Trigger>
</ControlTemplate.Triggers>

This compiles, but gives me an error message at run-time:

InvalidOperationException: Cannot freeze this Storyboard timeline tree
  for use across threads.

How can I bind my DoubleAnimation's Duration to a dependency variable in a custom control's ControlTemplate?

Thanks!

UPDATE

Data-binding is actually gross overkill for what I want to do. Real data-binding would allow for the property's value to change at run-time. All I really want is a way for the developer who is using my custom control to be able to set the Duration of the DoubleAnimation at design time, without having to edit the ControlTemplate. It's okay if the value the developer chooses never changes at run time.

Body:
Basically, you can't use normal bindings inside the storyboard of a control template. Since you just want a way for developers to change the value, one of the following options might work for you:

(1) Use StaticResource: Place a duration object somewhere outside the control template, where it's easier to change for developers. However, it needs to be somewhere statically accessible to the control template, since DynamicResource won't work in this place.

<Duration x:Key="MyCustomDuration">0:0:1</Duration>
... then later
Duration="{StaticResource MyCustomDuration}"

(2) Use a static code behind field with x:Static:

public static class SettingsClass
{
    public static Duration MyCustomDuration = new Duration(new TimeSpan(0, 0, 1));
}

and use:

Duration="{x:Static local:SettingsClass.MyCustomDuration}"


问:
Order of evaluation
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

```<code>struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};
</code>```

If yes I personally would prefer this way to the more conventional:

```<code>    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}
</code>```

答:
Yes. As shown in your code, the members will be initialized in the same order they are declared in the struct/class definition (the order of initializers in the constructor definition is irrelevant, at best you will get a warning telling you they are in an incorrect order).

12.6.2 §5: Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

Note that this is only true for variables that are part of the same access specifier, so for instance variables found in a public: specifier may be initialized before or after those found in a private: specifier (the struct counts as a public: specifier, of course).

EDIT: the above paragraph was incorrect, I was thinking of allocation, not initialization:

9.2 §12: Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (class.access.spec).

However, the more conventional way has a reason to exist, namely that if the order of declaration of the variables changes (for instance, due to refactoring), the code will not break silently. People don't readily assume the order of declaration is relevant, unless a warning tells them otherwise.

Title: Order of evaluation

Body:
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};

If yes I personally would prefer this way to the more conventional:

    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}


问:
Including another class in SCSS
I have this in my SCSS file:

.class-a{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }
}

.class-b{

 //Inherite class-a here

 //some properties
}
```

In class-b, I would like to inherite all properties and nested declarations of class-a. How is this done? I tried using @include class-a, but that just throws an error when compiling.

答:
Another option could be using an Attribute Selector:

```<code>[class^="your-class-name"]{
  //your style here
}
</code>```

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

```<code>[class^="class"]{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }
}

.class-b{
  //specifically for class b
  width: 100px;
  &:hover{
     color: darken(#FFFFFF, 20%);
  }
}
</code>```

More about Attribute Selectors on w3Schools

Title: Including another class in SCSS

Body:
I have this in my SCSS file:

.class-a{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }
}

.class-b{

 //Inherite class-a here

 //some properties
}

In class-b, I would like to inherite all properties and nested declarations of class-a. How is this done? I tried using @include class-a, but that just throws an error when compiling.

Body:
Another option could be using an Attribute Selector:

[class^="your-class-name"]{
  //your style here
}

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

[class^="class"]{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }
}

.class-b{
  //specifically for class b
  width: 100px;
  &:hover{
     color: darken(#FFFFFF, 20%);
  }
}

More about Attribute Selectors on w3Schools


问:
Displaying content of file in tabular format in linux (xargs)
I have a file test.txt with content as:

```<code>1\1
2
3
4
5\3
6
7
8\66
9
10
11
12
13
14
</code>```

I want to print this file in tabular format having 7 columns like below:

```<code>1\1 || 2 || 3 || 4 || 5\3 || 6 || 7
8\66 || 9 || 10 || 11 || 12 || 13 || 14
</code>```

i have tried below cmd in linux:

```<code>xargs -L 4 < test.txt | awk '$1=$1' OFS=' || '
</code>```

But on running this cmd '\' symbol get removes from the output. It come like this
    11 || 2 || 3 || 4 || 53 || 6 || 7
    866 || 9 || 10 || 11 || 12 || 13 || 14

I don't want \ symbol to be removed. please provide your valuable feedback on this.

答:
Perl to the rescue:

```<code>perl -pe 'chomp, $_ .= " || " if $. % 7'
</code>```

-p reads the input line by line.

chomp removes the final newline.

$_ .= ... appends the given string.

Both chomping and appending only happens if $., the current input line number, is not divisible by 7, i.e. the modulo operator % doesn't return 0 for the expression.

Body:
I have a file test.txt with content as:

1\1
2
3
4
5\3
6
7
8\66
9
10
11
12
13
14

I want to print this file in tabular format having 7 columns like below:

1\1 || 2 || 3 || 4 || 5\3 || 6 || 7
8\66 || 9 || 10 || 11 || 12 || 13 || 14

i have tried below cmd in linux:

xargs -L 4 < test.txt | awk '$1=$1' OFS=' || '

But on running this cmd '\' symbol get removes from the output. It come like this
    11 || 2 || 3 || 4 || 53 || 6 || 7
    866 || 9 || 10 || 11 || 12 || 13 || 14

I don't want \ symbol to be removed. please provide your valuable feedback on this.

Body:
Perl to the rescue:

perl -pe 'chomp, $_ .= " || " if $. % 7'

-p reads the input line by line.

chomp removes the final newline.

$_ .= ... appends the given string.

Both chomping and appending only happens if $., the current input line number, is not divisible by 7, i.e. the modulo operator % doesn't return 0 for the expression.


问:
Convert string to Title Case with JavaScript
Is there a simple way to convert a string to Title Case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

答:
For those of us who are scared of regular expressions (lol):

function titleCase(str)
{
    var words = str.split(" ");
    for ( var i = 0; i < words.length; i++ )
    {
        var j = words[i].charAt(0).toUpperCase();
        words[i] = j + words[i].substr(1);
    }
    return words.join(" ");
}```

OwnerDisplayName: MDCore

ContentLicense: CC BY-SA 4.0


问:
how to connect mongodb on localhost:27017 in window?
mongodb.bat

"C:\Program Files\MongoDB\Server\3.4\bin\mongo.exe" --dbpath "f:\mongodb\data"

My localhost Run on port : 8080

i can't mongodb connect Robomongo..

How connect robomongo connect to mongodb for Node.js in Windows8.1 64-bit ?

See the Image ---
enter image description here

答:
Robombongo 0.9.0 has no support for MongoDB 3.4.
Please use Robomongo 1.1 - Beta version with MongoDB 3.4 Support.</p>


问:
Using collection size in for loop comparison
Is there a compiler optimization for the size() methods of Collections in Java?

Consider the following code:

```<code>for(int i=0;i<list.size();i++)
      ...some operation.....
</code>```

There is a call to the size() methods for every i. Won't it be better to find out the size and reuse it? (Method calls have overheads).

```<code>final int len = list.size()
for(int i=0;i<len;i++)
      ...some operation.....
</code>```

However, when I timed both these code pieces there was no significant time difference, even for i as high as 10000000.
Am I missing something here?

Update1: I understand that the size is not computed again unless the collection changes. But there has to be some overhead associated with a method call. Is it the case that the compiler always inlines these (See Esko's answer)?

Update 2: My curiosity has been fueled further. From the answers given, I see that good JIT compilers will often inline this function call. But they will still have to determine whether the collection was modified or not. I am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers.

答:
The value returned by collection's .size() method is usually cached and recalculated only when the actual collection is modified (new elements are added or old ones removed).

Instead of comparing for loop control scoping, try using the for each loop since that actually uses Iterator which in some collection implementations is a lot faster than iterating by using index.

Body:
Is there a compiler optimization for the size() methods of Collections in Java?

Consider the following code:

for(int i=0;i<list.size();i++)
      ...some operation.....

There is a call to the size() methods for every i. Won't it be better to find out the size and reuse it? (Method calls have overheads).

final int len = list.size()
for(int i=0;i<len;i++)
      ...some operation.....

However, when I timed both these code pieces there was no significant time difference, even for i as high as 10000000.
Am I missing something here?

Update1: I understand that the size is not computed again unless the collection changes. But there has to be some overhead associated with a method call. Is it the case that the compiler always inlines these (See Esko's answer)?

Update 2: My curiosity has been fueled further. From the answers given, I see that good JIT compilers will often inline this function call. But they will still have to determine whether the collection was modified or not. I am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers.


问:
Face Detection Algorithm using Emgu CV
Is there any method to dectecting face using emgu cv from just image?
I'm not looking using color segmentation method or from motion detect method</p>

答:
You can use Haar Cascade Classifier Classifier.
Here an example http://ahmedopeyemi.com/main/face-detection-and-recognition-in-c-using-emgucv-3-0-opencv-wrapper-part-1/.

And here a good (and concise) explanation on how HCC works and how to train your own classifier (for face detection you can find several good classifiers ready to use) http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html

Title: Face Detection Algorithm using Emgu CV


问:
Format xml output in spring boot
I have a simple endpoint as follows:

```<code>@RequestMapping("/foo")
public Foo[] getFoo() {
    List<Foo> list = new ArrayList<>();
    list.add(new Foo("bar"));
    list.add(new Foo("baz"));
    list.add(new Foo("bat"));
    return list.toArray(new Foo[list.size()]);
}
</code>```

When I send a request to this endpoint using curl as follows:

```<code>curl -i -H "Accept: application/xml" localhost:8080/foo
</code>```

The output is like this:

```<code><Foos>
 <item>
   <name>bar</name>
 </item>
 <item>
   <name>baz</name>
 </item>
 <item>
   <name>bat</name>
</item>
</Foos>
</code>```

Is there a way to instruct spring boot to change item to name of class Foo?

Here is the Foo class:

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

private String name;

public Foo() {
}

public Foo(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}
</code>```

Jersey for the same endpoint and class outputs the desired format (Foo instead of item). How can I achieve this in spring mvn without changing the Foo class?

Here is the desired xml output:

```<code><Foos>
<Foo>
  <name>bar</name>
</Foo>
<Foo>
  <name>baz</name>
</Foo>
<Foo>
  <name>bat</name>
</Foo>
</code>```

So basically I would like to be able to have control over the name of the elements without modifying the Foo class.

答:
Maybe try:

```<code> @XmlRootElement(name="Foos")
    public class GetFooResponse{

        private List<Foo> someList;

        @XmlElement(name="Foo")
        public List<Foo> getSomeList() {
            return someList;
        }

        public void setSomeList(List<Foo> someList) {
            this.someList = someList;
        }

        public GetResponse(List<Foo> someListValue) {
            this();
            this.someList = someListValue;
        }

        /**
         *
         */
        public GetResponse() {
            // TODO Auto-generated constructor stub
        }
    }
</code>```

This will maybe generate the output you want. You have to replace the return type of your method from Foo[] -> GetFooResponse.

Title: Format xml output in spring boot

Body:
I have a simple endpoint as follows:

@RequestMapping("/foo")
public Foo[] getFoo() {
    List<Foo> list = new ArrayList<>();
    list.add(new Foo("bar"));
    list.add(new Foo("baz"));
    list.add(new Foo("bat"));
    return list.toArray(new Foo[list.size()]);
}

When I send a request to this endpoint using curl as follows:

curl -i -H "Accept: application/xml" localhost:8080/foo

The output is like this:

<Foos>
 <item>
   <name>bar</name>
 </item>
 <item>
   <name>baz</name>
 </item>
 <item>
   <name>bat</name>
</item>
</Foos>

Is there a way to instruct spring boot to change item to name of class Foo?

Here is the Foo class:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

private String name;

public Foo() {
}

public Foo(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

Jersey for the same endpoint and class outputs the desired format (Foo instead of item). How can I achieve this in spring mvn without changing the Foo class?

Here is the desired xml output:

<Foos>
<Foo>
  <name>bar</name>
</Foo>
<Foo>
  <name>baz</name>
</Foo>
<Foo>
  <name>bat</name>
</Foo>

So basically I would like to be able to have control over the name of the elements without modifying the Foo class.

Body:
Maybe try:

 @XmlRootElement(name="Foos")
    public class GetFooResponse{

        private List<Foo> someList;

        @XmlElement(name="Foo")
        public List<Foo> getSomeList() {
            return someList;
        }

        public void setSomeList(List<Foo> someList) {
            this.someList = someList;
        }

        public GetResponse(List<Foo> someListValue) {
            this();
            this.someList = someListValue;
        }

        /**
         *
         */
        public GetResponse() {
            // TODO Auto-generated constructor stub
        }
    }

This will maybe generate the output you want. You have to replace the return type of your method from Foo[] -> GetFooResponse.


问:
How do I get notified if a connection is established in bluetooth settings of iPhone?
I have a iPhone which is trying to connect to a peripheral through my app, the connection drops after a min for some reason(not the issue). My app does not try to auto reconnect to this peripheral, but in the iPhone settings I can see that the peripheral is still shown as connected.
I get the disconnect callback from the CoreBluetooth framework, but no following didConnect callback because the app is not trying to connect again.

Is there any way I can know in my app when the system auto connects to this peripheral?. Or any system notifications I can subscribe in order to know when the connection status changes?

Thanks in advance for the help.

答:
CoreBluetooth framework gives you a delegate method to know the status of the Bluetooth connectivity.

```<code>import CoreBluetooth

class ViewController: CBPeripheralManagerDelegate {

var bluetoothPeripheralManager: CBPeripheralManager?

override func viewDidLoad() {
    super.viewDidLoad()
    let options = [CBCentralManagerOptionShowPowerAlertKey:0]
    bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)
}

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
    var statusMessage = ""

    switch peripheral.state {
    case CBPeripheralManagerState.PoweredOn:
        statusMessage = "Bluetooth Status: Turned On"

    case CBPeripheralManagerState.PoweredOff:
        statusMessage = "Bluetooth Status: Turned Off"

    case CBPeripheralManagerState.Resetting:
        statusMessage = "Bluetooth Status: Resetting"

    case CBPeripheralManagerState.Unauthorized:
        statusMessage = "Bluetooth Status: Not Authorized"

    case CBPeripheralManagerState.Unsupported:
        statusMessage = "Bluetooth Status: Not Supported"

    default:
        statusMessage = "Bluetooth Status: Unknown"
    }
    print(statusMessage)
  }
}
</code>```

This peripheralManagerDidUpdateState method gives you the state of the bluetooth. Hope it helps.Get the status message and do according to your needs.

Body:
CoreBluetooth framework gives you a delegate method to know the status of the Bluetooth connectivity.

import CoreBluetooth

class ViewController: CBPeripheralManagerDelegate {

var bluetoothPeripheralManager: CBPeripheralManager?

override func viewDidLoad() {
    super.viewDidLoad()
    let options = [CBCentralManagerOptionShowPowerAlertKey:0]
    bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)
}

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
    var statusMessage = ""

    switch peripheral.state {
    case CBPeripheralManagerState.PoweredOn:
        statusMessage = "Bluetooth Status: Turned On"

    case CBPeripheralManagerState.PoweredOff:
        statusMessage = "Bluetooth Status: Turned Off"

    case CBPeripheralManagerState.Resetting:
        statusMessage = "Bluetooth Status: Resetting"

    case CBPeripheralManagerState.Unauthorized:
        statusMessage = "Bluetooth Status: Not Authorized"

    case CBPeripheralManagerState.Unsupported:
        statusMessage = "Bluetooth Status: Not Supported"

    default:
        statusMessage = "Bluetooth Status: Unknown"
    }
    print(statusMessage)
  }
}

This peripheralManagerDidUpdateState method gives you the state of the bluetooth. Hope it helps.Get the status message and do according to your needs.


问:
Selenium FirefoxDriver throws IllegalStateException
```<code>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
    at com.google.common.base.Preconditions.checkState(Preconditions.java:199)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:109)
    at org.openqa.selenium.firefox.GeckoDriverService.access$000(GeckoDriverService.java:37)
    at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:95)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:296)
    at org.openqa.selenium.firefox.FirefoxDriver.createCommandExecutor(FirefoxDriver.java:277)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:247)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:242)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:238)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:127)
    at Pack1.L1.main(L1.java:10)
</code>```

Program:

```<code>package Pack1;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class L1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        WebDriver driver= new FirefoxDriver();

        driver.get("https://mail.google.com/");
    }
}
</code>```

答:
For current version of selenium you need to set geckodriver exe path to run your script using FireFoxDriver

So get download geckodriver exe from here

and setup in your code like :

```<code>System.setProperty("webdriver.gecko.driver","D:\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
</code>```

Body:
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
    at com.google.common.base.Preconditions.checkState(Preconditions.java:199)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:109)
    at org.openqa.selenium.firefox.GeckoDriverService.access$000(GeckoDriverService.java:37)
    at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:95)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:296)
    at org.openqa.selenium.firefox.FirefoxDriver.createCommandExecutor(FirefoxDriver.java:277)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:247)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:242)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:238)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:127)
    at Pack1.L1.main(L1.java:10)

Program:

package Pack1;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class L1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        WebDriver driver= new FirefoxDriver();

        driver.get("https://mail.google.com/");
    }
}

Body:
For current version of selenium you need to set geckodriver exe path to run your script using FireFoxDriver

So get download geckodriver exe from here

and setup in your code like :

System.setProperty("webdriver.gecko.driver","D:\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();


问:
How to add ' to generated link in php
```<code>$output .= '<a class="dropdown-toggle has-category" data-toggle="dropdown" href="'.$this->getLink($menu).'" target="'.$menu['target'].'">';
</code>```

I have php file with this code href="'.$this->getLink($menu).'"

its generates in html this href="https://www.myweb.com/"

Now i need to do it with onClick so that the output turned out like this

```<code>onclick="location.href='https://www.myweb.com'"
</code>```

Changed php code onclick="location.href='.$this->getLink($menu).'"

and result is onclick="location.href=https://www.myweb.com"
Link not working cuz lacks '
Can someone help me?

答:
Try this

```<code>onclick="location.href=\''.$this->getLink($menu).'\'">
</code>```

Example:-

```<code>echo '<a onclick="location.href=\''.$this->getLink($menu).'\'">';
</code>```

Title: How to add ' to generated link in php

Body:
$output .= 'getLink($menu).'" target="'.$menu['target'].'">';

I have php file with this code href="'.$this->getLink($menu).'"

its generates in html this href="https://www.myweb.com/"

Now i need to do it with onClick so that the output turned out like this

onclick="location.href='https://www.myweb.com'"

Changed php code onclick="location.href='.$this->getLink($menu).'"

and result is onclick="location.href=https://www.myweb.com"
Link not working cuz lacks '
Can someone help me?

Body:
Try this

onclick="location.href=\''.$this->getLink($menu).'\'">

Example:-

echo '<a onclick="location.href=\''.$this->getLink($menu).'\'">';


问:
How to pass enum as method parameter?
The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:( </p>

<p>Would be great to get any help from you, guys, cause I am completely new to coding. </p>

```<code>class Program
{

    public enum options
    {
        UpSortOption,
        DownSortOption
    }

    public static void Main(string[] args)
    {
        int[] arr = new int[] { 3, 8, 0, 2, 16 };
    }

    static void orderArray(int [] array, options op)
    {
        switch(op)
        {
            case options.UpSortOption:
                Array.Sort(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

            case options.DownSortOption:
                Array.Sort(array);
                Array.Reverse(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

        }
    }
}
</code>```

答:
The signature of the method looks fine, Now you wanted to call this method by passing the first parameter of type integer array and the second parameter of type options for that you can use the following code:

```<code>orderArray(arr,options.UpSortOption);
</code>```

Or else you can declare a variable of type options and pass that variable, the change you have to make for that case will be:

```<code>options optionsVariable = options.DownSortOption;
orderArray(arr,optionsVariable);
</code>```

Title: How to pass enum as method parameter?

Body:
The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:(

Would be great to get any help from you, guys, cause I am completely new to coding.

class Program
{

    public enum options
    {
        UpSortOption,
        DownSortOption
    }

    public static void Main(string[] args)
    {
        int[] arr = new int[] { 3, 8, 0, 2, 16 };
    }

    static void orderArray(int [] array, options op)
    {
        switch(op)
        {
            case options.UpSortOption:
                Array.Sort(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

            case options.DownSortOption:
                Array.Sort(array);
                Array.Reverse(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

        }
    }
}

Body:
The signature of the method looks fine, Now you wanted to call this method by passing the first parameter of type integer array and the second parameter of type options for that you can use the following code:

orderArray(arr,options.UpSortOption);

Or else you can declare a variable of type options and pass that variable, the change you have to make for that case will be:

options optionsVariable = options.DownSortOption;
orderArray(arr,optionsVariable);


问:
Handsontable increase row header width
I'm using custom row header names and there is one that happens to be a little longer than others.

```<code>rowHeaders: ["Entree", "", "Plat", "", "Dessert", "", "Prix 2", "Prix 3"]
</code>```

My question is how do I increase the row header width?

I have thoroughly checked the documentation without luck.

I've tried using colWidths: 200 in the options but that only works on everything except row header width.

Options documentation here.

答:
When creating the table in JS you can add the parameter</p>

```<code>new Handsontable(container, {
    // ...
    rowHeaderWidth: 180,
    // ...
})
</code>```

Title: Handsontable increase row header width

Body:
I'm using custom row header names and there is one that happens to be a little longer than others.

rowHeaders: ["Entree", "", "Plat", "", "Dessert", "", "Prix 2", "Prix 3"]

My question is how do I increase the row header width?

I have thoroughly checked the documentation without luck.

I've tried using colWidths: 200 in the options but that only works on everything except row header width.

Options documentation here.

Body:
When creating the table in JS you can add the parameter

new Handsontable(container, {
    // ...
    rowHeaderWidth: 180,
    // ...
})


问:
Ionic app takes too much time to load on android nexus 5X
I am developing an Ionic app, It works fine in other android devices even on iPhone, but on it takes too much time to load on android nexus 5X.

This is the screens showing for like 3-4 minutes

Then This screen shows up,

Then app finally loads.

Is there any solution to fix this?

答:
This might be because of the debug build in Android Studio.

Goto Build -> Build APK

Now install this apk on your device. It should work fine.


问:
Dynamic SQL - something up with the where clause
I have this proc:

```<code>Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ' + @RowID ;
    EXECUTE(@SQLQuery);
END
</code>```

I basically want to return the resulting row from this, without a where clause, its all good.

答:
You need to be very careful as you've opened yourself up to SQL injection attacks. I'd strongly recommend being very defensive with this and parameterise as much as possible. e.g.

```<code>Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int
AS
BEGIN
    DECLARE @SQLQuery NVARCHAR(500);
    IF (OBJECT_ID(@TableName) IS NOT NULL)
        BEGIN
            SET @SQLQuery = 'Select * from ' + QUOTENAME(@TableName) + ' where ID = @RowId'
            EXECUTE sp_executesql @SQLQuery, N'@RowId INTEGER', @RowID
        END
END
</code>```

It would also be worth considering "locking down" what @TableName values are explicitly supported - check against a whitelist before building/executing the dynamic SQL.

Body:
I have this proc:

Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ' + @RowID ;
    EXECUTE(@SQLQuery);
END

I basically want to return the resulting row from this, without a where clause, its all good.

Body:
You need to be very careful as you've opened yourself up to SQL injection attacks. I'd strongly recommend being very defensive with this and parameterise as much as possible. e.g.

Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100),
@RowID int
AS
BEGIN
    DECLARE @SQLQuery NVARCHAR(500);
    IF (OBJECT_ID(@TableName) IS NOT NULL)
        BEGIN
            SET @SQLQuery = 'Select * from ' + QUOTENAME(@TableName) + ' where ID = @RowId'
            EXECUTE sp_executesql @SQLQuery, N'@RowId INTEGER', @RowID
        END
END

It would also be worth considering "locking down" what @TableName values are explicitly supported - check against a whitelist before building/executing the dynamic SQL.


问:
BackupPc doesn't backup mounted LVM Snapshot?
I resetup my BackupPc and running into a Problem:

I want to backup "/backup" on all hosts. I started with ONE host for test purposes.

Process:

BackupPC calls a Shell-Script on the Client

That script generates some snapshots and Mount them to /backup/...

Now BackupPC should backup

At least BackupPC calls another Shell-Script, wich unmounts and removes the snapshots

The /backup gets "backed up" but just the Folder, not their Contents.

I enhanced the first shell-script to make sure the Folders have Content, here the Output:

```<code>2017-06-04 20:11:14 Created directory /data/backuppc/pc/v3.lipperts-web.de/refCnt
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 256,00 MiB.
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Logical volume "snaptshot-zabbix" created
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 256,00 MiB.
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Logical volume "snaptshot-filebeat" created
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 1,01 GiB.
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Logical volume "snaptshot-teamspeak" created
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Logical volume "snaptshot-schnoddi" created
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Logical volume "snaptshot-sentry" created
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 256,00 MiB.
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Logical volume "snaptshot-nginx" created
2017-06-04 20:11:16 Output from DumpPreUserCmd: insgesamt 13
2017-06-04 20:11:16 Output from DumpPreUserCmd: -rw-r--r-- 1 root root   329 Jun  3 17:43 docker-compose.yml
2017-06-04 20:11:16 Output from DumpPreUserCmd: drwx------ 2 root root 12288 Jun  3 17:43 lost+found
2017-06-04 20:11:16 full backup started for directory /backup
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-zabbix" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-filebeat" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-teamspeak" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-schnoddi" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-sentry" successfully removed
2017-06-04 20:11:18 Output from DumpPostUserCmd:   Logical volume "snaptshot-nginx" successfully removed
2017-06-04 20:11:18 Got fatal error during xfer (No files dumped for share /backup)
2017-06-04 20:11:23 Backup aborted (No files dumped for share /backup)
</code>```

You can se there is an File listed "docker-compose.yml", but backup is empty

https://i.imgur.com/u6hfIh3.png

What could be the Problem here?

答:
By changing RsyncArgs from Default to the Args wich I had (by Default) in BackupPC 3 it worked:

http://imgur.com/a/rYcHL

Body:
I resetup my BackupPc and running into a Problem:

I want to backup "/backup" on all hosts. I started with ONE host for test purposes.

Process:

BackupPC calls a Shell-Script on the Client

That script generates some snapshots and Mount them to /backup/...

Now BackupPC should backup

At least BackupPC calls another Shell-Script, wich unmounts and removes the snapshots

The /backup gets "backed up" but just the Folder, not their Contents.

I enhanced the first shell-script to make sure the Folders have Content, here the Output:

2017-06-04 20:11:14 Created directory /data/backuppc/pc/v3.lipperts-web.de/refCnt
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 256,00 MiB.
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Logical volume "snaptshot-zabbix" created
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 256,00 MiB.
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Logical volume "snaptshot-filebeat" created
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 1,01 GiB.
2017-06-04 20:11:15 Output from DumpPreUserCmd:   Logical volume "snaptshot-teamspeak" created
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Logical volume "snaptshot-schnoddi" created
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Logical volume "snaptshot-sentry" created
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Reducing COW size 5,00 GiB down to maximum usable size 256,00 MiB.
2017-06-04 20:11:16 Output from DumpPreUserCmd:   Logical volume "snaptshot-nginx" created
2017-06-04 20:11:16 Output from DumpPreUserCmd: insgesamt 13
2017-06-04 20:11:16 Output from DumpPreUserCmd: -rw-r--r-- 1 root root   329 Jun  3 17:43 docker-compose.yml
2017-06-04 20:11:16 Output from DumpPreUserCmd: drwx------ 2 root root 12288 Jun  3 17:43 lost+found
2017-06-04 20:11:16 full backup started for directory /backup
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-zabbix" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-filebeat" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-teamspeak" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-schnoddi" successfully removed
2017-06-04 20:11:17 Output from DumpPostUserCmd:   Logical volume "snaptshot-sentry" successfully removed
2017-06-04 20:11:18 Output from DumpPostUserCmd:   Logical volume "snaptshot-nginx" successfully removed
2017-06-04 20:11:18 Got fatal error during xfer (No files dumped for share /backup)
2017-06-04 20:11:23 Backup aborted (No files dumped for share /backup)

You can se there is an File listed "docker-compose.yml", but backup is empty

https://i.imgur.com/u6hfIh3.png

What could be the Problem here?


问:
How to run Jupyter notebook and Tensorboard at the same time inside virtualenv?
I already found its workaround inside Docker. But, in my case, I am running TensorFlow inside virtualenv so that I could run my Jupyter notebook to make a code and to run it.

But I also needed to run the Tensorboard. How can I run two web application inside virtualenv? I have never run two things at the same time. If I want to, I don't know how to run it in a background.

答: I found a simple solution. Just open another shell and run virtualenv / Jupyter notebook after it is already running a Tensorboard in other shell.</p>


问:
How to detect scroll inside “body” and get rid of scrollTop() returns 0
I have set a Scroll event to trigger fade out or fade in effect for "$("#btn")" , but I am not even able to detect the scroll event when its is scrolled, when check the value of scroll it return as 0, due to which it is not reflecting anything.

Issue: Not able to detect any kind of scroll event and not able to get scrolled values

Here is the which I tried

https://jsfiddle.net/evwrs0jq/1/

```<code>$(document).ready(function(){

$("body").on("scroll", function(){
alert();
        var currentScroll = $(this).scrollTop()
        var BtnAction = $("#btn");
        if (currentScroll > offset) {
            BtnAction.fadeOut(duration);
        } else {
            BtnAction.fadeIn(duration);
        }
        offset = currentScroll;
      });
});
</code>```

答:
I guess you want this: https://jsfiddle.net/evwrs0jq/2/

```<code><div id="test" ...

$("#test").on("scroll", function(){ ...
</code>```

The body itself doesn't scroll here, it is the div that scrolls. That's why your alert didn't show up.

Body:
I have set a Scroll event to trigger fade out or fade in effect for "$("#btn")" , but I am not even able to detect the scroll event when its is scrolled, when check the value of scroll it return as 0, due to which it is not reflecting anything.

Issue: Not able to detect any kind of scroll event and not able to get scrolled values

Here is the which I tried

https://jsfiddle.net/evwrs0jq/1/

$(document).ready(function(){

$("body").on("scroll", function(){
alert();
        var currentScroll = $(this).scrollTop()
        var BtnAction = $("#btn");
        if (currentScroll > offset) {
            BtnAction.fadeOut(duration);
        } else {
            BtnAction.fadeIn(duration);
        }
        offset = currentScroll;
      });
});

Body:
I guess you want this: https://jsfiddle.net/evwrs0jq/2/

<div id="test" ...

$("#test").on("scroll", function(){ ...

The body itself doesn't scroll here, it is the div that scrolls. That's why your alert didn't show up.


问:
Force python axis to show specific numbers
I have a python plot, using the following code:

```<code>fig = plt.figure()
ax = plt.add_subplot(111)
ax.imshow(an_image)
</code>```

What I want to do, is simply force the x and y axes, to span a certain minimum and maximum number. (Cannot do this with ax.set_xlim() or ax.set_ylim() because those actually change the axis limits). I just want some particular x_min , x_max , y_min, and y_max numbers to show up on my image.

How do I do that?

EDIT: To further clarify what I mean, look at this image below. What I want, are the numbers on the axes written in red. I want them to replace what is already there in black.  How do I accomplish that?

Thanks

答:
You may consider using the image extent to set the actual scale of the image.
I.e. to let your image scale from -30to 100 in x- and -20 to 20 you can use

```<code>ax.imshow(data, origin="lower", extent=[-30, 100, -20,20])
</code>```

An example:

```<code>import matplotlib.pyplot as plt
import numpy as np

data = np.random.normal(size=(10,20))
xmin, xmax = -30, 100
ymin, ymax = -20, 20

fig, ax = plt.subplots()

extent= [xmin, xmax, ymin, ymax]
ax.imshow(data, origin="lower", extent=extent)

ax.set_xticks(np.arange(xmin,xmax+1,10))
ax.set_yticks([-20,0,20])
plt.show()
</code>```

Note that this might scale the image pixels to be non-square. To preserve square pixels, you may use the aspect argument.

```<code>extent= [xmin, xmax, ymin, ymax]
aspect=data.shape[0]/float(ymax-ymin)/(data.shape[1]/float(xmax-xmin))
ax.imshow(data, origin="lower", extent=extent, aspect=aspect)
</code>```

You might also want to look at this question: Matplotlib: how to make imshow read x,y coordinates from other numpy arrays? for how to put the ticks to the pixel centers, which makes sense depending on the actual meaning of the data.

Body:
I have a python plot, using the following code:

fig = plt.figure()
ax = plt.add_subplot(111)
ax.imshow(an_image)

What I want to do, is simply force the x and y axes, to span a certain minimum and maximum number. (Cannot do this with ax.set_xlim() or ax.set_ylim() because those actually change the axis limits). I just want some particular x_min , x_max , y_min, and y_max numbers to show up on my image.

How do I do that?

EDIT: To further clarify what I mean, look at this image below. What I want, are the numbers on the axes written in red. I want them to replace what is already there in black.  How do I accomplish that?

Thanks

Body:
You may consider using the image extent to set the actual scale of the image.
I.e. to let your image scale from -30to 100 in x- and -20 to 20 you can use

ax.imshow(data, origin="lower", extent=[-30, 100, -20,20])

An example:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.normal(size=(10,20))
xmin, xmax = -30, 100
ymin, ymax = -20, 20

fig, ax = plt.subplots()

extent= [xmin, xmax, ymin, ymax]
ax.imshow(data, origin="lower", extent=extent)

ax.set_xticks(np.arange(xmin,xmax+1,10))
ax.set_yticks([-20,0,20])
plt.show()

Note that this might scale the image pixels to be non-square. To preserve square pixels, you may use the aspect argument.

extent= [xmin, xmax, ymin, ymax]
aspect=data.shape[0]/float(ymax-ymin)/(data.shape[1]/float(xmax-xmin))
ax.imshow(data, origin="lower", extent=extent, aspect=aspect)

You might also want to look at this question: Matplotlib: how to make imshow read x,y coordinates from other numpy arrays? for how to put the ticks to the pixel centers, which makes sense depending on the actual meaning of the data.