问:
Integer.parseInt(scanner.nextLine()) vs scanner.nextInt()
My professor tends to do the following to get a number from the user:

```<code>Scanner scanner = new Scanner(System.in);
Integer.parseInt(scanner.nextLine());
</code>```

What are the benefits as opposed to simply doing scanner.nextInt() ?

java.util.Scanner.java has the following in it:

```<code>public int nextInt() {
    return nextInt(defaultRadix);
}

public int nextInt(int radix) {
    // Check cached result
    if ((typeCache != null) && (typeCache instanceof Integer)
        && this.radix == radix) {
        int val = ((Integer)typeCache).intValue();
        useTypeCache();
        return val;
    }
    setRadix(radix);
    clearCaches();
    // Search for next int
    try {
        String s = next(integerPattern());
        if (matcher.group(SIMPLE_GROUP_INDEX) == null)
            s = processIntegerToken(s);
        return Integer.parseInt(s, radix);
    } catch (NumberFormatException nfe) {
        position = matcher.start(); // don't skip bad token
        throw new InputMismatchException(nfe.getMessage());
    }
}
</code>```

As I see it, Scanner calls Integer.parseInt() itself as well, on top of additional hocus pocus. Are there significant performance gains in doing simply Integer.parseInt(scanner.nextLine()) ? Are there on the other hand any drawbacks?

How about when scanning through a file with significant amount of data, and not a user input?

答:
I also used to face this problem often. So i use to code like this..

```<code>public static void main(String[] args) {
    Scanner key= new Scanner(System.in);
    String name;
    int    age;
    age = key.nextInt();
    key.nextLine();
    name = key.nextLine();  //to carry the new line character left behind nextInt()
    System.out.println("Age : "+age);
    System.out.println("Name: "+name);
}
</code>```

here as the key.nextInt() leaves a new line character we are using key.nextLine() to carry the new Line character and then move to the nextline where the actual data is present. As we discussed above using Integer.parseInt() will be more efficient than using nextInt(). But this is also one of the way to code to overcome the problem.

Body:
My professor tends to do the following to get a number from the user:

Scanner scanner = new Scanner(System.in);
Integer.parseInt(scanner.nextLine());

What are the benefits as opposed to simply doing scanner.nextInt() ?

java.util.Scanner.java has the following in it:

public int nextInt() {
    return nextInt(defaultRadix);
}

public int nextInt(int radix) {
    // Check cached result
    if ((typeCache != null) && (typeCache instanceof Integer)
        && this.radix == radix) {
        int val = ((Integer)typeCache).intValue();
        useTypeCache();
        return val;
    }
    setRadix(radix);
    clearCaches();
    // Search for next int
    try {
        String s = next(integerPattern());
        if (matcher.group(SIMPLE_GROUP_INDEX) == null)
            s = processIntegerToken(s);
        return Integer.parseInt(s, radix);
    } catch (NumberFormatException nfe) {
        position = matcher.start(); // don't skip bad token
        throw new InputMismatchException(nfe.getMessage());
    }
}

As I see it, Scanner calls Integer.parseInt() itself as well, on top of additional hocus pocus. Are there significant performance gains in doing simply Integer.parseInt(scanner.nextLine()) ? Are there on the other hand any drawbacks?

How about when scanning through a file with significant amount of data, and not a user input?

Body:
I also used to face this problem often. So i use to code like this..

public static void main(String[] args) {
    Scanner key= new Scanner(System.in);
    String name;
    int    age;
    age = key.nextInt();
    key.nextLine();
    name = key.nextLine();  //to carry the new line character left behind nextInt()
    System.out.println("Age : "+age);
    System.out.println("Name: "+name);
}

here as the key.nextInt() leaves a new line character we are using key.nextLine() to carry the new Line character and then move to the nextline where the actual data is present. As we discussed above using Integer.parseInt() will be more efficient than using nextInt(). But this is also one of the way to code to overcome the problem.


来源: stackexchange

问:
Difference in creating an object in the heap and in the stack
Supposing that I have the following two classes:

```<code>#ifndef CLASS1_H
#define CLASS1_H

#include <QDebug>

class Class1
{
public:
    Class1(){}

    void printName()
    {
        qDebug() << "Class1";
    }
};

#endif // CLASS1_H
</code>```

and

```<code>#ifndef CLASS2_H
#define CLASS2_H

#include "class1.h"

class Class2
{
public:
    Class2(Class1 *pointerToClass1)
    {
        this->pointerToClass1 = pointerToClass1;
    }

    void doSomething()
    {
        this->pointerToClass1->printName();
    }

private:
    Class1 *pointerToClass1;
};

#endif // CLASS2_H
</code>```

And the main function looks like this:

```<code>#include <QCoreApplication>

#include "class1.h"
#include "class2.h"

void func1()
{
    Class1 class1;

    Class2 *class2_1 = new Class2(&class1);
    Class2 class2_2(&class1);

    class2_1->doSomething();
    class2_2.doSomething();

    delete class2_1;
    class2_1 = NULL;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    func1();

    return a.exec();
}
</code>```

What is the main difference of creating an object in the heap (e.g. Class2 *class2_1 = new Class2(&class1);) and just create the object on the stack (e.g. Class2 class2_2(&class1);)?

As far as I know, it is preferred to create the object on the stack when it is declared locally and has a short life. Also, the data is lost when the object exits the stack and in the heap, we need to call delete to free the memory. Is that correct?

Therefore, there is some advantage in using one or another?

答:
With the pointer and the new keyword you create an object on the heap and a assign it to a pointer which is on the stack. Thus when the pointer goes out of scope and it gets "popped" from the stack you won't be able to access your object anymore. (Which is memory leaking)
If you create the object on the stack you don't have to worry about freeing the memory (in this case deleting the object that is pointed to by the pointer)

For normal use i would go with the stack version. There are some old-school implementations of design patterns where you start using inheritance and there you use ptrs.

ContentLicense: CC BY-SA 3.0

Body:
Supposing that I have the following two classes:

#ifndef CLASS1_H
#define CLASS1_H

#include <QDebug>

class Class1
{
public:
    Class1(){}

    void printName()
    {
        qDebug() << "Class1";
    }
};

#endif // CLASS1_H

and

#ifndef CLASS2_H
#define CLASS2_H

#include "class1.h"

class Class2
{
public:
    Class2(Class1 *pointerToClass1)
    {
        this->pointerToClass1 = pointerToClass1;
    }

    void doSomething()
    {
        this->pointerToClass1->printName();
    }

private:
    Class1 *pointerToClass1;
};

#endif // CLASS2_H

And the main function looks like this:

#include <QCoreApplication>

#include "class1.h"
#include "class2.h"

void func1()
{
    Class1 class1;

    Class2 *class2_1 = new Class2(&class1);
    Class2 class2_2(&class1);

    class2_1->doSomething();
    class2_2.doSomething();

    delete class2_1;
    class2_1 = NULL;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    func1();

    return a.exec();
}

What is the main difference of creating an object in the heap (e.g. Class2 *class2_1 = new Class2(&class1);) and just create the object on the stack (e.g. Class2 class2_2(&class1);)?

As far as I know, it is preferred to create the object on the stack when it is declared locally and has a short life. Also, the data is lost when the object exits the stack and in the heap, we need to call delete to free the memory. Is that correct?

Therefore, there is some advantage in using one or another?


问:
How to get records from table having join with mapping table in SQL Server
How to get records from table having join with mapping table

Below example:

User table

```<code>ID | Name
---+-------
1  | ABC
2  | xyz
3  | NYS
</code>```

Feature table

```<code>ID | Name
---+------
1  | F1
2  | F2
3  | F3
4  | F4
</code>```

Mapping table

```<code>ID  |  UserID | FeatureID
----+---------+----------
1   |    1    |    1
2   |    1    |    2
3   |    2    |    2
4   |    3    |    1
</code>```

I need the result to look like this:

```<code>UserName | FeatureName |  IsMap
---------+-------------+------------
ABC      |    F1       |   True
ABC      |    F2       |   True
ABC      |    F3       |   False
ABC      |    F4       |   False
XYZ      |    F1       |   False
XYZ      |    F2       |   True
XYZ      |    F3       |   False
XYZ      |    F4       |   False
NYS      |    F1       |   True
NYS      |    F2       |   False
NYS      |    F3       |   False
NYS      |    F4       |   False
</code>```

Please help me with this..

答:
Start by cross joining your User data to your Feature data to get all combinations.  You can then left join this to your Mapping table to check if a mapping exists.  Where this returns a null value, you don't have a match, which you can handle with a case expression:

```<code>declare @User table(ID int,Name nvarchar(100));
insert into @User values (1,'ABC'),(2,'xyz'),(3,'NYS');

declare @Feature table(ID int,Name nvarchar(100));
insert into @Feature values (1,'F1'),(2,'F2'),(3,'F3'),(4,'F4');

declare @Mapping table(ID int,UserID int,FeatureID int);
insert into @Mapping values (1,1,1),(2,1,2),(3,2,2),(4,3,1);

select u.Name as UserName
        ,f.Name as FeatureName
        ,case when m.ID is not null then 'True' else 'False' end as IsMap
from @User u
    cross join @Feature f
    left join @Mapping m
        on(u.ID = m.UserID
            and f.ID = m.FeatureID
            )
order by u.Name
        ,f.Name;
</code>```

Output:

```<code>+----------+-------------+-------+
| UserName | FeatureName | IsMap |
+----------+-------------+-------+
| ABC      | F1          | True  |
| ABC      | F2          | True  |
| ABC      | F3          | False |
| ABC      | F4          | False |
| NYS      | F1          | True  |
| NYS      | F2          | False |
| NYS      | F3          | False |
| NYS      | F4          | False |
| xyz      | F1          | False |
| xyz      | F2          | True  |
| xyz      | F3          | False |
| xyz      | F4          | False |
+----------+-------------+-------+
</code>```

Body:
How to get records from table having join with mapping table

Below example:

User table

ID | Name
---+-------
1  | ABC
2  | xyz
3  | NYS

Feature table

ID | Name
---+------
1  | F1
2  | F2
3  | F3
4  | F4

Mapping table

ID  |  UserID | FeatureID
----+---------+----------
1   |    1    |    1
2   |    1    |    2
3   |    2    |    2
4   |    3    |    1

I need the result to look like this:

UserName | FeatureName |  IsMap
---------+-------------+------------
ABC      |    F1       |   True
ABC      |    F2       |   True
ABC      |    F3       |   False
ABC      |    F4       |   False
XYZ      |    F1       |   False
XYZ      |    F2       |   True
XYZ      |    F3       |   False
XYZ      |    F4       |   False
NYS      |    F1       |   True
NYS      |    F2       |   False
NYS      |    F3       |   False
NYS      |    F4       |   False

Please help me with this..

Body:
Start by cross joining your User data to your Feature data to get all combinations.  You can then left join this to your Mapping table to check if a mapping exists.  Where this returns a null value, you don't have a match, which you can handle with a case expression:

declare @User table(ID int,Name nvarchar(100));
insert into @User values (1,'ABC'),(2,'xyz'),(3,'NYS');

declare @Feature table(ID int,Name nvarchar(100));
insert into @Feature values (1,'F1'),(2,'F2'),(3,'F3'),(4,'F4');

declare @Mapping table(ID int,UserID int,FeatureID int);
insert into @Mapping values (1,1,1),(2,1,2),(3,2,2),(4,3,1);

select u.Name as UserName
        ,f.Name as FeatureName
        ,case when m.ID is not null then 'True' else 'False' end as IsMap
from @User u
    cross join @Feature f
    left join @Mapping m
        on(u.ID = m.UserID
            and f.ID = m.FeatureID
            )
order by u.Name
        ,f.Name;

Output:

+----------+-------------+-------+
| UserName | FeatureName | IsMap |
+----------+-------------+-------+
| ABC      | F1          | True  |
| ABC      | F2          | True  |
| ABC      | F3          | False |
| ABC      | F4          | False |
| NYS      | F1          | True  |
| NYS      | F2          | False |
| NYS      | F3          | False |
| NYS      | F4          | False |
| xyz      | F1          | False |
| xyz      | F2          | True  |
| xyz      | F3          | False |
| xyz      | F4          | False |
+----------+-------------+-------+


问:
Access denied to mysql database as root in rails app
I am running a rails app with mysql.
My computer shut down in an unorthodox way and now when I am trying to run rails s I get Access denied for user 'root'@'localhost' (using password: NO)

My database.yml file looks like :

```<code>default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  socket: /tmp/mysql.sock

development:
  <<: *default
  database: or_deco__site_development
</code>```

when Im trying to launch mysql server as root with mysql start I get this trace :

```<code> ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (61 "Connection refused")

when I try mysqld --user=mysql as why suggested on mysql website I get this trace:

2017-06-07 18:10:54 140735296021248 [Note] mysqld (mysqld 10.1.19-MariaDB) starting as process 1462 ...
2017-06-07 18:10:54 140735296021248 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/var/mysql/ is case insensitive
2017-06-07 18:10:54 140735296021248 [Warning] One can only use the --user switch if running as root

2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: The InnoDB memory heap is disabled
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Compressed tables use zlib 1.2.5
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Using SSE crc32 instructions
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Completed initialization of buffer pool
2017-06-07 18:10:55 140735296021248 [Note] InnoDB: Highest supported file format is Barracuda.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/gtid_slave_pos'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"mysql"."gtid_slave_pos"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_index_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"mysql"."innodb_index_stats"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_table_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"mysql"."innodb_table_stats"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/active_admin_comments'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."active_admin_comments"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/administrators'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."administrators"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/ar_internal_metadata'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."ar_internal_metadata"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/carousels'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."carousels"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/contacts'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."contacts"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/headers'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."headers"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/images'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."images"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/schema_migrations'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."schema_migrations"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/sections'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."sections"', ignored.
2017-06-07 18:10:55 140735296021248 [Note] InnoDB: 128 rollback segment(s) are active.
2017-06-07 18:10:55 140735296021248 [Note] InnoDB: Waiting for purge to start
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"mysql"."innodb_table_stats"' in the cache. Attempting to load the tablespace with space id 1.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_table_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"mysql"."innodb_index_stats"' in the cache. Attempting to load the tablespace with space id 2.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_index_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"or_deco__site_development"."images"' in the cache. Attempting to load the tablespace with space id 27.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/images'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"or_deco__site_development"."carousels"' in the cache. Attempting to load the tablespace with space id 13.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/carousels'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"or_deco__site_development"."schema_migrations"' in the cache. Attempting to load the tablespace with space id 4.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/schema_migrations'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.32-79.0 started; log sequence number 2135725
2017-06-07 18:10:55 4961533952 [Note] InnoDB: Dumping buffer pool(s) not yet started
2017-06-07 18:10:55 140735296021248 [Note] Plugin 'FEEDBACK' is disabled.
2017-06-07 18:10:55 140735296021248 [ERROR] Could not open mysql.plugin table. Some plugins may be not loaded
2017-06-07 18:10:55 140735296021248 [ERROR] Can't open and lock privilege tables: Table 'mysql.servers' doesn't exist
2017-06-07 18:10:55 140735296021248 [Note] Server socket created on IP: '::'.
2017-06-07 18:10:55 140735296021248 [ERROR] Can't start server : Bind on unix socket: Address already in use
2017-06-07 18:10:55 140735296021248 [ERROR] Do you already have another mysqld server running on socket: /tmp/mysql.sock ?
2017-06-07 18:10:55 140735296021248 [ERROR] Aborting
</code>```

What should I do to fix this ?

EDIT

After looking around, I tried numerous things:

1) I tried to stop all mysql running processes
I still have one process that I cant kill because the pid is constantly changing

```<code>ps aux |grep mysql

davidgeismar    19342   0.0  0.0  2432772    532 s000  R+    7:00PM   0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn mysql
</code>```

2) I also tried creating the mysql.sock file in /tmp as my original error message was :     ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (61 "Connection refused")
without more success

3) I tried desinstalling and reinstalling mysql via homebrew several times

4) I also checked the rights on cd /usr/local/Cellar/mysql/5.7.18_1/ and Im getting this :

```<code>-rw-r--r--   1 _mysql  _mysql  17987 Mar 18 08:56 COPYING
-rw-r--r--   1 _mysql  _mysql   1234 Jun  9 18:27 INSTALL_RECEIPT.json
-rw-r--r--   1 _mysql  _mysql   2478 Mar 18 08:56 README
drwxr-xr-x  42 _mysql  _mysql   1428 Jun  9 18:27 bin
drwxr-xr-x   2 _mysql  _mysql     68 Jun  9 18:51 data
-rw-r--r--   1 _mysql  _mysql    543 Jun  9 18:27 homebrew.mxcl.mysql.plist
drwxr-xr-x   3 _mysql  _mysql    102 Mar 18 08:56 include
drwxr-xr-x   9 _mysql  _mysql    306 Mar 18 08:56 lib
drwxr-xr-x   3 _mysql  _mysql    102 Mar 18 08:56 scripts
drwxr-xr-x   6 _mysql  _mysql    204 Mar 18 08:56 share
drwxr-xr-x   6 _mysql  _mysql    204 Jun  9 18:27 support-files
</code>```

everything seems to be owned by mysql which is supposed to be the correct permissions from what I read...

I really dont know what to do next.

答:
Access denied for user 'root'@'localhost' (using password: NO)

You should supply the password of the DB in the database.yml file that is associated with the username root

```<code>default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: Your_DB_Password_Here
  socket: /tmp/mysql.sock

development:
  <<: *default
  database: or_deco__site_development
</code>```

Update:

You should set password to a root user and use that in database.yml. Try the below to set the password.

```<code>$ mysql -u root -p

mysql> SET PASSWORD FOR 'root'@'localhost' = 'your_password_here'
</code>```

Body:
I am running a rails app with mysql.
My computer shut down in an unorthodox way and now when I am trying to run rails s I get Access denied for user 'root'@'localhost' (using password: NO)

My database.yml file looks like :

default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  socket: /tmp/mysql.sock

development:
  <<: *default
  database: or_deco__site_development

when Im trying to launch mysql server as root with mysql start I get this trace :

 ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (61 "Connection refused")

when I try mysqld --user=mysql as why suggested on mysql website I get this trace:

2017-06-07 18:10:54 140735296021248 [Note] mysqld (mysqld 10.1.19-MariaDB) starting as process 1462 ...
2017-06-07 18:10:54 140735296021248 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/var/mysql/ is case insensitive
2017-06-07 18:10:54 140735296021248 [Warning] One can only use the --user switch if running as root

2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: The InnoDB memory heap is disabled
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Compressed tables use zlib 1.2.5
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Using SSE crc32 instructions
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2017-06-07 18:10:54 140735296021248 [Note] InnoDB: Completed initialization of buffer pool
2017-06-07 18:10:55 140735296021248 [Note] InnoDB: Highest supported file format is Barracuda.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/gtid_slave_pos'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"mysql"."gtid_slave_pos"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_index_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"mysql"."innodb_index_stats"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_table_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"mysql"."innodb_table_stats"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/active_admin_comments'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."active_admin_comments"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/administrators'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."administrators"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/ar_internal_metadata'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."ar_internal_metadata"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/carousels'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."carousels"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/contacts'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."contacts"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/headers'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."headers"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/images'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."images"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/schema_migrations'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."schema_migrations"', ignored.
2017-06-07 18:10:55 7fff7d53a300  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/sections'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [ERROR] InnoDB: Tablespace open failed for '"or_deco__site_development"."sections"', ignored.
2017-06-07 18:10:55 140735296021248 [Note] InnoDB: 128 rollback segment(s) are active.
2017-06-07 18:10:55 140735296021248 [Note] InnoDB: Waiting for purge to start
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"mysql"."innodb_table_stats"' in the cache. Attempting to load the tablespace with space id 1.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_table_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"mysql"."innodb_index_stats"' in the cache. Attempting to load the tablespace with space id 2.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_index_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"or_deco__site_development"."images"' in the cache. Attempting to load the tablespace with space id 27.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/images'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"or_deco__site_development"."carousels"' in the cache. Attempting to load the tablespace with space id 13.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/carousels'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Failed to find tablespace for table '"or_deco__site_development"."schema_migrations"' in the cache. Attempting to load the tablespace with space id 4.
2017-06-07 18:10:55 127a27000  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2017-06-07 18:10:55 4959924224 [ERROR] InnoDB: Could not find a valid tablespace file for 'or_deco__site_development/schema_migrations'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2017-06-07 18:10:55 140735296021248 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.32-79.0 started; log sequence number 2135725
2017-06-07 18:10:55 4961533952 [Note] InnoDB: Dumping buffer pool(s) not yet started
2017-06-07 18:10:55 140735296021248 [Note] Plugin 'FEEDBACK' is disabled.
2017-06-07 18:10:55 140735296021248 [ERROR] Could not open mysql.plugin table. Some plugins may be not loaded
2017-06-07 18:10:55 140735296021248 [ERROR] Can't open and lock privilege tables: Table 'mysql.servers' doesn't exist
2017-06-07 18:10:55 140735296021248 [Note] Server socket created on IP: '::'.
2017-06-07 18:10:55 140735296021248 [ERROR] Can't start server : Bind on unix socket: Address already in use
2017-06-07 18:10:55 140735296021248 [ERROR] Do you already have another mysqld server running on socket: /tmp/mysql.sock ?
2017-06-07 18:10:55 140735296021248 [ERROR] Aborting

What should I do to fix this ?

EDIT

After looking around, I tried numerous things:

1) I tried to stop all mysql running processes
I still have one process that I cant kill because the pid is constantly changing

ps aux |grep mysql

davidgeismar    19342   0.0  0.0  2432772    532 s000  R+    7:00PM   0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn mysql

2) I also tried creating the mysql.sock file in /tmp as my original error message was :     ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (61 "Connection refused")
without more success

3) I tried desinstalling and reinstalling mysql via homebrew several times

4) I also checked the rights on cd /usr/local/Cellar/mysql/5.7.18_1/ and Im getting this :

-rw-r--r--   1 _mysql  _mysql  17987 Mar 18 08:56 COPYING
-rw-r--r--   1 _mysql  _mysql   1234 Jun  9 18:27 INSTALL_RECEIPT.json
-rw-r--r--   1 _mysql  _mysql   2478 Mar 18 08:56 README
drwxr-xr-x  42 _mysql  _mysql   1428 Jun  9 18:27 bin
drwxr-xr-x   2 _mysql  _mysql     68 Jun  9 18:51 data
-rw-r--r--   1 _mysql  _mysql    543 Jun  9 18:27 homebrew.mxcl.mysql.plist
drwxr-xr-x   3 _mysql  _mysql    102 Mar 18 08:56 include
drwxr-xr-x   9 _mysql  _mysql    306 Mar 18 08:56 lib
drwxr-xr-x   3 _mysql  _mysql    102 Mar 18 08:56 scripts
drwxr-xr-x   6 _mysql  _mysql    204 Mar 18 08:56 share
drwxr-xr-x   6 _mysql  _mysql    204 Jun  9 18:27 support-files

everything seems to be owned by mysql which is supposed to be the correct permissions from what I read...

I really dont know what to do next.

Body:
Access denied for user 'root'@'localhost' (using password: NO)

You should supply the password of the DB in the database.yml file that is associated with the username root

default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: Your_DB_Password_Here
  socket: /tmp/mysql.sock

development:
  <<: *default
  database: or_deco__site_development

Update:

You should set password to a root user and use that in database.yml. Try the below to set the password.

$ mysql -u root -p

mysql> SET PASSWORD FOR 'root'@'localhost' = 'your_password_here'


问:
Data from iOS app not saving to Firebase Database
I'm looking to save data that has been stored in 4 labels and 1 text view in my app onto my Firebase Database but I am not having any success, below is the code I have written.  The app is a form that gets filled in and has a save button that once pressed should send the data to my firebase database but when I check there is nothing there?

I'm not even sure how I would check for errors in the console for this problem.

```<code>import UIKit
import CoreLocation
import Firebase

class AddSightingViewController: UIViewController {

    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UITextView!

    var locManager = CLLocationManager()
    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set Date & Time

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium

        dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d, yyyy") // // set template after setting locale

        let dateString = "\(dateFormatter.string(from: Date() as Date))"
        dateLabel.text = String(dateString)

        let timeFormatter = DateFormatter()
        timeFormatter.timeStyle = .medium

        timeFormatter.setLocalizedDateFormatFromTemplate("hhmm")

        let timeString = "\(timeFormatter.string(from: Date() as Date))"

        timeLabel.text = String(timeString)

        // Set Latitude & Longitude

        locManager.requestWhenInUseAuthorization()

        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
            currentLocation = locManager.location
            self.latitudeLabel.text = String("\(currentLocation.coordinate.latitude)")
            self.longitudeLabel.text = String("\(currentLocation.coordinate.longitude)")
        }
    }

    func post() {

        let date = dateLabel.text
        let time = timeLabel.text
        let latitude = latitudeLabel.text
        let longitude = longitudeLabel.text
        let sightingDescription = descriptionLabel.text

        let post: [String : AnyObject] = ["date" : date as AnyObject,
                                          "time" : time as AnyObject,
                                          "latitude" : latitude as AnyObject,
                                          "longitude" : longitude as AnyObject,
                                          "Description" : sightingDescription as AnyObject]

        var ref: DatabaseReference!

        ref = Database.database().reference()

        ref.child("Sightings").childByAutoId().setValue(post)

    }

    @IBAction func saveButton(_ sender: Any) {

        post()

    }
}
</code>```

答:
Do you get any erroneous messages on console when you initialize Firebase, in AppDelegate, or when you actually do post? If you do, update your post

If not:
make sure Allows Arbitrary Loads is set to true on your info.plist.

Make sure the write permissions are appropriate:

By default Firebase implements users of apps to be authenticated with firebase through one of the Auth methods provided by the service. Sometimes this is overlooked when creating new projects. If you dont want authentification (not recommended, but can be a solution for publicly accessible databases), you just need to go to Database (in your project) > Rules and change it to this:

```<code>// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}
</code>```

You can check out how to play around with the basic-level rules here.

Otherwise if these dont fix it, provide more code or the console logs on app launch and when you post! (Also make sure the IBAction does actually fire.. you'd be surprised) Usually, you should get console messages on App Launch by default if firebase is being initialized. Otherwise, you wont get XCode console logs when you do post with the setValue method you're using. It's usually better to use the setValue(_ value: Any?, withCompletionBlock block: @escaping (Error?, FIRDatabaseReference) -> Void) method like so:

```<code>    let ref = Database.database().reference().[..all the childs until where you post]

    ref.setValue(item) { (err, resp) in
                guard err == nil else {
                    print("Posting failed : ")
                    print(err)

                    return
                }
                print("No errors while posting, :")
                print(resp)
            }
</code>```

From here, post the err, and resp content when you do if none of the previous suggestions work!

Body:
I'm looking to save data that has been stored in 4 labels and 1 text view in my app onto my Firebase Database but I am not having any success, below is the code I have written.  The app is a form that gets filled in and has a save button that once pressed should send the data to my firebase database but when I check there is nothing there?

I'm not even sure how I would check for errors in the console for this problem.

import UIKit
import CoreLocation
import Firebase

class AddSightingViewController: UIViewController {

    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UITextView!

    var locManager = CLLocationManager()
    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set Date & Time

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium

        dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d, yyyy") // // set template after setting locale

        let dateString = "\(dateFormatter.string(from: Date() as Date))"
        dateLabel.text = String(dateString)

        let timeFormatter = DateFormatter()
        timeFormatter.timeStyle = .medium

        timeFormatter.setLocalizedDateFormatFromTemplate("hhmm")

        let timeString = "\(timeFormatter.string(from: Date() as Date))"

        timeLabel.text = String(timeString)

        // Set Latitude & Longitude

        locManager.requestWhenInUseAuthorization()

        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
            currentLocation = locManager.location
            self.latitudeLabel.text = String("\(currentLocation.coordinate.latitude)")
            self.longitudeLabel.text = String("\(currentLocation.coordinate.longitude)")
        }
    }

    func post() {

        let date = dateLabel.text
        let time = timeLabel.text
        let latitude = latitudeLabel.text
        let longitude = longitudeLabel.text
        let sightingDescription = descriptionLabel.text

        let post: [String : AnyObject] = ["date" : date as AnyObject,
                                          "time" : time as AnyObject,
                                          "latitude" : latitude as AnyObject,
                                          "longitude" : longitude as AnyObject,
                                          "Description" : sightingDescription as AnyObject]

        var ref: DatabaseReference!

        ref = Database.database().reference()

        ref.child("Sightings").childByAutoId().setValue(post)

    }

    @IBAction func saveButton(_ sender: Any) {

        post()

    }
}

Body:
Do you get any erroneous messages on console when you initialize Firebase, in AppDelegate, or when you actually do post? If you do, update your post

If not:
make sure Allows Arbitrary Loads is set to true on your info.plist.

Make sure the write permissions are appropriate:

By default Firebase implements users of apps to be authenticated with firebase through one of the Auth methods provided by the service. Sometimes this is overlooked when creating new projects. If you dont want authentification (not recommended, but can be a solution for publicly accessible databases), you just need to go to Database (in your project) > Rules and change it to this:

// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

You can check out how to play around with the basic-level rules here.

Otherwise if these dont fix it, provide more code or the console logs on app launch and when you post! (Also make sure the IBAction does actually fire.. you'd be surprised) Usually, you should get console messages on App Launch by default if firebase is being initialized. Otherwise, you wont get XCode console logs when you do post with the setValue method you're using. It's usually better to use the setValue(_ value: Any?, withCompletionBlock block: @escaping (Error?, FIRDatabaseReference) -> Void) method like so:

    let ref = Database.database().reference().[..all the childs until where you post]

    ref.setValue(item) { (err, resp) in
                guard err == nil else {
                    print("Posting failed : ")
                    print(err)

                    return
                }
                print("No errors while posting, :")
                print(resp)
            }

From here, post the err, and resp content when you do if none of the previous suggestions work!


问:
mysql query for multiple fields
I am using mysql for survey answers.
the schema of the survey table is as follows:

id  | rating1 | rating2 | rating3 | rating4 | .... | rating20 |
  1      10        10       2          8       ....       4
  2       8         8       8          5       ....       7

As you can see, there's rating scores (from 1 to 10) inserted into rating1 - rating20 fields.
I can easily find biggest or smallest scores from rating(1-20) fields for each row using this query: "SELECT greatest(rating1, rating2 ..  rating20) FROM TBL_SURVEY WHERE id=1" which returns 10 for id 1.
But I don't know that greatest score belongs which field. And I like to count distnct rating scores. How many 10s or any other scores from rating1-rating20 fields for id 1?
Is there mysql queries for this? or Is there a way to get what I want using php?

Any help would be very appreciated...

答:
I'm going to suggest that you change your table design to something like this:

```<code>id | rating_id | rating
1  | 1         | 10
1  | 2         | 10
1  | 3         | 2
1  | 4         | 8
etc.
</code>```

With this improved and normalized design, we can find the max rating and its corresponding rating_id using a query like this:

```<code>SELECT t1.*
FROM ratings t1
INNER JOIN
(
    SELECT id, MAX(rating) AS max_rating
    FROM ratings
    GROUP BY id
) t2
    ON t1.id = t2.id AND
       t1.rating = t2.max_rating
</code>```

For your second question of e.g. how many 10s there are for id 1 we could use this:

```<code>SELECT COUNT(*)
FROM ratings
WHERE id = 1 AND rating = 10
</code>```

Title: mysql query for multiple fields

Body:
I'm going to suggest that you change your table design to something like this:

id | rating_id | rating
1  | 1         | 10
1  | 2         | 10
1  | 3         | 2
1  | 4         | 8
etc.

With this improved and normalized design, we can find the max rating and its corresponding rating_id using a query like this:

SELECT t1.*
FROM ratings t1
INNER JOIN
(
    SELECT id, MAX(rating) AS max_rating
    FROM ratings
    GROUP BY id
) t2
    ON t1.id = t2.id AND
       t1.rating = t2.max_rating

For your second question of e.g. how many 10s there are for id 1 we could use this:

SELECT COUNT(*)
FROM ratings
WHERE id = 1 AND rating = 10


问:
creating .htaccess
I am developing a project with Struts2. I use jsp for web-side. I use MySQL database for my application and I installed wamp server for it. My urls are like localhost/xxx?name.action?blablabla... instead of this I wanna redirect urls. For example instead of name.action on my url I wanna use localhost/name or something like that. Also with .htaccess I wanna send data over it as like name.action?Id=$1... for my action at Struts2 side. However I couldn't redirect the urls, I couldn't define document root properly and .htaccess file. What should I do, can you explain it step by step?

Thanks.

答: You don't need to use the .action extension in Struts2. You can opt for a different extension or no extension (which it sounds like is what you want).</p>

Title: creating .htaccess

ContentLicense: CC BY-SA 2.5


问:
i want java stream channel like filewriter
i just want fileoutputstream like filewriter at same style

like this

```<code>//filewriter code
        try {
        File file = ('some file link');
        fw=new FileWriter(file,true);
        fw.write("2017-06-08");
        fw.write("#");//separator
        fw.write("ABCD");
        fw.write("#");//separator
        fw.write("\r\n");
        fw.flush();
    }
</code>```

is answer at file :: 2017-06-08#ABCD#

but i want filelock, so use fos&channel.

```<code>try {
        //date = string "2017-06-08", menu= string"ABCD"
        fos = new FileOutputStream('file_addr',true);
        channel = fos.getChannel();
        lock=channel.tryLock();
        //if (lock==null){ //<- not yet work
        //  channel.close();
        //  throw new Exception();
        //}

        ByteBuffer buf = ByteBuffer.allocate(512);

        for (char ch : date.toCharArray())
            buf.putChar(ch);

            buf.putChar('#');

        for (char ch : menu.toCharArray())
            buf.putChar(ch);

            buf.putChar('\r');

            buf.putChar('\n');
            buf.rewind();
        channel.write(buf);

        //if (lock!=null){
        //  lock.release();
        //  channel.close();
        //}
</code>```

but isn't work. is output is '2 0 1 7 - 0 6 - 0 8'(and crushed)

how can write like this '2017-06-08#ABCD#' using fos & filechannel?

答:
The documentation for ByteBuffer.putChar() explains the problem you are having.

Writes two bytes containing the given char value, in the current byte order, into this buffer at the current position, and then increments the position by two.

In other words, putChar() writes a UTF-16 character (so that it can be read using getChar() ). This is probably not what you want.

If your characters are all in ascii, you can write them as single bytes simply by casting them. buf.put((byte)ch) should give you what you expected.

Body:
i just want fileoutputstream like filewriter at same style

like this

//filewriter code
        try {
        File file = ('some file link');
        fw=new FileWriter(file,true);
        fw.write("2017-06-08");
        fw.write("#");//separator
        fw.write("ABCD");
        fw.write("#");//separator
        fw.write("\r\n");
        fw.flush();
    }

is answer at file :: 2017-06-08#ABCD#

but i want filelock, so use fos&channel.

try {
        //date = string "2017-06-08", menu= string"ABCD"
        fos = new FileOutputStream('file_addr',true);
        channel = fos.getChannel();
        lock=channel.tryLock();
        //if (lock==null){ //<- not yet work
        //  channel.close();
        //  throw new Exception();
        //}

        ByteBuffer buf = ByteBuffer.allocate(512);

        for (char ch : date.toCharArray())
            buf.putChar(ch);

            buf.putChar('#');

        for (char ch : menu.toCharArray())
            buf.putChar(ch);

            buf.putChar('\r');

            buf.putChar('\n');
            buf.rewind();
        channel.write(buf);

        //if (lock!=null){
        //  lock.release();
        //  channel.close();
        //}

but isn't work. is output is '2 0 1 7 - 0 6 - 0 8'(and crushed)

how can write like this '2017-06-08#ABCD#' using fos & filechannel?


问:
Check for element being present then check if its displayed
I need to check if the pop up exists, if it does then I need to check if its displayed then perform certain action on it.

I have implemented the below. I was wanting to know if there is any better way of achieving this.

```<code> licenseUpdate.isPresent().then(function (item) {

                if (item == true) {
                    licenseUpdate.isDisplayed().then(function (res) {

                        if (res == true){

                            licenseUpdate.click();
                        };
                         });

                }

            });
</code>```

答:
If you are using page object (you should) you can write something like this:

```<code>clickLicenseUpdate() {
    const licenseUpdate = $(licenseUpdateCssSelector);

    return licenseUpdate.isPresent()
        .then((isPresent) => {
            if (!isPresent) { return false; }

            return licenseUpdate.isDisplayed();
        })
        .then((isDisplayed) => {
            if (!isDisplayed) { return false; }

            return licenseUpdate.click().then(() => true);
        })
}
</code>```

Note that if you are using and old JS version (you shouldn't) you need to replace arrow functions with traditional anonymous functions.

Some helpful links about Page Object Design Pattern:

PageObjects

Martin Fowler PageObject

Code explained (or at least, that is the plan):

Using $ to locate an element but you can use any strategy
supported by Protractor.
browser.findElement(by.className('license')) equivalent to
$('license'), browser.findElement(by.id('license')) equivalent to
$('#license'). Check Protractor documentation for more examples.

Once you a have found a web element that match your locator, you can
use isPresent method to determine whether the element is present on
the page. isPresent returns a promise that resolve to a boolean
value.

then always return a promise. You can return a primitive value from
onFulfilled callback and that value would be cast to a promise with
resolve with same value. That is what is done here:  if (!isPresent) { return false; };  or you can return another promise

from onFulfilled callback and the promise returned by then will be resolved or rejected with same value of returned promise.
That is what is done here: return licenseUpdate.isDisplayed();. isDisplayed() also return a
promise that will resolve with whether this element is currently
visible on the page.

This can be a bit overwhelming if you are not
used to deal with promises. Check this out Promises/A+

Finally, if the element is present and is displayed, click the element with theclick method that, surprise, also return a
promise (WebDriverJS API is based on promises).

Note that if element is not present, isPresent is false in this
line if (!isPresent), returning false immediately bypass
licenseUpdate.isDisplayed() execution and resolve with a false value. In that
case isDisplayed value is false and again false is returned
immediately bypassing the licenseUpdate.click() execution.

Also note that clickLicenseUpdate return a promise that will
resolve to false if the element is not present or if is present but not
displayed. To keep clickLicenseUpdate returned value consistent, I recommend you to wait for licenseUpdate.click() and then return a boolean value as it is done here: return licenseUpdate.click().then(() => true); (using implicit return from arrow functions) because promise returned by click() resolve with a void value.
That is harmless but is considered a good practice maintain a consistent return value, always a boolean value, not sometime a boolean and others a void value.

Body:
I need to check if the pop up exists, if it does then I need to check if its displayed then perform certain action on it.

I have implemented the below. I was wanting to know if there is any better way of achieving this.

 licenseUpdate.isPresent().then(function (item) {

                if (item == true) {
                    licenseUpdate.isDisplayed().then(function (res) {

                        if (res == true){

                            licenseUpdate.click();
                        };
                         });

                }

            });

Body:
If you are using page object (you should) you can write something like this:

clickLicenseUpdate() {
    const licenseUpdate = $(licenseUpdateCssSelector);

    return licenseUpdate.isPresent()
        .then((isPresent) => {
            if (!isPresent) { return false; }

            return licenseUpdate.isDisplayed();
        })
        .then((isDisplayed) => {
            if (!isDisplayed) { return false; }

            return licenseUpdate.click().then(() => true);
        })
}

Note that if you are using and old JS version (you shouldn't) you need to replace arrow functions with traditional anonymous functions.

Some helpful links about Page Object Design Pattern:

PageObjects

Martin Fowler PageObject

Code explained (or at least, that is the plan):

Using $ to locate an element but you can use any strategy
supported by Protractor.
browser.findElement(by.className('license')) equivalent to
$('license'), browser.findElement(by.id('license')) equivalent to
$('#license'). Check Protractor documentation for more examples.

Once you a have found a web element that match your locator, you can
use isPresent method to determine whether the element is present on
the page. isPresent returns a promise that resolve to a boolean
value.

then always return a promise. You can return a primitive value from
onFulfilled callback and that value would be cast to a promise with
resolve with same value. That is what is done here:  if (!isPresent) { return false; };  or you can return another promise

from onFulfilled callback and the promise returned by then will be resolved or rejected with same value of returned promise.
That is what is done here: return licenseUpdate.isDisplayed();. isDisplayed() also return a
promise that will resolve with whether this element is currently
visible on the page.

This can be a bit overwhelming if you are not
used to deal with promises. Check this out Promises/A+

Finally, if the element is present and is displayed, click the element with theclick method that, surprise, also return a
promise (WebDriverJS API is based on promises).

Note that if element is not present, isPresent is false in this
line if (!isPresent), returning false immediately bypass
licenseUpdate.isDisplayed() execution and resolve with a false value. In that
case isDisplayed value is false and again false is returned
immediately bypassing the licenseUpdate.click() execution.

Also note that clickLicenseUpdate return a promise that will
resolve to false if the element is not present or if is present but not
displayed. To keep clickLicenseUpdate returned value consistent, I recommend you to wait for licenseUpdate.click() and then return a boolean value as it is done here: return licenseUpdate.click().then(() => true); (using implicit return from arrow functions) because promise returned by click() resolve with a void value.
That is harmless but is considered a good practice maintain a consistent return value, always a boolean value, not sometime a boolean and others a void value.


问:
'undefined' getting appended to a specific Web API call
'Undefined' is getting appended to a specific WebAPI call in my angular application where as other calls succeed without issue.

Both registerUser and login call fails because of 'Undefined' character:

Request URL: http://localhost:25971/undefined/api/Account/Register

Request URL: http://localhost:25971/undefined/Token

Here is my code:

```<code>    (function () {
    "use strict";
    angular
        .module("userManagement")
        .controller("mainCtrl", ["userAccount", mainCtrl])

    function mainCtrl(userAccount) {
        var vm = this;
        vm.isLoggedIn = false;
        vm.message = '';
        vm.userData = {
            userName: '',
            email: '',
            password: '',
            confirmPassword: ''
        };

        vm.registerUser = function () {
            vm.userData.confirmPassword = vm.userData.password;
            userAccount.registration.registerUser(vm.userData, function (data) {
                vm.confirmPassword = "";
                vm.message = "...Registration successful";
                // vm.login();
            });
        }
        vm.login = function () {
            vm.userData.grant_type = "password";
            vm.userData.userName = vm.userData.email;
            userAccount.login.loginUser(vm.userData, function (data) {
                vm.isLoggedIn = true;
                vm.password = "";
                vm.message = "";
                vm.token = data.access_token;
            });
        }
    }
}());
</code>```

Here is the code in userAccount factory method:

```<code> (function () {
    "use strict";
    angular.module("common.services")
    .factory("userAccount", ["$resource", "appsettings", userAccount])
    function userAccount($resource, appsettings) {
        return {
            registration: $resource(appsettings.serverPath + "/api/Account/Register", null,
                {
                    'registerUser': { method: 'POST' }
                }),
            login: $resource(appsettings.serverPath + "/Token", null,
                {
                    'loginUser': {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: function (data, headersGetter) {
                        var str = [];
                        for (var d in data) {
                            str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                            return str.join("&")
                        }
                    }
                }
            })
        }
    }

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

Appsettings is defined like this:

```<code>(function () {
   "use strict";
    angular.module("common.services", ["ngResource"]).constant("appsettings", {
        serverpath:"http://localhost:25879/"
    });
}());
</code>```

I am new to Angular and WebAPI, any help or direction to find the issue would be appreciated!

答:
You appsettings constant should look like:

```<code>(function (angular) {
   "use strict";
    angular.module("common.services", ["ngResource"]).constant("appsettings", {
        serverPath: "http://localhost:25879"
    });
}(angular));
</code>```

The property serverpath is not the same as serverPath and in you case serverPath is undefined. You should respect the casing.

Body:
'Undefined' is getting appended to a specific WebAPI call in my angular application where as other calls succeed without issue.

Both registerUser and login call fails because of 'Undefined' character:

Request URL: http://localhost:25971/undefined/api/Account/Register

Request URL: http://localhost:25971/undefined/Token

Here is my code:

    (function () {
    "use strict";
    angular
        .module("userManagement")
        .controller("mainCtrl", ["userAccount", mainCtrl])

    function mainCtrl(userAccount) {
        var vm = this;
        vm.isLoggedIn = false;
        vm.message = '';
        vm.userData = {
            userName: '',
            email: '',
            password: '',
            confirmPassword: ''
        };

        vm.registerUser = function () {
            vm.userData.confirmPassword = vm.userData.password;
            userAccount.registration.registerUser(vm.userData, function (data) {
                vm.confirmPassword = "";
                vm.message = "...Registration successful";
                // vm.login();
            });
        }
        vm.login = function () {
            vm.userData.grant_type = "password";
            vm.userData.userName = vm.userData.email;
            userAccount.login.loginUser(vm.userData, function (data) {
                vm.isLoggedIn = true;
                vm.password = "";
                vm.message = "";
                vm.token = data.access_token;
            });
        }
    }
}());

Here is the code in userAccount factory method:

 (function () {
    "use strict";
    angular.module("common.services")
    .factory("userAccount", ["$resource", "appsettings", userAccount])
    function userAccount($resource, appsettings) {
        return {
            registration: $resource(appsettings.serverPath + "/api/Account/Register", null,
                {
                    'registerUser': { method: 'POST' }
                }),
            login: $resource(appsettings.serverPath + "/Token", null,
                {
                    'loginUser': {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: function (data, headersGetter) {
                        var str = [];
                        for (var d in data) {
                            str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                            return str.join("&")
                        }
                    }
                }
            })
        }
    }

})();

Appsettings is defined like this:

(function () {
   "use strict";
    angular.module("common.services", ["ngResource"]).constant("appsettings", {
        serverpath:"http://localhost:25879/"
    });
}());

I am new to Angular and WebAPI, any help or direction to find the issue would be appreciated!

Body:
You appsettings constant should look like:

(function (angular) {
   "use strict";
    angular.module("common.services", ["ngResource"]).constant("appsettings", {
        serverPath: "http://localhost:25879"
    });
}(angular));

The property serverpath is not the same as serverPath and in you case serverPath is undefined. You should respect the casing.


问:
Grouping and sorting data with R
Super new to R - like, started yesterday new. I'm trying to group and sort a data set and it seems as though samples like:

```<code>aggdata <- aggregate(mtcars, by = list(cyl, vs), FUN = mean, na.rm = TRUE)
</code>```

Only work with numeric data. I've also tried working off this example: R Dataframe: aggregating strings within column, across rows, by group to build something new for my purpose but it's not giving me the output I need.

For the example, I have a data set that would look like:

```<code>Name       DateTime
Jan        2017-05-26T12:38:50.537
Tim        2017-05-23T11:52:40.423
Rob        2017-05-24T10:52:40.423
Jan        2017-05-25T10:38:50.537
Tim        2017-05-19T11:52:40.423
Rob        2017-05-19T11:52:40.423
Jan        2017-05-22T12:38:50.537
Tim        2017-05-23T11:52:40.423
Rob        2017-05-20T11:52:40.423
</code>```

I would like to group the data by name then sort the groups by time so the end result would be:

```<code>Name          DateTime
Jan           2017-05-22T12:38:50.537
Jan           2017-05-25T10:38:50.537
Jan           2017-05-26T12:38:50.537
Rob           2017-05-19T11:52:40.423
Rob           2017-05-20T11:52:40.423
Rob           2017-05-24T10:52:40.423
Tim           2017-05-19T11:52:40.423
Tim           2017-05-23T11:50:40.423
Tim           2017-05-23T11:52:40.423
</code>```

After grouping is successful, this sample for datetime seems promising Ordering date/time in descending order in R

In any case, if someone in the know could point me in the direction of an example that groups by string or alphanumeric I'd greatly appreciate it.

答:
You can use the dplyr library:

```<code>install.packages("dplyr")
require(dplyr)
</code>```

Use arrange(data, Name, DateTime) to order by Name, and within name by DateTime.

Title: Grouping and sorting data with R

Body:
Super new to R - like, started yesterday new. I'm trying to group and sort a data set and it seems as though samples like:

aggdata <- aggregate(mtcars, by = list(cyl, vs), FUN = mean, na.rm = TRUE)

Only work with numeric data. I've also tried working off this example: R Dataframe: aggregating strings within column, across rows, by group to build something new for my purpose but it's not giving me the output I need.

For the example, I have a data set that would look like:

Name       DateTime
Jan        2017-05-26T12:38:50.537
Tim        2017-05-23T11:52:40.423
Rob        2017-05-24T10:52:40.423
Jan        2017-05-25T10:38:50.537
Tim        2017-05-19T11:52:40.423
Rob        2017-05-19T11:52:40.423
Jan        2017-05-22T12:38:50.537
Tim        2017-05-23T11:52:40.423
Rob        2017-05-20T11:52:40.423

I would like to group the data by name then sort the groups by time so the end result would be:

Name          DateTime
Jan           2017-05-22T12:38:50.537
Jan           2017-05-25T10:38:50.537
Jan           2017-05-26T12:38:50.537
Rob           2017-05-19T11:52:40.423
Rob           2017-05-20T11:52:40.423
Rob           2017-05-24T10:52:40.423
Tim           2017-05-19T11:52:40.423
Tim           2017-05-23T11:50:40.423
Tim           2017-05-23T11:52:40.423

After grouping is successful, this sample for datetime seems promising Ordering date/time in descending order in R

In any case, if someone in the know could point me in the direction of an example that groups by string or alphanumeric I'd greatly appreciate it.

Body:
You can use the dplyr library:

install.packages("dplyr")
require(dplyr)

Use arrange(data, Name, DateTime) to order by Name, and within name by DateTime.


问:
Embedding Xamarin Forms or native embedding
I will make an app where I need the native map. Either I do the app with Xamarin native and Embedding Xamarin.Forms in Xamarin Native on all pages without the page with the map. Or if it's possible I'll do an Xamarin Forms app and embedding the native map control, if it's possible? I read Adding Platform-Specific Controls to a Xamarin.Forms Layout but is the map included? Or is it only "small" controls as the label?

What should I use?

答:
Well Native Embedding is hard to implement ( you basically need to use the shared project instead of PCL), therefore for many it is easier to user CustomRenderers.

Xamarin.Forms Embedding in the otherhand, is still preview looks like easy to use , but to be honest I have no idea what advantages it gives us. Like if we are making a native app why do we need to have a xamarin.forms loaded to our projects and not only it will make our app bigger but it will make it harder to follow.

The way I see it from your question is to use the maps given by Xamarin.Forms here and you can access it's custom renderer if it is necessary. Or use TKCustomMap which they have already extended the map


问:
How to go to next computer in list of file does not exist when using shutil?
I have a program that goes through a list of computers and grabs a config file and saves it locally to my computer.  Currently, if the computer on the list does not have the config, the program will just continue on executing other functions on that same computer name.

I want to make it stop and say something such as "Filename does not exist on that computer." if the file does not exist.  Then instead of continue on with the other functions, I want it to stop and go to the next computer on the list for performing functions.

Any suggestions on how I can do this?

```<code>import os
import shutil
import fileinput
import re  # some of these used for other functions
import sys

def direrror():
    print (" Error Here. ")

    # copy config from server/computer
def copyfrom(servername):
    source = r'//' + servername + '/c$/remotedirectory/'
    dest = r"../mylocaldirectory"
    file = "filename.config"
    try:
         # here is where I want to stop and go to next computer in the list
         # if filename.config does not exist on remote computer
        shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))

    except:
        direrror()

    otherfunctions(servername) #continue on to other functions if filename exists

# open list of servers/computers
os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
    for servername in f:

        copyfrom(servername.strip())
</code>```

答:
```<code>if os.path.isfile(os.path.join(dest,file)):
    try:
        ....
    except:
        ....
else:
    #doesn't exist...
    return "some_marker"
</code>```

then in your for loop check if the returned value is equal the the marker and break your loop.

Body:
I have a program that goes through a list of computers and grabs a config file and saves it locally to my computer.  Currently, if the computer on the list does not have the config, the program will just continue on executing other functions on that same computer name.

I want to make it stop and say something such as "Filename does not exist on that computer." if the file does not exist.  Then instead of continue on with the other functions, I want it to stop and go to the next computer on the list for performing functions.

Any suggestions on how I can do this?

import os
import shutil
import fileinput
import re  # some of these used for other functions
import sys

def direrror():
    print (" Error Here. ")

    # copy config from server/computer
def copyfrom(servername):
    source = r'//' + servername + '/c$/remotedirectory/'
    dest = r"../mylocaldirectory"
    file = "filename.config"
    try:
         # here is where I want to stop and go to next computer in the list
         # if filename.config does not exist on remote computer
        shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))

    except:
        direrror()

    otherfunctions(servername) #continue on to other functions if filename exists

# open list of servers/computers
os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
    for servername in f:

        copyfrom(servername.strip())

Body:
if os.path.isfile(os.path.join(dest,file)):
    try:
        ....
    except:
        ....
else:
    #doesn't exist...
    return "some_marker"

then in your for loop check if the returned value is equal the the marker and break your loop.


问:
Direct child selection in jQuery

$(document).ready(function () {
    $("#one > li").text("fruits");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="one">
        <li>Apple</li>
        <li>
            <ul id="two">
                <li>Mango</li>
                <li>Grapes</li>
            </ul>
        </li>
        <li id="kela">Banana</li>
        <li class="sanatara">Orange</li>
    </ul></code>```

When I run this javascript on the above HTML then the output changes all the list items to "fruits" including the ones with id="two". Since direct selector (>) should only select the direct child of ul element with id="one" then why is this happening?

答:
You're telling jQuery to change the content of all child list items to "fruits", so it wipes out the nested list and does just that. If you want to skip list items that contains other lists, then you need to tell it that:

$(document).ready(function () {
    $("#one > li:not(:has('ul'))").text("fruits");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="one">
        <li>Apple</li>
        <li>
            <ul id="two">
                <li>Mango</li>
                <li>Grapes</li>
            </ul>
        </li>
        <li id="kela">Banana</li>
        <li class="sanatara">Orange</li>
    </ul></code>```

Title: Direct child selection in jQuery

Body:
$(document).ready(function () {
    $("#one > li").text("fruits");
})

Apple

Mango

Grapes

Banana

Orange

When I run this javascript on the above HTML then the output changes all the list items to "fruits" including the ones with id="two". Since direct selector (>) should only select the direct child of ul element with id="one" then why is this happening?

Body:
You're telling jQuery to change the content of all child list items to "fruits", so it wipes out the nested list and does just that. If you want to skip list items that contains other lists, then you need to tell it that:

$(document).ready(function () {
    $("#one > li:not(:has('ul'))").text("fruits");
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="one">
        <li>Apple</li>
        <li>
            <ul id="two">
                <li>Mango</li>
                <li>Grapes</li>
            </ul>
        </li>
        <li id="kela">Banana</li>
        <li class="sanatara">Orange</li>
    </ul>


问:
How to work with detached object in CF9?
If User is an entity, and I need to store User in Session, it will be detached on next request.

AFAIK there're only 2 methods to handle these detached objects

EntityMerge(session.user) - update DB with session's object (unsafe)

session.userID - entityLoadByPK() again on next request (more load)

Are these the only 2 workarounds?  Any other ways?

According to Advanced Techniques with ColdFusion 9 ORM Integration Slide Deck Concurrency with method #1 will throw error if entity has been changed on merge, but how is this useful? catch the exception and use method #2?

When to use EntityReload()?  I thought it works the same way as EntityMerge(entity) but it doesn't.

Thanks!

答:
Hibernate sessions are lazy loaded, and do not persist. So while you have the CF object in memory, they're pointing to a Hibernate session which is out of scope, for lack of better terminology. To get back in scope, you basically need to wake it up on your subsequent requests, using something like EntitySave() or EntityLoadByExample()

I do agree that wrapping in a service not only helps you avoid some of these issues, but is overall better architecturally than touching the entity directly.


问:
Using jq to update objects within a JSON document if the value corresponding to a given key starts with a specified string
I have the given JSON and want to change the id value of all elements, which starts with test in the name element:

```<code>{
    "other-value": "some-id",
    "values": [
        {
            "name": "test-2017-12-01",
            "id": "1"

        },
        {
            "name": "othert",
            "id": "2"
        }

    ]
}
</code>```

The following jq commands works jqplay

```<code>jq (.values[] | select(.name == "test-afs").id) |= "NEWID"
</code>```

But when I try it with startswith it stops working, what am I missing? jqplay

```<code>(.values[] | select(.name | startswith("test")).id) |= "NEWID"
</code>```

jq: error (at :14): Invalid path expression near attempt to access element "id" of {"name":"test-afs","id":"id"}
  exit status 5

答:
Please note that since the release of jq 1.5, jq has been enhanced to support the query that previously failed.  For example, using the current 'master' version:

```<code>jq -c '(.values[] | select(.name | startswith("test")).id) |= "NEWID"'
{"other-value":"some-id","values":[{"name":"test-2017-12-01","id":"NEWID"},{"name":"othert","id":"2"}]}
</code>```

Using earlier versions of jq, if/then/else/end can be used in this type of situation as follows:

```<code>.values[] |= if .name | startswith("test") then .id = "NEWID" else . end
</code>```

If using map, a minimalist expression would be:

```<code>.values |= map(if .name|startswith("test") then .id = "NEWID" else . end)
</code>```

Body:
I have the given JSON and want to change the id value of all elements, which starts with test in the name element:

{
    "other-value": "some-id",
    "values": [
        {
            "name": "test-2017-12-01",
            "id": "1"

        },
        {
            "name": "othert",
            "id": "2"
        }

    ]
}

The following jq commands works jqplay

jq (.values[] | select(.name == "test-afs").id) |= "NEWID"

But when I try it with startswith it stops working, what am I missing? jqplay

(.values[] | select(.name | startswith("test")).id) |= "NEWID"

jq: error (at :14): Invalid path expression near attempt to access element "id" of {"name":"test-afs","id":"id"}
  exit status 5

Body:
Please note that since the release of jq 1.5, jq has been enhanced to support the query that previously failed.  For example, using the current 'master' version:

jq -c '(.values[] | select(.name | startswith("test")).id) |= "NEWID"'
{"other-value":"some-id","values":[{"name":"test-2017-12-01","id":"NEWID"},{"name":"othert","id":"2"}]}

Using earlier versions of jq, if/then/else/end can be used in this type of situation as follows:

.values[] |= if .name | startswith("test") then .id = "NEWID" else . end

If using map, a minimalist expression would be:

.values |= map(if .name|startswith("test") then .id = "NEWID" else . end)


问:
How to abort old request processing when new request arrives on ASP.NET MVC 5?
I have a form with hundreds of check boxes and dropdown menus (Which value of many of them are coupled together). In the action there is updating mechanism to update an object in Session. This object does all validation and coupling of values, for example if user types %50 in one input filed, we might add 3 new SelectListItem to a dropdown.

Everything works fine, but if use starts to clicking on check boxes very quick (which is the normal case in our scenario), controller get multiple posts while it is processing previous ones. Fortunately we are only interested in the last POST, so we need a way to abort\cancel on going requests when newer request from same form comes.

What I tried:
1- blocking client side to make multiple posts when server still working on previous one. It is not desirable because it makes noticeable pauses on browser side.

2- There are several solutions for blocking multiple post backs by using HASH codes or AntiForgeryToken. But they don't what I need, I need to abort on-going thread in favor of new request, not blocking incoming request.

3- I tried to extend pipeline by adding two message handlers (one before action and another after executing action) to keep a hash code (or AntiForgeryToken) but problem is still there, even I can detect there is on-going thread working on same request, I have no way to abort that thread or set older request to Complete.

Any thoughts?

答:
The only thing you can do is throttle the requests client-side. Basically, you need to set a timeout when a checkbox is clicked. You can let that initial request go through, but then any further requests are queued (or actually dropped after the first queued request in your scenario) and don't run that until the timeout clears.

There's no way to abort a request server-side. Each request is idempotent. There is no inherent knowledge of anything that's happened before or since. The server has multiple threads fielding requests and will simply process those as fast as it can. There's no order to how the requests are processed or how responses are sent out. The first request could be the third one that receives a response, simply due to how the processing of each request goes.


问:
angular.cli - Webpack compile scss to css
I'm using Angular-cli - Webpack and when I use ng-build , I see all scss files but not compiled css.

I expect that assets/styles/_default.scss will compile to assets/styles/_default.css

what can be the problem ?

thanks.

答:
a known issue. it will be fixed in next updates of angular-cli I think.

if you need to load .scss in runtime so you need to use this line:

```<code>require('style-loader!assets/styles/_default.scss');
</code>```

you must install first type/node

npm install --save @types/node

and add it to tsconfig file.

Body:
a known issue. it will be fixed in next updates of angular-cli I think.

if you need to load .scss in runtime so you need to use this line:

require('style-loader!assets/styles/_default.scss');

you must install first type/node

npm install --save @types/node

and add it to tsconfig file.


问:
Unable to install the System.Data.SqlClient
I am trying to create Web API that will connect to the SQL server and run the stored procedure. I wanted to install the System.Data.SqlClient in to the project so I can give the connection details. But when tried to install that through the Nuget Manager it throws error like

```<code> Install failed. Rolling back...
 Could not install package 'System.Data.SqlClient 4.3.0'.
 You are trying to install this package into a project that targets.
 '.NETFramework,Version=v4.5', but the package does not contain any
 assembly references or content files that are compatible with that
 framework. For more information, contact the package author.
</code>```

How can I install them or is there any other way of giving the connectionStrings in web.config

答:
I could solve this problem with a little workaround for Xamarin PCL:

Change your PCL target to .NetStandard. You can do it in the PCL project properties.

Create a new .NetStandard ClassLibrary project.

Add the System.Data.SqlClient and your code

Reference the ClassLibrary project dll to the PCL project

With this library you can use the SqlClient.

In your case with asp.net: Perhaps, you can try to create a .NetFramework ClassLibrary and follow the steps above.

I hope it will help you!

Body:
I am trying to create Web API that will connect to the SQL server and run the stored procedure. I wanted to install the System.Data.SqlClient in to the project so I can give the connection details. But when tried to install that through the Nuget Manager it throws error like

 Install failed. Rolling back...
 Could not install package 'System.Data.SqlClient 4.3.0'.
 You are trying to install this package into a project that targets.
 '.NETFramework,Version=v4.5', but the package does not contain any
 assembly references or content files that are compatible with that
 framework. For more information, contact the package author.

How can I install them or is there any other way of giving the connectionStrings in web.config


问:
Publish a react component to npm and reuse it
I am trying to publish a basic React component to my npm registry and trying to reuse it. I think I am not following proper way to distribute my react component. Here's what I have:

This is the directory structure:

```<code>MyReactPOC
    -> main.jsx
    -> .npmrc
    -> package.json
    -> webpack.config.js
</code>```

main.jsx

```<code>import React from 'react';

class MyComponent extends React.Component {
    render() {
        return (
            <div>
                <p>Hello from MyComponent!!</p>
            </div>
        );
    }
}

export default MyComponent
</code>```

package.json

```<code>{
  "name": "@pankaj/my-component",
  "version": "1.0.7",
  "description": "POC for importing a component",
  "main": "./dist/bundle.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "prepublish": "webpack --config webpack.config.js"
  },
  "repository": {
    "type": "git",
    "url": "my git repo"
  },
  "author": "Pankaj",
  "license": "ISC",
  "dependencies": {
    "react": "~15.5.4",
    "react-dom": "~15.5.4"
  },
  "devDependencies": {
    "babel-cli": "~6.24.1",
    "babel-core": "~6.24.1",
    "babel-loader": "~6.4.1",
    "babel-preset-es2015": "~6.24.1",
    "babel-preset-react": "~6.24.1",
    "webpack": "~2.4.1"
  }
}
</code>```

webpack.config.js

```<code>var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './main.jsx',
    output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' },
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
};
</code>```

I import the module in another project using import MyComponent from '@pankaj/my-component'.

When I use this component like

I get the following error:

React.createElement: type is invalid -- expected a string (for
  built-in components) or a class/function (for composite components)
  but got: object. You likely forgot to export your component from the
  file it's defined in.

Please help me understand the right way to distribute the react components so that they can be used by other projects within my org.

Here is how I use this component:

ComponentUse.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from '@pankaj/my-component';

ReactDOM.render(
  <MyComponent/>,
  document.getElementById('root')
);
</code>```

I have an index.html that has the 'root' div.

答:
I wrote a full Medium story because I had the same issue as you and there is no information about it.
Check it out: https://medium.com/@BrodaNoel/how-to-create-a-react-component-and-publish-it-in-npm-668ad7d363ce

The main fix is to add libraryTarget: 'umd' in the webpack.config.js file

Body:
I am trying to publish a basic React component to my npm registry and trying to reuse it. I think I am not following proper way to distribute my react component. Here's what I have:

This is the directory structure:

MyReactPOC
    -> main.jsx
    -> .npmrc
    -> package.json
    -> webpack.config.js

main.jsx

import React from 'react';

class MyComponent extends React.Component {
    render() {
        return (

Hello from MyComponent!!

        );
    }
}

export default MyComponent

package.json

{
  "name": "@pankaj/my-component",
  "version": "1.0.7",
  "description": "POC for importing a component",
  "main": "./dist/bundle.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "prepublish": "webpack --config webpack.config.js"
  },
  "repository": {
    "type": "git",
    "url": "my git repo"
  },
  "author": "Pankaj",
  "license": "ISC",
  "dependencies": {
    "react": "~15.5.4",
    "react-dom": "~15.5.4"
  },
  "devDependencies": {
    "babel-cli": "~6.24.1",
    "babel-core": "~6.24.1",
    "babel-loader": "~6.4.1",
    "babel-preset-es2015": "~6.24.1",
    "babel-preset-react": "~6.24.1",
    "webpack": "~2.4.1"
  }
}

webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './main.jsx',
    output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' },
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
};

I import the module in another project using import MyComponent from '@pankaj/my-component'.

When I use this component like

I get the following error:

React.createElement: type is invalid -- expected a string (for
  built-in components) or a class/function (for composite components)
  but got: object. You likely forgot to export your component from the
  file it's defined in.

Please help me understand the right way to distribute the react components so that they can be used by other projects within my org.

Here is how I use this component:

ComponentUse.js

import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from '@pankaj/my-component';

ReactDOM.render(
  <MyComponent/>,
  document.getElementById('root')
);

I have an index.html that has the 'root' div.