问:
Spring Boot Multiple Datasource
I'm quite new to spring boot and I'd like to create a multiple datasource for my project.
Here is my current case. I have two packages for entity for multiple database. Let's say

```<code>com.test.entity.db.mysql ; for entities that belong to MySql
com.test.entity.db.h2 ; for entities that belong to H2 Databases
</code>```

So, currently I have two entities class

UserMySql.java

```<code>@Entity
@Table(name="usermysql")
public class UserMysql{

    @Id
    @GeneratedValue
    public int id;

    public String name;

}
</code>```

UserH2.java

```<code>@Entity
@Table(name="userh2")
public class Userh2 {

    @Id
    @GeneratedValue
    public int id;

    public String name;
}
</code>```

I'd like to achieve a configuration where if I create user from UserMySql, it will be saved to MySql Database, and if I create user from Userh2 it will be saved to H2 Databases. So, I also have two DBConfig, let's say MySqlDbConfig and H2DbConfig.

(com.test.model is package where I'll put my Repositories class. It will be defined below)

MySqlDbConfig.java

```<code>@Configuration
@EnableJpaRepositories(
    basePackages="com.test.model",
    entityManagerFactoryRef = "mysqlEntityManager")
public class MySqlDBConfig {

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.test.mysql")
public DataSource mysqlDataSource(){
    return DataSourceBuilder
            .create()
            .build();
}

@Bean(name="mysqlEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(mysqlDataSource())
            .packages("com.test.entity.db.mysql")
            .build();
}

}
</code>```

H2DbConfig.java

```<code>@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "h2EntityManager")
public class H2DbConfig {

@Bean
@ConfigurationProperties(prefix="datasource.test.h2")
public DataSource h2DataSource(){
    return DataSourceBuilder
            .create()
            .driverClassName("org.h2.Driver")
            .build();
}

@Bean(name="h2EntityManager")
public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(h2DataSource())
            .packages("com.test.entity.db.h2")
            .build();
}
}
</code>```

My application.properties file

```<code>#DataSource settings for mysql
datasource.test.mysql.jdbcUrl = jdbc:mysql://127.0.0.1:3306/test
datasource.test.mysql.username = root
datasource.test.mysql.password = root
datasource.test.mysql.driverClassName = com.mysql.jdbc.Driver

#DataSource settings for H2
datasource.test.h2.jdbcUrl = jdbc:h2:~/test
datasource.test.h2.username = sa

# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.validation-query=SELECT 1

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.show_sql = true
spring.jpa.hibernate.format_sql = true

server.port=8080
endpoints.shutdown.enabled=false
</code>```

And then for crud I have UserMySqlDao and UserH2Dao

UserMySqlDao.java

```<code>@Transactional
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{

    public UserMysql findByName(String name);
}
</code>```

UserH2Dao.java

```<code>@Transactional
@Repositories
public interface UserH2Dao extends CrudRepository<Userh2, Integer>{

    public Userh2 findByName(String name);
}
</code>```

And for last, I have an UserController as endpoint to access my service

UserController.java

```<code>@Controller
@RequestMapping("/user")
public class UserController {

@Autowired
private UserMysqlDao userMysqlDao;

@Autowired
private UserH2Dao userH2Dao;

@RequestMapping("/createM")
@ResponseBody
public String createUserMySql(String name){
    UserMysql user = new UserMysql();
    try{
        user.name = name;
        userMysqlDao.save(user);
        return "Success creating user with Id: "+user.id;
    }catch(Exception ex){
        return "Error creating the user: " + ex.toString();
    }
}

@RequestMapping("/createH")
@ResponseBody
public String createUserH2(String name){
    Userh2 user = new Userh2();
    try{
        user.name = name;
        userH2Dao.save(user);
        return "Success creating user with Id: "+user.id;
    }catch(Exception ex){
        return "Error creating the user: " + ex.toString();
    }
}
}
</code>```

Application.java

```<code>@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EntityScan(basePackages="com.test.entity.db")
@ComponentScan
public class Application {

public static void main(String[] args) {
    System.out.println("Entering spring boot");
    ApplicationContext ctx = SpringApplication.run(Application.class, args);

    System.out.println("Let's inspect the beans provided by Spring Boot:");
    String[] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);
    for (String beanName : beanNames) {
        System.out.print(beanName);
        System.out.print(" ");
    }

    System.out.println("");
}

}
</code>```

With this configuration my Spring boot run well, but when I access

```<code>http://localhost/user/createM?name=myname it writes an exception

Error creating the user: org.springframework.dao.InvalidDataAccessResourceUsageException:   could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
</code>```

I've googling around and haven't got a solution yet. Any ideas why this exception occurs? And is this the best way to implement multiple datasource to implement my case above? I'm open to full refactor if needed.

Thanks

答:
Thanks all for your help but it is not complicated as it seems; almost everything is handled internally by SpringBoot.

In my case I want to use Mysql and Mongodb and the solution was to use EnableMongoRepositories and EnableJpaRepositories annotations on to my application class.

```<code>@SpringBootApplication
@EnableTransactionManagement
@EnableMongoRepositories(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
@EnableJpaRepositories(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
class TestApplication { ...
</code>```

NB: All mysql entities have to extend JpaRepository and mongo enities have to extend MongoRepository.

The datasource configs are straight forward as presented by spring documentation:

```<code>//mysql db config
spring.datasource.url= jdbc:mysql://localhost:3306/tangio
spring.datasource.username=test
spring.datasource.password=test

#mongodb config
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=tangio
spring.data.mongodb.username=tangio
spring.data.mongodb.password=tangio
spring.data.mongodb.repositories.enabled=true
</code>```

Title: Spring Boot Multiple Datasource

Body:
I'm quite new to spring boot and I'd like to create a multiple datasource for my project.
Here is my current case. I have two packages for entity for multiple database. Let's say

com.test.entity.db.mysql ; for entities that belong to MySql
com.test.entity.db.h2 ; for entities that belong to H2 Databases

So, currently I have two entities class

UserMySql.java

@Entity
@Table(name="usermysql")
public class UserMysql{

    @Id
    @GeneratedValue
    public int id;

    public String name;

}

UserH2.java

@Entity
@Table(name="userh2")
public class Userh2 {

    @Id
    @GeneratedValue
    public int id;

    public String name;
}

I'd like to achieve a configuration where if I create user from UserMySql, it will be saved to MySql Database, and if I create user from Userh2 it will be saved to H2 Databases. So, I also have two DBConfig, let's say MySqlDbConfig and H2DbConfig.

(com.test.model is package where I'll put my Repositories class. It will be defined below)

MySqlDbConfig.java

@Configuration
@EnableJpaRepositories(
    basePackages="com.test.model",
    entityManagerFactoryRef = "mysqlEntityManager")
public class MySqlDBConfig {

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.test.mysql")
public DataSource mysqlDataSource(){
    return DataSourceBuilder
            .create()
            .build();
}

@Bean(name="mysqlEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(mysqlDataSource())
            .packages("com.test.entity.db.mysql")
            .build();
}

}

H2DbConfig.java

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "h2EntityManager")
public class H2DbConfig {

@Bean
@ConfigurationProperties(prefix="datasource.test.h2")
public DataSource h2DataSource(){
    return DataSourceBuilder
            .create()
            .driverClassName("org.h2.Driver")
            .build();
}

@Bean(name="h2EntityManager")
public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(h2DataSource())
            .packages("com.test.entity.db.h2")
            .build();
}
}

My application.properties file

#DataSource settings for mysql
datasource.test.mysql.jdbcUrl = jdbc:mysql://127.0.0.1:3306/test
datasource.test.mysql.username = root
datasource.test.mysql.password = root
datasource.test.mysql.driverClassName = com.mysql.jdbc.Driver

#DataSource settings for H2
datasource.test.h2.jdbcUrl = jdbc:h2:~/test
datasource.test.h2.username = sa

# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.validation-query=SELECT 1

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.show_sql = true
spring.jpa.hibernate.format_sql = true

server.port=8080
endpoints.shutdown.enabled=false

And then for crud I have UserMySqlDao and UserH2Dao

UserMySqlDao.java

@Transactional
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{

    public UserMysql findByName(String name);
}

UserH2Dao.java

@Transactional
@Repositories
public interface UserH2Dao extends CrudRepository<Userh2, Integer>{

    public Userh2 findByName(String name);
}

And for last, I have an UserController as endpoint to access my service

UserController.java

@Controller
@RequestMapping("/user")
public class UserController {

@Autowired
private UserMysqlDao userMysqlDao;

@Autowired
private UserH2Dao userH2Dao;

@RequestMapping("/createM")
@ResponseBody
public String createUserMySql(String name){
    UserMysql user = new UserMysql();
    try{
        user.name = name;
        userMysqlDao.save(user);
        return "Success creating user with Id: "+user.id;
    }catch(Exception ex){
        return "Error creating the user: " + ex.toString();
    }
}

@RequestMapping("/createH")
@ResponseBody
public String createUserH2(String name){
    Userh2 user = new Userh2();
    try{
        user.name = name;
        userH2Dao.save(user);
        return "Success creating user with Id: "+user.id;
    }catch(Exception ex){
        return "Error creating the user: " + ex.toString();
    }
}
}

Application.java

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EntityScan(basePackages="com.test.entity.db")
@ComponentScan
public class Application {

public static void main(String[] args) {
    System.out.println("Entering spring boot");
    ApplicationContext ctx = SpringApplication.run(Application.class, args);

    System.out.println("Let's inspect the beans provided by Spring Boot:");
    String[] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);
    for (String beanName : beanNames) {
        System.out.print(beanName);
        System.out.print(" ");
    }

    System.out.println("");
}

}

With this configuration my Spring boot run well, but when I access

http://localhost/user/createM?name=myname it writes an exception

Error creating the user: org.springframework.dao.InvalidDataAccessResourceUsageException:   could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement

I've googling around and haven't got a solution yet. Any ideas why this exception occurs? And is this the best way to implement multiple datasource to implement my case above? I'm open to full refactor if needed.

Thanks

Body:
Thanks all for your help but it is not complicated as it seems; almost everything is handled internally by SpringBoot.

In my case I want to use Mysql and Mongodb and the solution was to use EnableMongoRepositories and EnableJpaRepositories annotations on to my application class.

@SpringBootApplication
@EnableTransactionManagement
@EnableMongoRepositories(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
@EnableJpaRepositories(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
class TestApplication { ...

NB: All mysql entities have to extend JpaRepository and mongo enities have to extend MongoRepository.

The datasource configs are straight forward as presented by spring documentation:

//mysql db config
spring.datasource.url= jdbc:mysql://localhost:3306/tangio
spring.datasource.username=test
spring.datasource.password=test

#mongodb config
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=tangio
spring.data.mongodb.username=tangio
spring.data.mongodb.password=tangio
spring.data.mongodb.repositories.enabled=true


来源: stackexchange

问:
How to sniff Wi-Fi AP name and associated devices
I am recently working on a traffic monitoring projet based on counting how many wi-fi devices are present. I want to get a list of available AP SSIDs and all the client devices that are connected to that AP. Basically, I want to get a list of information like follows:

```<code>Network-Name    BSSID    RSSI
    Client-Mac1 RSSI
    Client-Mac2 RSSI
    Client-Mac3 RSSI
Orphan Clients：
    Client-Mac4 RSSI
</code>```

I hope this can be done by using a raspberry pi with Wi-Fi adapter using python. If that is not possible, I have an ESP 8266 and can link it to a Linux machine/Arduino.

Please post your ideas about how this could be implemented with what type of platform/library. It would be the best if you can include some code samples!

答:
Copied from esp8266 examples - ESP8266Wifi - WifiScan:
Then you can send it using serial connection to your main process</p>

```<code>    /*
 *  This sketch demonstrates how to scan WiFi networks.
 *  The API is almost the same as with the WiFi Shield library,
 *  the most obvious difference being the different file you need to include:
 */
#include "ESP8266WiFi.h"

void setup() {
  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am recently working on a traffic monitoring projet based on counting how many wi-fi devices are present. I want to get a list of available AP SSIDs and all the client devices that are connected to that AP. Basically, I want to get a list of information like follows:

Network-Name    BSSID    RSSI
    Client-Mac1 RSSI
    Client-Mac2 RSSI
    Client-Mac3 RSSI
Orphan Clients：
    Client-Mac4 RSSI

I hope this can be done by using a raspberry pi with Wi-Fi adapter using python. If that is not possible, I have an ESP 8266 and can link it to a Linux machine/Arduino.

Please post your ideas about how this could be implemented with what type of platform/library. It would be the best if you can include some code samples!

Body:
Copied from esp8266 examples - ESP8266Wifi - WifiScan:
Then you can send it using serial connection to your main process

    /*
 *  This sketch demonstrates how to scan WiFi networks.
 *  The API is almost the same as with the WiFi Shield library,
 *  the most obvious difference being the different file you need to include:
 */
#include "ESP8266WiFi.h"

void setup() {
  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}


问:
What is wrong with this operator being undefined
I have a component that has the following lines in the ngOnInit method

```<code>    this.businessTypesService.get()
        .subscribe((businessTypes: string[]) => {
            _.each(businessTypes,
                (businessType: string) => {
                    this.businessTypes.push({ label: businessType, value: businessType });
                });
        });
</code>```

Now I have this same type of block 10 times each loading different drop lists of options.  Each is the same except for which service it calls and which array it pushes the results into, so I want to refactor this into a single method, so that I can change the code to something like this.

```<code>this.loadReferenceList(this.businessTypesService.get, this.businessTypes);
</code>```

and the new loadReferenceList method looks like this

```<code>loadReferenceList(loadMethod: () => Observable<string[]>, lookupList: SelectItem[]): any {
    loadMethod()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}
</code>```

Each of the service classes look like this

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

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

@Injectable()
export class BusinessUnitsService {

    get(): Observable<string[]> {
        return Observable.of(this.getData());
    }

    constructor(private readonly http: Http) { }

    getData(): string[] {
        return [
            'Beverage',
            'Food',
            'Beverage & Food',
            'Promo Pack'
        ];
    }

}
</code>```

Right now it is just hard coded data, but will be changed to use Http to pull down the real values later.

The problem is that the this.getdata() line is failing saying that this is undefined.  I don't understand why this would be undefined when I change it around to be called like this.

********Answer************
I made the following changes to get this to work based off of the answer below
the loadReferenceList method was changed to look like this.  Basically added a parameter for the service, so that I could have a reference to what this was supposed to be and then added the .bind method to give the method scope.

```<code>loadReferenceList(loadMethod: () => Observable<string[]>, service: any, lookupList: SelectItem[]): any {
    const method = loadMethod.bind(service);

    method()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}
</code>```

答:
I made a live simple version of what you're doing.

I was having problems using Observable.of(...). It worked when i used Observable.create(...) and new Observable(...).

With pretty much anything that has to do with rxjs, I use a plunkr like this to test. Let me know if it helps?

Body:
I have a component that has the following lines in the ngOnInit method

    this.businessTypesService.get()
        .subscribe((businessTypes: string[]) => {
            _.each(businessTypes,
                (businessType: string) => {
                    this.businessTypes.push({ label: businessType, value: businessType });
                });
        });

Now I have this same type of block 10 times each loading different drop lists of options.  Each is the same except for which service it calls and which array it pushes the results into, so I want to refactor this into a single method, so that I can change the code to something like this.

this.loadReferenceList(this.businessTypesService.get, this.businessTypes);

and the new loadReferenceList method looks like this

loadReferenceList(loadMethod: () => Observable<string[]>, lookupList: SelectItem[]): any {
    loadMethod()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}

Each of the service classes look like this

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

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

@Injectable()
export class BusinessUnitsService {

    get(): Observable<string[]> {
        return Observable.of(this.getData());
    }

    constructor(private readonly http: Http) { }

    getData(): string[] {
        return [
            'Beverage',
            'Food',
            'Beverage & Food',
            'Promo Pack'
        ];
    }

}

Right now it is just hard coded data, but will be changed to use Http to pull down the real values later.

The problem is that the this.getdata() line is failing saying that this is undefined.  I don't understand why this would be undefined when I change it around to be called like this.

********Answer************
I made the following changes to get this to work based off of the answer below
the loadReferenceList method was changed to look like this.  Basically added a parameter for the service, so that I could have a reference to what this was supposed to be and then added the .bind method to give the method scope.

loadReferenceList(loadMethod: () => Observable<string[]>, service: any, lookupList: SelectItem[]): any {
    const method = loadMethod.bind(service);

    method()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}


问:
what is a good mocking framework to start mocking with in asp.net MVC? (novice and probably not a hardcore mocker)
i want to use mocking in my unit tests.

Till now i more programmed 'tests' and not 'unittests' because i tested whole program flows, but reading discussions i can see the beauty of a mock object, from time to time.

But, looking around, there are a lot of frameworks available, and i want to make sure i start with a good one, because i'd like to invest time in learning a mock framework only once.

So as i said in the title, i'm a novice for mocking, using asp.net mvc, and don't think i'll be a hardcore mocker, investigating the edges of a mocking framework.

To give you an idea of what i like in the IOC frameworks i like unity and structuremap.

Michel

答:
I have used both Rhino Mocks and Moq as part of ASP.NET MVC projects with great success. While in the past these frameworks differed quite a bit, their feature sets have converged over the years and so either one would be a good choice.

Since you're specifically targeting MVC, you should consider what Phil Haack has to say as well.

ContentLicense: CC BY-SA 2.5


问:
How to access variables in OOP
I am trying to find a way to get the variable called $connect to run but don't know how.

Filename: /engine/init.php

```<code>class Engine {
    function MySQL() {
        $connect = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char", $db_user, $db_pass);
    }
}
</code>```

Filename: /inc/database.php

```<code>require 'engine/init.php;
$engine = new Engine;
$conn = $engine->MySQL;
// Activate $connect variable
</code>```

If it's not clear, please request for more info.

Thanks,
CrAzYz_

答:
About to run off so this is a little quickly done.

```<code>class Engine
{
    public $db;

    public function connect($host, $database, $charset, $user, $pass)
    {
        $this->db = new PDO("mysql:host=$host;dbname=$database;charset=$charset", $user, $pass);
    }
}
</code>```

First of we have your Engine class that you want to create, we've created a property named db on the class that we can access with ->db. We also have a method called connect which we pass our database variables into so that PDO can connect to our database.

Now we pass in our database credentials to our connect method, in a production environment I really would advise against hard coding these and instead use something like environment variables.

```<code>$engine = new Engine();
$engine->connect('127.0.0.1', 'example_database', 'UTF-8', 'root', 'root');
</code>```

We can then use our newly initiated PDO connection like so:

```<code>$statement = $engine->db->query('SELECT * FROM some_table');
$result    = $statement->execute();
</code>```

That should at least give you a starting point, there are other ways to go about this but I didn't want to stray too far from your original code.

Also if anyone spots anything wrong, let me know and i'll update it when I'm back in, need to run off in a sec.

Title: How to access variables in OOP

Body:
I am trying to find a way to get the variable called $connect to run but don't know how.

Filename: /engine/init.php

class Engine {
    function MySQL() {
        $connect = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char", $db_user, $db_pass);
    }
}

Filename: /inc/database.php

require 'engine/init.php;
$engine = new Engine;
$conn = $engine->MySQL;
// Activate $connect variable

If it's not clear, please request for more info.

Thanks,
CrAzYz_

Body:
About to run off so this is a little quickly done.

class Engine
{
    public $db;

    public function connect($host, $database, $charset, $user, $pass)
    {
        $this->db = new PDO("mysql:host=$host;dbname=$database;charset=$charset", $user, $pass);
    }
}

First of we have your Engine class that you want to create, we've created a property named db on the class that we can access with ->db. We also have a method called connect which we pass our database variables into so that PDO can connect to our database.

Now we pass in our database credentials to our connect method, in a production environment I really would advise against hard coding these and instead use something like environment variables.

$engine = new Engine();
$engine->connect('127.0.0.1', 'example_database', 'UTF-8', 'root', 'root');

We can then use our newly initiated PDO connection like so:

$statement = $engine->db->query('SELECT * FROM some_table');
$result    = $statement->execute();

That should at least give you a starting point, there are other ways to go about this but I didn't want to stray too far from your original code.

Also if anyone spots anything wrong, let me know and i'll update it when I'm back in, need to run off in a sec.


问:
Undefined symbols for architecture x86_64: MPMusicPlayerController
I am using XCode 8.3 and Swift 3.

I am getting the following error related to the AudioToolboxFramework and x86_64 architecture:

```<code>Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_MPMusicPlayerController", referenced from:
      objc-class-ref in libdtdev.a(AudioStream.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

My project targets iOS 10.3 and in build settings the Architectures are listed as:
Standard Architecture (armv7, arm64) - $(ARCH_STANDARD)

The valid architectures are:
arm64 armv7 armv7s

For the settings Build Active Architectures Only, I have it set to YES for DEBUG and NO for RELEASE.

Can anyone tell me why I'm still getting an error relating to x86_64? Is it possibly from another Framework?

My Podfile contains:

```<code>pod 'Alamofire', '~> 4.4'
pod 'SwiftyJSON'
pod 'Fabric'
pod 'Crashlytics'
pod 'ReachabilitySwift'
</code>```

Actually, I've just changed the Build Active Architectures Only for DEBUG to NO and got a lot of errors saying No such module 'ReachabilitySwift' so maybe its related to that library? I also get the same error if I remove the AudioToolbox.framework from General -> Linked Frameworks and Libraries.

Also, I ran:
lipo -info ./MyProject/Library/libdtdev.a

and got this:
Architectures in the fat file: ./MyProject/Library/libdtdev.a are: armv7 i386 x86_64 arm64

So there is definitely something defining the x86_64 arch.

答:
I got the solution from this link:
MPMusicPlayerController and setNowPlayingItem

The solution was to add the MediaPlayer.framework to the Linked Frameworks and Libraries.

Body:
I am using XCode 8.3 and Swift 3.

I am getting the following error related to the AudioToolboxFramework and x86_64 architecture:

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_MPMusicPlayerController", referenced from:
      objc-class-ref in libdtdev.a(AudioStream.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

My project targets iOS 10.3 and in build settings the Architectures are listed as:
Standard Architecture (armv7, arm64) - $(ARCH_STANDARD)

The valid architectures are:
arm64 armv7 armv7s

For the settings Build Active Architectures Only, I have it set to YES for DEBUG and NO for RELEASE.

Can anyone tell me why I'm still getting an error relating to x86_64? Is it possibly from another Framework?

My Podfile contains:

pod 'Alamofire', '~> 4.4'
pod 'SwiftyJSON'
pod 'Fabric'
pod 'Crashlytics'
pod 'ReachabilitySwift'

Actually, I've just changed the Build Active Architectures Only for DEBUG to NO and got a lot of errors saying No such module 'ReachabilitySwift' so maybe its related to that library? I also get the same error if I remove the AudioToolbox.framework from General -> Linked Frameworks and Libraries.

Also, I ran:
lipo -info ./MyProject/Library/libdtdev.a

and got this:
Architectures in the fat file: ./MyProject/Library/libdtdev.a are: armv7 i386 x86_64 arm64

So there is definitely something defining the x86_64 arch.


问:
MongoDB: updateOne query , set unset values if exists
I am looking to create a mongodb query to update once document such a way that it will set a few fields with values and if there are already fields available (other fields which are not is set) unset them.

I did it like this:

```<code>db.collection('collectionName").find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    }
                },
                { "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })
</code>```

Now the problem is if the field1,2 or 3 are not there in the document then the query fails to set the field 4 and 5.

Is there any flag which i am missing in the mongo query?
Please help.

EDIT: Solution

```<code>db.collection('collectionName').find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    },
                  "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })
</code>```

答:
I think you got the braces wrong.

You're using .collection(...).find(...).updateOne({"$unset" :{} }, {"$set": {} }).

You should use .collection(...).find(...).updateOne({"$unset" :{}, "$set": {} }).

Note that you're missing the filter argument to updateOne. Have you looked at findOneAndUpdate?

Lastly, it's probably a copy/paste mistake, but the quotes are mismatched in the collection access (collection('name")).

Body:
I am looking to create a mongodb query to update once document such a way that it will set a few fields with values and if there are already fields available (other fields which are not is set) unset them.

I did it like this:

db.collection('collectionName").find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    }
                },
                { "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })

Now the problem is if the field1,2 or 3 are not there in the document then the query fails to set the field 4 and 5.

Is there any flag which i am missing in the mongo query?
Please help.

EDIT: Solution

db.collection('collectionName').find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    },
                  "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })


问:
Call HttpUtility from within Azure Functions
I am trying to make a REST call from within Azure Functions. For these lines of code:

```<code>var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
</code>```

I get the following error.

```<code>The name 'HttpUtility' does not exist in the current context
</code>```

I am using the web interface in Azure.com.

答:
You are probably missing a proper reference to System.Web:

```<code>#r "System.Web"
using System.Web;
</code>```

See Referencing External Assemblies.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a REST call from within Azure Functions. For these lines of code:

var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);

I get the following error.

The name 'HttpUtility' does not exist in the current context

I am using the web interface in Azure.com.

Body:
You are probably missing a proper reference to System.Web:

#r "System.Web"
using System.Web;

See Referencing External Assemblies.


问:
What is 'code repeat' exactly
I read from the book(Beginning Python From Novice to Profession) that "it is usually thought as a bad thing to repeat code"(I'm not native speaker, so I'm not sure how it is wrote Initially), and says:

```<code>#===11-7===
file = open(PATH)
while True:
    char = file.read(1)
    if not char:
        break
    print('Processing:', char)
file.close()
</code>```

Is better than:

```<code>#===11-6===
file = open(PATH)
char = file.read(1)
    while char:
        print('Processing:', char)
        char = file.read(1)
file.close()
</code>```

because 11-7 avoids the code repeating. So I'm here to ask: what is code repeating? And is it so bad?

Merely judged form 11-6 I din't see some sort of the... disadvantages, and to be honest, if I haven't watch the book, I would perfer to code like 11-6. Thanks~

答:
The second example does does the read operation in two places. So--

Imagine that you wrote this code, and at some point in the future, you change how you're reading the data; perhaps now you want to read it over the network instead of from a file, or you want to use a different function to read from the file. In the first example you only have to change "file.read(1)" in one place, whereas in the second you have to do it in two, and you might miss one of them, or make a mistake, etc.

Similarly, you might discover a bug in the code, and accidentally only fix it in one of the two places.

Now this is obviously a simplified example, where it doesn't matter too much, but in real-world programs mistakes like this are very easy to make: imagine that it's not a single line but 50 lines of duplicated code, and someone fixes a bug in one copy but not in the other. You now have a problem that is potentially very difficult to debug!

Title: What is 'code repeat' exactly

Body:
I read from the book(Beginning Python From Novice to Profession) that "it is usually thought as a bad thing to repeat code"(I'm not native speaker, so I'm not sure how it is wrote Initially), and says:

#===11-7===
file = open(PATH)
while True:
    char = file.read(1)
    if not char:
        break
    print('Processing:', char)
file.close()

Is better than:

#===11-6===
file = open(PATH)
char = file.read(1)
    while char:
        print('Processing:', char)
        char = file.read(1)
file.close()

because 11-7 avoids the code repeating. So I'm here to ask: what is code repeating? And is it so bad?

Merely judged form 11-6 I din't see some sort of the... disadvantages, and to be honest, if I haven't watch the book, I would perfer to code like 11-6. Thanks~


问:
How to place dynamic templates in elk instead of using dev tools in kibana
I'm new to ELK can any one help me. I'm able to get query results by placing following in dev tools of Kibana. But I need to load this template dynamically instead of querying from dev tools.

```<code>PUT /my_index
{
    "mappings": {
        "type1" : {
            "properties" : {
                "obj1" : {
                    "type" : "nested"
                }
            }
        }
    }
}
</code>```

Can anyone help me in configuring this.
Thanks in advance!

答:
You need to use an index template if you want to set the mapping at index creation time.  You can use the ES dev tools to set that up so that it matches by name.  For example:

```<code>PUT _template/my_index
{
  "template": "my_index*",
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "type1" : {
        "properties" : {
            "obj1" : {
                "type" : "nested"
            }
        }
    }
  }
}
</code>```

This is especially needed for time-based indexes.

If you are just looking for a tool, use curl:

```<code>curl -XPUT http://your_cluster:9200/index -d '{your json here}'
</code>```

You can script the insert of the template in the same way if needed

Body:
I'm new to ELK can any one help me. I'm able to get query results by placing following in dev tools of Kibana. But I need to load this template dynamically instead of querying from dev tools.

PUT /my_index
{
    "mappings": {
        "type1" : {
            "properties" : {
                "obj1" : {
                    "type" : "nested"
                }
            }
        }
    }
}

Can anyone help me in configuring this.
Thanks in advance!

Body:
You need to use an index template if you want to set the mapping at index creation time.  You can use the ES dev tools to set that up so that it matches by name.  For example:

PUT _template/my_index
{
  "template": "my_index*",
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "type1" : {
        "properties" : {
            "obj1" : {
                "type" : "nested"
            }
        }
    }
  }
}

This is especially needed for time-based indexes.

If you are just looking for a tool, use curl:

curl -XPUT http://your_cluster:9200/index -d '{your json here}'

You can script the insert of the template in the same way if needed


问:
How to point my compass to Mecca?
I took the code of compass from this link.

http://www.androidcode.ninja/android-compass-code-example/

How to set mecca location on my compass??

What do i need to do to point my compass to Mecca?

答:
You need to determine your location relatively to Mecca, so you will need Location permission and implement Location Updates.

You can implement that using: Receveing location updates

With this information you can determine where Mecca would be on your compass and set it accordingly. To determine the angle, use this code:

```<code>private double angleFromCoordinate(double lat1, double long1, double lat2,
    double long2) {

double dLon = (long2 - long1);

double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
        * Math.cos(lat2) * Math.cos(dLon);

double brng = Math.atan2(y, x);

brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
brng = 360 - brng; // count degrees counter-clockwise - remove to make clockwise

return brng;
}
</code>```

from: Calculate angle between two Latitude/Longitude points

Title: How to point my compass to Mecca?

Body:
You need to determine your location relatively to Mecca, so you will need Location permission and implement Location Updates.

You can implement that using: Receveing location updates

With this information you can determine where Mecca would be on your compass and set it accordingly. To determine the angle, use this code:

private double angleFromCoordinate(double lat1, double long1, double lat2,
    double long2) {

double dLon = (long2 - long1);

double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
        * Math.cos(lat2) * Math.cos(dLon);

double brng = Math.atan2(y, x);

brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
brng = 360 - brng; // count degrees counter-clockwise - remove to make clockwise

return brng;
}

from: Calculate angle between two Latitude/Longitude points


问:
How to prevent overflow of div content
I have a html that when the window shrinks, the content of sub divs gets cutoff. Even though the outermost div is overflow:auto, and there is a scroll bar..
I notice that overflow:hidden is set in multiple child divs. The thing is the inner html are generated from some API and it would impractical to reset all these overflow properties.

My question is:

the height/width of these child divs are not set, why the overflow property still applies?

is there another way to prevent cutoff in child div? Like making sure the parent div has enough height?

Below is a simplified version of my html:

          Section A

          Section B

 subtitle A

 paragrah A

                       some text for the ssdfasdfdsfffffffffffffffffffffffffffffffffffffffffffffffffffff.
dddddd

 subtitle B

 paragrah A

                       some text for the testing. This text will get cutoff when the window is small enough....
dddddd

 paragrah B

                       some text for the testing. This text will get cutoff when the window is small enough....
dddddd

```

答:
Thats just how overflow works.  If you set it to hidden on a div, any content that flows outside of its boundaries, regardless of what makes it flow outside, it gets clipped.

Ideally the proper solution would be to change the markup.  However, if you really can't, you can hack it with css using !important:

```<code>#main div {
  overflow: initial !important;
}

#main {
  width: initial !important;
  overflow: initial !important;

}

div#SecListB {
  overflow: initial !important;
}
</code>```

Check out a fiddle here.

Title: How to prevent overflow of div content

Body:
Thats just how overflow works.  If you set it to hidden on a div, any content that flows outside of its boundaries, regardless of what makes it flow outside, it gets clipped.

Ideally the proper solution would be to change the markup.  However, if you really can't, you can hack it with css using !important:

#main div {
  overflow: initial !important;
}

#main {
  width: initial !important;
  overflow: initial !important;

}

div#SecListB {
  overflow: initial !important;
}

Check out a fiddle here.


问:
frontend backend class exchange
I'm writing application using Angular2 and PHP (REST API mostly). The problem is that I have almost the same classes for angular and for php. For example in php I have a class Contract with some fields like title, description, provider. Also I have api endpoint getContract() to return all these fields. And I have the same class in angular, so I can add some logic here like getters and setters. That's really annoying me to write 2 similar classes each time, and if I need to change something, I have to change it twice. But now I have a new requirement, to create separated project with API, so in two words now I have to create 3 classes each time.

So, if the problem is clear, I want to talk about possible solutions, after google some time I didn't find anything, for now I'm on the first step and hope someone can turn me in the right direction. What's the best practices there? May be store classes in json, and then parse in with angular and php? Thanks for any advices

答:
I mean this with complete respect - if you have a problem with writing two different classes, one for Angular and one for your backend, then you shouldn't be using Angular.

Angular is a single page application framework. It's a different technique of building a web application whereby you build your user interface as a standalone application in Javascript/Typescript. This application then communicates with a separate server side application through HTTP (or web sockets in some cases).

Therefore, almost by definition, you are going to have two applications. Some people (myself included) combine those applications in a myriad of ways to ease deployment/source code management, but that's just for convenience and with the full understanding that the two applications are still separate entities.

If the idea of having to create similarly named classes for your front end and back end application is too much of a pain, then honestly, I would stick to a normal web application where the user interface is served directly from the server application, and just use javascript to enhance the user interface as needed. (And that use-case is a very poor fit for Angular - AngularJS i.e. Angular 1, maybe, but definitely not Angular version 2 and beyond)

Title: frontend backend class exchange


问:
Switching from one control (textbox) to another makes disabled text box to be enabled WPF
By pressing enter I am moving from one control to another, all of my controls are located in Grid, here is an image of that:

and what is issue here, in case some of my controls are disabled, when I "jump" to that control it's becoming enabled, and if one of my controls is button, its being fired like its mouse clicked.

I dont know how to solve this,
this is how It looks right (my code) now and how I tried to solve this (To keep control disabled when I jumpt on it).

Here is my xaml 3 textboxes, and 3 comboboxes

```<code><TextBox Name="txt1"   Grid.Row="0"  Grid.Column="1"         Margin="0,0,10,0" FontSize="15"  VerticalContentAlignment="Center" />
<TextBox Name="txt2"   Grid.Row="1"  Grid.Column="1"         Margin="0,5,10,0" FontSize="15" VerticalContentAlignment="Center"/>
<TextBox Name="txt2"   Grid.Row="2"  TextWrapping="Wrap"     Grid.Column="1" Margin="0,5,10,0" FontSize="15"  />
<ComboBox Name="cmb1"  Grid.Row="3"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0" />
<ComboBox Name="cmb2"  Grid.Row="4"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0"  />
<ComboBox Name="cmb3"  Grid.Row="5"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0" />

<Grid Grid.Row="6" Grid.Column="1" Margin="0,5,10,0">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="85*"/>
    <ColumnDefinition Width="15*"/>
</Grid.ColumnDefinitions>
<ComboBox Name="cmb4" Grid.Column="0" IsEnabled="False" FontSize="15" >
    <ComboBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#E0E4E5" />
    </ComboBox.Resources>
</ComboBox>

<Button x:Name="btnUnlockcmb4"
                Grid.Column="5"
                FontSize="15"
                BorderThickness="1.5"
                HorizontalContentAlignment="Center"
                VerticalContentAlignment="Center"
                Margin="4,0,0,0"
                Foreground="White"
                Background="White"
                BorderBrush="#0091EA"  Click="btnUnlockcmb4_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border BorderThickness="{TemplateBinding BorderThickness}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            Background="{TemplateBinding Background}">
                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                        <Image Source="/Icons/unclock.png" Margin="4" Grid.Column="0" Width="Auto"/>
                        </Grid>
                </Button>
            </Grid>
</code>```

Acctually that are controls that i am "jumping from one to another".

And cmb4 should stay disabled, just jump it away but dont change his state..

Here is my code:

```<code>private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.Key == Key.Enter)
            {

                UIElement element = e.Source as UIElement;

                //check is enabled = false as it is, so keep it disabled
                if (element.IsEnabled == false)
                {
                    element.IsEnabled = false;
                }
                else
                {
                    element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
</code>```

NOTICE BUTTON btnUnlockcm4, which is ussualy setting IsEnabled property to True on my cmb4, so by pressing enter is being fired I guess that is reason why it is enabling my cmb4?

EDIT:

Grid which holds controls:

```<code><Grid Grid.Row="1" Grid.Column="0" Margin="0,3" PreviewKeyDown="Grid_PreviewKeyDown_1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="25*"/>
                    <ColumnDefinition Width="75*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="45" />
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="70"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45" />
                    <RowDefinition Height="45"/>
                    <RowDefinition MinHeight="150"/>
                    <RowDefinition Height="45" />
                </Grid.RowDefinitions>
</code>```

答:
Try to set the IsTabStop property of the Button to false:

```<code><Button x:Name="btnUnlockcmb4"
         IsTabStop="False"
         Grid.Column="5"
         FontSize="15"
         ...
</code>```

Body:
By pressing enter I am moving from one control to another, all of my controls are located in Grid, here is an image of that:

and what is issue here, in case some of my controls are disabled, when I "jump" to that control it's becoming enabled, and if one of my controls is button, its being fired like its mouse clicked.

I dont know how to solve this,
this is how It looks right (my code) now and how I tried to solve this (To keep control disabled when I jumpt on it).

Here is my xaml 3 textboxes, and 3 comboboxes

<TextBox Name="txt1"   Grid.Row="0"  Grid.Column="1"         Margin="0,0,10,0" FontSize="15"  VerticalContentAlignment="Center" />
<TextBox Name="txt2"   Grid.Row="1"  Grid.Column="1"         Margin="0,5,10,0" FontSize="15" VerticalContentAlignment="Center"/>
<TextBox Name="txt2"   Grid.Row="2"  TextWrapping="Wrap"     Grid.Column="1" Margin="0,5,10,0" FontSize="15"  />
<ComboBox Name="cmb1"  Grid.Row="3"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0" />
<ComboBox Name="cmb2"  Grid.Row="4"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0"  />
<ComboBox Name="cmb3"  Grid.Row="5"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0" />

<Grid Grid.Row="6" Grid.Column="1" Margin="0,5,10,0">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="85*"/>
    <ColumnDefinition Width="15*"/>
</Grid.ColumnDefinitions>
<ComboBox Name="cmb4" Grid.Column="0" IsEnabled="False" FontSize="15" >
    <ComboBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#E0E4E5" />
    </ComboBox.Resources>
</ComboBox>

<Button x:Name="btnUnlockcmb4"
                Grid.Column="5"
                FontSize="15"
                BorderThickness="1.5"
                HorizontalContentAlignment="Center"
                VerticalContentAlignment="Center"
                Margin="4,0,0,0"
                Foreground="White"
                Background="White"
                BorderBrush="#0091EA"  Click="btnUnlockcmb4_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border BorderThickness="{TemplateBinding BorderThickness}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            Background="{TemplateBinding Background}">
                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                        <Image Source="/Icons/unclock.png" Margin="4" Grid.Column="0" Width="Auto"/>
                        </Grid>
                </Button>
            </Grid>

Acctually that are controls that i am "jumping from one to another".

And cmb4 should stay disabled, just jump it away but dont change his state..

Here is my code:

private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.Key == Key.Enter)
            {

                UIElement element = e.Source as UIElement;

                //check is enabled = false as it is, so keep it disabled
                if (element.IsEnabled == false)
                {
                    element.IsEnabled = false;
                }
                else
                {
                    element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

NOTICE BUTTON btnUnlockcm4, which is ussualy setting IsEnabled property to True on my cmb4, so by pressing enter is being fired I guess that is reason why it is enabling my cmb4?

EDIT:

Grid which holds controls:

<Grid Grid.Row="1" Grid.Column="0" Margin="0,3" PreviewKeyDown="Grid_PreviewKeyDown_1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="25*"/>
                    <ColumnDefinition Width="75*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="45" />
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="70"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45" />
                    <RowDefinition Height="45"/>
                    <RowDefinition MinHeight="150"/>
                    <RowDefinition Height="45" />
                </Grid.RowDefinitions>

Body:
Try to set the IsTabStop property of the Button to false:

<Button x:Name="btnUnlockcmb4"
         IsTabStop="False"
         Grid.Column="5"
         FontSize="15"
         ...


问:
Android background service never starts when killed app from recent task list
I want to create a never ending background service in Android. To do this I am using AlarmManager with Simple Service Alarmmanger send broadcast after some interval ,In broadcast Receiver I'm checking wether the service is running, if running then do nothing else start it again .

My service code is

```<code>public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
           return null;
    }
    @Override
    public void onCreate() {
        super.onCreate ( );
        Log.e ("My service ", "oncreate");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        scheduleAlarm ();
        super.onTaskRemoved (rootIntent);
    }
     // Setup a recurring alarm every half hour
    public void scheduleAlarm() {
        // Construct an intent that will execute the ServiceAlarmReceiver
        Intent intent = new Intent("com.hmkcode.android.USER_ACTION");
        // Create a PendingIntent to be triggered when the alarm goes off
        final PendingIntent pIntent = PendingIntent.getBroadcast(this, ServiceReceiver.REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Setup periodic alarm every 5 seconds
        long firstMillis = System.currentTimeMillis()+5000; // alarm is set right away
        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTCWAKEUP
        // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
                6000, pIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

         Log.e ("My Service:", " on Start Command");
          return START_STICKY;
    }
 }
</code>```

Broadcast Receiver

```<code>public class ServiceReceiver extends WakefulBroadcastReceiver {

    public static final int REQUEST_CODE=12355;
    public ServiceReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        // check service  is running or not
        if (isMyServiceRunning (MessageService.class,context)){
            // don nothing

        }
        else {
            // launch the service
            if (isConnectedToInternet (context)) {
                Intent serviceIntent = new Intent (context, MyService.class);
                context.startService (serviceIntent);
            }
        }

        Log.e ("hello","wer are in Receiver" );
       // throw new UnsupportedOperationException ("Not yet implemented");
    }
}
</code>```

My Manifest:

```<code> <receiver
            android:name=".Services.ServiceReceiver"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">

            <intent-filter>
                <action android:name="com.hmkcode.android.USER_ACTION" />
            </intent-filter>
        </receiver>

        <service
            android:name=".Services.MyService"
            android:enabled="true"
            android:stopWithTask="false"
            android:process=":remote"

        >
        </service>
</code>```

It worked fine when the app is in foreground or in background but the problem is when I swipe out the app from recent Task list in Android, the app got killed so as the service and My broadcast Receiver never able to start it again? I am rescheduling my Alarmmanger in onTaskRemoved Method, but still the service is not starting again.

Also Return START_STICKY from onStartCommand() as people said  With this, system will re-start the service even if it has to be stopped for resources limitations.

Also used "stopWithTask"=false in  <service> tag of manifest file. It also had no impact.

答:
I've had success with creating a PendingIntent through the alarm manager and instantiating it through code instead of declaratively.

```<code>public class HeartbeatReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try{
            Log.i(MainService.TAG, "** Heartbeat onReceive **");
            if (!Utility.isMyServiceRunning(context)){
                Log.i(MainService.TAG, "Service is dead. Restarting...");
                context.startService(new Intent(context, MainService.class));
                return;
            }
        }
    }

    public void StartHeartbeat(Context context, int interval) {
        this.CancelHeartbeat(context);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, HeartbeatReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pi);
    }

    public void CancelHeartbeat(Context context) {
        Intent intent = new Intent(context, HeartbeatReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
}
</code>```

I initialize the receiver programmatically in the Application class. It didn't seem to work when the intent was created in the manifest.

```<code>public class MainApp extends Application {
    @Override
    public void onCreate(){
        super.onCreate();
        MainService.baseContext = getBaseContext();
        HeartbeatReceiver heartBeat = new HeartbeatReceiver();
        heartBeat.StartHeartbeat(MainService.baseContext, 60 * 1000 * 5);

    }
}
</code>```

Then just the receiver in the manifest with no intent

```<code> <receiver android:name="HeartbeatReceiver"/>
</code>```

This was the result of experimenting so I'm not exactly sure why it works but if I kill the app it comes back successfully when the next alarm runs. Hope that helps.

Body:
I want to create a never ending background service in Android. To do this I am using AlarmManager with Simple Service Alarmmanger send broadcast after some interval ,In broadcast Receiver I'm checking wether the service is running, if running then do nothing else start it again .

My service code is

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
           return null;
    }
    @Override
    public void onCreate() {
        super.onCreate ( );
        Log.e ("My service ", "oncreate");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        scheduleAlarm ();
        super.onTaskRemoved (rootIntent);
    }
     // Setup a recurring alarm every half hour
    public void scheduleAlarm() {
        // Construct an intent that will execute the ServiceAlarmReceiver
        Intent intent = new Intent("com.hmkcode.android.USER_ACTION");
        // Create a PendingIntent to be triggered when the alarm goes off
        final PendingIntent pIntent = PendingIntent.getBroadcast(this, ServiceReceiver.REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Setup periodic alarm every 5 seconds
        long firstMillis = System.currentTimeMillis()+5000; // alarm is set right away
        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTCWAKEUP
        // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
                6000, pIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

         Log.e ("My Service:", " on Start Command");
          return START_STICKY;
    }
 }

Broadcast Receiver

public class ServiceReceiver extends WakefulBroadcastReceiver {

    public static final int REQUEST_CODE=12355;
    public ServiceReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        // check service  is running or not
        if (isMyServiceRunning (MessageService.class,context)){
            // don nothing

        }
        else {
            // launch the service
            if (isConnectedToInternet (context)) {
                Intent serviceIntent = new Intent (context, MyService.class);
                context.startService (serviceIntent);
            }
        }

        Log.e ("hello","wer are in Receiver" );
       // throw new UnsupportedOperationException ("Not yet implemented");
    }
}

My Manifest:

 <receiver
            android:name=".Services.ServiceReceiver"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">

            <intent-filter>
                <action android:name="com.hmkcode.android.USER_ACTION" />
            </intent-filter>
        </receiver>

        <service
            android:name=".Services.MyService"
            android:enabled="true"
            android:stopWithTask="false"
            android:process=":remote"

        >
        </service>

It worked fine when the app is in foreground or in background but the problem is when I swipe out the app from recent Task list in Android, the app got killed so as the service and My broadcast Receiver never able to start it again? I am rescheduling my Alarmmanger in onTaskRemoved Method, but still the service is not starting again.

Also Return START_STICKY from onStartCommand() as people said  With this, system will re-start the service even if it has to be stopped for resources limitations.

Also used "stopWithTask"=false in  <service> tag of manifest file. It also had no impact.

Body:
I've had success with creating a PendingIntent through the alarm manager and instantiating it through code instead of declaratively.

public class HeartbeatReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try{
            Log.i(MainService.TAG, "** Heartbeat onReceive **");
            if (!Utility.isMyServiceRunning(context)){
                Log.i(MainService.TAG, "Service is dead. Restarting...");
                context.startService(new Intent(context, MainService.class));
                return;
            }
        }
    }

    public void StartHeartbeat(Context context, int interval) {
        this.CancelHeartbeat(context);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, HeartbeatReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pi);
    }

    public void CancelHeartbeat(Context context) {
        Intent intent = new Intent(context, HeartbeatReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
}

I initialize the receiver programmatically in the Application class. It didn't seem to work when the intent was created in the manifest.

public class MainApp extends Application {
    @Override
    public void onCreate(){
        super.onCreate();
        MainService.baseContext = getBaseContext();
        HeartbeatReceiver heartBeat = new HeartbeatReceiver();
        heartBeat.StartHeartbeat(MainService.baseContext, 60 * 1000 * 5);

    }
}

Then just the receiver in the manifest with no intent

 <receiver android:name="HeartbeatReceiver"/>

This was the result of experimenting so I'm not exactly sure why it works but if I kill the app it comes back successfully when the next alarm runs. Hope that helps.


问:
Apple push notification not working with aps_production.cer
I added push notification to my iOS application. Currently my app is in app store. it receives push notification whilst using aps_development.cer with it's corresponding .p12 file but it's not receiving notification using aps_production.cer... I'm using simplepush.php to send push notification with reference of [link]:http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1

please help me out.... thanks in advance..

答: You need to convert your .p12 file into .pem file first. </p>


问:
NSUserDefaults objectForKey sometimes nil
I've just noticed that a key that exists in my **NSUserDefaults**
is returning nil quite often.  It seems about half the time it's
correct and the other half it's not.  I say half the time, but I dont
mean that its flip-flopping, its just 40-50% I see it not work.
When I write the initial value, I call synchronize immediately.
I use this key as the applications
revision I set when a new user signs up.

The following code returns nil:

```<code>#define kDBrevision  @"revision"

NSString *rev = [[NSUserDefaults standardUserDefaults] objectForKey:kDBrevision];
</code>```

When I launch the app and just monitor the value (without
writing any NSUserDefaults), the value sometimes is valid
with no modifications to the NSUserDefaults at all.

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSString *r = [[NSUserDefaults standardUserDefaults] objectForKey:kDBrevision];
    NSLog(@"revision %@", r);
    _exit(1);
</code>```

I have no idea why this is happening.  Im running iOS 10 on my
device connected to Xcode 8.2.1.  Anyone have any ideas?
Thanks

EDIT:
I started talking to apple about fixing this and found out that if you have
file protection complete turned on, it can be the cause of this issue
showing up from time to time, however apple told me that my particular
case (which is the only one I was sure of at this time) is a bug.
The case is when you use Xcode to launch the app on the device it should
not fail like this and it occasionally does.  No idea when or if it will
be fixed.  Instead I moved my critical strings from the defaults to
the keychain instead.

答:
try below code in didFinishLaunchingWithOptions

Swift 3.0

```<code>UserDefaults.standard.synchronize()
</code>```

Obective - C

```<code>[[NSUserDefaults standardUserDefaults] synchronize];
</code>```

Body:
I've just noticed that a key that exists in my **NSUserDefaults**
is returning nil quite often.  It seems about half the time it's
correct and the other half it's not.  I say half the time, but I dont
mean that its flip-flopping, its just 40-50% I see it not work.
When I write the initial value, I call synchronize immediately.
I use this key as the applications
revision I set when a new user signs up.

The following code returns nil:

#define kDBrevision  @"revision"

NSString *rev = [[NSUserDefaults standardUserDefaults] objectForKey:kDBrevision];

When I launch the app and just monitor the value (without
writing any NSUserDefaults), the value sometimes is valid
with no modifications to the NSUserDefaults at all.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSString *r = [[NSUserDefaults standardUserDefaults] objectForKey:kDBrevision];
    NSLog(@"revision %@", r);
    _exit(1);

I have no idea why this is happening.  Im running iOS 10 on my
device connected to Xcode 8.2.1.  Anyone have any ideas?
Thanks

EDIT:
I started talking to apple about fixing this and found out that if you have
file protection complete turned on, it can be the cause of this issue
showing up from time to time, however apple told me that my particular
case (which is the only one I was sure of at this time) is a bug.
The case is when you use Xcode to launch the app on the device it should
not fail like this and it occasionally does.  No idea when or if it will
be fixed.  Instead I moved my critical strings from the defaults to
the keychain instead.

Body:
try below code in didFinishLaunchingWithOptions

Swift 3.0

UserDefaults.standard.synchronize()

Obective - C

[[NSUserDefaults standardUserDefaults] synchronize];


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答:
Make a serializing function per type that needs to be persistent.

Call this for each member.

It is actually similar to serializing over network or visualizing for debug-purposes.

boost.serialize can help you.

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?


答:
You will have to update the class to access members outside.
You have several options to do it.

1: store the connection in a public property

```<code>class Engine {
    public $connection;

    public function MySQL() {
        $this->connection = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char",$db_user, $db_pass);
    }
}
</code>```

This way you can retrieve it by

```<code>$engine = new Engine();
$engine->MySQL();
$conn = $engine->connection;
</code>```

2: Make the function return the connection

```<code>class Engine {
    public function MySQL() {
        return new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char",$db_user, $db_pass);
    }
}
</code>```

This way your example will work (if you use Mysql as a function):

```<code>$engine = new Engine();
$conn = $engine->MySQL();
</code>```

3: A more complicated but generally better aproach:

```<code>class Engine {
    protected $connection;

    public function __construct($db_host, $db_name, $db_user, $db_pass $db_char = "utf-8") {
        $this->connection = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char",$db_user, $db_pass);
    }

    public function MySQL() {
        if ( !$this->connection instanceof PDO ) {
            throw new Exception("Connection is not set up");
        }

        return $this->connection;
    }
}
</code>```

This would work almost as you wanted, except you cant access the connection directly (its protected), but only through the MySql function. This way if you forgot to init the connection an exception is thrown.

```<code>$engine = new Engine("localhost", "db_name", "user", "pass");
$conn   = $engine->MySQL();  // you don't even need to save the connection to a local variable, because the function only references the connection and won't start a new one
</code>```

Footnote:
If you had to as this kind of question you should probably look up and learn more about OOP. For php this is a start: http://php.net/manual/en/language.oop5.php

Title: How to access variables in OOP

Body:
I am trying to find a way to get the variable called $connect to run but don't know how.

Filename: /engine/init.php

class Engine {
    function MySQL() {
        $connect = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char", $db_user, $db_pass);
    }
}

Filename: /inc/database.php

require 'engine/init.php;
$engine = new Engine;
$conn = $engine->MySQL;
// Activate $connect variable

If it's not clear, please request for more info.

Thanks,
CrAzYz_

Body:
You will have to update the class to access members outside.
You have several options to do it.

1: store the connection in a public property

class Engine {
    public $connection;

    public function MySQL() {
        $this->connection = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char",$db_user, $db_pass);
    }
}

This way you can retrieve it by

$engine = new Engine();
$engine->MySQL();
$conn = $engine->connection;

2: Make the function return the connection

class Engine {
    public function MySQL() {
        return new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char",$db_user, $db_pass);
    }
}

This way your example will work (if you use Mysql as a function):

$engine = new Engine();
$conn = $engine->MySQL();

3: A more complicated but generally better aproach:

class Engine {
    protected $connection;

    public function __construct($db_host, $db_name, $db_user, $db_pass $db_char = "utf-8") {
        $this->connection = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char",$db_user, $db_pass);
    }

    public function MySQL() {
        if ( !$this->connection instanceof PDO ) {
            throw new Exception("Connection is not set up");
        }

        return $this->connection;
    }
}

This would work almost as you wanted, except you cant access the connection directly (its protected), but only through the MySql function. This way if you forgot to init the connection an exception is thrown.

$engine = new Engine("localhost", "db_name", "user", "pass");
$conn   = $engine->MySQL();  // you don't even need to save the connection to a local variable, because the function only references the connection and won't start a new one

Footnote:
If you had to as this kind of question you should probably look up and learn more about OOP. For php this is a start: http://php.net/manual/en/language.oop5.php


问:
How to check if a List of Lists contains another List
I want to create a list which will hold two int values lets say it arrfirst and another list that will hold lists of arrfirst, lets say it arrsecond then check if arrsecond contains a defined arrfirst . Now i created lists but when i try to use .Contains it doesn't work.

```<code>List<List<int>> Eklenenler = new List<List<int>>();

for (int i = 0; i < YourTable.Rows.Count; i++)
        {
            prjAd = YourTable.Rows[i].Field<string>("F1");
            if (prjAd != "Servis Adresi")
            {
                wesAd = YourTable.Rows[i].Field<string>("F2");
                RowPrj = tbProjeler.AsEnumerable().Where(r => r.Field<string>("prjAd") == prjAd).FirstOrDefault();
                RowWes = tbServisler.AsEnumerable().Where(k => k.Field<string>("wesAd") == wesAd).FirstOrDefault();
                prjId = RowPrj.Field<int>("prjId");
                wesId = RowWes.Field<int>("wesId");
                List<int> temp = new List<int>();
                temp.Add(prjId);
                temp.Add(wesId);
                if (!Eklenenler.Contains(temp))
                {
                    sqlExProjeEkle = "INSERT INTO NLK_PRJ_Webservisler (prjId,wesId) Values (" + prjId + "," + wesId + ")";
                    dco.Execute(sqlExProjeEkle);
                    Eklenenler.Add(temp);

                }
                else
                {

                }
            }
        }
</code>```

This is my code. When i debugging, i can see temp values are right and also at second loop, temp is in Eklenenler list but it always goes in if block. For example, first loop shows temp[0]=36 and temp[1]=42 goes in if block and at second loop again temp[0]=36 and temp[1]=42 also Eklenenler[0][0]=36 and Eklenenler[0][1]=42 so it contains temp but it still goes in. How can i solve this problem and why this returns false and can't find this temp in Eklenenler. Thank you.

答:
You could do it with linq in just one line with something like this

```<code>if (!Eklenenler.Any(c => c.SequenceEqual(temp)))
{
    sqlExProjeEkle = "INSERT INTO NLK_PRJ_Webservisler (prjId,wesId) Values (" + prjId + "," + wesId + ")";
    dco.Execute(sqlExProjeEkle);
    Eklenenler.Add(temp);

}
else
{

}
</code>```

Don't forget to add

```<code>using System.Linq;
</code>```

Body:
I want to create a list which will hold two int values lets say it arrfirst and another list that will hold lists of arrfirst, lets say it arrsecond then check if arrsecond contains a defined arrfirst . Now i created lists but when i try to use .Contains it doesn't work.

List<List<int>> Eklenenler = new List<List<int>>();

for (int i = 0; i < YourTable.Rows.Count; i++)
        {
            prjAd = YourTable.Rows[i].Field<string>("F1");
            if (prjAd != "Servis Adresi")
            {
                wesAd = YourTable.Rows[i].Field<string>("F2");
                RowPrj = tbProjeler.AsEnumerable().Where(r => r.Field<string>("prjAd") == prjAd).FirstOrDefault();
                RowWes = tbServisler.AsEnumerable().Where(k => k.Field<string>("wesAd") == wesAd).FirstOrDefault();
                prjId = RowPrj.Field<int>("prjId");
                wesId = RowWes.Field<int>("wesId");
                List<int> temp = new List<int>();
                temp.Add(prjId);
                temp.Add(wesId);
                if (!Eklenenler.Contains(temp))
                {
                    sqlExProjeEkle = "INSERT INTO NLK_PRJ_Webservisler (prjId,wesId) Values (" + prjId + "," + wesId + ")";
                    dco.Execute(sqlExProjeEkle);
                    Eklenenler.Add(temp);

                }
                else
                {

                }
            }
        }

This is my code. When i debugging, i can see temp values are right and also at second loop, temp is in Eklenenler list but it always goes in if block. For example, first loop shows temp[0]=36 and temp[1]=42 goes in if block and at second loop again temp[0]=36 and temp[1]=42 also Eklenenler[0][0]=36 and Eklenenler[0][1]=42 so it contains temp but it still goes in. How can i solve this problem and why this returns false and can't find this temp in Eklenenler. Thank you.

Body:
You could do it with linq in just one line with something like this

if (!Eklenenler.Any(c => c.SequenceEqual(temp)))
{
    sqlExProjeEkle = "INSERT INTO NLK_PRJ_Webservisler (prjId,wesId) Values (" + prjId + "," + wesId + ")";
    dco.Execute(sqlExProjeEkle);
    Eklenenler.Add(temp);

}
else
{

}

Don't forget to add

using System.Linq;


问:
gimp text on a dial placed at specific locations (degrees)
I have a (circular) dial. I would like to place text centered at a specific angle on the dial. A simple analogy would be a clock face with text above each hour mark. I can write text along an arc, placing text at the top (12h) position, then rotate that path to place it at a specific angle. The only solution I could think of was to create 1 layer for each text then rotate that layer appropriately (10 deg, 20 deg, 30 deg, etc.). This seems a brute force method, and I have not even been able to get it to work (yet). So, is there a better, standard way to do this?

TIA

ken

答:
Definitely no standard way. But there are scripts that can make that easier. They can be found here (some come with a self-contained doc, go directly to the download page.

dial-marks will generate marks (with round sides if required). It's easy to remove the excess point to keep only arcs. You can have other uses for that one if you are in clocks.

ofn-path-edit (break apart function) is used to make one path per stroke

text-along-path can then be used to add text (centered) on each of these paths.

Results of the three main steps

If you want to script this, plenty of code to borrow from in these scripts.


问:
Azure service bus queue error in the logic app
I am trying to use Service Bus Queue send action in my logic app which sends a message to a queue. When the logic app runs the action returns this error:

```<code>{
  "status": 403,
  "message": "Cannot use a trigger on an entity with auto-forwarding enabled.",
  "source": "127.0.0.1"
}
</code>```

Although at the time of creation of the queue I didn't set the auto-forwarding enabled. Any help?

答:
Check that you do not have partitioning turned on for the Service Bus Queue.
It is default on when creating queues in the "new" azure portal.

Got the same misleading error.

Body:
I am trying to use Service Bus Queue send action in my logic app which sends a message to a queue. When the logic app runs the action returns this error:

{
  "status": 403,
  "message": "Cannot use a trigger on an entity with auto-forwarding enabled.",
  "source": "127.0.0.1"
}

Although at the time of creation of the queue I didn't set the auto-forwarding enabled. Any help?


问:
How to make UITextField move up when keyboard is present?
How do I prevent a UITextField from being hidden by the keyboard?

答:
In case you are using a UIScrollView or any of its subclasses, e.g., UITableView, you can also manipulate the contentInset property. That way you do not have to mess with frame, bounds, NSLayoutConstraint or NSLayoutAnchor.

```<code>func keyboardWillShow(notification: Notification) {
    let info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let keyboardHeight: CGFloat = keyboardSize.height
    let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
    UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        self.tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
    }, completion: nil)
}

func keyboardWillHide(notification: Notification) {
    let info = notification.userInfo!
    let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
    UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        self.tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }, completion: nil)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
</code>```

Body:
In case you are using a UIScrollView or any of its subclasses, e.g., UITableView, you can also manipulate the contentInset property. That way you do not have to mess with frame, bounds, NSLayoutConstraint or NSLayoutAnchor.

func keyboardWillShow(notification: Notification) {
    let info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let keyboardHeight: CGFloat = keyboardSize.height
    let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
    UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        self.tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
    }, completion: nil)
}

func keyboardWillHide(notification: Notification) {
    let info = notification.userInfo!
    let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
    UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        self.tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }, completion: nil)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}


问:
How to display firstname in UILabel?I am developing IOS app with Firebase and Swift
I am practicing IOS app using Firebase and Swift.

This is an basic app where a user logs in with username and password. User can Signup, login, and logout. For this I have created 3 viewcontrollers.One for userlogin, 2nd to signup, and third to display user's firstname and picture.

I have created a viewcontroller "loginPageViewController" to display user's firstname and picture. I am trying to display firstname in "userFirstName" label. But I am unable to do. Error message is attached in screenshot.

Supplements:

Error is occured here

Storyboard

Swift Code:

```<code>import UIKit
import Firebase
import FirebaseAuth

class loginPageViewController: ViewController {

@IBOutlet weak var userFirstName: UILabel!
@IBOutlet weak var userImage: UIImageView!

let userID = FIRAuth.auth()?.currentUser?.uid

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    let userID = (FIRAuth.auth()?.currentUser?.uid)!

    ref.child("expatsappmembers").child(userID).observeSingleEventOfType(
        .Value, withBlock: { (snapshot) in
            let firstName = snapshot.value!["firstName"] as! String
            self.userFirstName.text = firstName
    })
}

@IBAction func LogoutButtoninLoginPage(sender: AnyObject) {

    if FIRAuth.auth()?.currentUser != nil{ //there is a user signed in

        do{

        try FIRAuth.auth()?.signOut()

            if FIRAuth.auth()?.currentUser == nil{

                let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("InitialView") as? ViewController

                self.presentViewController(loginVC!, animated: true, completion: nil)
            }

        }catch let signOutError as NSError{
        print ("Erros signing out: %@", signOutError)
        }

    }
}
</code>```

}
 "
Any suggestions will be a great help for me.
Thank you in advance.

答:
Before the user have logged in the FIRAuth.auth()?.currentUser?.uid is nil. The problem is that you force unwrap it (!).
You should first check that the user is logged in, and only then continue with your logic.

I would start with this:

```<code>if let userID = FIRAuth.auth()?.currentUser?.uid  {
    ref.child("expatsappmembers").child(userID).observeSingleEventOfType(
        .Value, withBlock: { (snapshot) in
            if let firstName = snapshot.value?["firstName"] as? String {
                self.userFirstName.text = firstName
            }
    })
}
</code>```

Body:
I am practicing IOS app using Firebase and Swift.

This is an basic app where a user logs in with username and password. User can Signup, login, and logout. For this I have created 3 viewcontrollers.One for userlogin, 2nd to signup, and third to display user's firstname and picture.

I have created a viewcontroller "loginPageViewController" to display user's firstname and picture. I am trying to display firstname in "userFirstName" label. But I am unable to do. Error message is attached in screenshot.

Supplements:

Error is occured here

Storyboard

Swift Code:

import UIKit
import Firebase
import FirebaseAuth

class loginPageViewController: ViewController {

@IBOutlet weak var userFirstName: UILabel!
@IBOutlet weak var userImage: UIImageView!

let userID = FIRAuth.auth()?.currentUser?.uid

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    let userID = (FIRAuth.auth()?.currentUser?.uid)!

    ref.child("expatsappmembers").child(userID).observeSingleEventOfType(
        .Value, withBlock: { (snapshot) in
            let firstName = snapshot.value!["firstName"] as! String
            self.userFirstName.text = firstName
    })
}

@IBAction func LogoutButtoninLoginPage(sender: AnyObject) {

    if FIRAuth.auth()?.currentUser != nil{ //there is a user signed in

        do{

        try FIRAuth.auth()?.signOut()

            if FIRAuth.auth()?.currentUser == nil{

                let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("InitialView") as? ViewController

                self.presentViewController(loginVC!, animated: true, completion: nil)
            }

        }catch let signOutError as NSError{
        print ("Erros signing out: %@", signOutError)
        }

    }
}

}
 "
Any suggestions will be a great help for me.
Thank you in advance.

Body:
Before the user have logged in the FIRAuth.auth()?.currentUser?.uid is nil. The problem is that you force unwrap it (!).
You should first check that the user is logged in, and only then continue with your logic.

I would start with this:

if let userID = FIRAuth.auth()?.currentUser?.uid  {
    ref.child("expatsappmembers").child(userID).observeSingleEventOfType(
        .Value, withBlock: { (snapshot) in
            if let firstName = snapshot.value?["firstName"] as? String {
                self.userFirstName.text = firstName
            }
    })
}


问:
WAMP Server not working
Okay so a continuation from this question, where you experts intro'd me to WAMP, which can basically execute PHP within a Windows XP environment.

So now I've got it installed, but the tray icon forever shows YELLOW, and when I visit any PHP page in my browser, it just shows me the PHP source!

Also, when I visit "http://localhost/" in IE7 it gives me a 404 Not Found, FF3 just shows a blank page.

BTW I've tried "Restart All Services" and restarting my machine, but it still won't work.

Any ideas? Any of you had this problem and solved it? Please help me here, I'm desperate to execute PHP client-side and I'm just reverting to testing on-server for now!

答:
Glad you got it sorted - Skype is notorious for that.

If you want to use Skype and WAMP together, you can edit your httpd.conf file - change the 'listen' value from 80 to something else and restart all services.

OwnerDisplayName: Jeremy Rudd

Title: WAMP Server not working

OwnerDisplayName: John McCollum