问:
Integrate Firebase Realtime Database with Google app engine web app (Python API)
Beginner here:
I just learned web development in google app engine using Python API. What I intend to do is use firebase's real-time database with my already built web app. When I go to Firebase doc, I only see support for javascript apps. Can someone please show me the big picture what's going on. Does firebase only integrate with javascript web apps or what?

I understand you inject your javascript code in your Html file. But the app still runs on Python on the server side. How do I incorporate firebase with this??

答:
Firebase is primarily designed to be a realtime database which integrates directly into your browser using JavaScript + WebSockets. It has a feature called Firebase functions which allows you to run server side JavaScript such as NodeJS, and an Admin API which allows read/write of data from other applications.

If you are designed a web application you need to decide which parts of the functionality require realtime technologies, and which use server-side. Normally Firebase would be a good use-case for features such as:

Notifications

Chat

Live updates

Instant Messaging

etc

Once you have chosen the features you need Firebase for, you can integrate Firebase into the Frontend using the Web API (JavaScript):
https://firebase.google.com/docs/web/setup

Then you can read/write data in python using the Admin API (Python, Java, NodeJS)
https://firebase.google.com/docs/admin/setup


来源: stackexchange

问:
Angular JWT Profile user(getting field of json)
I have a gettProfile() method which includes below code:

```<code>gettProfile(){
    var headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type','application/json');
    let options = new RequestOptions({headers: headers});
    return this.http.get('http://localhost:3000/api/profile', options)
      .map(res => res.json()); //res.json() localStorage.getItem('students')
  }
</code>```

In this code, when I write console.log(this.authToken); It shows right JWT Token. But when I pass this data to my ProfileComponent it says:

ERROR TypeError: Cannot read property 'name' of undefined

Profile.component.ts code is below:

```<code>  export class ProfileComponent implements OnInit {
        students: Object;
          constructor(private authService:AuthService,  private router:Router) { }

          ngOnInit() {
            this.authService.gettProfile().subscribe(profile =>
            {
              this.students= profile.students;
            },
            err => {
              console.log(err);
              return false;
            });
          }
}
</code>```

Profile.component.html code:

```<code><div class="col-md-6 col-md-offset-3">
    <h1>Hi {{students.name}}!</h1>
    <p>You're logged in!!</p>
    <h3>Registered user detail:</h3>
    <ul>
        <li *ngIf="students">
            {{students.email}} ({{students.surname}} {{students.address}})
        </li>
    </ul>
    <p><a [routerLink]="['/login']">Logout</a></p>
</div>
</code>```

When I look into LocalStorage:

```<code>students:
{"id":"5960fa785017042b9c54f05c","name":"aaa","surname":"aaa","email":"aaa@gmail.com","address":"aaaa","phoneNumber":"aaaa"}
token: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQiOnt9LCJnZXR0ZXJzIjp7fSwiX2lkIjoiNTk2MGZhNzg1MDE3MDQyYjljNTRmMDVjIiwid2FzUG9wdWxhdGVkIjpmYWxzZFeiYWN0aXZlUGF0aHMiOnsicGF0aHMiOnsicGFzc3dvcmQiOiJpbml0IiwiZW1haWwiOiJpbml0IiwiX192IjoiaW5pdCIsInBob25lTnVtYmVyIjoiaW5pdCIsImFkZHJlc3MiOiJpbml0Iiwic3VybmFtZSI6ImluaXQiLCJuYW1lIjoiaW5pdCIsIl9pZCI6ImluaXQifSwic3RhdGVzIjp7Imlnbm9yZSI6e30sImRlZmF1bHQiOnt9LCJpbml0Ijp7Il9fdiI6dHJ1ZSwicGhvbmVOdW1iZXIiOnRydWUsImFkZHJlc3MiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwic3VybmFtZSI6dHJ1ZSwibmFtZSI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwicGF0aHNUb1Njb3BlcyI6e30sImVtaXR0ZXIiOnsiZG9tYWluIjpudWxsLCJfZXZlbnRzIjp7fSwiX2V2ZW50c0NvdW50IjowLCJfbWF4TGlzdGVuZXJzIjowfX0sImlzTmV3IjpmYWxzZSwiX2RvYyI6eyJfX3YiOjAsInBob25lTnVtYmVyIjoiYWFhYSIsImFkZHJlc3MiOiJhYWFhIiwicGFzc3dvcmQiOiIkMmEkMTAkeDlGcTd1SlBIL3VHeUlEeUd3dnRwdUxlS0w2ZVFTTFpJRzRGVVBQQ2loOGg3RVNwZENPN08iLCJlbWFpbCI6ImFhYUBnbWFpbC5jb20iLCJzdXJuYW1lIjoiYWFhIiwibmFtZSI6ImFhYSIsIl9pZCI6IjU5NjBmYTc4NTAxNzA0MmI5YzU0ZjA1YyJ9LCIkaW5pdCI6dHJ1ZSwiaWF0IjoxNDk5NTI5NzA5LCJleHAiOjE1MDAxMzQ1MDl9.UEtThW_30lmPeIUCa8sIZtCfjtb4ek6qWxXyKpnWveI
</code>```

My register and authentication work well. But Profile does not work.

How can I handle with this problem?

答:
Use safe navigation operator. Like so:</p>

```<code>{{students?.name}}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a gettProfile() method which includes below code:

gettProfile(){
    var headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type','application/json');
    let options = new RequestOptions({headers: headers});
    return this.http.get('http://localhost:3000/api/profile', options)
      .map(res => res.json()); //res.json() localStorage.getItem('students')
  }

In this code, when I write console.log(this.authToken); It shows right JWT Token. But when I pass this data to my ProfileComponent it says:

ERROR TypeError: Cannot read property 'name' of undefined

Profile.component.ts code is below:

  export class ProfileComponent implements OnInit {
        students: Object;
          constructor(private authService:AuthService,  private router:Router) { }

          ngOnInit() {
            this.authService.gettProfile().subscribe(profile =>
            {
              this.students= profile.students;
            },
            err => {
              console.log(err);
              return false;
            });
          }
}

Profile.component.html code:

Hi {{students.name}}!

You're logged in!!

Registered user detail:

            {{students.email}} ({{students.surname}} {{students.address}})

Logout

When I look into LocalStorage:

students:
{"id":"5960fa785017042b9c54f05c","name":"aaa","surname":"aaa","email":"aaa@gmail.com","address":"aaaa","phoneNumber":"aaaa"}
token: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQiOnt9LCJnZXR0ZXJzIjp7fSwiX2lkIjoiNTk2MGZhNzg1MDE3MDQyYjljNTRmMDVjIiwid2FzUG9wdWxhdGVkIjpmYWxzZFeiYWN0aXZlUGF0aHMiOnsicGF0aHMiOnsicGFzc3dvcmQiOiJpbml0IiwiZW1haWwiOiJpbml0IiwiX192IjoiaW5pdCIsInBob25lTnVtYmVyIjoiaW5pdCIsImFkZHJlc3MiOiJpbml0Iiwic3VybmFtZSI6ImluaXQiLCJuYW1lIjoiaW5pdCIsIl9pZCI6ImluaXQifSwic3RhdGVzIjp7Imlnbm9yZSI6e30sImRlZmF1bHQiOnt9LCJpbml0Ijp7Il9fdiI6dHJ1ZSwicGhvbmVOdW1iZXIiOnRydWUsImFkZHJlc3MiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwic3VybmFtZSI6dHJ1ZSwibmFtZSI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwicGF0aHNUb1Njb3BlcyI6e30sImVtaXR0ZXIiOnsiZG9tYWluIjpudWxsLCJfZXZlbnRzIjp7fSwiX2V2ZW50c0NvdW50IjowLCJfbWF4TGlzdGVuZXJzIjowfX0sImlzTmV3IjpmYWxzZSwiX2RvYyI6eyJfX3YiOjAsInBob25lTnVtYmVyIjoiYWFhYSIsImFkZHJlc3MiOiJhYWFhIiwicGFzc3dvcmQiOiIkMmEkMTAkeDlGcTd1SlBIL3VHeUlEeUd3dnRwdUxlS0w2ZVFTTFpJRzRGVVBQQ2loOGg3RVNwZENPN08iLCJlbWFpbCI6ImFhYUBnbWFpbC5jb20iLCJzdXJuYW1lIjoiYWFhIiwibmFtZSI6ImFhYSIsIl9pZCI6IjU5NjBmYTc4NTAxNzA0MmI5YzU0ZjA1YyJ9LCIkaW5pdCI6dHJ1ZSwiaWF0IjoxNDk5NTI5NzA5LCJleHAiOjE1MDAxMzQ1MDl9.UEtThW_30lmPeIUCa8sIZtCfjtb4ek6qWxXyKpnWveI

My register and authentication work well. But Profile does not work.

How can I handle with this problem?

Body:
Use safe navigation operator. Like so:

{{students?.name}}


问:
Upgrade to Angular 4 broke implementation of external JS dependency
When I upgraded my angular application to angular 4 the following happened:

```<code>Uncaught ReferenceError: Keycloak is not defined
        at Function.webpackJsonp.../../../../../src/app/services/auth/auth.service.ts.AuthService.init (auth.service.ts:22)
        at Object.../../../../../src/main.ts (main.ts:9)
        at __webpack_require__ (bootstrap 1f6d90b…:54)
        at Object.1 (polyfills.ts:19)
        at __webpack_require__ (bootstrap 1f6d90b…:54)
        at webpackJsonpCallback (bootstrap 1f6d90b…:25)
        at main.bundle.js:1
</code>```

I have removed my script tags from the index.html file and instead included them into the angular-cli.json file:

```<code>  "scripts": [
    "./app/js/keycloak/keycloak.js",
    "./app/js/wavesurfer/wavesurfer.min.js",
    "./bower_components/bootstrap/dist/css/bootstrap.min.css",
    "./app/js/bootstrap/bootstrap.min.js",
    "./app/js/bootstrap/jquery.min.js"
  ]
</code>```

I now get an error on the following code:

```<code>declare let Keycloak: any;

static init(): Promise<any> {
   let keycloakAuth: any = new Keycloak("app/js/keycloak/keycloak.json");

   // other code here
}
</code>```

What did I do wrong? The import of the javascript file or the declaration of this object.

With Angular 2 this worked perfectly.

Let me know if I need to provide more information to solve this issue.

答:
I would install Keycloak JS as well as its typing through npm:

```<code>npm install --save keycloak-js @types/keycloak-js
</code>```

Now, you can import it as a polyfill library -- a library that should be loaded before your app is initialized.

In ./src/polyfills.ts, add

```<code>import 'keycloak-js' // <- use the keycloak foldername in ./node_modules folder
</code>```

Because we also installed the types, you should even remove the declare let Keycloak line because TypeScript will use the @types/keycloak-js package to provide strong typing.  Finally, remove the keycloak line from the scripts array of .angular-cli.json file.

You should now be able to use Keycloak in your project.

Body:
When I upgraded my angular application to angular 4 the following happened:

Uncaught ReferenceError: Keycloak is not defined
        at Function.webpackJsonp.../../../../../src/app/services/auth/auth.service.ts.AuthService.init (auth.service.ts:22)
        at Object.../../../../../src/main.ts (main.ts:9)
        at __webpack_require__ (bootstrap 1f6d90b…:54)
        at Object.1 (polyfills.ts:19)
        at __webpack_require__ (bootstrap 1f6d90b…:54)
        at webpackJsonpCallback (bootstrap 1f6d90b…:25)
        at main.bundle.js:1

I have removed my script tags from the index.html file and instead included them into the angular-cli.json file:

  "scripts": [
    "./app/js/keycloak/keycloak.js",
    "./app/js/wavesurfer/wavesurfer.min.js",
    "./bower_components/bootstrap/dist/css/bootstrap.min.css",
    "./app/js/bootstrap/bootstrap.min.js",
    "./app/js/bootstrap/jquery.min.js"
  ]

I now get an error on the following code:

declare let Keycloak: any;

static init(): Promise<any> {
   let keycloakAuth: any = new Keycloak("app/js/keycloak/keycloak.json");

   // other code here
}

What did I do wrong? The import of the javascript file or the declaration of this object.

With Angular 2 this worked perfectly.

Let me know if I need to provide more information to solve this issue.

Body:
I would install Keycloak JS as well as its typing through npm:

npm install --save keycloak-js @types/keycloak-js

Now, you can import it as a polyfill library -- a library that should be loaded before your app is initialized.

In ./src/polyfills.ts, add

import 'keycloak-js' // <- use the keycloak foldername in ./node_modules folder

Because we also installed the types, you should even remove the declare let Keycloak line because TypeScript will use the @types/keycloak-js package to provide strong typing.  Finally, remove the keycloak line from the scripts array of .angular-cli.json file.

You should now be able to use Keycloak in your project.


问:
Why compiler gives the message "call of overloaded function is ambiguous" here in C++11?
I am testing below code but compiler says following when I compile in C++11:

error: call of overloaded ‘func_A(int)’ is ambiguous

Could anyone give an explanation?

Here is the code:

```<code>template<typename T> class MC {
    public:
    void func_A(int a, T initvalue = T()) {}
    void func_A(int a) {}

    void func_B(int b, T) {}
    void func_B(int b) {}
};

int main(void) {
    MC<int> mc;
    mc.func_A(1);     // error: detects call of overloaded
    mc.func_A(1,2);   // OK

    mc.func_B(10);    // OK
    mc.func_B(10,11); // OK

    return 0;
}
</code>```

The full compile message:

```<code>$ g++ -std=c++11 test.cpp
test.cpp: In function ‘int main()’:
test.cpp:12:16: error: call of overloaded ‘func_A(int)’ is ambiguous
     mc.func_A(1);
                ^
test.cpp:12:16: note: candidates are:
test.cpp:3:10: note: void MC<T>::func_A(int, T) [with T = int]
     void func_A(int a, T initvalue = T()) {}
          ^
test.cpp:4:10: note: void MC<T>::func_A(int) [with T = int]
     void func_A(int a) {}
          ^
</code>```

答:
You have a member function:

```<code>void func_A(int a, T initvalue = T()) {}
</code>```

that can be called like this:

```<code>mc.func_A(1);
</code>```

Then you have an overloaded member function:

```<code>  void func_A(int a) {}
</code>```

that can also be called like this:

```<code> mc.func_A(1);
</code>```

How could the compiler know which function you intend to call by that line? Answer: It can not. Such ambiguous function call is ill-formed. Solution: Remove either the overload or the default argument so that there is no ambiguity.

Body:
I am testing below code but compiler says following when I compile in C++11:

error: call of overloaded ‘func_A(int)’ is ambiguous

Could anyone give an explanation?

Here is the code:

template<typename T> class MC {
    public:
    void func_A(int a, T initvalue = T()) {}
    void func_A(int a) {}

    void func_B(int b, T) {}
    void func_B(int b) {}
};

int main(void) {
    MC<int> mc;
    mc.func_A(1);     // error: detects call of overloaded
    mc.func_A(1,2);   // OK

    mc.func_B(10);    // OK
    mc.func_B(10,11); // OK

    return 0;
}

The full compile message:

$ g++ -std=c++11 test.cpp
test.cpp: In function ‘int main()’:
test.cpp:12:16: error: call of overloaded ‘func_A(int)’ is ambiguous
     mc.func_A(1);
                ^
test.cpp:12:16: note: candidates are:
test.cpp:3:10: note: void MC<T>::func_A(int, T) [with T = int]
     void func_A(int a, T initvalue = T()) {}
          ^
test.cpp:4:10: note: void MC<T>::func_A(int) [with T = int]
     void func_A(int a) {}
          ^

Body:
You have a member function:

void func_A(int a, T initvalue = T()) {}

that can be called like this:

mc.func_A(1);

Then you have an overloaded member function:

  void func_A(int a) {}

that can also be called like this:

 mc.func_A(1);

How could the compiler know which function you intend to call by that line? Answer: It can not. Such ambiguous function call is ill-formed. Solution: Remove either the overload or the default argument so that there is no ambiguity.


问:
Bootstrap navbar transparent on mobile
I've set up my homepage the way I wanted it to look. However, when looking at it on a mobile device, the navbar, which on mobile changes to a dropdown menu, has no background color. I've been trying to change the color itself, but it doesn't do anything.</p>

答:
I think better will be to use your own css like this:-</p>

```<code>.navbar-collapse {
   background: #000;
}
</code>```

Title: Bootstrap navbar transparent on mobile

Body:
I think better will be to use your own css like this:-

.navbar-collapse {
   background: #000;
}


问:
Spring Profiles org.springframework.beans.factory.NoSuchBeanDefinitionException
My sample project is Maven based structure, all my application proeprties files under src/main/resources folder. Below is the complete sample code. I am not understanding why my code not able to find profiles properly unless I use @PropertySource annotation.

My actual doubt is:  I've configured spring properties pretty well in application.properties file, but yet why it cannot find profile and their respective property files? Unless I am using @PropertySource annotation, iam not getting value for env.getProperty("mysql.url"). I mean Environment class not able to pick up values from profiles property files. WHY?

Iam getting error as below:

```<code>Jul 08, 2017 7:54:26 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@300ffa5d: startup date [Sat Jul 08 19:54:26 IST 2017]; root of context hierarchy
helloBean
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'datasource' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1084)
    at com.oreilly.datasource.Main2.main(Main2.java:15)
</code>```

DatasourceConfig.java

```<code>package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

@Configuration
/*@PropertySource("classpath:/application.properties")
@PropertySource("classpath:/dev/application-dev.properties")
@PropertySource("classpath:/prod/application-prod.properties")*/
public class DatasourceConfig {

    @Autowired
    private Environment env;

    @Bean(name="helloBean")
    public String helloWorld() {
        System.out.println("helloBean");
        return "helloWorld....";
    }

    @Bean(name="datasource")
    @Profile("dev")
    public DataSource datasourceForDev(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }

    @Bean(name="datasource")
    @Profile("prod")
    public DataSource datasourceForProd(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }
}
</code>```

Main2.java

```<code>package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main2 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DatasourceConfig.class);

        DataSource dataSource = context.getBean("datasource", DataSource.class);
        String helloBean = context.getBean("helloBean", String.class);

    }

}
</code>```

application.properties

```<code>spring.profiles.active=prod
spring.config.name=application
spring.config.location=classpath:/application.properties,classpath:/dev/application-dev.properties,classpath:/prod/application-dev.properties
</code>```

Below is the project folder structure:

Please tell me what went wrong?

答:
Spring is smart, it chooses the application-x.properties (where x is the environment) depending of the value assigned to spring.profiles.active in the application.properties, so you don't have to worry about register all the files in different @PropertySource annotations.

You can get more info here: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

I suggest you remove all the @Profile annotations and let just one datasource that will be variable (depending on the seleced environment from application.properties). You may understand this with the example that i put at the end of this post.

If you want to define a mysql.url for a particular profile (lets say dev), you need to add the "mysql.url" in the application-dev.properties file, and then set the spring.profiles.active value to dev in application.properties.

Then, in your DatasourceConfig.java, you can perform something like this:

```<code>@Autowired
private Environment env;

//Takes the mysqlUrl from application-x.properties (where x is the value of spring.profiles.active that comes from application.properties)
@Value("${mysql.url}")
private String mysqlUrl;

@Bean(name="helloBean")...

@Bean(name="datasource")
public DataSource datasource() {
    BasicDataSource dataSource = new BasicDataSource();
    System.out.println(mySqlUrl); //This value is variable depending of the profile that you're pointing on.
    return dataSource;
}
</code>```

Please let me know it this is useful for you.

Body:
My sample project is Maven based structure, all my application proeprties files under src/main/resources folder. Below is the complete sample code. I am not understanding why my code not able to find profiles properly unless I use @PropertySource annotation.

My actual doubt is:  I've configured spring properties pretty well in application.properties file, but yet why it cannot find profile and their respective property files? Unless I am using @PropertySource annotation, iam not getting value for env.getProperty("mysql.url"). I mean Environment class not able to pick up values from profiles property files. WHY?

Iam getting error as below:

Jul 08, 2017 7:54:26 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@300ffa5d: startup date [Sat Jul 08 19:54:26 IST 2017]; root of context hierarchy
helloBean
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'datasource' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1084)
    at com.oreilly.datasource.Main2.main(Main2.java:15)

DatasourceConfig.java

package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

@Configuration
/*@PropertySource("classpath:/application.properties")
@PropertySource("classpath:/dev/application-dev.properties")
@PropertySource("classpath:/prod/application-prod.properties")*/
public class DatasourceConfig {

    @Autowired
    private Environment env;

    @Bean(name="helloBean")
    public String helloWorld() {
        System.out.println("helloBean");
        return "helloWorld....";
    }

    @Bean(name="datasource")
    @Profile("dev")
    public DataSource datasourceForDev(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }

    @Bean(name="datasource")
    @Profile("prod")
    public DataSource datasourceForProd(){
        BasicDataSource dataSource = new BasicDataSource();
        System.out.println(env.getProperty("mysql.url"));
        return dataSource;
    }
}

Main2.java

package com.oreilly.datasource;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main2 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DatasourceConfig.class);

        DataSource dataSource = context.getBean("datasource", DataSource.class);
        String helloBean = context.getBean("helloBean", String.class);

    }

}

application.properties

spring.profiles.active=prod
spring.config.name=application
spring.config.location=classpath:/application.properties,classpath:/dev/application-dev.properties,classpath:/prod/application-dev.properties

Below is the project folder structure:

Please tell me what went wrong?

Body:
Spring is smart, it chooses the application-x.properties (where x is the environment) depending of the value assigned to spring.profiles.active in the application.properties, so you don't have to worry about register all the files in different @PropertySource annotations.

You can get more info here: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

I suggest you remove all the @Profile annotations and let just one datasource that will be variable (depending on the seleced environment from application.properties). You may understand this with the example that i put at the end of this post.

If you want to define a mysql.url for a particular profile (lets say dev), you need to add the "mysql.url" in the application-dev.properties file, and then set the spring.profiles.active value to dev in application.properties.

Then, in your DatasourceConfig.java, you can perform something like this:

@Autowired
private Environment env;

//Takes the mysqlUrl from application-x.properties (where x is the value of spring.profiles.active that comes from application.properties)
@Value("${mysql.url}")
private String mysqlUrl;

@Bean(name="helloBean")...

@Bean(name="datasource")
public DataSource datasource() {
    BasicDataSource dataSource = new BasicDataSource();
    System.out.println(mySqlUrl); //This value is variable depending of the profile that you're pointing on.
    return dataSource;
}

Please let me know it this is useful for you.


问:
How to dynamically create an image with a specified number on it?
I have  a place holder image saying something like:

```<code>Your rating is:
   [rating here]
</code>```

My PHP code is supposed to dynamically insert the rating number where there is a blank space left out for it on the placeholder image. How can I do that?

答: I know that the question is "How to dynamically create an image with a specified number on it?" but I'll address the underlying problem instead.  Dynamic image manipulation is heavy on the CPU.  Just don't do it.  And certainly don't do it in the context of a web request.  Consider having static images instead and then show the correct one depending on the rating.  Even if your rating system goes all the way to 100, it would be better to have 100 static images than to keep redrawing the same image over and over.</p>

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Body:
I have  a place holder image saying something like:

Your rating is:
   [rating here]

My PHP code is supposed to dynamically insert the rating number where there is a blank space left out for it on the placeholder image. How can I do that?

OwnerDisplayName: Al W


问:
Cannot resolve symbol animation
I am getting an error in the below two import statements </p>

```<code>import android.animation.AnimatorSet
import android.animation.ObjectAnimator
</code>```

<p>Android Studio is showing cannot resolve symbol animation </p>

答:
Try:
"File" -> "Invalidate Caches..."

Look at this question too (probably a duplicate of):
Android Studio says "cannot resolve symbol" but project compiles

Also check if you have imported the animation class in your class.

Title: Cannot resolve symbol animation

Body:
I am getting an error in the below two import statements

import android.animation.AnimatorSet
import android.animation.ObjectAnimator

Android Studio is showing cannot resolve symbol animation


答:
```<code>void func_A(int a, T initvalue = T()) {} // (1)
void func_A(int a) {} // (2)
</code>```

1 can be called with

```<code>func_A (10, someT); // (a)
</code>```

and

```<code>func_A (10); // (b)
</code>```

while 2 can be called with

```<code>func_A (10); // (c)
</code>```

There is no way for the compiler to tell b from c.

Title: Why compiler gives the message "call of overloaded function is ambiguous" here in C++11?

Body:
void func_A(int a, T initvalue = T()) {} // (1)
void func_A(int a) {} // (2)

1 can be called with

func_A (10, someT); // (a)

and

func_A (10); // (b)

while 2 can be called with

func_A (10); // (c)

There is no way for the compiler to tell b from c.


问:
Error while Compiling "|75|error: cannot convert 'std::vector<int>' to 'int'" while implementing bfs
I am implementing bfs (Breadth First Search ) for the graph , but I am getting an error while I pass  the starting value of the vector to an integer, for the dfs function to perform, as in the dfs function I have passed the source of the vector, i.e the first element of the vector.
error is on the line where start is declared to v[i]
Here is the complete code

```<code>#include <iostream>
#include <vector>
#include <queue>
#include <stdio.h>

using namespace std;
vector<int> v[10];
bool visited[10];
int level[10];
int a = 0;
int arr[10];

void dfs(int s) //function should run only one time

{
    queue<int> q;
    q.push(s);
    visited[s] = true;
    level[s] = 0;
    while (!q.empty())

    {
        int p = q.front();
        arr[a] = p;
        a++;

        q.pop();
        for (int i = 0; i < v[p].size(); i++)

        {
            if (visited[v[p][i]] == false) {
                level[v[p][i]] = level[p] + 1;
                q.push(v[p][i]);
                visited[v[p][i]] = true;
            }
        }
    }
}
int main()
{
    char c;
    int start; // starting element of the vector
    int i = 0; // for keeping track of the parent
    int countt = 0; // keep track of the no of parents
    bool check;
    printf("Child or Parent ?");
    scanf("%c", &c);
    while (countt <= 10) {
        if (c == 'c') {
            check = true;
            int j = 0;
            while (check) {
                // to keep the track of the child;
                scanf("%d", &v[i][j]);
                j++;
            }
        }
        if (c == 'p')

        {

            scanf("%d", &v[i]);
            if (i == 0)

            {
                start = v[i];
            }
            i++;
            countt++;
        }
    }
    printf(" Vector input completed");
    dfs(start);
    printf("DFS completed, printing the dfs now  ");
    for (int g = 0; g <= 10; g++)

    {
        printf("%d", &arr[g]);
    }
}
</code>```

答:
In your current code, v is an array of size 10 containing vector's. However, start is an int, so there is nothing strange in getting an error when trying to assign one to another.

I believe that you wanted v to be either an array of ints or vector of ints. In such a case you just have to declare v properly: int v[10] or vector<int> v(10).

This is general syntax: if you want to declare a vector with known size then you have to put it in (), not in []. Note that you can also fill the vector with some initial values (say zeroes) by writing vector<int> v(10, 0).

In case got you wrong and you wanted to store a graph as vector of vectors, then you can write vector<vector<int>> v(10).

Body:
I am implementing bfs (Breadth First Search ) for the graph , but I am getting an error while I pass  the starting value of the vector to an integer, for the dfs function to perform, as in the dfs function I have passed the source of the vector, i.e the first element of the vector.
error is on the line where start is declared to v[i]
Here is the complete code

#include <iostream>
#include <vector>
#include <queue>
#include <stdio.h>

using namespace std;
vector<int> v[10];
bool visited[10];
int level[10];
int a = 0;
int arr[10];

void dfs(int s) //function should run only one time

{
    queue<int> q;
    q.push(s);
    visited[s] = true;
    level[s] = 0;
    while (!q.empty())

    {
        int p = q.front();
        arr[a] = p;
        a++;

        q.pop();
        for (int i = 0; i < v[p].size(); i++)

        {
            if (visited[v[p][i]] == false) {
                level[v[p][i]] = level[p] + 1;
                q.push(v[p][i]);
                visited[v[p][i]] = true;
            }
        }
    }
}
int main()
{
    char c;
    int start; // starting element of the vector
    int i = 0; // for keeping track of the parent
    int countt = 0; // keep track of the no of parents
    bool check;
    printf("Child or Parent ?");
    scanf("%c", &c);
    while (countt <= 10) {
        if (c == 'c') {
            check = true;
            int j = 0;
            while (check) {
                // to keep the track of the child;
                scanf("%d", &v[i][j]);
                j++;
            }
        }
        if (c == 'p')

        {

            scanf("%d", &v[i]);
            if (i == 0)

            {
                start = v[i];
            }
            i++;
            countt++;
        }
    }
    printf(" Vector input completed");
    dfs(start);
    printf("DFS completed, printing the dfs now  ");
    for (int g = 0; g <= 10; g++)

    {
        printf("%d", &arr[g]);
    }
}


问:
Parsing XML file in python
```<code>    import requests
    import xml.etree.ElementTree as ET

    def abc(area_code, office_code):
        args = area_code + office_code
     url = (described bellow)
     r = requests.get(url=url)
     tree=ET.ElementTree()
     parsed_data=tree.parse(r.content)
      return parsed_data

   abc('503', '402')
</code>```

where url is

```<code>url="http://www.networksolutions.ds.adp.com/NSPhoneToolDB/template/GetBusRouteFilterExpressions.xml?"\
               "Telnum=" +args+ "&FilterNamePrefix=ORPORTCDK&ReturnResult=detail"
</code>```

when i run this thing i am getting

```<code><Element 'GetBusRouteFilterExpressions' at 0x7f2abf526f48>
</code>```

as output instead of entire file.

答:
Read and try the example from

The ElementTree XML API: 20.5.1.2. Parsing XML

As an Element, root has a tag and a dictionary of attributes:

```<code>    \>>> root.tag
    'data'
    \>>> root.attrib
    {}
</code>```

It also has children nodes over which we can iterate:

```<code>    \>>> for child in root:
    ...     print(child.tag, child.attrib)
    ...
    country {'name': 'Liechtenstein'}
    country {'name': 'Singapore'}
    country {'name': 'Panama'}
</code>```

Children are nested, and we can access specific child nodes by index:

```<code>   \ >>> root[0][1].text
    '2008'
</code>```

Title: Parsing XML file in python

Body:
    import requests
    import xml.etree.ElementTree as ET

    def abc(area_code, office_code):
        args = area_code + office_code
     url = (described bellow)
     r = requests.get(url=url)
     tree=ET.ElementTree()
     parsed_data=tree.parse(r.content)
      return parsed_data

   abc('503', '402')

where url is

url="http://www.networksolutions.ds.adp.com/NSPhoneToolDB/template/GetBusRouteFilterExpressions.xml?"\
               "Telnum=" +args+ "&FilterNamePrefix=ORPORTCDK&ReturnResult=detail"

when i run this thing i am getting

<Element 'GetBusRouteFilterExpressions' at 0x7f2abf526f48>

as output instead of entire file.

Body:
Read and try the example from

The ElementTree XML API: 20.5.1.2. Parsing XML

As an Element, root has a tag and a dictionary of attributes:

    \>>> root.tag
    'data'
    \>>> root.attrib
    {}

It also has children nodes over which we can iterate:

    \>>> for child in root:
    ...     print(child.tag, child.attrib)
    ...
    country {'name': 'Liechtenstein'}
    country {'name': 'Singapore'}
    country {'name': 'Panama'}

Children are nested, and we can access specific child nodes by index:

   \ >>> root[0][1].text
    '2008'


问:
Update the table to set the word_count column with the number of words in text column separated with a delimiter comma(,)
Update the table to set the word_count column with the number of words in text column separated with a delimiter comma(,)

Columns

```<code>ID  TEXT                         WORD_COUNT EMAIL                      DOMAIN    AGE
--- ---------------------------- ---------- ------------------------- ---------- ----
1   word1,word2,word3                     3 abc@gmail.com               gmail    10
2   word1,word2                             abc@yahoo.com                        23
3   word1,word2,word3,word4                 abc@gmail.com                        1A
4   word1                                   abc@hello.com                        2A
</code>```

答:
You don't need the subquery:</p>

```<code>update aptroid
    set word_count = length(text)-length(replace(text, ',', ''))+1
</code>```

Body:
Update the table to set the word_count column with the number of words in text column separated with a delimiter comma(,)

Columns

ID  TEXT                         WORD_COUNT EMAIL                      DOMAIN    AGE
--- ---------------------------- ---------- ------------------------- ---------- ----
1   word1,word2,word3                     3 abc@gmail.com               gmail    10
2   word1,word2                             abc@yahoo.com                        23
3   word1,word2,word3,word4                 abc@gmail.com                        1A
4   word1                                   abc@hello.com                        2A

Body:
You don't need the subquery:

update aptroid
    set word_count = length(text)-length(replace(text, ',', ''))+1


问:
Correct way of storing custom text wrapped with styles - Database or Text File?
I am running ASP.NET connecting to a SQL Server 2005 database.

Currently all my data get's saved in the database but when I use my HTML editor control (to allow the user to add styles to the text) sometimes I get the following error when I copy text with lots of styles from another website into the text area (error comes up when data is trying to save to database):

String or binary data would be truncated. The statement has been terminated.

Why is this and how do I handle this? Save the text rather to a text file?

The size of the field in the database is big enough!

Edits

```<code>INSERT INTO TableName(Name, Age, Comments) VALUES (@Name, @Age, @Comments)
</code>```

Then from my code behind I simply call my SQLDatasource like so

```<code>SqlDataSource.Insert()
</code>```

答:
It sounds like you are passing a string variable to a stored procedure whit p.e. varchar(250) and the string length is over 251, even if the field in the table is varchar(1025) you'll get the error because of the param length is not ok.

Or... Try to use "text" type on db field?

It's an idea, if you get more info we'll be more usefull. :)

Body:
I am running ASP.NET connecting to a SQL Server 2005 database.

Currently all my data get's saved in the database but when I use my HTML editor control (to allow the user to add styles to the text) sometimes I get the following error when I copy text with lots of styles from another website into the text area (error comes up when data is trying to save to database):

String or binary data would be truncated. The statement has been terminated.

Why is this and how do I handle this? Save the text rather to a text file?

The size of the field in the database is big enough!

Edits

INSERT INTO TableName(Name, Age, Comments) VALUES (@Name, @Age, @Comments)

Then from my code behind I simply call my SQLDatasource like so

SqlDataSource.Insert()


问:
Angular 2 naviagate
I am learning Angular 2 and I have some trouble with navigate in my app. I have a login component and a app component. The app component is is the index file :

<!doctype html>

  <meta charset="utf-8">
  <title>Test</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

```
</div>
</div>
</p>

<p>In my app.module I created routes :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: AppComponent }
];</code>```

and in the imports of my ngModule I do that :

RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )```
</div>
</div>
</p>

<p>But when I write "/login" in my address bar it redirect me in "/home" why ? How I do to display my login page ? I read a lot of tutorials on that but I understand nothing. Thank you</p>

<p>Edit :
LoginComponent :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AuthService } from './../auth.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent  {

  email: string;
  password: string;
  constructor(public authService: AuthService, private router: Router) {

  }
  signup() {
    this.authService.signup(this.email, this.password);
    this.email = this.password = '';
  }

  login() {
    this.authService.login(this.email, this.password).then(res => {
      this.router.navigateByUrl('/kanban');
      console.log("works");
    }).catch(err => {
      console.log("not works");

    });
    this.email = this.password = '';
  }

  logout() {
    this.authService.logout();
  }

}</code>```

Simply  Login

  <form fxLayout="column">
    <md-input-container>
      <input [(ngModel)]="email" name="email" required mdInput type="email" placeholder="Email">
    </md-input-container>
    <md-input-container>
      <input mdInput [(ngModel)]="password" name="password" required type="password" placeholder="Mot de passe">
    </md-input-container>

    <button (click)="login()" md-button type="submit">Se connecter</button>
  </form>

```

答:
In template of app.component put this

```<code><router-outlet></router-outlet>
</code>```

and in routing

```<code>const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
];
</code>```

The app Angular start in app.component is the root component

Title: Angular 2 naviagate

Body:
I am learning Angular 2 and I have some trouble with navigate in my app. I have a login component and a app component. The app component is is the index file :

<!doctype html>

  <meta charset="utf-8">
  <title>Test</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

In my app.module I created routes :

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: AppComponent }
];

and in the imports of my ngModule I do that :

RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )

But when I write "/login" in my address bar it redirect me in "/home" why ? How I do to display my login page ? I read a lot of tutorials on that but I understand nothing. Thank you

Edit :
LoginComponent :

import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AuthService } from './../auth.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent  {

  email: string;
  password: string;
  constructor(public authService: AuthService, private router: Router) {

  }
  signup() {
    this.authService.signup(this.email, this.password);
    this.email = this.password = '';
  }

  login() {
    this.authService.login(this.email, this.password).then(res => {
      this.router.navigateByUrl('/kanban');
      console.log("works");
    }).catch(err => {
      console.log("not works");

    });
    this.email = this.password = '';
  }

  logout() {
    this.authService.logout();
  }

}

Simply  Login

  <form fxLayout="column">
    <md-input-container>
      <input [(ngModel)]="email" name="email" required mdInput type="email" placeholder="Email">
    </md-input-container>
    <md-input-container>
      <input mdInput [(ngModel)]="password" name="password" required type="password" placeholder="Mot de passe">
    </md-input-container>

    <button (click)="login()" md-button type="submit">Se connecter</button>
  </form>

Body:
In template of app.component put this

<router-outlet></router-outlet>

and in routing

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
];

The app Angular start in app.component is the root component


问:
720kb SocialShare share with dinamic created button
what am i trying to achieve is on click the generate a button that can handle the venets for Social Share. Im creating the button with all the attributes as described at https://github.com/720kb/angular-socialshare but when i click on the button nothing happens. I know that i have to bind the event after the button is created but i really dont know how.</p>

```<code>var testingUrl = response.id;
var twitterButton = '<a id="thisButton"type="button" class="btns twitter-new twitter-skin mdm-btn pull-right" socialshare="" socialshare-provider="twitter" socialshare-trigger="click"  socialshare-url="'+testingUrl+'" socialshare-hashtags="something, something, something" socialshare-via="something," socialshare-text="Checkout this chart" socialshare-popup-height="300" socialshare-popup-width="400" socialshare-trigger="click">Share to <i class="fa fa-twitter"></i></a>'
$('#chart_1_content').append(twitterButton);
</code>```

答:
You need to compile the HTML code first, in order to let angular recognize the directives.
Something like this

var testingUrl = response.id;
var twitterButton = 'Share to '
$('#chart_1_content').append($compile(twitterButton)($scope));
```

Also you might check if the value of testingUrl is a valid URL.

Body:
what am i trying to achieve is on click the generate a button that can handle the venets for Social Share. Im creating the button with all the attributes as described at https://github.com/720kb/angular-socialshare but when i click on the button nothing happens. I know that i have to bind the event after the button is created but i really dont know how.

var testingUrl = response.id;
var twitterButton = 'Share to '
$('#chart_1_content').append(twitterButton);

Body:
You need to compile the HTML code first, in order to let angular recognize the directives.
Something like this

var testingUrl = response.id;
var twitterButton = '<a id="thisButton"type="button" class="btns twitter-new twitter-skin mdm-btn pull-right" socialshare="" socialshare-provider="twitter" socialshare-trigger="click"  socialshare-url="'+testingUrl+'" socialshare-hashtags="something, something, something" socialshare-via="something," socialshare-text="Checkout this chart" socialshare-popup-height="300" socialshare-popup-width="400" socialshare-trigger="click">Share to <i class="fa fa-twitter"></i></a>'
$('#chart_1_content').append($compile(twitterButton)($scope));

Also you might check if the value of testingUrl is a valid URL.


问:
Is transpiling optimizing fields away?
I'm trying to just get a basic Knockout model working in TypeScript, but I think that when I'm transpiling through webpack, that it's optimizing away "unused" variables

```<code>import * as ko from "knockout";

export class ViewModel {
    public firstName: "James";
}

ko.applyBindings(new ViewModel());
</code>```

but the compiled version of ViewModel is

var ViewModel = (function () {\r\n    function ViewModel() {\r\n    }

so I'm getting an error when binding like so

```<code>Uncaught ReferenceError: Unable to process binding "text: function (){return firstName }"
Message: firstName is not defined
</code>```

答:
```<code>export class ViewModel {
    public firstName: "James";
}
</code>```

A colon indicates a type annotation, so you're saying that the firstName field will have type "James" (a string literal type). As with all types in TypeScript, this gets erased at compile time.

I think what you're trying to do is set an initial value for the firstName field, so you should use = instead:

```<code>export class ViewModel {
    public firstName = "James";
}
</code>```

Or with a type:

```<code>export class ViewModel {
    public firstName : string = "James";
}
</code>```

Both compile to the expected output:

```<code>var ViewModel = (function () {
    function ViewModel() {
        this.firstName = "James";
    }
    return ViewModel;
}());
</code>```

Title: Is transpiling optimizing fields away?

Body:
I'm trying to just get a basic Knockout model working in TypeScript, but I think that when I'm transpiling through webpack, that it's optimizing away "unused" variables

import * as ko from "knockout";

export class ViewModel {
    public firstName: "James";
}

ko.applyBindings(new ViewModel());

but the compiled version of ViewModel is

var ViewModel = (function () {\r\n    function ViewModel() {\r\n    }

so I'm getting an error when binding like so

Uncaught ReferenceError: Unable to process binding "text: function (){return firstName }"
Message: firstName is not defined

Body:
export class ViewModel {
    public firstName: "James";
}

A colon indicates a type annotation, so you're saying that the firstName field will have type "James" (a string literal type). As with all types in TypeScript, this gets erased at compile time.

I think what you're trying to do is set an initial value for the firstName field, so you should use = instead:

export class ViewModel {
    public firstName = "James";
}

Or with a type:

export class ViewModel {
    public firstName : string = "James";
}

Both compile to the expected output:

var ViewModel = (function () {
    function ViewModel() {
        this.firstName = "James";
    }
    return ViewModel;
}());


问:
Mongoose Schema with nested optional object with required fields
I'd like to create a Mongoose Schema that validates the object below with the following restrictions:

field2 is optional (0-1 relationship),

field2.type is required if field2 exists (notice that the name of the field is "type" as mongoose reserved word for type definitions),

field2 and the the base object must be in the same document.

Code example

```<code>{
  field1: "data",
  field2: {
    type: "data",
    data: "data"
  }
}
</code>```

Thanks in advance.

答:
You can refer to this answer:

```<code>{
  field1: "your data",
  field2: {
    type: {
      "your data"
    },
    required: false
  }
}
</code>```

So an example would be:

```<code>{
  field1: String,
  field2: {
    type: {
      nestedField1: { type: String, required: true },
      nestedField2: String
    },
    required:false
  }
}
</code>```

If field2 exists, then nestedField1 would be required.

Body:
I'd like to create a Mongoose Schema that validates the object below with the following restrictions:

field2 is optional (0-1 relationship),

field2.type is required if field2 exists (notice that the name of the field is "type" as mongoose reserved word for type definitions),

field2 and the the base object must be in the same document.

Code example

{
  field1: "data",
  field2: {
    type: "data",
    data: "data"
  }
}

Thanks in advance.

Body:
You can refer to this answer:

{
  field1: "your data",
  field2: {
    type: {
      "your data"
    },
    required: false
  }
}

So an example would be:

{
  field1: String,
  field2: {
    type: {
      nestedField1: { type: String, required: true },
      nestedField2: String
    },
    required:false
  }
}

If field2 exists, then nestedField1 would be required.

ContentLicense: CC BY-SA 4.0


问:
How to render custom syntax in Markdown with Gatsby
We're moving a large static site built in Assemble to Gatsby. The neat thing we built was custom syntax in Markdown for non-technical authors. Think of it as a CMS without DB where authors use Github as a tool to edit/approve posts and deploy. Besides the ability to add classes to the Markdown (with markdown-it-attrs), we also added the ability for author to inject components into the markdown which it would get rendered as HTML on the page. This has proven to be a very effective way for collaboration amongst teams. I'll show you an example of an accordion component we built with custom syntax in markdown and its output.

If the author needed to use an accordion on the page, all he/she needed to do was this:

```<code>:::: accordion

::: accordionPanel For Designers

- [WebAIM Color Contrast Checker](http://webaim.org/resources/contrastchecker/ "external"){.ds-link--external}
- [Color Contrast Analyzer (Windows)](https://www.paciellogroup.com/resources/contrastanalyser/ "external"){.ds-link--external}
{.ds-list}

:::

::: accordionPanel For Developers

- [Chrome Accessibility Tools](https://www.npmjs.com/package/accessibility-developer-tools "external"){.ds-link--external}
- [Keyboard testing (WebAIM.org)](http://webaim.org/techniques/keyboard/ "external"){.ds-link--external}
- [quail](https://plugins.jquery.com/quail/){.ds-link--external} - jQuery plugin for checking content against accessibility guidelines
- [a11y](https://github.com/addyosmani/a11y "external"){.ds-link--external} - Accessibility audit tooling for the web
{.ds-list}

:::

::::
</code>```

The code above would get rendered as:

```<code><ul class="accordion">
  <li id="accordion-panel_For Designers" class="ds-accordion--item accordion--item" data-behavior="toggle">
    <h3>
      <a id="accordion-panel_For Designers--toggle" href="#null" class="accordion--title" aria-label="For Designers
        shows more content
      WebAIM Color Contrast CheckerColor Contrast Analyzer (Windows) - shows more content">
        For Designers
        <span class="h-sr-only a11y-text-toggle">shows more content</span>
      </a>
    </h3>
    <section id="accordion-panel_For Designers--panel" class="accordion--content" tabindex="-1">
      <ul class="ds-list">
        <li>
          <a href="http://webaim.org/resources/contrastchecker/" title="external" class="ds-link--external" aria-label="For Designers - shows more content WebAIM Color Contrast CheckerColor Contrast Analyzer (Windows) - shows more content">
              WebAIM Color Contrast Checker
          </a>
        </li>
        <li>
          <a href="https://www.paciellogroup.com/resources/contrastanalyser/" title="external" class="ds-link--external" aria-label="For Designers - shows more content WebAIM Color Contrast CheckerColor Contrast Analyzer (Windows) - shows more content">
              Color Contrast Analyzer (Windows)
          </a>
        </li>
      </ul>
      </section>
    </li>
  </ul>
</code>```

As you can see, we use four colons (::::) as the opening and closing tag for a component, in this case an accordion. The question is how to do this in Gatsby since React renders components in a very different way than Assemble. My team is also learning React as move the site so it's been an interesting challenge. Please, feel free to share ideas. Thanks!

答: You can write plugins which operate on the Remark (markdown parser) AST to do custom stuff like this. Check out the source of the various remark plugins in https://www.gatsbyjs.org/docs/plugins/</p>

Body:
We're moving a large static site built in Assemble to Gatsby. The neat thing we built was custom syntax in Markdown for non-technical authors. Think of it as a CMS without DB where authors use Github as a tool to edit/approve posts and deploy. Besides the ability to add classes to the Markdown (with markdown-it-attrs), we also added the ability for author to inject components into the markdown which it would get rendered as HTML on the page. This has proven to be a very effective way for collaboration amongst teams. I'll show you an example of an accordion component we built with custom syntax in markdown and its output.

If the author needed to use an accordion on the page, all he/she needed to do was this:

:::: accordion

::: accordionPanel For Designers

- [WebAIM Color Contrast Checker](http://webaim.org/resources/contrastchecker/ "external"){.ds-link--external}
- [Color Contrast Analyzer (Windows)](https://www.paciellogroup.com/resources/contrastanalyser/ "external"){.ds-link--external}
{.ds-list}

:::

::: accordionPanel For Developers

- [Chrome Accessibility Tools](https://www.npmjs.com/package/accessibility-developer-tools "external"){.ds-link--external}
- [Keyboard testing (WebAIM.org)](http://webaim.org/techniques/keyboard/ "external"){.ds-link--external}
- [quail](https://plugins.jquery.com/quail/){.ds-link--external} - jQuery plugin for checking content against accessibility guidelines
- [a11y](https://github.com/addyosmani/a11y "external"){.ds-link--external} - Accessibility audit tooling for the web
{.ds-list}

:::

::::

The code above would get rendered as:

        For Designers
        shows more content

              WebAIM Color Contrast Checker

              Color Contrast Analyzer (Windows)

As you can see, we use four colons (::::) as the opening and closing tag for a component, in this case an accordion. The question is how to do this in Gatsby since React renders components in a very different way than Assemble. My team is also learning React as move the site so it's been an interesting challenge. Please, feel free to share ideas. Thanks!


问:
Deploying PhoneGap Applications to Web instead of to App Store
I've built a web platform where one small feature allows users to contribute data to the system. Now that smartphones are so common, I want to build an app that allows people to submit some information, along with a camera photo and their GPS location.

As our users use varying phones, I'd like to build a single universal app to accomplish that task. I found PhoneGap online for that very purpose, but I have a question: can PhoneGap applications be deployed to the web instead of to app stores? By that, I'm asking whether camera and geolocation functionality will still work if the HTML and Javascript files are placed on a web server.

If not, I've also seen JQTouch. Can I use JQTouch instead for such camera and GPS functionality?

答:
I believe that a PhoneGap application is running inside an "interpreter" that will let you access the Camera Accelerometer and so on... So this means that it cannot run outside an Application. So no web deployement

jQTouch is a UI framework, so no access to Camera or GPS

You can use HTML5 to access location via web


答:
Just give the .navbar-collapse a background in your css:

```<code>.navbar-collapse {
   background: #333;
}
</code>```

Title: Bootstrap navbar transparent on mobile

Body: I've set up my homepage the way I wanted it to look. However, when looking at it on a mobile device, the navbar, which on mobile changes to a dropdown menu, has no background color. I've been trying to change the color itself, but it doesn't do anything.

Body:
Just give the .navbar-collapse a background in your css:

.navbar-collapse {
   background: #333;
}


问:
exception Dl.DL_error : undefined symbol: SDL_GetError
So, I wanted to use Tsdl and here's what I did :

I couldn't find SDL 2.0.5 with apt-get so I downloaded it, ./configure && make && sudo make install

opam install tsdl

Then I created a file main.ml (given as an example on tsdl website) :

```<code>open Tsdl
open Result

let main () = match Sdl.init Sdl.Init.video with
  | Error (`Msg e) -> Sdl.log "Init error: %s" e; exit 1
  | Ok () ->
    match Sdl.create_window ~w:640 ~h:480 "SDL OpenGL" Sdl.Window.opengl with
     | Error (`Msg e) -> Sdl.log "Create window error: %s" e; exit 1
     | Ok w ->
       Sdl.delay 3000l;
       Sdl.destroy_window w;
       Sdl.quit ();
       exit 0

let () = main ()
</code>```

ocamlfind ocamlopt -package tsdl -linkpkg -o main.native main.ml

It works and now comes my problem :

```<code>./main.native
Fatal error: exception Dl.DL_error("./main.native: undefined symbol: SDL_GetError")
</code>```

Did I do something wrong or do I need to tell explicitly where my SDL2 lib is or something else ?

Update :

```<code>> ocamlobjinfo $(opam config var tsdl:lib)/tsdl.cmxa | grep Extra
Extra C object files: -L/usr/local/lib -Wl,-rpath,/usr/local/lib -Wl,--enable-new-dtags -lSDL2 -ltsdl
Extra C options:

> sdl2-config --libs
-L/usr/local/lib -Wl,-rpath,/usr/local/lib -Wl,--enable-new-dtags -lSDL2
</code>```

Update 2 :

```<code>> ldd ./main.native
    linux-vdso.so.1 =>  (0x00007fff1f4c1000)
    libffi.so.6 => /usr/lib/x86_64-linux-gnu/libffi.so.6 (0x00007f4aff55e000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f4aff255000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f4aff050000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f4afec87000)
    /lib64/ld-linux-x86-64.so.2 (0x000055dc05e17000)
</code>```

Update 3

```<code>lhooq@lhooq ~/tsdl $ ocamlfind ocamlopt -cclib -lSDL2 -package tsdl -linkpkg -o min.native min.ml -verbose

Effective set of compiler predicates: pkg_result,pkg_unix,pkg_bigarray,pkg_str,pkg_bytes,pkg_ctypes,pkg_ctypes.foreign.base,pkg_ctypes.foreign.unthreaded,pkg_ctypes.foreign,pkg_tsdl,autolink,native
+ ocamlopt.opt -o min.native -verbose -I /home/lhooq/.opam/4.04.0/lib/result -I /home/lhooq/.opam/4.04.0/lib/bytes -I /home/lhooq/.opam/4.04.0/lib/ctypes -I /home/lhooq/.opam/4.04.0/lib/tsdl /home/lhooq/.opam/4.04.0/lib/result/result.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/unix.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/str.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.cmxa /home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.cmxa -cclib -lSDL2 min.ml
+ as -o 'min.o' '/tmp/camlasm9ab424.s'
+ as -o '/tmp/camlstartupe796c9.o' '/tmp/camlstartup4a1081.s'
+ gcc -o 'min.native'   '-L/home/lhooq/.opam/4.04.0/lib/result' '-L/home/lhooq/.opam/4.04.0/lib/bytes' '-L/home/lhooq/.opam/4.04.0/lib/ctypes' '-L/home/lhooq/.opam/4.04.0/lib/tsdl' '-L/home/lhooq/.opam/4.04.0/lib/ocaml'  '/tmp/camlstartupe796c9.o' '/home/lhooq/.opam/4.04.0/lib/ocaml/std_exit.o' 'min.o' '/home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/str.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/unix.a' '/home/lhooq/.opam/4.04.0/lib/result/result.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/stdlib.a' '-L/usr/local/lib' '-Wl,-rpath,/usr/local/lib' '-Wl,--enable-new-dtags' '-lSDL2' '-ltsdl' '-Wl,--no-as-needed' '-lffi' '-lctypes-foreign-base_stubs' '-Wl,--no-as-needed' '-lffi' '-lctypes_stubs' '-Wl,--no-as-needed' '-lcamlstr' '-lbigarray' '-lunix' '-lSDL2' '/home/lhooq/.opam/4.04.0/lib/ocaml/libasmrun.a' -lm  -ldl

lhooq@lhooq ~/tsdl $ ocamlfind ocamlopt -package tsdl -linkpkg -o min.native min.ml -verbose

Effective set of compiler predicates: pkg_result,pkg_unix,pkg_bigarray,pkg_str,pkg_bytes,pkg_ctypes,pkg_ctypes.foreign.base,pkg_ctypes.foreign.unthreaded,pkg_ctypes.foreign,pkg_tsdl,autolink,native
+ ocamlopt.opt -o min.native -verbose -I /home/lhooq/.opam/4.04.0/lib/result -I /home/lhooq/.opam/4.04.0/lib/bytes -I /home/lhooq/.opam/4.04.0/lib/ctypes -I /home/lhooq/.opam/4.04.0/lib/tsdl /home/lhooq/.opam/4.04.0/lib/result/result.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/unix.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/str.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.cmxa /home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.cmxa min.ml
+ as -o 'min.o' '/tmp/camlasm201bd8.s'
+ as -o '/tmp/camlstartup7113e2.o' '/tmp/camlstartup4724f2.s'
+ gcc -o 'min.native'   '-L/home/lhooq/.opam/4.04.0/lib/result' '-L/home/lhooq/.opam/4.04.0/lib/bytes' '-L/home/lhooq/.opam/4.04.0/lib/ctypes' '-L/home/lhooq/.opam/4.04.0/lib/tsdl' '-L/home/lhooq/.opam/4.04.0/lib/ocaml'  '/tmp/camlstartup7113e2.o' '/home/lhooq/.opam/4.04.0/lib/ocaml/std_exit.o' 'min.o' '/home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/str.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/unix.a' '/home/lhooq/.opam/4.04.0/lib/result/result.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/stdlib.a' '-L/usr/local/lib' '-Wl,-rpath,/usr/local/lib' '-Wl,--enable-new-dtags' '-lSDL2' '-ltsdl' '-Wl,--no-as-needed' '-lffi' '-lctypes-foreign-base_stubs' '-Wl,--no-as-needed' '-lffi' '-lctypes_stubs' '-Wl,--no-as-needed' '-lcamlstr' '-lbigarray' '-lunix' '/home/lhooq/.opam/4.04.0/lib/ocaml/libasmrun.a' -lm  -ldl
</code>```

答:
This appears to be a minor issue in tsdl, see this for more information: https://github.com/dbuenzli/tsdl/issues/38

It is fixed in master. As the author suggests you can (for now) do this as a temporary fix:

opam pin add tsdl --dev

EDIT: as indicated by @dbuenzli below this is fixed in 0.9.4 which is on its way to opam.

Body:
So, I wanted to use Tsdl and here's what I did :

I couldn't find SDL 2.0.5 with apt-get so I downloaded it, ./configure && make && sudo make install

opam install tsdl

Then I created a file main.ml (given as an example on tsdl website) :

open Tsdl
open Result

let main () = match Sdl.init Sdl.Init.video with
  | Error (`Msg e) -> Sdl.log "Init error: %s" e; exit 1
  | Ok () ->
    match Sdl.create_window ~w:640 ~h:480 "SDL OpenGL" Sdl.Window.opengl with
     | Error (`Msg e) -> Sdl.log "Create window error: %s" e; exit 1
     | Ok w ->
       Sdl.delay 3000l;
       Sdl.destroy_window w;
       Sdl.quit ();
       exit 0

let () = main ()

ocamlfind ocamlopt -package tsdl -linkpkg -o main.native main.ml

It works and now comes my problem :

./main.native
Fatal error: exception Dl.DL_error("./main.native: undefined symbol: SDL_GetError")

Did I do something wrong or do I need to tell explicitly where my SDL2 lib is or something else ?

Update :

> ocamlobjinfo $(opam config var tsdl:lib)/tsdl.cmxa | grep Extra
Extra C object files: -L/usr/local/lib -Wl,-rpath,/usr/local/lib -Wl,--enable-new-dtags -lSDL2 -ltsdl
Extra C options:

> sdl2-config --libs
-L/usr/local/lib -Wl,-rpath,/usr/local/lib -Wl,--enable-new-dtags -lSDL2

Update 2 :

> ldd ./main.native
    linux-vdso.so.1 =>  (0x00007fff1f4c1000)
    libffi.so.6 => /usr/lib/x86_64-linux-gnu/libffi.so.6 (0x00007f4aff55e000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f4aff255000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f4aff050000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f4afec87000)
    /lib64/ld-linux-x86-64.so.2 (0x000055dc05e17000)

Update 3

lhooq@lhooq ~/tsdl $ ocamlfind ocamlopt -cclib -lSDL2 -package tsdl -linkpkg -o min.native min.ml -verbose

Effective set of compiler predicates: pkg_result,pkg_unix,pkg_bigarray,pkg_str,pkg_bytes,pkg_ctypes,pkg_ctypes.foreign.base,pkg_ctypes.foreign.unthreaded,pkg_ctypes.foreign,pkg_tsdl,autolink,native
+ ocamlopt.opt -o min.native -verbose -I /home/lhooq/.opam/4.04.0/lib/result -I /home/lhooq/.opam/4.04.0/lib/bytes -I /home/lhooq/.opam/4.04.0/lib/ctypes -I /home/lhooq/.opam/4.04.0/lib/tsdl /home/lhooq/.opam/4.04.0/lib/result/result.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/unix.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/str.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.cmxa /home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.cmxa -cclib -lSDL2 min.ml
+ as -o 'min.o' '/tmp/camlasm9ab424.s'
+ as -o '/tmp/camlstartupe796c9.o' '/tmp/camlstartup4a1081.s'
+ gcc -o 'min.native'   '-L/home/lhooq/.opam/4.04.0/lib/result' '-L/home/lhooq/.opam/4.04.0/lib/bytes' '-L/home/lhooq/.opam/4.04.0/lib/ctypes' '-L/home/lhooq/.opam/4.04.0/lib/tsdl' '-L/home/lhooq/.opam/4.04.0/lib/ocaml'  '/tmp/camlstartupe796c9.o' '/home/lhooq/.opam/4.04.0/lib/ocaml/std_exit.o' 'min.o' '/home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/str.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/unix.a' '/home/lhooq/.opam/4.04.0/lib/result/result.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/stdlib.a' '-L/usr/local/lib' '-Wl,-rpath,/usr/local/lib' '-Wl,--enable-new-dtags' '-lSDL2' '-ltsdl' '-Wl,--no-as-needed' '-lffi' '-lctypes-foreign-base_stubs' '-Wl,--no-as-needed' '-lffi' '-lctypes_stubs' '-Wl,--no-as-needed' '-lcamlstr' '-lbigarray' '-lunix' '-lSDL2' '/home/lhooq/.opam/4.04.0/lib/ocaml/libasmrun.a' -lm  -ldl

lhooq@lhooq ~/tsdl $ ocamlfind ocamlopt -package tsdl -linkpkg -o min.native min.ml -verbose

Effective set of compiler predicates: pkg_result,pkg_unix,pkg_bigarray,pkg_str,pkg_bytes,pkg_ctypes,pkg_ctypes.foreign.base,pkg_ctypes.foreign.unthreaded,pkg_ctypes.foreign,pkg_tsdl,autolink,native
+ ocamlopt.opt -o min.native -verbose -I /home/lhooq/.opam/4.04.0/lib/result -I /home/lhooq/.opam/4.04.0/lib/bytes -I /home/lhooq/.opam/4.04.0/lib/ctypes -I /home/lhooq/.opam/4.04.0/lib/tsdl /home/lhooq/.opam/4.04.0/lib/result/result.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/unix.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.cmxa /home/lhooq/.opam/4.04.0/lib/ocaml/str.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.cmxa /home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.cmxa /home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.cmxa min.ml
+ as -o 'min.o' '/tmp/camlasm201bd8.s'
+ as -o '/tmp/camlstartup7113e2.o' '/tmp/camlstartup4724f2.s'
+ gcc -o 'min.native'   '-L/home/lhooq/.opam/4.04.0/lib/result' '-L/home/lhooq/.opam/4.04.0/lib/bytes' '-L/home/lhooq/.opam/4.04.0/lib/ctypes' '-L/home/lhooq/.opam/4.04.0/lib/tsdl' '-L/home/lhooq/.opam/4.04.0/lib/ocaml'  '/tmp/camlstartup7113e2.o' '/home/lhooq/.opam/4.04.0/lib/ocaml/std_exit.o' 'min.o' '/home/lhooq/.opam/4.04.0/lib/tsdl/tsdl.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-unthreaded.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes-foreign-base.a' '/home/lhooq/.opam/4.04.0/lib/ctypes/ctypes.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/str.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/bigarray.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/unix.a' '/home/lhooq/.opam/4.04.0/lib/result/result.a' '/home/lhooq/.opam/4.04.0/lib/ocaml/stdlib.a' '-L/usr/local/lib' '-Wl,-rpath,/usr/local/lib' '-Wl,--enable-new-dtags' '-lSDL2' '-ltsdl' '-Wl,--no-as-needed' '-lffi' '-lctypes-foreign-base_stubs' '-Wl,--no-as-needed' '-lffi' '-lctypes_stubs' '-Wl,--no-as-needed' '-lcamlstr' '-lbigarray' '-lunix' '/home/lhooq/.opam/4.04.0/lib/ocaml/libasmrun.a' -lm  -ldl


问:
Unable to build firebase gradle in Android studio
I am adding Firebase database gradle into my Android Project, but gradle is unable to build.I added Firebase gradle in my app gradle and one google gradle in Project gradle  I am getting this message:

this is my app gradle

```<code> apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "iamrajendra.github.io"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-database:11.0.2'

}
</code>```

and this is my project gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
         classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
I solved the problem. the problem is the version of library

working library

```<code>implementation'com.google.firebase:firebase-database:10.0.0'
</code>```

If the tutorial android library version is 11.01  but this version is not working in android studio

not working library

```<code>com.google.firebase:firebase-database:11.0.2
</code>```

In tutorial gradle dependencies are wrongly written.

https://firebase.google.com/docs/android/setup

Body:
I am adding Firebase database gradle into my Android Project, but gradle is unable to build.I added Firebase gradle in my app gradle and one google gradle in Project gradle  I am getting this message:

this is my app gradle

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "iamrajendra.github.io"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-database:11.0.2'

}

and this is my project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
         classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
I solved the problem. the problem is the version of library

working library

implementation'com.google.firebase:firebase-database:10.0.0'

If the tutorial android library version is 11.01  but this version is not working in android studio

not working library

com.google.firebase:firebase-database:11.0.2

In tutorial gradle dependencies are wrongly written.

https://firebase.google.com/docs/android/setup


问:
Undeclared object variable showing undefined instead of ReferenceError
```<code>var obj = {a : 2};
console.log(obj.b); //prints undefined
console.log(b);      //ReferenceError
</code>```

Here both obj.b and  b are not defined. Can anyone explain the reason behind the different outputs?

答:
You can make the first part work by this

```<code>var obj = {a : 2};
console.log(obj.a); //Your property `b` was not defined or you typed `b` instead of `a`
</code>```

..and the second part by this

```<code>var b = 3;
console.log(b);// `b` was not defined at all
</code>```

Explanations in the comments

Body:
var obj = {a : 2};
console.log(obj.b); //prints undefined
console.log(b);      //ReferenceError

Here both obj.b and  b are not defined. Can anyone explain the reason behind the different outputs?

Body:
You can make the first part work by this

var obj = {a : 2};
console.log(obj.a); //Your property `b` was not defined or you typed `b` instead of `a`

..and the second part by this

var b = 3;
console.log(b);// `b` was not defined at all

Explanations in the comments


问:
How to add auto increment value to realm
I have recently moved from core data to realm. In core data I have auto increment pk for each record that is inserted.

In the realm I couldn't find such thing as auto increment.

At the moment I'm using uuid as pk.

```<code>+(NSString *)primaryKey{
    return @"uuid";
}
</code>```

I still need to have a reference to old pk, so I have added a new field oldPK to realm, so I can use this to reference the other sqlite tables.This is not a long term solution. I'm looking for short term solution till I migrate completely from sqlite to Realm.

Right now my approach is to get the largest value from the existing oldPk values in the db, and increment it for newly added record.

Is there any better of adding auto increment to Realm model ?

答:
Realm hasn't any auto incremental primary keys. You should set it for each record. You can use a unique primary key for each record:

```<code>[NSUUID UUID].UUIDString;
</code>```

or if you want to make primary keys be successively, you can query all records, sort them by primary keys, get the latest record's primary key, increment it and use as a primary key for a new record:

```<code>RLMResults<YourRecordClass *> *records = [[YourRecordClass allObjects] sortedResultsUsingKeyPath:@"uuid" ascending:YES];
NSInteger newPrimaryKey = [records lastObject].uuid + 1;
YourRecordClass *newRecord = [[YourRecordClass alloc] init];
newRecord.uuid = newPrimaryKey;

RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm addObject:author];
[realm commitWriteTransaction];
</code>```

Body:
I have recently moved from core data to realm. In core data I have auto increment pk for each record that is inserted.

In the realm I couldn't find such thing as auto increment.

At the moment I'm using uuid as pk.

+(NSString *)primaryKey{
    return @"uuid";
}

I still need to have a reference to old pk, so I have added a new field oldPK to realm, so I can use this to reference the other sqlite tables.This is not a long term solution. I'm looking for short term solution till I migrate completely from sqlite to Realm.

Right now my approach is to get the largest value from the existing oldPk values in the db, and increment it for newly added record.

Is there any better of adding auto increment to Realm model ?

Body:
Realm hasn't any auto incremental primary keys. You should set it for each record. You can use a unique primary key for each record:

[NSUUID UUID].UUIDString;

or if you want to make primary keys be successively, you can query all records, sort them by primary keys, get the latest record's primary key, increment it and use as a primary key for a new record:

RLMResults<YourRecordClass *> *records = [[YourRecordClass allObjects] sortedResultsUsingKeyPath:@"uuid" ascending:YES];
NSInteger newPrimaryKey = [records lastObject].uuid + 1;
YourRecordClass *newRecord = [[YourRecordClass alloc] init];
newRecord.uuid = newPrimaryKey;

RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm addObject:author];
[realm commitWriteTransaction];


问:
Akka Http - how to read Content-Disposition from HttpResponse headers?
I'm using Akka Http to download a file and I'm having trouble extracting the filename from response headers. My response headers look like this:

```<code>Server: custom_server
Date: Sat, 8 Jul 2017 01:30:39 GMT
Connection: keep-alive
Pragma: public
Cache-Control: must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
content-disposition: attachment;filename*=UTF-8''my_custom_name.pdf
Strict-Transport-Security: max-age=15768000
</code>```

When i'm trying to check if the content-disposition header exists I'm always receiving false:

```<code>val hasDispositionHeader = response.headers.exists {
  case headers.`Content-Disposition`(contentDisposition, params) => true
  case _ => false
}
</code>```

Tried to use the java api too with no success:

```<code>val fileName = response.header[ContentDisposition].get.value
</code>```

I have noticed that the content-disposition header key is lowercase (it's a remote server I have no control over) - any idea on how to deal with this?

Many thanks for your help!

答:
You could use lowercaseName:

```<code>val contentDispositionValue =
  response.headers
          .find(_.lowercaseName == "content-disposition")
          .map(_.value)
</code>```

The above returns an Option[String] that contains the entire header value.

To get the file name (my_custom_name.pdf) from the header value, you have to extract it yourself. If you want to avoid using a regex, as you mentioned in a comment, then you can split the String on the '' delimiter:

```<code>val fileName =
  response.headers
          .find(_.lowercaseName == "content-disposition")
          .map(_.value)
          .map(_.split("''"))
          .collect { case Array(first, second) => second }
</code>```

The above returns an Option[String] that contains only the file name. Obviously this will work only for the specific header value format in your example (i.e., the file name is the last part of the header value and is immediately preceded by a '', and the '' appears only once in the header value). For other header value formats you'll have to adapt the approach as needed.

Body:
I'm using Akka Http to download a file and I'm having trouble extracting the filename from response headers. My response headers look like this:

Server: custom_server
Date: Sat, 8 Jul 2017 01:30:39 GMT
Connection: keep-alive
Pragma: public
Cache-Control: must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
content-disposition: attachment;filename*=UTF-8''my_custom_name.pdf
Strict-Transport-Security: max-age=15768000

When i'm trying to check if the content-disposition header exists I'm always receiving false:

val hasDispositionHeader = response.headers.exists {
  case headers.`Content-Disposition`(contentDisposition, params) => true
  case _ => false
}

Tried to use the java api too with no success:

val fileName = response.header[ContentDisposition].get.value

I have noticed that the content-disposition header key is lowercase (it's a remote server I have no control over) - any idea on how to deal with this?

Many thanks for your help!

Body:
You could use lowercaseName:

val contentDispositionValue =
  response.headers
          .find(_.lowercaseName == "content-disposition")
          .map(_.value)

The above returns an Option[String] that contains the entire header value.

To get the file name (my_custom_name.pdf) from the header value, you have to extract it yourself. If you want to avoid using a regex, as you mentioned in a comment, then you can split the String on the '' delimiter:

val fileName =
  response.headers
          .find(_.lowercaseName == "content-disposition")
          .map(_.value)
          .map(_.split("''"))
          .collect { case Array(first, second) => second }

The above returns an Option[String] that contains only the file name. Obviously this will work only for the specific header value format in your example (i.e., the file name is the last part of the header value and is immediately preceded by a '', and the '' appears only once in the header value). For other header value formats you'll have to adapt the approach as needed.


问:
Updating my Django website's database from a third party service, strategies?
I'm learning Django and to practice I'm currently developing a clone page of YTS, it's a movie torrents repository*.

As of right now, I scrapped all the movies in the website and have them on a single db table called Movie with all the basic information of each movie (I'm planning on adding one more for Genre).

Every few days YTS will post new movies and I want my clone-web to automatically add them to the database. I'm currently stuck on deciding how to do this:

I was planning on comparing the movie id of the last movie in my db against the last movie in the YTS db each time the user enters the website, but that'd mean make a request to YTS every time my page loads, it'd also mean some very slow code should be executed inside my index() views method.

Another strategy would be to query the last time my db was updated (new entries were introduced) and if it's let's say bigger than a day then request new movies to YTS. Problem with this is I don't seem to find any method to query the time of last db updates. Does it even exist such method?

I could also set a cron job to update the information but I'm having problems to make changes from a separated Python function (I import django.db and such but the interpreter refuses to execute django db instructions).

So, all in all, what's the best strategy to update my database from a third party service/website without bothering the user with loading times? How do you set such updates in non-intrusive way to the user? How do you generally do it?

* I know a torrents website borders the illegal and I'm not intended, in any way, to make my project available to the public

答: The simplest way would be to write a custom management command and run it periodically from a cron job.</p>


问:
AffineTransform and flipping the y-axis
i ran into a strange problem when trying to flip the y-axis of a coordinate system that im creating:

```<code>   private AffineTransform getTransform() {
        if (transform == null) {
            transform = new AffineTransform();
            double scaleX = (double) this.getWidth() / (coordinateSystem.getMaxX() - coordinateSystem.getMinY());
            double scaleY = (double) this.getHeight() / (coordinateSystem.getMaxY() - coordinateSystem.getMinY());
            transform.setToScale(scaleX, scaleY);
            double deltaX = (coordinateSystem.getMaxX() - coordinateSystem.getMinX()) / 2;
            double deltaY = (coordinateSystem.getMaxY() - coordinateSystem.getMinY()) / 2;
            transform.translate(deltaX, deltaY);
        }
        return transform;
    }
</code>```

The  AffineTransform is set to scaling and translation. and everything works fine except that my y-values are inverted (max value is a the bottom of the coordinate system, min value is at the top). I tried switching this by inverting the scale factor for the y axis. but this was not working.

Do i have to let the Transform rotate by PI, to achieve the flipped y axis?
Shouldn't multiplying the scale factor for the y axis by minus 1 be the same?

答:
You have a typo on

```<code>double scaleX = (double) this.getWidth() / (coordinateSystem.getMaxX() - coordinateSystem.getMinY());
</code>```

(Last Y should be an X.) Perhaps that's it.

Title: AffineTransform and flipping the y-axis

Body:
i ran into a strange problem when trying to flip the y-axis of a coordinate system that im creating:

   private AffineTransform getTransform() {
        if (transform == null) {
            transform = new AffineTransform();
            double scaleX = (double) this.getWidth() / (coordinateSystem.getMaxX() - coordinateSystem.getMinY());
            double scaleY = (double) this.getHeight() / (coordinateSystem.getMaxY() - coordinateSystem.getMinY());
            transform.setToScale(scaleX, scaleY);
            double deltaX = (coordinateSystem.getMaxX() - coordinateSystem.getMinX()) / 2;
            double deltaY = (coordinateSystem.getMaxY() - coordinateSystem.getMinY()) / 2;
            transform.translate(deltaX, deltaY);
        }
        return transform;
    }

The  AffineTransform is set to scaling and translation. and everything works fine except that my y-values are inverted (max value is a the bottom of the coordinate system, min value is at the top). I tried switching this by inverting the scale factor for the y axis. but this was not working.

Do i have to let the Transform rotate by PI, to achieve the flipped y axis?
Shouldn't multiplying the scale factor for the y axis by minus 1 be the same?

Body:
You have a typo on

double scaleX = (double) this.getWidth() / (coordinateSystem.getMaxX() - coordinateSystem.getMinY());

(Last Y should be an X.) Perhaps that's it.


问:
Bootstrap navbar transparent on mobile
I've set up my homepage the way I wanted it to look. However, when looking at it on a mobile device, the navbar, which on mobile changes to a dropdown menu, has no background color. I've been trying to change the color itself, but it doesn't do anything.</p>

答:
The opacity is set to 0.9

Set it to 1 to be opaque

Title: Bootstrap navbar transparent on mobile


问:
Failover Load balance
What is the best solution to have a backup for your servers? I have a Web server and a SQL data server. I would like to have fail over backup for each of them, I don't know what would I need. I've bought another 4 servers to have a backup for web and data and two server for domain controller and its backup. confused I am going on track or I lost. </p>

答:
Microsoft DPM can be used for backing up SQL and DC servers, with DAS/NAS or azure cloud as preferred storage.
It has a clean and simple GUI for configuring the backups.
Another 3rd party tools like Cloudberry and Backblaze can also be used if you have a small infrastructure and prefer a cost effective cloud backup software.
So if you back up your data to be 100% sure that it's safe and not just to make some backups, you'd better go with professional backup solution.</p>

Title: Failover Load balance


问:
How to Open a new tab or windows from controller MVC ASP
I need to process something on the server from DetailsController from my DetailsView and then I need to return to the DetailsView, but I need display a new windows with the proceced info in new view (DetailsPrint) too, so, any idea how I can make this?

Note: is mandatory go to server, so

```<code>@Html.ActionLink("linkText", "Action", new {controller="ControllerName"}, new {target="_blank"})
</code>```

or

```<code><button onclick="location.href='@Url.Action("Edit", "Home",new { Model.ID })';return false;">Detail</button>

    <input type="button" title="Delete" value="D" onclick="location.href='@Url.Action("Edit", "Home", new { id = item.ID })'" />
</code>```

dont work for me

答:
Action link must, as you correctly coded, have target = _blank to open a new window.

At the same time, a parameter must be supplied to DetailsController to let him know he must return DetailsPrint view instead of the normal DetailsView.

You can supply this parameter by query string

```<code>@Html.ActionLink("linkText", "Action?print=true", new {controller="ControllerName"}, new {target="_blank"})
</code>```

Body:
I need to process something on the server from DetailsController from my DetailsView and then I need to return to the DetailsView, but I need display a new windows with the proceced info in new view (DetailsPrint) too, so, any idea how I can make this?

Note: is mandatory go to server, so

@Html.ActionLink("linkText", "Action", new {controller="ControllerName"}, new {target="_blank"})

or

<button onclick="location.href='@Url.Action("Edit", "Home",new { Model.ID })';return false;">Detail</button>

    <input type="button" title="Delete" value="D" onclick="location.href='@Url.Action("Edit", "Home", new { id = item.ID })'" />

dont work for me

Body:
Action link must, as you correctly coded, have target = _blank to open a new window.

At the same time, a parameter must be supplied to DetailsController to let him know he must return DetailsPrint view instead of the normal DetailsView.

You can supply this parameter by query string

@Html.ActionLink("linkText", "Action?print=true", new {controller="ControllerName"}, new {target="_blank"})


问:
How to change the color of text in text field by selecting color from a drop down menu in HTML
I want to select a value from

   Select Colour

 <button class = "btn _select_color dropdown-toggle"
type = "button"
id = "dropdownMenu1"
data - toggle = "dropdown"
aria - haspopup = "true"
aria - expanded = "false" > Green    < /button>

  <input type = "hidden"
name = "_color"
value = "Green" >

```
</div>
</div>
</p>

<p>and i want the color will be selected in</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="myForm" action="#">
  <div class="form-group">
    <label for="message"> Text Here</label>
    <textarea name="txt1" id="message" cols="30" rows="9" class="form-control"></textarea>
    <input type="text" value="something" onclick="this.value='';this.style.color=_color;" /> </div>
</form></code>```

The color selected from the color list must be reflect in the textfile. I am new to HTML CSS and JS.

答:
This is a basic implementation of how I understood your question.

var colorSelect = document.getElementById("selectColor")
var textbox = document.getElementById("textbox");
function applyColor(){
  var color = colorSelect.value;
  textbox.style.color = color
}

applyColor();

colorSelect.addEventListener("change", applyColor);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="textbox">
text
</textarea>

<select id="selectColor">
  <option value="blue">blue</option>
  <option value="red"> red </option>
</select></code>```

Body:
I want to select a value from

   Select Colour

 <button class = "btn _select_color dropdown-toggle"
type = "button"
id = "dropdownMenu1"
data - toggle = "dropdown"
aria - haspopup = "true"
aria - expanded = "false" > Green    < /button>

  <input type = "hidden"
name = "_color"
value = "Green" >

and i want the color will be selected in

<form name="myForm" action="#">

     Text Here
    <textarea name="txt1" id="message" cols="30" rows="9" class="form-control"></textarea>
    <input type="text" value="something" onclick="this.value='';this.style.color=_color;" />

</form>

The color selected from the color list must be reflect in the textfile. I am new to HTML CSS and JS.

Body:
This is a basic implementation of how I understood your question.

var colorSelect = document.getElementById("selectColor")
var textbox = document.getElementById("textbox");
function applyColor(){
  var color = colorSelect.value;
  textbox.style.color = color
}

applyColor();

colorSelect.addEventListener("change", applyColor);

<textarea id="textbox">
text
</textarea>

<select id="selectColor">
  <option value="blue">blue</option>
  <option value="red"> red </option>
</select>


问:
count element on the basis of matching id javascript
```<code>var data = [{
    id: '1',
    status: 'pending'
}, {
    id: '2',
    status: 'delivered'
}, {
    id: '2',
    status: 'pending'
}, {
    id: '1',
    status: 'shipped'
}, {
    id: '1',
    status: 'pending'
}, {
    id: '2',
    status: 'delivered'
}, {
    id: '2',
    status: 'shipped'
}]

output: [{
    id: 1,
    order: {
        pending: 2,
        shipped: 1
    },
    id: 2,
    order: {
        pending: 1,
        delivered: 2,
        shipped: 1
    }
}]
</code>```

答:
Use Array#reduce to create object with id as keys and Object#values() to convert

var data = [{
  id: '1',
  status: 'pending'
}, {
  id: '2',
  status: 'delivered'
}, {
  id: '2',
  status: 'pending'
}, {
  id: '1',
  status: 'shipped'
}, {
  id: '1',
  status: 'pending'
}, {
  id: '2',
  status: 'delivered'
}, {
  id: '2',
  status: 'shipped'
}]

let res = Object.values(
  data.reduce((a, c) => {
    if (!a[c.id]) {
      a[c.id] = {id: c.id, order: {pending:0, shipped:0, delivered:0}};
    }
    a[c.id].order[c.status] ++;
    return a
  }, {})
);

console.log(res)```

back to array:

Body:
Use Array#reduce to create object with id as keys and Object#values() to convert

var data = [{
  id: '1',
  status: 'pending'
}, {
  id: '2',
  status: 'delivered'
}, {
  id: '2',
  status: 'pending'
}, {
  id: '1',
  status: 'shipped'
}, {
  id: '1',
  status: 'pending'
}, {
  id: '2',
  status: 'delivered'
}, {
  id: '2',
  status: 'shipped'
}]

let res = Object.values(
  data.reduce((a, c) => {
    if (!a[c.id]) {
      a[c.id] = {id: c.id, order: {pending:0, shipped:0, delivered:0}};
    }
    a[c.id].order[c.status] ++;
    return a
  }, {})
);

console.log(res)

back to array: