问:
kivy Scrollview can't Scroll
FileView extends the kivy ScrollView. In the app I can see three out of the four image, but I am not able to scroll to the fourth image. Therefore the widget is larger than my app window and I thought that I should be able to scroll. But, I cannot scroll.

This is my python code:

```<code>import os
import sys

#self-programmed modules
import modules.pmail as pmail
import modules.log as log

#kivy modules
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.properties import StringProperty

logging = True
log.start(logging)

class FileViewPhoto(Button):
    source = StringProperty()

class FileView(ScrollView):
    pass

class Photo(BoxLayout):
    pass

class PhotoCamera(BoxLayout):
    '''
    Start screen, from here a photo or gif can be taken or previously taken images be viewed
    '''
    def take_pic(self):
        log.printlog('take_pic', logging)
        App.get_running_app().root.show_Photo()

    def take_gif(self):
        log.printlog('take_gif', logging)
        App.get_running_app().root.show_Photo()

class PhotoRoot(BoxLayout):
    '''
    Root widget
    -all methods which change the content of the screen are called from here.
    '''
    def show_Photo(self):
        self.clear_widgets()
        self.add_widget(Photo())

    def show_Photos_in_folder(self):
        self.clear_widgets()
        self.add_widget(FileView())

class PhotoboothApp(App):

    def build(self):
        self.icon = 'Icons/photo.png'

if __name__ == '__main__':
    PhotoboothApp().run()
</code>```

This is my kv file:

```<code>PhotoRoot:
    PhotoCamera:

<PhotoCamera>:
    Button:
        text: 'Camera-Gif'
        on_press: root.take_gif()
        BoxLayout:
            orientation:'vertical'
            pos: self.parent.pos
            size: self.parent.size
            Image:
                source: 'Icons/photo.png'
            Image:
                source: 'Icons/photo.png'
            Image:
                source: 'Icons/photo.png'
    Button:
        on_press: root.take_pic()
        Image:
            width: self.parent.width
            source: 'Icons/photo.png'
            center: self.parent.center

    Button:
        text: 'Photos'
        on_press: app.root.show_Photos_in_folder()

<Photo>:
    Label:
        text: 'Photo'
    Image:
        source: 'Images/Astronaut1.jpg'

<FileViewPhoto>:
    source: ''
    size_hint_y: None
    height: '300sp'
    Image:
        source: root.source
        center: root.center
        size: root.size

<FileView>:

    GridLayout:
        cols: 1
        size_hint_y: None
        row_default_height: '200dp'
        row_force_default: True
        minimum_height: self.minimum_height

        FileViewPhoto:
            source: 'Images/Astronaut1.jpg'

        FileViewPhoto
            source: 'Images/Astronaut1.jpg'

        FileViewPhoto
            source: 'Images/Astronaut1.jpg'

        FileViewPhoto:
            source: 'Images/Astronaut1.jpg'
</code>```

The method show_Photos_in_folder() of my PhotoRoot is called to display the supposedly scrollable GridLayout of photos.

答:
In GridLayout kv code instead of:

```<code>minimum_height: self.minimum_height
</code>```

do:

```<code>height: self.minimum_height
</code>```

Then it should work just fine. :)

Also, in future try NOT to include custom modules you made (import unknown_module...) as it makes the code hard to reproduce unless the other person knows what to look for...

Title: kivy Scrollview can't Scroll

Body:
FileView extends the kivy ScrollView. In the app I can see three out of the four image, but I am not able to scroll to the fourth image. Therefore the widget is larger than my app window and I thought that I should be able to scroll. But, I cannot scroll.

This is my python code:

import os
import sys

#self-programmed modules
import modules.pmail as pmail
import modules.log as log

#kivy modules
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.properties import StringProperty

logging = True
log.start(logging)

class FileViewPhoto(Button):
    source = StringProperty()

class FileView(ScrollView):
    pass

class Photo(BoxLayout):
    pass

class PhotoCamera(BoxLayout):
    '''
    Start screen, from here a photo or gif can be taken or previously taken images be viewed
    '''
    def take_pic(self):
        log.printlog('take_pic', logging)
        App.get_running_app().root.show_Photo()

    def take_gif(self):
        log.printlog('take_gif', logging)
        App.get_running_app().root.show_Photo()

class PhotoRoot(BoxLayout):
    '''
    Root widget
    -all methods which change the content of the screen are called from here.
    '''
    def show_Photo(self):
        self.clear_widgets()
        self.add_widget(Photo())

    def show_Photos_in_folder(self):
        self.clear_widgets()
        self.add_widget(FileView())

class PhotoboothApp(App):

    def build(self):
        self.icon = 'Icons/photo.png'

if __name__ == '__main__':
    PhotoboothApp().run()

This is my kv file:

PhotoRoot:
    PhotoCamera:

<PhotoCamera>:
    Button:
        text: 'Camera-Gif'
        on_press: root.take_gif()
        BoxLayout:
            orientation:'vertical'
            pos: self.parent.pos
            size: self.parent.size
            Image:
                source: 'Icons/photo.png'
            Image:
                source: 'Icons/photo.png'
            Image:
                source: 'Icons/photo.png'
    Button:
        on_press: root.take_pic()
        Image:
            width: self.parent.width
            source: 'Icons/photo.png'
            center: self.parent.center

    Button:
        text: 'Photos'
        on_press: app.root.show_Photos_in_folder()

<Photo>:
    Label:
        text: 'Photo'
    Image:
        source: 'Images/Astronaut1.jpg'

<FileViewPhoto>:
    source: ''
    size_hint_y: None
    height: '300sp'
    Image:
        source: root.source
        center: root.center
        size: root.size

<FileView>:

    GridLayout:
        cols: 1
        size_hint_y: None
        row_default_height: '200dp'
        row_force_default: True
        minimum_height: self.minimum_height

        FileViewPhoto:
            source: 'Images/Astronaut1.jpg'

        FileViewPhoto
            source: 'Images/Astronaut1.jpg'

        FileViewPhoto
            source: 'Images/Astronaut1.jpg'

        FileViewPhoto:
            source: 'Images/Astronaut1.jpg'

The method show_Photos_in_folder() of my PhotoRoot is called to display the supposedly scrollable GridLayout of photos.

Body:
In GridLayout kv code instead of:

minimum_height: self.minimum_height

do:

height: self.minimum_height

Then it should work just fine. :)

Also, in future try NOT to include custom modules you made (import unknown_module...) as it makes the code hard to reproduce unless the other person knows what to look for...


来源: stackexchange

问:
Finding many duplicates based on multiple properties in one database hit
I'm trying to perform a check on the database to see if the combination of two properties exists in the database check (pre-Unique constraint check for better UX). Doing the check with a single property is easy, no matter how many you're trying to check. I'm unable to find how to do it with multiple properties in an enumerable.

```<code>public class Foo
{
    public int Id { get; set; }
    public int Bar { get; set; }
    public int Bat { get; set; }
    public string Name { get; set; }
    //...
}

public class FooDupeCheckModel
{
    public int Bar { get; set; }
    public int Bat { get; set; }
}

public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    return _db.Foos
              .Where(f => matches.Any(m => m.BarId == f.BarId &&
                                           m.BatId == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}
</code>```

This unfortunately gives an exception because the complex property matches cannot be converted into a SQL script. Only primitive types can be included into a query.

I also tried converting matches to a multidimensional array before using it within the query, but indexes are not supported within a query. .First() is not allowed to be used their either.

```<code>public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    var matchArray = matches.Select(m => new [] {m.BarId, m.BatId})
                            .ToArray();

    return _db.Foos
              .Where(f => matchArray.Any(m => m[0] == f.BarId &&
                                              m[1] == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}
</code>```

This may be one of those situations that is such a niche case, or requires a SQL query that is too complex for Entity Framework that it is not possible. If it is possible, then this would be very helpful if someone else runs into the same issue.

I did get around this by looping through and calling the database for each element in matches, but if I could do this in one database call, that'd be quicker.

答:
Since Foo is a type that belongs to the model, you could project your matches to IEnumerable<Foo>, mapping only the two properties of interest, then issue the query. That should make it work.

```<code>public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    //Convert small set to check for dups to objects recognized by the EF
    var fooMatches = matches.Select(m => new Foo() { BarId = m.BardId, BatId = m.BatId });

    //This should now work
    return _db.Foos
              .Where(f => fooMatches.Any(m => m.BarId == f.BarId &&
                                           m.BatId == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to perform a check on the database to see if the combination of two properties exists in the database check (pre-Unique constraint check for better UX). Doing the check with a single property is easy, no matter how many you're trying to check. I'm unable to find how to do it with multiple properties in an enumerable.

public class Foo
{
    public int Id { get; set; }
    public int Bar { get; set; }
    public int Bat { get; set; }
    public string Name { get; set; }
    //...
}

public class FooDupeCheckModel
{
    public int Bar { get; set; }
    public int Bat { get; set; }
}

public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    return _db.Foos
              .Where(f => matches.Any(m => m.BarId == f.BarId &&
                                           m.BatId == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}

This unfortunately gives an exception because the complex property matches cannot be converted into a SQL script. Only primitive types can be included into a query.

I also tried converting matches to a multidimensional array before using it within the query, but indexes are not supported within a query. .First() is not allowed to be used their either.

public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    var matchArray = matches.Select(m => new [] {m.BarId, m.BatId})
                            .ToArray();

    return _db.Foos
              .Where(f => matchArray.Any(m => m[0] == f.BarId &&
                                              m[1] == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}

This may be one of those situations that is such a niche case, or requires a SQL query that is too complex for Entity Framework that it is not possible. If it is possible, then this would be very helpful if someone else runs into the same issue.

I did get around this by looping through and calling the database for each element in matches, but if I could do this in one database call, that'd be quicker.

Body:
Since Foo is a type that belongs to the model, you could project your matches to IEnumerable<Foo>, mapping only the two properties of interest, then issue the query. That should make it work.

public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    //Convert small set to check for dups to objects recognized by the EF
    var fooMatches = matches.Select(m => new Foo() { BarId = m.BardId, BatId = m.BatId });

    //This should now work
    return _db.Foos
              .Where(f => fooMatches.Any(m => m.BarId == f.BarId &&
                                           m.BatId == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}


问:
Hive Join Query throws Error
If a user_id  has multiple records then keep the latest record as per event_timestamp .

My HIVE query :

```<code>SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;
</code>```

When I try to run this hive query I get the below error

```<code>SemanticException [Error 10002]: Line 8:43 Invalid column reference 'converted_event_timestamp'
</code>```

Can Someone tell me what went wrong on this hive query and how do I fix this ?

答:
I see where you have named a.converted_event_timestamp  in your query. You can't use it in the join because that is likely evaluated before the conversions in the select. Join to this instead

unix_timestamp(a.event_timestamp,'dd/MM/YYYY HH:MM')

Title: Hive Join Query throws Error

Body:
If a user_id  has multiple records then keep the latest record as per event_timestamp .

My HIVE query :

SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;

When I try to run this hive query I get the below error

SemanticException [Error 10002]: Line 8:43 Invalid column reference 'converted_event_timestamp'

Can Someone tell me what went wrong on this hive query and how do I fix this ?


问:
Split an html file into multiple files in ionic2
Is there any way to split a large html file into several files in ionic2?

I tried

```<code><div ng-include src="file1.html"></div>
</code>```

and

```<code><link rel="import" href="./file1.html">
</code>```

with no success

答:
Try </p>

```<code><div ng-include="'file1.htm'"></div>
</code>```

Body:
Is there any way to split a large html file into several files in ionic2?

I tried

and

<link rel="import" href="./file1.html">

with no success

Body:
Try

<div ng-include="'file1.htm'"></div>


问:
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
I tried to find the solution for the below problem, but none of them worked for me. I am developing Angular + Spring Boot application using MySQL + flyway. Please guide whats going wrong here.

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.boot.App.main(App.java:9) [classes/:na]
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.flywaydb.core.Flyway.doValidate(Flyway.java:1108) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.access$300(Flyway.java:62) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1012) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 18 common frames omitted
</code>```

application.properties

```<code>logging.level.org.springframework.web=DEBUG

server.port=8080

spring.h2.console.enabled=true
spring.h2.console.path=/h2

## For H2 DB
#spring.datasource.url=jdbc:h2:file:~/dasboot
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driver-class-name=org.h2.Driver

## For MYSQL DB
spring.datasource.url=jdbc:mysql://localhost:3306/dasboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1

flyway.baseline-on-migrate=true
spring.jpa.hibernate.ddl-auto=false;

#datasource.flyway.url=jdbc:h2:file:~/dasboot
#datasource.flyway.username=sa
#datasource.flyway.password=
#datasource.flyway.driver-class-name=org.h2.Driver

datasource.flyway.url=jdbc:mysql://localhost:3306/dasboot
datasource.flyway.username=root
datasource.flyway.password=root
datasource.flyway.driver-class-name=com.mysql.jdbc.Driver
</code>```

pom.xml

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <name>das-boot</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</code>```

V2__create_shipwreck.sql

```<code>-- For H2 DB
--CREATE TABLE SHIPWRECK(
--  ID INT AUTO_INCREMENT,
--  NAME VARCHAR(255),
--  DESCRIPTION VARCHAR(2000),
--  CONDITION VARCHAR(255),
--  DEPTH INT,
--  LATITUDE DOUBLE,
--  LONGITUDE DOUBLE,
--  YEAR_DISCOVERED INT
--);

CREATE TABLE `dasboot`.`shipwreck` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(255) NULL,
  `DESCRIPTION` VARCHAR(2000) NULL,
  `CONDITION` VARCHAR(255) NULL,
  `DEPTH` INT NULL,
  `LATITUDE` DOUBLE NULL,
  `LONGITUDE` DOUBLE NULL,
  `YEAR_DISCOVERED` INT NULL,
  PRIMARY KEY (`ID`));
</code>```

答:
IF YOU ARE NOT IN PRODUCTION, you can look in your flywayTable in the data base and remove the line which contain the name of the script which has been applied.

flywayTable is a project option which define the name of the table in the db used by flyway which contain information about the version of this db, already applied scripts...

Body:
I tried to find the solution for the below problem, but none of them worked for me. I am developing Angular + Spring Boot application using MySQL + flyway. Please guide whats going wrong here.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.boot.App.main(App.java:9) [classes/:na]
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.flywaydb.core.Flyway.doValidate(Flyway.java:1108) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.access$300(Flyway.java:62) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1012) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 18 common frames omitted

application.properties

logging.level.org.springframework.web=DEBUG

server.port=8080

spring.h2.console.enabled=true
spring.h2.console.path=/h2

## For H2 DB
#spring.datasource.url=jdbc:h2:file:~/dasboot
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driver-class-name=org.h2.Driver

## For MYSQL DB
spring.datasource.url=jdbc:mysql://localhost:3306/dasboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1

flyway.baseline-on-migrate=true
spring.jpa.hibernate.ddl-auto=false;

#datasource.flyway.url=jdbc:h2:file:~/dasboot
#datasource.flyway.username=sa
#datasource.flyway.password=
#datasource.flyway.driver-class-name=org.h2.Driver

datasource.flyway.url=jdbc:mysql://localhost:3306/dasboot
datasource.flyway.username=root
datasource.flyway.password=root
datasource.flyway.driver-class-name=com.mysql.jdbc.Driver

pom.xml

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

    <name>das-boot</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

V2__create_shipwreck.sql

-- For H2 DB
--CREATE TABLE SHIPWRECK(
--  ID INT AUTO_INCREMENT,
--  NAME VARCHAR(255),
--  DESCRIPTION VARCHAR(2000),
--  CONDITION VARCHAR(255),
--  DEPTH INT,
--  LATITUDE DOUBLE,
--  LONGITUDE DOUBLE,
--  YEAR_DISCOVERED INT
--);

CREATE TABLE `dasboot`.`shipwreck` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(255) NULL,
  `DESCRIPTION` VARCHAR(2000) NULL,
  `CONDITION` VARCHAR(255) NULL,
  `DEPTH` INT NULL,
  `LATITUDE` DOUBLE NULL,
  `LONGITUDE` DOUBLE NULL,
  `YEAR_DISCOVERED` INT NULL,
  PRIMARY KEY (`ID`));

ContentLicense: CC BY-SA 4.0


问:
scriptaculous-like component to avoid double-submit
I'm looking for a script to prevent the user from hitting the submit button twice specially for long time background processing forms. I'd like to implement something not just functional but visually appealing too. Can anybody share some tips of how to accomplish this using, for instance, scriptaculous ?

Thanks

答:
Using prototype you can try something like this:</p>

```<code>var DoubleSubmit = {
prevent: function(){
    var forms = document.body.select('form');
    forms.invoke('observe', 'submit', DoubleSubmit.observeSubmit);
},
observeSubmit: function(event){
    var submitButtton = event.element().select('input[type="submit"]')[0];
    submitButtton.disable();
    return true;
}};document.observe('dom:loaded',DoubleSubmit.prevent);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Using prototype you can try something like this:

var DoubleSubmit = {
prevent: function(){
    var forms = document.body.select('form');
    forms.invoke('observe', 'submit', DoubleSubmit.observeSubmit);
},
observeSubmit: function(event){
    var submitButtton = event.element().select('input[type="submit"]')[0];
    submitButtton.disable();
    return true;
}};document.observe('dom:loaded',DoubleSubmit.prevent);


问:
TypeScript: how to delete the *.js.map files from the project
I had set "sourceMap": true in my tsconfig.json file. After compiling every ts file got its js.map file. I reset "sourceMap": false and recompiled. The *js.map files did not get deleted. How can I get rid of them?

答:
With a unix-based system you can use find and execute:

```<code>find . -name "*.js.map" -exec rm {} \;
</code>```

I find it to be very useful.

Body:
With a unix-based system you can use find and execute:

find . -name "*.js.map" -exec rm {} \;

I find it to be very useful.


问:
NotFoundHttpException in RouteCollection.php line 161: error

I get the NotFoundHttpException in RouteCollection.php line 161: but I can't find the error. I'm using Laravel 5.4.

I ran php artisan route:list command and I see the defined (named) route.

And here is the route file.

```<code><?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'LinkController@create');

Route::post('/create', 'LinkController@store');

Route::get('show/{id}', 'LinkController@show')->name('show');
</code>```

And here is the part from the resource controller.

```<code>public function store(Request $request)
{
    $this->validate($request, [
        'url' => 'required|url'
    ]);

    // Generate string length of 6 characters
    $newHash = Str::random(6);

    // creates a $link object
    $link = new Link;

    //checks if link already exists in the database
    $link_in_db = DB::table('links')->where('url', '=', $request->url)->get();

    if($link_in_db === null){
        // sets the $link variables
        $link->url = $request->url;
        $link->hash = $newHash;

        // $link is saved in the database
        $link->save();

        // redirects to the route
        return redirect()->route('show', $link->id);
    }else{ // link is in the database
        // print_r($link_in_db); // testing purposes
        return redirect()->route('show', $link->id);
    }
}
</code>```

And I highly appreciate any suggestion. If there are any other methods to redirect with data, please suggest.

Thank you!

答:
If you define a variable on a route, you must provide it unless you make it optional.

```<code>Route::get('show/{id?}', 'LinkController@show');
</code>```

will make the id segment optional and route /show to the method with a null value in id.

Essentially you do not have a route set up for /show you have a route set up for /show/somethinghere

Body:
I get the NotFoundHttpException in RouteCollection.php line 161: but I can't find the error. I'm using Laravel 5.4.

I ran php artisan route:list command and I see the defined (named) route.

And here is the route file.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'LinkController@create');

Route::post('/create', 'LinkController@store');

Route::get('show/{id}', 'LinkController@show')->name('show');

And here is the part from the resource controller.

public function store(Request $request)
{
    $this->validate($request, [
        'url' => 'required|url'
    ]);

    // Generate string length of 6 characters
    $newHash = Str::random(6);

    // creates a $link object
    $link = new Link;

    //checks if link already exists in the database
    $link_in_db = DB::table('links')->where('url', '=', $request->url)->get();

    if($link_in_db === null){
        // sets the $link variables
        $link->url = $request->url;
        $link->hash = $newHash;

        // $link is saved in the database
        $link->save();

        // redirects to the route
        return redirect()->route('show', $link->id);
    }else{ // link is in the database
        // print_r($link_in_db); // testing purposes
        return redirect()->route('show', $link->id);
    }
}

And I highly appreciate any suggestion. If there are any other methods to redirect with data, please suggest.

Thank you!

Body:
If you define a variable on a route, you must provide it unless you make it optional.

Route::get('show/{id?}', 'LinkController@show');

will make the id segment optional and route /show to the method with a null value in id.

Essentially you do not have a route set up for /show you have a route set up for /show/somethinghere


问:
r - Binding sparse matrices of different sizes on rows
I am attempting to use the Matrix package to bind two sparse matrices of different size together. The binding is on rows, using the column names for matching.

Table A:

```<code>ID     | AAAA   | BBBB   |
------ | ------ | ------ |
XXXX   | 1      | 2      |
</code>```

Table B:

```<code>ID     | BBBB   | CCCC   |
------ | ------ | ------ |
YYYY   | 3      | 4      |
</code>```

Binding table A and B:

```<code>ID     | AAAA   | BBBB   | CCCC   |
------ | ------ | ------ | ------ |
XXXX   | 1      | 2      |        |
YYYY   |        | 3      | 4      |
</code>```

The intention is to insert a large number of small matrices into a single large matrix, to enable continuous querying and update/inserts.

I find that neither the Matrix or slam packages have functionality to handle this.

Similar questions have been asked in the past, but it seems no solution has been found:

Post 1: in-r-when-using-named-rows-can-a-sparse-matrix-column-be-added-concatenated

Post 2: bind-together-sparse-model-matrices-by-row-names

Ideas on how to solve it will be highly appreciated.

Best regards,

Frederik

答:
It looks it's necessary to have empty columns (columns with 0s) added to the matrices so to make them compatible for a rbind (matrices with the same column names, and on the same order). The following code does it:

```<code># dummy data
set.seed(3344)
A = Matrix(matrix(rbinom(16, 2, 0.2), 4))
colnames(A)=letters[1:4]
B = Matrix(matrix(rbinom(9, 2, 0.2), 3))
colnames(B) = letters[3:5]

# finding what's missing
misA = colnames(B)[!colnames(B) %in% colnames(A)]
misB = colnames(A)[!colnames(A) %in% colnames(B)]

misAl = as.vector(numeric(length(misA)), "list")
names(misAl) = misA
misBl = as.vector(numeric(length(misB)), "list")
names(misBl) = misB

## adding missing columns to initial matrices
An = do.call(cbind, c(A, misAl))
Bn = do.call(cbind, c(B, misBl))[,colnames(An)]

# final bind
rbind(An, Bn)
</code>```

Body:
I am attempting to use the Matrix package to bind two sparse matrices of different size together. The binding is on rows, using the column names for matching.

Table A:

ID     | AAAA   | BBBB   |
------ | ------ | ------ |
XXXX   | 1      | 2      |

Table B:

ID     | BBBB   | CCCC   |
------ | ------ | ------ |
YYYY   | 3      | 4      |

Binding table A and B:

ID     | AAAA   | BBBB   | CCCC   |
------ | ------ | ------ | ------ |
XXXX   | 1      | 2      |        |
YYYY   |        | 3      | 4      |

The intention is to insert a large number of small matrices into a single large matrix, to enable continuous querying and update/inserts.

I find that neither the Matrix or slam packages have functionality to handle this.

Similar questions have been asked in the past, but it seems no solution has been found:

Post 1: in-r-when-using-named-rows-can-a-sparse-matrix-column-be-added-concatenated

Post 2: bind-together-sparse-model-matrices-by-row-names

Ideas on how to solve it will be highly appreciated.

Best regards,

Frederik

Body:
It looks it's necessary to have empty columns (columns with 0s) added to the matrices so to make them compatible for a rbind (matrices with the same column names, and on the same order). The following code does it:

# dummy data
set.seed(3344)
A = Matrix(matrix(rbinom(16, 2, 0.2), 4))
colnames(A)=letters[1:4]
B = Matrix(matrix(rbinom(9, 2, 0.2), 3))
colnames(B) = letters[3:5]

# finding what's missing
misA = colnames(B)[!colnames(B) %in% colnames(A)]
misB = colnames(A)[!colnames(A) %in% colnames(B)]

misAl = as.vector(numeric(length(misA)), "list")
names(misAl) = misA
misBl = as.vector(numeric(length(misB)), "list")
names(misBl) = misB

## adding missing columns to initial matrices
An = do.call(cbind, c(A, misAl))
Bn = do.call(cbind, c(B, misBl))[,colnames(An)]

# final bind
rbind(An, Bn)


问:
Deploy Angular 2 with Azure Webapp
How can can I deploy an angular 2 webapp to azure? I guess I need some type of final compilation script.

Thanks in advance.

答:
In order to run angular2 app in azure follow these steps:

create a new ng app (with ng cli) : ng new testApp and push to some github repo.

create Azure deployment files for Kudu :

```<code>npm install azure-cli -g
azure site deploymentscript --node
</code>```

this will create 2 files .deployment and deploy.cmd

edit the deploy.cmd remove the --production from the line

:: 3. Install npm packages

so that all dependencies will be installed (including ng cli)

add under the section of :: 3. Install npm packages

this snippet:

```<code>echo Handling Angular build
    :: 4. Build ng app
    IF EXIST "%DEPLOYMENT_TARGET%\package.json" (
      pushd "%DEPLOYMENT_TARGET%"
      call :ExecuteCmd "!NODE_EXE!" ./node_modules/@angular/cli/bin/ng build --prod --env=prod --aot
      IF !ERRORLEVEL! NEQ 0 goto error
      :: the next line is optional to fix 404 error see section #8
      call :ExecuteCmd cp "%DEPLOYMENT_TARGET%"/web.config "%DEPLOYMENT_TARGET%"/dist/
      IF !ERRORLEVEL! NEQ 0 goto error
      popd
    )
</code>```

create a new webapp in azure and bind it to your github repository

now just change the root of the app in the  Azure "Application Settings"

under "Virtual applications and directories"
from

site\wwwroot

to

site\wwwroot\dist

 7. trigger a deployment. (by pushing to github or manually from the azure portal)

 8. (optional) for fixing the 404 when refreshing, you need to add a web.config on the root with this content:

```<code>   <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
        <rewrite>
          <rules>
            <rule name="AngularJS" stopProcessing="true">
              <match url=".*" />
              <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              </conditions>
              <action type="Rewrite" url="index.html" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>
</code>```

open your app .. BOOM!

Title: Deploy Angular 2 with Azure Webapp

Body:
In order to run angular2 app in azure follow these steps:

create a new ng app (with ng cli) : ng new testApp and push to some github repo.

create Azure deployment files for Kudu :

npm install azure-cli -g
azure site deploymentscript --node

this will create 2 files .deployment and deploy.cmd

edit the deploy.cmd remove the --production from the line

:: 3. Install npm packages

so that all dependencies will be installed (including ng cli)

add under the section of :: 3. Install npm packages

this snippet:

echo Handling Angular build
    :: 4. Build ng app
    IF EXIST "%DEPLOYMENT_TARGET%\package.json" (
      pushd "%DEPLOYMENT_TARGET%"
      call :ExecuteCmd "!NODE_EXE!" ./node_modules/@angular/cli/bin/ng build --prod --env=prod --aot
      IF !ERRORLEVEL! NEQ 0 goto error
      :: the next line is optional to fix 404 error see section #8
      call :ExecuteCmd cp "%DEPLOYMENT_TARGET%"/web.config "%DEPLOYMENT_TARGET%"/dist/
      IF !ERRORLEVEL! NEQ 0 goto error
      popd
    )

create a new webapp in azure and bind it to your github repository

now just change the root of the app in the  Azure "Application Settings"

under "Virtual applications and directories"
from

site\wwwroot

to

site\wwwroot\dist

 7. trigger a deployment. (by pushing to github or manually from the azure portal)

 8. (optional) for fixing the 404 when refreshing, you need to add a web.config on the root with this content:

   <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
        <rewrite>
          <rules>
            <rule name="AngularJS" stopProcessing="true">
              <match url=".*" />
              <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              </conditions>
              <action type="Rewrite" url="index.html" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>

open your app .. BOOM!


问:
Fill div with image without stretching
I have an image with high resolution (width: 5540px, height: 2680px), and I need
this image to cover an entire div (this div goes full width and 80% of height). This image is displayed on screens with resolutions of 768px till 1600px.

When I use background-size: cover, the image goes full width but the bottom part is cut off.

When I use background-size: contain, the image is resized to fit the height but the width isn't entirely filled.

When I user background-size: 100%, the image fill the entire div, but gets stretch out.

Is there any way to do that or do I need to resize the image (for example, resize image to 1600px (width) because this image is only displayed on screens with width from 768px to 1600px)?

答:
If your original image is 5540x2680px, you should probably start by resizing it manually, because that's just to much to load if you want to display it at max. 1600px width.

For the resizing it then depends on the content of the image. Since the ratios you mentioned are almost similar, I guess your best bet is to go with background-size:cover and reposition it using background-position property.

eg

```<code>background-position: center bottom;
</code>```

because you mentioned that the bottom was cut off.

Title: Fill div with image without stretching

Body:
If your original image is 5540x2680px, you should probably start by resizing it manually, because that's just to much to load if you want to display it at max. 1600px width.

For the resizing it then depends on the content of the image. Since the ratios you mentioned are almost similar, I guess your best bet is to go with background-size:cover and reposition it using background-position property.

eg

background-position: center bottom;

because you mentioned that the bottom was cut off.


问:
How to present view controller behind another view controller?
I am trying to present two view controllers. I'm trying to avoid presenting one after the other as this doesn't give a good user experience.

I'm using storyboards / segues to present the view controllers, each embedded in navigation controllers.

The behaviour should be:

View Controller 1 presents view controller 2 - but when view controller 2 dismisses I'd like view controller 3 to be the one showing to the user. And ideally an ability to also dismiss to view controller 1.

I understand I can accomplish this with child views. But I'd ideally like to learn how it can be done by manipulating the navigation stack.

答:
I don't think you can do what you want with segue, but certainly you can do it with a little code...

This will (on a button tap, for example) perform a standard slide-in navigation controller animation directly from the current ViewController (call it vc1) to ViewController2, but "insert" ViewController3 into the stack. Tapping the Back button will take you from vc2 to vc3 to vc1.

```<code>@IBAction func didTap(_ sender: Any) {

    guard let vc3 = storyboard?.instantiateViewController(withIdentifier: "vc3"),
        let vc2 = storyboard?.instantiateViewController(withIdentifier: "vc2")
        else { return }

    let vcArray = [self, vc3, vc2]

    self.navigationController?.setViewControllers(vcArray, animated: true)

}
</code>```

If you want to go from vc2 back to vc1 and "skip over" vc3, in vc2 add (on a button tap, for example):

```<code>@IBAction func backToStartTap(_ sender: Any) {

    self.navigationController?.popToRootViewController(animated: true)

}
</code>```

Body:
I don't think you can do what you want with segue, but certainly you can do it with a little code...

This will (on a button tap, for example) perform a standard slide-in navigation controller animation directly from the current ViewController (call it vc1) to ViewController2, but "insert" ViewController3 into the stack. Tapping the Back button will take you from vc2 to vc3 to vc1.

@IBAction func didTap(_ sender: Any) {

    guard let vc3 = storyboard?.instantiateViewController(withIdentifier: "vc3"),
        let vc2 = storyboard?.instantiateViewController(withIdentifier: "vc2")
        else { return }

    let vcArray = [self, vc3, vc2]

    self.navigationController?.setViewControllers(vcArray, animated: true)

}

If you want to go from vc2 back to vc1 and "skip over" vc3, in vc2 add (on a button tap, for example):

@IBAction func backToStartTap(_ sender: Any) {

    self.navigationController?.popToRootViewController(animated: true)

}


问:
Mail function can be misused
```<code><?php
if(isset($_POST[submit])){
    $name=$_POST['name'];
    $email=$_POST['email'];
    $msg=$_POST['msg'];
    $to='s.charancherry22@gmail.com';
    $subject='Feedback on Petro e- lib  Website';
    $message="Name:" .$name. "/ n" ."Wrote the Following:" ."/n/n". $msg;
    $headers="From:".$email;
    if(mail($to,$subject,$message, $headers)){
        echo"Thankyou You for Sending the  Feedback"
    }
}
</code>```

I have a feedback form in PHP which sends the mail to me when the form is submitted.
I submitted the feedback with my friend's email in it, the mail was recieved to me as sent by him but he didn't.
My problem is this can be misused by putting others' emails.

How do I prevent this?

答:
PHP Mail function allows any email address as from address in headers variable. It won't ask for password of from address.
But you don't worry about misusing, Beacuase it becomes the spam mail only.

If the server host name and mail host name is same then only it will be saved to inbox otherwise it will be saved in to spam folder only.

For more reference on Spam : https://support.google.com/mail/answer/1366858?hl=en&expand=5

Title: Mail function can be misused

Body:
<?php
if(isset($_POST[submit])){
    $name=$_POST['name'];
    $email=$_POST['email'];
    $msg=$_POST['msg'];
    $to='s.charancherry22@gmail.com';
    $subject='Feedback on Petro e- lib  Website';
    $message="Name:" .$name. "/ n" ."Wrote the Following:" ."/n/n". $msg;
    $headers="From:".$email;
    if(mail($to,$subject,$message, $headers)){
        echo"Thankyou You for Sending the  Feedback"
    }
}

I have a feedback form in PHP which sends the mail to me when the form is submitted.
I submitted the feedback with my friend's email in it, the mail was recieved to me as sent by him but he didn't.
My problem is this can be misused by putting others' emails.

How do I prevent this?


问:
Tensorflow segfault when using with numpy-quaternion library
The following code snippet crashes on the second last line, so where tf.train.latest_checkpoint) is called:

```<code>import tensorflow as tf
from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm
import quaternion

latest_checkpoint = tf.train.latest_checkpoint('checkpoints/default_model/run_000')
print(latest_checkpoint)
</code>```

The ouput is:

```<code>I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcurand.so locally
*** Error in `.../anaconda3/envs/tensorflow_env/bin/python': double free or corruption (!prev): 0x0000000001c7a850 ***

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
</code>```

I am using Python 3.5.2, Tensorflow GPU-version 0.12 in a conda virtual environment, Ubuntu 14.04. The import quaternion statement refers to the external library called numpy-quaternion.

The error does not happen if either the batch_norm or the quaternion import is omitted (so second or third line in the above snippet). Does somebody know why this is happening and how to fix it?

答:
There are two possible ways to work around/fix the error:

Don't import batch_norm

Just always use tf.contrib.layers.python.layers.batch_norm directly in the code, thus omitting the import statement (admittedly, creates a lot of clutter).

Set environment variable LD_PRELOAD

The following fix posted by dennybritz on February 10th in this github issue helped:

```<code>sudo apt-get install libtcmalloc-minimal4
export LD_PRELOAD="/usr/lib/libtcmalloc_minimal.so.4"
</code>```

Note that if you're using PyCharm, you either have to specify this environment variable in the run configurations (see this post) or - if you put the above export statement into your .bashrc - you have to start PyCharm from the command line so that it inherits the environment variables (as explained in this post).

However, while this fixes the issue, I don't know why this error occurs in the first place and if it should be considered a bug that should be reported to either tensorflow or numpy-quaternion devs.

Body:
The following code snippet crashes on the second last line, so where tf.train.latest_checkpoint) is called:

import tensorflow as tf
from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm
import quaternion

latest_checkpoint = tf.train.latest_checkpoint('checkpoints/default_model/run_000')
print(latest_checkpoint)

The ouput is:

I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcurand.so locally
*** Error in `.../anaconda3/envs/tensorflow_env/bin/python': double free or corruption (!prev): 0x0000000001c7a850 ***

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

I am using Python 3.5.2, Tensorflow GPU-version 0.12 in a conda virtual environment, Ubuntu 14.04. The import quaternion statement refers to the external library called numpy-quaternion.

The error does not happen if either the batch_norm or the quaternion import is omitted (so second or third line in the above snippet). Does somebody know why this is happening and how to fix it?

Body:
There are two possible ways to work around/fix the error:

Don't import batch_norm

Just always use tf.contrib.layers.python.layers.batch_norm directly in the code, thus omitting the import statement (admittedly, creates a lot of clutter).

Set environment variable LD_PRELOAD

The following fix posted by dennybritz on February 10th in this github issue helped:

sudo apt-get install libtcmalloc-minimal4
export LD_PRELOAD="/usr/lib/libtcmalloc_minimal.so.4"

Note that if you're using PyCharm, you either have to specify this environment variable in the run configurations (see this post) or - if you put the above export statement into your .bashrc - you have to start PyCharm from the command line so that it inherits the environment variables (as explained in this post).

However, while this fixes the issue, I don't know why this error occurs in the first place and if it should be considered a bug that should be reported to either tensorflow or numpy-quaternion devs.


问:
'entity of the same type already has the same primary key value' error using AutoMapper
When I use AutoMapper, this Error occured:

Attaching an entity of type 'MyProject.DAL.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

I want to map User to UserModel when I retrive it from database. I change UserModel properties in UI and then map it again to User and Update it.
My code is here:

```<code>public UserModel GetUserByUserId(int id)
    {
        var user = db.Users.Where(p => p.UserId == id).FirstOrDefault();
        var userModel = Mapper.Map<UserModel>(user);
        return userModel;
    }

public void Update(UserModel userModel)
    {
        var user = Mapper.Map<User>(userModel);
        db.Entry(user).State = EntityState.Modified;
        db.SaveChanges();
    }
</code>```

but if I don't Use auto mapper and write something like below code, it work correctly.

```<code>public void Update(UserModel userModel)
    {
        updatingUser.Email = userModel.Email;
        updatingUser.FirstName = userModel.FirstName;
        updatingUser.ModifiedDate = DateTime.Now;
        updatingUser.LastName = userModel.LastName;
        updatingUser.Password = userModel.Password;
        updatingUser.UserName = userModel.UserName;

        db.Entry(updatingUser).State = EntityState.Modified;
        db.SaveChanges();
    }
</code>```

What should I do:

答:
object A and his child object B and then setting all properties from and then flushing it towards the .
We no longer: attached the (Object A and B from previous )
We no longer fetched object B separately.</p>

Body:
When I use AutoMapper, this Error occured:

Attaching an entity of type 'MyProject.DAL.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

I want to map User to UserModel when I retrive it from database. I change UserModel properties in UI and then map it again to User and Update it.
My code is here:

public UserModel GetUserByUserId(int id)
    {
        var user = db.Users.Where(p => p.UserId == id).FirstOrDefault();
        var userModel = Mapper.Map<UserModel>(user);
        return userModel;
    }

public void Update(UserModel userModel)
    {
        var user = Mapper.Map<User>(userModel);
        db.Entry(user).State = EntityState.Modified;
        db.SaveChanges();
    }

but if I don't Use auto mapper and write something like below code, it work correctly.

public void Update(UserModel userModel)
    {
        updatingUser.Email = userModel.Email;
        updatingUser.FirstName = userModel.FirstName;
        updatingUser.ModifiedDate = DateTime.Now;
        updatingUser.LastName = userModel.LastName;
        updatingUser.Password = userModel.Password;
        updatingUser.UserName = userModel.UserName;

        db.Entry(updatingUser).State = EntityState.Modified;
        db.SaveChanges();
    }

What should I do:


问:
Retrofit enqueue doesn't work but execute work
I'm using com.squareup.retrofit2:retrofit:2.2.0

```<code>    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://localhost:9000")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();

    final UserService service = retrofit.create(UserService.class);

    Call<User> userCall = service.createUser(user)
</code>```

Here is the problem: when I run the execute it make REST API request but when I use enqueue it does nothing (no exception, no log)

```<code>  userCall.execute(); //this work

  //this does not work
  userCall.enqueue(new Callback<User>() {
      @Override
      public void onResponse(Call<User> call, Response<User> response) {
          // no response
      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
          //nothing here
      }
  });
</code>```

答:
Well,

The issue was because I was using an emulator and try to call the localhost however, it turn out if you want call the localhost you have to use this ip 10.0.2.2

The execute works because I was running as unit test but when it runs enqueue I think it need to run on android platform.

refer to this
https://developer.android.com/studio/run/emulator.html#networkaddresses

How to get the Android Emulator's IP address?

Body:
I'm using com.squareup.retrofit2:retrofit:2.2.0

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://localhost:9000")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient.build())
            .build();

    final UserService service = retrofit.create(UserService.class);

    Call<User> userCall = service.createUser(user)

Here is the problem: when I run the execute it make REST API request but when I use enqueue it does nothing (no exception, no log)

  userCall.execute(); //this work

  //this does not work
  userCall.enqueue(new Callback<User>() {
      @Override
      public void onResponse(Call<User> call, Response<User> response) {
          // no response
      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
          //nothing here
      }
  });


问:
How to get client ip from request metadata with grpc-java
I use grpc-java and get the metadata by ServerInterceptor, but i get below information without client ip address, the authority is server ip, how can i get the client ip?Thanks.

Metadata({:scheme=[http], :method=[POST], :path=[/test/test1],
  :authority=[192.168.199.9:50051], grpc-encoding=[identity],
  grpc-accept-encoding=[identity,deflate,gzip], te=[trailers],
  content-type=[application/grpc], user-agent=[grpc-objc/0.13.0
  grpc-c/0.13.0 (ios)]})

答: In latest (1.2.0) gRPC use io.grpc.Grpc.TRANSPORT_ATTR_REMOTE_ADDR attribute in interceptor to get remote address.


答:
It does not support join by alias. Use unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') in join condition instead or calculate it in a subquery.

```<code>ON( a.user_id =b.user_id AND unix_timestamp(a.event_timestamp,'dd/MM/YYYY HH:MM')=b.max_event_timestamp)
</code>```

Title: Hive Join Query throws Error

Body:
If a user_id  has multiple records then keep the latest record as per event_timestamp .

My HIVE query :

SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;

When I try to run this hive query I get the below error

SemanticException [Error 10002]: Line 8:43 Invalid column reference 'converted_event_timestamp'

Can Someone tell me what went wrong on this hive query and how do I fix this ?

Body:
It does not support join by alias. Use unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') in join condition instead or calculate it in a subquery.

ON( a.user_id =b.user_id AND unix_timestamp(a.event_timestamp,'dd/MM/YYYY HH:MM')=b.max_event_timestamp)


问:
Why can't I reference a character in a string that was previously cast to void?
To use pthreads, I used as input a char* that was cast to void* as input. If it's later cast to (char*) it can be printed and used normally ( (char*)var ). However, if one does (char*)var[i], where 'i' will help us reference a character, it doesn't. Why?

e.g. MS says 'expression must be a pointer to a complete object type'.

答:
The cast, in this case, is lower precedence than the array indexing. Instead, you would have to do something like *((char *)var + i), but the clearest approach is probably to assign it to a temporary:

```<code> char *str = var;
 printf("%c", str[i]);
</code>```

Body:
The cast, in this case, is lower precedence than the array indexing. Instead, you would have to do something like *((char *)var + i), but the clearest approach is probably to assign it to a temporary:

 char *str = var;
 printf("%c", str[i]);


问:
Send silent push notification from Firebase console
Trying to prove a concept I've been working on for a while, which involves my app recieving a silent notification. I am using Firebase Cloud Messaging as it has less overhead than native APNs for the developer.

I know FCM supports silent notifications when you build the payload yourself on your own backend, which is of course my intention. However, I want to make sure I can do what I want to do with this notification, and therefore want to prove it using the FCM console before I spend time writing my backend.

I have managed to send standard notifications from here, but not silent ones. Even when I include the content-available flag I'm still alerted. I think this is due to FCM always including the alert parameter in the JSON. Is there a way to disable this in the test console?

Many Thanks,

答:
There is no way to send notifications different from the standard kind from the Firebase Console.

A quite convenient way is to use Postman or curl with a set Authorization Header.

```<code>curl -H "Content-type: application/json" -H "Authorization:key=<YOUR-API-KEY>"  -X POST -d '{ "data": { "foo": "1","bar": "2"},"to" : "<YOUR-DEVICE-TOKEN>"}' https://fcm.googleapis.com/fcm/send
</code>```

Body:
There is no way to send notifications different from the standard kind from the Firebase Console.

A quite convenient way is to use Postman or curl with a set Authorization Header.

curl -H "Content-type: application/json" -H "Authorization:key=<YOUR-API-KEY>"  -X POST -d '{ "data": { "foo": "1","bar": "2"},"to" : "<YOUR-DEVICE-TOKEN>"}' https://fcm.googleapis.com/fcm/send


问:
Angular CLI (ng) use single instead of double quotes
When I use the 'ng generate' commands, it's writing my import statements using quotes for the path.  I would like it to instead use single quotes.  Is it possible to configure this somehow? </p>

答:
I believ components are generated based on the blueprint here: https://github.com/angular/angular-cli/blob/master/packages/%40angular/cli/blueprints/component/files/path/name.component.ts

as you can see, it has single quotes all over. I dont think you can change this in the cli. but you can definitely build a small script to replace all single quotes with double quotes


问:
mongodb 3 java: aggregation sum of keys
I have collection which is have _id and searchKey . I want to know count of each stored key like "java 2, C++ 3 " .
My entity is

```<code>public class SearchKeyModel implements Serializable {

    private static final long serialVersionUID = 2099119595418807689L;

    private String searchKey;
    private Integer count;
</code>```

Aggregation like this:

```<code>Iterator<Document> sortedList = collection
            .aggregate(Arrays.asList(new Document("$match", new Document("searchKey", 1)),
                    new Document("$sort", new Document("count", -1)),
                    new Document("$group", new Document("_id", null).append("count", new Document("$sum", 1)
                    ))
            )).iterator();

    System.out.println("list hasNext " + sortedList.hasNext());

    while (sortedList.hasNext()) {
        Document doc = sortedList.next();
        SearchKeyModel entity = gson.fromJson(doc.toJson(), SearchKeyModel.class);
        list.add(entity);
    }
        System.out.println("list size is " + list.size());
</code>```

But sortedList.hasNext() always false.

Can anyone help to understand how to finish this?

答:
You can try below aggregation to get the desired result.

Added $project stage to get the output with the same key names as java class fields name for Gson to map them correctly.

I have also changed query to use static helper method.

```<code>List<Bson> aggregation = Arrays.asList(
                Aggregates.group("$searchKey", Accumulators.sum("count", 1)),
                Aggregates.sort(Sorts.descending("count")),
                Aggregates.project(Projections.fields(Projections.excludeId(), Projections.computed("searchKey", "$_id"), Projections.include("count"))));

 Iterator<Document> sortedList = collection.aggregate(aggregation).iterator();
</code>```

Title: mongodb 3 java: aggregation sum of keys

Body:
I have collection which is have _id and searchKey . I want to know count of each stored key like "java 2, C++ 3 " .
My entity is

public class SearchKeyModel implements Serializable {

    private static final long serialVersionUID = 2099119595418807689L;

    private String searchKey;
    private Integer count;

Aggregation like this:

Iterator<Document> sortedList = collection
            .aggregate(Arrays.asList(new Document("$match", new Document("searchKey", 1)),
                    new Document("$sort", new Document("count", -1)),
                    new Document("$group", new Document("_id", null).append("count", new Document("$sum", 1)
                    ))
            )).iterator();

    System.out.println("list hasNext " + sortedList.hasNext());

    while (sortedList.hasNext()) {
        Document doc = sortedList.next();
        SearchKeyModel entity = gson.fromJson(doc.toJson(), SearchKeyModel.class);
        list.add(entity);
    }
        System.out.println("list size is " + list.size());

But sortedList.hasNext() always false.

Can anyone help to understand how to finish this?

Body:
You can try below aggregation to get the desired result.

Added $project stage to get the output with the same key names as java class fields name for Gson to map them correctly.

I have also changed query to use static helper method.

List<Bson> aggregation = Arrays.asList(
                Aggregates.group("$searchKey", Accumulators.sum("count", 1)),
                Aggregates.sort(Sorts.descending("count")),
                Aggregates.project(Projections.fields(Projections.excludeId(), Projections.computed("searchKey", "$_id"), Projections.include("count"))));

 Iterator<Document> sortedList = collection.aggregate(aggregation).iterator();


问:
Python generate all possible strings of length n
I am learning ethical hacking. I have the hash key of a password and the crypt algorithm (sha256/sha512). I want to parse all the strings from a file and to check if the hash of the password matches the hash of each of the string from the file.

The generated String may contain small letters, big letters and numbers.

Any ideas how to generate all the possible Strings of length n which may contain letters and numbers?

答:
You could use itertools.product:

```<code>print([''.join(x) for x in itertools.product('abcABC123', repeat=3)])
['aaa',
 'aab',
 'aac',
 'aaA',
 'aaB',
 'aaC',
 'aa1',
 'aa2',
 'aa3',
 'aba',
...
</code>```

Just add the remaining characters you need to the input string. You can use the constants from the strings module for this.

Be aware that this quickly grows. ;)

Body:
You could use itertools.product:

print([''.join(x) for x in itertools.product('abcABC123', repeat=3)])
['aaa',
 'aab',
 'aac',
 'aaA',
 'aaB',
 'aaC',
 'aa1',
 'aa2',
 'aa3',
 'aba',
...

Just add the remaining characters you need to the input string. You can use the constants from the strings module for this.

Be aware that this quickly grows. ;)


问:
Remove git mapping in Visual Studio 2015
This question has nothing to do with git itself; rather, it has to do with removing a binding/mapping to a git repository that Visual Studio 2015 (VS2015) has previously seen.

Here's a screen shot of the problem:

Notice that the remove button is grayed out (disabled). How can I remove this entry from the "Local Git Repositories" list?

答: Go to Control Panel\User Accounts\Credential Manager and select Windows Credential then remove account of git.


答:
Use itertools.product

```<code>from itertools import product
from string import ascii_letters, digits

for i in product(ascii_letters + digits, repeat=n):
    print(''.join(i))
</code>```

Title: Python generate all possible strings of length n

Body:
I am learning ethical hacking. I have the hash key of a password and the crypt algorithm (sha256/sha512). I want to parse all the strings from a file and to check if the hash of the password matches the hash of each of the string from the file.

The generated String may contain small letters, big letters and numbers.

Any ideas how to generate all the possible Strings of length n which may contain letters and numbers?

Body:
Use itertools.product

from itertools import product
from string import ascii_letters, digits

for i in product(ascii_letters + digits, repeat=n):
    print(''.join(i))


问:
Alternative way of executing for loop in scala
Pattern matching in SCALA

I have 2 lists, one of which contains 20k elements and another contains 200k elements.
I am performing pattern matching where each of the list_1 elements are matched in list_2. I have written a FOR loop which gives me correct answers but it takes more than 2 hours for complete execution.

Is there any other alternative way to perform this task? How can I speed up the process?

The code:

```<code>import scala.collection.mutable.ListBuffer
var list_x = new ListBuffer[Int]();
var list_y = new ListBuffer[Int]();
for( a <- 1 to list_1.length-1){
    println(a);
    if(list_1(a).length > 4){               // if the string in a specific row contains > 4 characters
        val pat = list_1(a).replace("[","").replace("]","");
        val temp = list_2.map(x=> pat.r.findAllIn(x.toString).toList.length).indexOf(1);
        if(temp > 0){
            list_x+=a;
            list_y+=temp;
        }
    }
}
</code>```

答:
Just a more scala-fashioned way to do that:

val findInList = for {
  (pat, index) <- list_1.zipWithIndex
  if pat.length > 4
  rexp = pat.replace("[","").replace("]","").r
  pos = list_2.indexWhere {
    rexp.findFirstIn(_).nonEmpty
  }
  if pos != -1
} yield (index, pos)

val (list_x, list_y) = findInList.unzip
```

Note: I'm assuming that matching at least one (1+) is acceptable, and that you need to not collect unmatched pos != -1 instead of !=0.

Maybe we could improve this by knowing more about your data and eventually also choose a different regexp library.

Body:
Pattern matching in SCALA

I have 2 lists, one of which contains 20k elements and another contains 200k elements.
I am performing pattern matching where each of the list_1 elements are matched in list_2. I have written a FOR loop which gives me correct answers but it takes more than 2 hours for complete execution.

Is there any other alternative way to perform this task? How can I speed up the process?

The code:

import scala.collection.mutable.ListBuffer
var list_x = new ListBuffer[Int]();
var list_y = new ListBuffer[Int]();
for( a <- 1 to list_1.length-1){
    println(a);
    if(list_1(a).length > 4){               // if the string in a specific row contains > 4 characters
        val pat = list_1(a).replace("[","").replace("]","");
        val temp = list_2.map(x=> pat.r.findAllIn(x.toString).toList.length).indexOf(1);
        if(temp > 0){
            list_x+=a;
            list_y+=temp;
        }
    }
}

Body:
Just a more scala-fashioned way to do that:

val findInList = for {
  (pat, index) <- list_1.zipWithIndex
  if pat.length > 4
  rexp = pat.replace("[","").replace("]","").r
  pos = list_2.indexWhere {
    rexp.findFirstIn(_).nonEmpty
  }
  if pos != -1
} yield (index, pos)

val (list_x, list_y) = findInList.unzip

Note: I'm assuming that matching at least one (1+) is acceptable, and that you need to not collect unmatched pos != -1 instead of !=0.

Maybe we could improve this by knowing more about your data and eventually also choose a different regexp library.


问:
Error when generating the SVA-object using package SVA in R
I am trying to apply the surrogate variable analysis (sva) package to my data, but I haven't been able to even pass beyond the model construction. I'm running into an error I can't seem to fix.

My code follows the vignette (though with my own data):

```<code>pheno <- pheno.groups
edata <- counts_all.norm.log #a normalized counts table, with log2(count+1) applied
mod <- model.matrix(~group, data=pheno.groups)
mod0 <- model.matrix(~1,data=pheno)
n.sv <- 1
svobj <- sva(edata,mod=mod,mod0=mod0,n.sv=n.sv)
</code>```

The latter gives an error:

```<code>Error in density.default(x, adjust = adj) : 'x' contains missing values
</code>```

The traceback is as follows:

```<code>7. stop("'x' contains missing values")
6. density.default(x, adjust = adj)
5. density(x, adjust = adj)
4. density(x, adjust = adj)
3. edge.lfdr(ptmp)
2. irwsva.build(dat = dat, mod = mod, mod0 = mod0, n.sv = n.sv, B = B)
1. sva(edata, mod = mod, mod0 = mod0, n.sv = n.sv)
</code>```

Here's my session info:

```<code>Session info -------------------------------------------------------------------------------------------------------------------------------------------
 setting  value
 version  R version 3.3.1 (2016-06-21)
 system   x86_64, darwin13.4.0
 ui       RStudio (1.0.136)
 language (EN)
 collate  en_US.UTF-8
 tz       America/Indiana/Indianapolis
 date     2017-03-29

Packages -----------------------------------------------------------------------------------------------------------------------------------------------
 package              * version  date       source
 acepack                1.4.1    2016-10-29 CRAN (R 3.3.0)
 annotate               1.50.1   2016-10-09 Bioconductor
 AnnotationDbi          1.34.4   2016-07-08 Bioconductor
 assertthat             0.1      2013-12-06 CRAN (R 3.3.0)
 backports              1.0.5    2017-01-18 CRAN (R 3.3.2)
 base64enc              0.1-3    2015-07-28 CRAN (R 3.3.0)
 Biobase              * 2.32.0   2016-05-04 Bioconductor
 BiocGenerics         * 0.18.0   2016-05-04 Bioconductor
 BiocInstaller        * 1.22.3   2016-06-26 Bioconductor
 BiocParallel           1.6.6    2016-08-15 Bioconductor
 bitops                 1.0-6    2013-08-17 CRAN (R 3.3.0)
 bladderbatch         * 1.10.0   2017-03-29 Bioconductor
 checkmate              1.8.2    2016-11-02 CRAN (R 3.3.0)
 cluster              * 2.0.6    2017-03-16 CRAN (R 3.3.2)
 colorspace             1.3-2    2016-12-14 CRAN (R 3.3.2)
 data.table             1.10.4   2017-02-01 CRAN (R 3.3.1)
 DBI                    0.6      2017-03-09 CRAN (R 3.3.2)
 DESeq2               * 1.12.4   2016-08-08 Bioconductor
 devtools               1.12.0   2016-06-24 CRAN (R 3.3.0)
 digest                 0.6.12   2017-01-27 CRAN (R 3.3.2)
 foreign                0.8-67   2016-09-13 CRAN (R 3.3.0)
 Formula                1.2-1    2015-04-07 CRAN (R 3.3.0)
 genefilter           * 1.54.2   2016-05-16 Bioconductor
 geneplotter            1.50.0   2016-05-04 Bioconductor
 GenomeInfoDb         * 1.8.7    2016-09-02 Bioconductor
 GenomicRanges        * 1.24.3   2016-09-11 Bioconductor
 ggplot2                2.2.1    2016-12-30 CRAN (R 3.3.2)
 gridExtra              2.2.1    2016-02-29 CRAN (R 3.3.0)
 gtable                 0.2.0    2016-02-26 CRAN (R 3.3.0)
 Hmisc                  4.0-2    2016-12-31 CRAN (R 3.3.2)
 htmlTable              1.9      2017-01-26 CRAN (R 3.3.2)
 htmltools              0.3.5    2016-03-21 CRAN (R 3.3.0)
 htmlwidgets            0.8      2016-11-09 CRAN (R 3.3.2)
 IRanges              * 2.6.1    2016-06-19 Bioconductor
 knitr                  1.15.1   2016-11-22 CRAN (R 3.3.2)
 lattice                0.20-35  2017-03-25 CRAN (R 3.3.2)
 latticeExtra           0.6-28   2016-02-09 CRAN (R 3.3.0)
 lazyeval               0.2.0    2016-06-12 CRAN (R 3.3.0)
 limma                * 3.28.21  2016-09-05 Bioconductor
 locfit                 1.5-9.1  2013-04-20 CRAN (R 3.3.0)
 magrittr               1.5      2014-11-22 CRAN (R 3.3.0)
 Matrix                 1.2-8    2017-01-20 CRAN (R 3.3.2)
 memoise                1.0.0    2016-01-29 CRAN (R 3.3.0)
 mgcv                 * 1.8-17   2017-02-08 CRAN (R 3.3.2)
 munsell                0.4.3    2016-02-13 CRAN (R 3.3.0)
 nlme                 * 3.1-131  2017-02-06 CRAN (R 3.3.2)
 nnet                   7.3-12   2016-02-02 CRAN (R 3.3.1)
 pamr                 * 1.55     2014-08-27 CRAN (R 3.3.0)
 pheatmap             * 1.0.8    2015-12-11 CRAN (R 3.3.0)
 plyr                   1.8.4    2016-06-08 CRAN (R 3.3.0)
 RColorBrewer           1.1-2    2014-12-07 CRAN (R 3.3.0)
 Rcpp                   0.12.10  2017-03-19 CRAN (R 3.3.2)
 RCurl                  1.95-4.8 2016-03-01 CRAN (R 3.3.0)
 rpart                  4.1-10   2015-06-29 CRAN (R 3.3.1)
 RSQLite                1.1-2    2017-01-08 CRAN (R 3.3.2)
 rstudioapi             0.6      2016-06-27 CRAN (R 3.3.0)
 S4Vectors            * 0.10.3   2016-08-16 Bioconductor
 scales                 0.4.1    2016-11-09 CRAN (R 3.3.2)
 stringi                1.1.3    2017-03-21 CRAN (R 3.3.1)
 stringr                1.2.0    2017-02-18 CRAN (R 3.3.2)
 SummarizedExperiment * 1.2.3    2016-06-10 Bioconductor
 survival             * 2.41-2   2017-03-16 CRAN (R 3.3.2)
 sva                  * 3.20.0   2016-05-04 Bioconductor
 tibble                 1.2      2016-08-26 CRAN (R 3.3.0)
 withr                  1.0.2    2016-06-20 CRAN (R 3.3.0)
 XML                    3.98-1.5 2016-11-10 CRAN (R 3.3.2)
 xtable                 1.8-2    2016-02-05 CRAN (R 3.3.0)
 XVector                0.12.1   2016-07-22 Bioconductor
 zlibbioc               1.18.0   2016-05-04 Bioconductor
</code>```

Any help, or even hints on where to go from here, would be greatly appreciated!

答: I have meanwhile figured out the problem: while my test dataset did not contain NAs or +/- infinite numbers, there were several genes with very low read counts in there. Once these were removed, the package worked!</p>

Body:
I am trying to apply the surrogate variable analysis (sva) package to my data, but I haven't been able to even pass beyond the model construction. I'm running into an error I can't seem to fix.

My code follows the vignette (though with my own data):

pheno <- pheno.groups
edata <- counts_all.norm.log #a normalized counts table, with log2(count+1) applied
mod <- model.matrix(~group, data=pheno.groups)
mod0 <- model.matrix(~1,data=pheno)
n.sv <- 1
svobj <- sva(edata,mod=mod,mod0=mod0,n.sv=n.sv)

The latter gives an error:

Error in density.default(x, adjust = adj) : 'x' contains missing values

The traceback is as follows:

7. stop("'x' contains missing values")
6. density.default(x, adjust = adj)
5. density(x, adjust = adj)
4. density(x, adjust = adj)
3. edge.lfdr(ptmp)
2. irwsva.build(dat = dat, mod = mod, mod0 = mod0, n.sv = n.sv, B = B)
1. sva(edata, mod = mod, mod0 = mod0, n.sv = n.sv)

Here's my session info:

Session info -------------------------------------------------------------------------------------------------------------------------------------------
 setting  value
 version  R version 3.3.1 (2016-06-21)
 system   x86_64, darwin13.4.0
 ui       RStudio (1.0.136)
 language (EN)
 collate  en_US.UTF-8
 tz       America/Indiana/Indianapolis
 date     2017-03-29

Packages -----------------------------------------------------------------------------------------------------------------------------------------------
 package              * version  date       source
 acepack                1.4.1    2016-10-29 CRAN (R 3.3.0)
 annotate               1.50.1   2016-10-09 Bioconductor
 AnnotationDbi          1.34.4   2016-07-08 Bioconductor
 assertthat             0.1      2013-12-06 CRAN (R 3.3.0)
 backports              1.0.5    2017-01-18 CRAN (R 3.3.2)
 base64enc              0.1-3    2015-07-28 CRAN (R 3.3.0)
 Biobase              * 2.32.0   2016-05-04 Bioconductor
 BiocGenerics         * 0.18.0   2016-05-04 Bioconductor
 BiocInstaller        * 1.22.3   2016-06-26 Bioconductor
 BiocParallel           1.6.6    2016-08-15 Bioconductor
 bitops                 1.0-6    2013-08-17 CRAN (R 3.3.0)
 bladderbatch         * 1.10.0   2017-03-29 Bioconductor
 checkmate              1.8.2    2016-11-02 CRAN (R 3.3.0)
 cluster              * 2.0.6    2017-03-16 CRAN (R 3.3.2)
 colorspace             1.3-2    2016-12-14 CRAN (R 3.3.2)
 data.table             1.10.4   2017-02-01 CRAN (R 3.3.1)
 DBI                    0.6      2017-03-09 CRAN (R 3.3.2)
 DESeq2               * 1.12.4   2016-08-08 Bioconductor
 devtools               1.12.0   2016-06-24 CRAN (R 3.3.0)
 digest                 0.6.12   2017-01-27 CRAN (R 3.3.2)
 foreign                0.8-67   2016-09-13 CRAN (R 3.3.0)
 Formula                1.2-1    2015-04-07 CRAN (R 3.3.0)
 genefilter           * 1.54.2   2016-05-16 Bioconductor
 geneplotter            1.50.0   2016-05-04 Bioconductor
 GenomeInfoDb         * 1.8.7    2016-09-02 Bioconductor
 GenomicRanges        * 1.24.3   2016-09-11 Bioconductor
 ggplot2                2.2.1    2016-12-30 CRAN (R 3.3.2)
 gridExtra              2.2.1    2016-02-29 CRAN (R 3.3.0)
 gtable                 0.2.0    2016-02-26 CRAN (R 3.3.0)
 Hmisc                  4.0-2    2016-12-31 CRAN (R 3.3.2)
 htmlTable              1.9      2017-01-26 CRAN (R 3.3.2)
 htmltools              0.3.5    2016-03-21 CRAN (R 3.3.0)
 htmlwidgets            0.8      2016-11-09 CRAN (R 3.3.2)
 IRanges              * 2.6.1    2016-06-19 Bioconductor
 knitr                  1.15.1   2016-11-22 CRAN (R 3.3.2)
 lattice                0.20-35  2017-03-25 CRAN (R 3.3.2)
 latticeExtra           0.6-28   2016-02-09 CRAN (R 3.3.0)
 lazyeval               0.2.0    2016-06-12 CRAN (R 3.3.0)
 limma                * 3.28.21  2016-09-05 Bioconductor
 locfit                 1.5-9.1  2013-04-20 CRAN (R 3.3.0)
 magrittr               1.5      2014-11-22 CRAN (R 3.3.0)
 Matrix                 1.2-8    2017-01-20 CRAN (R 3.3.2)
 memoise                1.0.0    2016-01-29 CRAN (R 3.3.0)
 mgcv                 * 1.8-17   2017-02-08 CRAN (R 3.3.2)
 munsell                0.4.3    2016-02-13 CRAN (R 3.3.0)
 nlme                 * 3.1-131  2017-02-06 CRAN (R 3.3.2)
 nnet                   7.3-12   2016-02-02 CRAN (R 3.3.1)
 pamr                 * 1.55     2014-08-27 CRAN (R 3.3.0)
 pheatmap             * 1.0.8    2015-12-11 CRAN (R 3.3.0)
 plyr                   1.8.4    2016-06-08 CRAN (R 3.3.0)
 RColorBrewer           1.1-2    2014-12-07 CRAN (R 3.3.0)
 Rcpp                   0.12.10  2017-03-19 CRAN (R 3.3.2)
 RCurl                  1.95-4.8 2016-03-01 CRAN (R 3.3.0)
 rpart                  4.1-10   2015-06-29 CRAN (R 3.3.1)
 RSQLite                1.1-2    2017-01-08 CRAN (R 3.3.2)
 rstudioapi             0.6      2016-06-27 CRAN (R 3.3.0)
 S4Vectors            * 0.10.3   2016-08-16 Bioconductor
 scales                 0.4.1    2016-11-09 CRAN (R 3.3.2)
 stringi                1.1.3    2017-03-21 CRAN (R 3.3.1)
 stringr                1.2.0    2017-02-18 CRAN (R 3.3.2)
 SummarizedExperiment * 1.2.3    2016-06-10 Bioconductor
 survival             * 2.41-2   2017-03-16 CRAN (R 3.3.2)
 sva                  * 3.20.0   2016-05-04 Bioconductor
 tibble                 1.2      2016-08-26 CRAN (R 3.3.0)
 withr                  1.0.2    2016-06-20 CRAN (R 3.3.0)
 XML                    3.98-1.5 2016-11-10 CRAN (R 3.3.2)
 xtable                 1.8-2    2016-02-05 CRAN (R 3.3.0)
 XVector                0.12.1   2016-07-22 Bioconductor
 zlibbioc               1.18.0   2016-05-04 Bioconductor

Any help, or even hints on where to go from here, would be greatly appreciated!


问:
Triggering Activity Indicator in Xamarin Forms
I have an icon on my Xamarin.Forms app, which when it is clicked, I would like to change it to an activity indicator. It looks as though I should use a Trigger, Event Triggers look good, but as my image is declared in XAML, I am not sure quite how it would fit together?

At the moment, I have this in XAML at the bottom of a stacklayout:

```<code><Button x:Name="NewDeviceButton"
          Image="glyphish_31_circle_x.png"
          HorizontalOptions="End"
          VerticalOptions="EndAndExpand" />
</code>```

When it is clicked, I would like to show this, for a set amount of time, then trigger some C# functionality:

```<code><ActivityIndicator Color="Black" IsRunning="true" />
</code>```

I am not sure whether it would be best to configure it all in XAML with a trigger, or if i can just have a placeholder type item in XAML and then have all the definitions in C#?

答:
James' answer is correct, however, I prefer to use the page's own IsBusy property, for two reasons:

I'm lazy and I don't want to set-up INotifyPropertyChanged implementation if I don't have to

XF is suppossed to use that property to display a notification by default. This doesn't appear to be working, but if it ever does, this approach will already have us covered to take advantage of it

The only difference with James' answer (besides deleting the INPC implementation) is that you need to give the page a name (x:Name="myPage") and then declare the binding using a reference to it using {Binding Source={x:Reference myPage}, Path=IsBusy} for the ActivityIndicator's IsVisible and IsRunning values.

i.e.:

MainPage.xaml:

```<code><ContentPage ... x:Name="myPage">
    ...
    <ActivityIndicator IsVisible="{Binding Source={x:Reference myPage}, Path=IsBusy}" IsRunning="{Binding Source={x:Reference myPage}, Path=IsBusy}" />
    ...
</ContentPage>
</code>```

MainPage.xaml.cs:

```<code>...
async void OnDoSomethingLong(...)
{
    if (!this.IsBusy)
    {
        try
        {
            this.IsBusy = true;

            //await long operation here, i.e.:
            await Task.Run(() => {/*your long code*/});
        }
        finally
        {
            this.IsBusy = false;
        }
    }
}
...
</code>```

Body:
I have an icon on my Xamarin.Forms app, which when it is clicked, I would like to change it to an activity indicator. It looks as though I should use a Trigger, Event Triggers look good, but as my image is declared in XAML, I am not sure quite how it would fit together?

At the moment, I have this in XAML at the bottom of a stacklayout:

<Button x:Name="NewDeviceButton"
          Image="glyphish_31_circle_x.png"
          HorizontalOptions="End"
          VerticalOptions="EndAndExpand" />

When it is clicked, I would like to show this, for a set amount of time, then trigger some C# functionality:

<ActivityIndicator Color="Black" IsRunning="true" />

I am not sure whether it would be best to configure it all in XAML with a trigger, or if i can just have a placeholder type item in XAML and then have all the definitions in C#?

Body:
James' answer is correct, however, I prefer to use the page's own IsBusy property, for two reasons:

I'm lazy and I don't want to set-up INotifyPropertyChanged implementation if I don't have to

XF is suppossed to use that property to display a notification by default. This doesn't appear to be working, but if it ever does, this approach will already have us covered to take advantage of it

The only difference with James' answer (besides deleting the INPC implementation) is that you need to give the page a name (x:Name="myPage") and then declare the binding using a reference to it using {Binding Source={x:Reference myPage}, Path=IsBusy} for the ActivityIndicator's IsVisible and IsRunning values.

i.e.:

MainPage.xaml:

<ContentPage ... x:Name="myPage">
    ...
    <ActivityIndicator IsVisible="{Binding Source={x:Reference myPage}, Path=IsBusy}" IsRunning="{Binding Source={x:Reference myPage}, Path=IsBusy}" />
    ...
</ContentPage>

MainPage.xaml.cs:

...
async void OnDoSomethingLong(...)
{
    if (!this.IsBusy)
    {
        try
        {
            this.IsBusy = true;

            //await long operation here, i.e.:
            await Task.Run(() => {/*your long code*/});
        }
        finally
        {
            this.IsBusy = false;
        }
    }
}
...


问:
Is there a way to retrieve single row from database as key value only in laravel
can i retrieve single row from database like this in Laravel</p>

```<code>["name"=>"jhon",
"age"=>"18"
]
</code>```

答:
Use the first() method:

```<code>User::where('name', 'John Smith')->first();
</code>```

Or the find() method:

```<code>User::find($id);
</code>```

It will return an object. If you need an array, use the toArray() method to convert an object to an array:

```<code>User::find($id)->toArray();
</code>```

Body:
can i retrieve single row from database like this in Laravel

["name"=>"jhon",
"age"=>"18"
]

Body:
Use the first() method:

User::where('name', 'John Smith')->first();

Or the find() method:

User::find($id);

It will return an object. If you need an array, use the toArray() method to convert an object to an array:

User::find($id)->toArray();