问:
551 error with Facebook Messenger bot - "This person isn't available right now"
I've written a simple bot for Facebook Messenger that takes a user's text, applies a simple transformation and immediately returns the result.

While testing it myself, I've never had a problem, but it seems that for some users, Facebook returns the following error when the transformed message is sent back (from my server logs):

"www-authenticate": "OAuth \"Facebook Platform\" \"invalid_request\" \"(#551) This person isn't available right now.\""

Any ideas what the cause of this would be? It seems to arbitrarily happen to random users, and users should be available as the result is returned immediately.

Thanks!

答:
This is currently a confirmed bug on the Facebook platform. Bug location: https://developers.facebook.com/bugs/465154327166499/ (as mentioned by @m90, Facebook developer account is required to view it).

Bug description and steps to reproduce:

Have a new Facebook user (who never interacted with your app before)

With that user, ask anything that normally produces automated response from the app

Expected result:
Bot should respond

Actual result:
For apps in development mode it is error code 551 as following:

```<code>{"error":{"message":"(#551) This person isn't available right now.","type":"OAuthException","code":551,"error_subcode":1545041, ...
</code>```

For apps in production mode (already submitted and public) it is error 200 as following:

```<code>{"error":{"message":"(#200) This person isn't available right now.","type":"OAuthException","code":200,"error_subcode":1545041,...
</code>```

Note: if the user sends more messages, bot starts to reply normally after the 2nd message from the same user.

Based on the information from the Facebook Platform bug page, the bug has appeared in the end of May 2017. On our side, we have been noticing this for the last week (since around June 5), important to note that new app submissions are also failing because of this issue.

UPDATE June 09, 2017 Bug is marked as fixed and works on our side now. If you still experience issues, Facebook asks to comment on the bug page.

Body:
This is currently a confirmed bug on the Facebook platform. Bug location: https://developers.facebook.com/bugs/465154327166499/ (as mentioned by @m90, Facebook developer account is required to view it).

Bug description and steps to reproduce:

Have a new Facebook user (who never interacted with your app before)

With that user, ask anything that normally produces automated response from the app

Expected result:
Bot should respond

Actual result:
For apps in development mode it is error code 551 as following:

{"error":{"message":"(#551) This person isn't available right now.","type":"OAuthException","code":551,"error_subcode":1545041, ...

For apps in production mode (already submitted and public) it is error 200 as following:

{"error":{"message":"(#200) This person isn't available right now.","type":"OAuthException","code":200,"error_subcode":1545041,...

Note: if the user sends more messages, bot starts to reply normally after the 2nd message from the same user.

Based on the information from the Facebook Platform bug page, the bug has appeared in the end of May 2017. On our side, we have been noticing this for the last week (since around June 5), important to note that new app submissions are also failing because of this issue.

UPDATE June 09, 2017 Bug is marked as fixed and works on our side now. If you still experience issues, Facebook asks to comment on the bug page.


来源: stackexchange

问:
Cursor in T-SQL doesn't work
I am using cursor to randomly copy data from one table(Family_tree) to two other tables(Family_tree1 + @time, Family_tree2 + @time). Code executes successfully, but no row is updated. There IS actually what to copy from a table.
I am using Microsoft SQL Server Management Studio. Here's the part of script with cursor:

```<code>---creating two tables beforehand
DECLARE @random int
DECLARE
@first_name nvarchar(20),
@last_name AS nvarchar(20),
@date_of_birth AS nchar(10),
@date_of_death AS nchar(10),
@place_of_death AS nvarchar(30),
@credit_card AS nchar(16),
@ID_member AS int,
@FK_gender AS nchar(3),

DECLARE curs CURSOR FOR SELECT first_name, last_name, date_of_birth, date_of_death, place_of_death, credit_card, ID_member, FK_gender,  FROM Family_tree
OPEN curs

FETCH NEXT FROM curs INTO  @first_name, @last_name, @date_of_birth, @date_of_death, @place_of_death, @credit_card, @ID_member, @FK_gender,
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @random = RAND() * 1000000
    IF @random % 2 = 1
    BEGIN
        SET @sqlString = 'INSERT INTO [Family_tree1' + @time +  ']  (first_name, last_name, date_of_birth, date_of_death, place_of_death,  credit_card, ID_member, FK_gender)
    VALUES ('
     + @first_name  + ','  + @last_name  + ',' + @date_of_birth + ',' + @date_of_death + ',' + @place_of_death + ',' + @credit_card + ','
     + CAST(@ID_member AS nvarchar)  +','+ @FK_gender  + ')'
    END
    ELSE
    BEGIN
    SET @sqlString = 'INSERT INTO [Family_tree2' + @time +  '] (first_name, last_name, date_of_birth, date_of_death, place_of_death, credit_card, ID_member, FK_gender)
    VALUES (' + @first_name  + ','  + @last_name  + ',' + @date_of_birth + ',' + @date_of_death + ',' + @place_of_death + ',' + @credit_card + ','
     + CAST(@ID_member AS nvarchar)  +','+ @FK_gender + ')'
END
EXECUTE(@sqlString)
FETCH NEXT FROM curs INTO  @first_name, @last_name, @date_of_birth, @date_of_death, @place_of_death, @credit_card, @ID_member, @FK_gender
END
CLOSE curs
DEALLOCATE curs
END;
</code>```

I am new to T-SQL and will appreciate any advice!
Thank You in advance (:

答:
If you "have" to do it in the cursor, then you need to watch out for nulls. You also need to watch out for the fact that you're using strings and these should be quoted when inserted into a VALUES clause.

Instead of

```<code>VALUES (' + @first_name  + ',
</code>```

You need something like:

```<code>VALUES (' + COALESCE('''' + REPLACE(@first_name,'''','''''') + '''','NULL')  + ',
</code>```

And so on for the rest of your values. This replaces any single quotes within the value with doubled-up quotes, then wraps the whole string in single quotes. NULLs survive through all of that processing so we then also use COALESCE to replace the NULL with a NULL literal in the eventual string1.

Before running the cursor in anger, I'd suggest you do this for one row and print the string rather than executing it, to check that it "looks right".

I'd also suggest you look into using better data types - dates of birth/death would be much better dealt with as actual date values rather than strings.

1Guido suggested ISNULL in the comments, which is similar to COALESCE but has some odd limitations and I'd usually recommend against using. They also suggested that the replacement should be an empty string, but here that would result in VALUES(... ,, ...) at the position of the NULL value which would generate an error.

ContentLicense: CC BY-SA 3.0

Title: Cursor in T-SQL doesn't work

Body:
I am using cursor to randomly copy data from one table(Family_tree) to two other tables(Family_tree1 + @time, Family_tree2 + @time). Code executes successfully, but no row is updated. There IS actually what to copy from a table.
I am using Microsoft SQL Server Management Studio. Here's the part of script with cursor:

---creating two tables beforehand
DECLARE @random int
DECLARE
@first_name nvarchar(20),
@last_name AS nvarchar(20),
@date_of_birth AS nchar(10),
@date_of_death AS nchar(10),
@place_of_death AS nvarchar(30),
@credit_card AS nchar(16),
@ID_member AS int,
@FK_gender AS nchar(3),

DECLARE curs CURSOR FOR SELECT first_name, last_name, date_of_birth, date_of_death, place_of_death, credit_card, ID_member, FK_gender,  FROM Family_tree
OPEN curs

FETCH NEXT FROM curs INTO  @first_name, @last_name, @date_of_birth, @date_of_death, @place_of_death, @credit_card, @ID_member, @FK_gender,
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @random = RAND() * 1000000
    IF @random % 2 = 1
    BEGIN
        SET @sqlString = 'INSERT INTO [Family_tree1' + @time +  ']  (first_name, last_name, date_of_birth, date_of_death, place_of_death,  credit_card, ID_member, FK_gender)
    VALUES ('
     + @first_name  + ','  + @last_name  + ',' + @date_of_birth + ',' + @date_of_death + ',' + @place_of_death + ',' + @credit_card + ','
     + CAST(@ID_member AS nvarchar)  +','+ @FK_gender  + ')'
    END
    ELSE
    BEGIN
    SET @sqlString = 'INSERT INTO [Family_tree2' + @time +  '] (first_name, last_name, date_of_birth, date_of_death, place_of_death, credit_card, ID_member, FK_gender)
    VALUES (' + @first_name  + ','  + @last_name  + ',' + @date_of_birth + ',' + @date_of_death + ',' + @place_of_death + ',' + @credit_card + ','
     + CAST(@ID_member AS nvarchar)  +','+ @FK_gender + ')'
END
EXECUTE(@sqlString)
FETCH NEXT FROM curs INTO  @first_name, @last_name, @date_of_birth, @date_of_death, @place_of_death, @credit_card, @ID_member, @FK_gender
END
CLOSE curs
DEALLOCATE curs
END;

I am new to T-SQL and will appreciate any advice!
Thank You in advance (:

Body:
If you "have" to do it in the cursor, then you need to watch out for nulls. You also need to watch out for the fact that you're using strings and these should be quoted when inserted into a VALUES clause.

Instead of

VALUES (' + @first_name  + ',

You need something like:

VALUES (' + COALESCE('''' + REPLACE(@first_name,'''','''''') + '''','NULL')  + ',

And so on for the rest of your values. This replaces any single quotes within the value with doubled-up quotes, then wraps the whole string in single quotes. NULLs survive through all of that processing so we then also use COALESCE to replace the NULL with a NULL literal in the eventual string1.

Before running the cursor in anger, I'd suggest you do this for one row and print the string rather than executing it, to check that it "looks right".

I'd also suggest you look into using better data types - dates of birth/death would be much better dealt with as actual date values rather than strings.

1Guido suggested ISNULL in the comments, which is similar to COALESCE but has some odd limitations and I'd usually recommend against using. They also suggested that the replacement should be an empty string, but here that would result in VALUES(... ,, ...) at the position of the NULL value which would generate an error.


问:
Overload resolution for multiply inherited operator()
First, consider this C++ code:

```<code>#include <stdio.h>

struct foo_int {
    void print(int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void print(const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::print;
    //using foo_str::print;
};

int main() {
    foo f;
    f.print(123);
    f.print("abc");
}
</code>```

As expected according to the Standard, this fails to compile, because print is considered separately in each base class for the purpose of overload resolution, and thus the calls are ambiguous. This is the case on Clang (4.0), gcc (6.3) and MSVC (17.0) - see godbolt results here.

Now consider the following snippet, the sole difference of which is that we use operator() instead of print:

```<code>#include <stdio.h>

struct foo_int {
    void operator() (int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void operator() (const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
};

int main() {
    foo f;
    f(123);
    f("abc");
}
</code>```

I would expect the results to be identical to the previous case, but it is not the case - while gcc still complains, Clang and MSVC can compile this fine!

Question #1: who is correct in this case? I expect it to be gcc, but the fact that two other unrelated compilers give a consistently different result here makes me wonder whether I'm missing something in the Standard, and things are different for operators when they're not invoked using function syntax.

Also note that if you only uncomment one of the using declarations, but not the other, then all three compilers will fail to compile, because they will only consider the function brought in by using during overload resolution, and thus one of the calls will fail due to type mismatch. Remember this; we'll get back to it later.

Now consider the following code:

```<code>#include <stdio.h>

auto print_int = [](int x) {
    printf("int %d\n", x);
};
typedef decltype(print_int) foo_int;

auto print_str = [](const char* x) {
    printf("str %s\n", x);
};
typedef decltype(print_str) foo_str;

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
};

int main() {
    foo f;
    f(123);
    f("foo");
}
</code>```

Again, same as before, except now we don't define operator() explicitly, but instead get it from a lambda type. Again, you'd expect the results to be consistent with the previous snippet; and this is true for the case where both using declarations are commented out, or if both are uncommented. But if you only comment out one but not the other, things are suddenly different again: now only MSVC complains as I would expect it to, while Clang and gcc both think it's fine - and use both inherited members for overload resolution, despite only one being brought in by using!

Question #2: who is correct in this case? Again, I'd expect it to be MSVC, but then why do both Clang and gcc disagree? And, more importantly, why this is different from the previous snippet? I would expect the lambda type to behave exactly the same as a manually defined type with overloaded operator()...

答:
The rule for name lookup in base classes of a class C only happens if C itself doesn't directly contain the name is [class.member.lookup]/6:

The following steps define the result of merging lookup set S(f,Bi)
   into the intermediate S(f,C):

If each of the subobject members of S(f,Bi) is a base class subobject of at least one of the subobject members of S(f,C), or if S(f,Bi) is empty, S(f,C) is unchanged and the merge is complete. Conversely, if each of the subobject members of S(f,C) is a base class subobject of at least one of the subobject members of S(f,Bi), or if S(f,C) is empty, the new S(f,C) is a copy of S(f,Bi).

Otherwise, if the declaration sets of S(f,Bi) and S(f,C) differ, the merge is ambiguous: the new S(f,C) is a lookup set with an invalid declaration set and the union of the subobject sets. In subsequent merges, an invalid declaration set is considered different from any other.

Otherwise, the new S(f,C) is a lookup set with the shared set of declarations and the union of the subobject sets.

If we have two base classes, that each declare the same name, that the derived class does not bring in with a using-declaration, lookup of that name in the derived class would run afoul of that second bullet point and the lookup should fail. All of your examples are basically the same in this regard.

Question #1: who is correct in this case?

gcc is correct. The only difference between print and operator() is the name that we're looking up.

Question #2: who is correct in this case?

This is the same question as #1 - except we have lambdas (which give you unnamed class types with overload operator()) instead of explicit class types. The code should be ill-formed for the same reason. At least for gcc, this is bug 58820.

Body:
First, consider this C++ code:

#include <stdio.h>

struct foo_int {
    void print(int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void print(const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::print;
    //using foo_str::print;
};

int main() {
    foo f;
    f.print(123);
    f.print("abc");
}

As expected according to the Standard, this fails to compile, because print is considered separately in each base class for the purpose of overload resolution, and thus the calls are ambiguous. This is the case on Clang (4.0), gcc (6.3) and MSVC (17.0) - see godbolt results here.

Now consider the following snippet, the sole difference of which is that we use operator() instead of print:

#include <stdio.h>

struct foo_int {
    void operator() (int x) {
        printf("int %d\n", x);
    }
};

struct foo_str {
    void operator() (const char* x) {
        printf("str %s\n", x);
    }
};

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
};

int main() {
    foo f;
    f(123);
    f("abc");
}

I would expect the results to be identical to the previous case, but it is not the case - while gcc still complains, Clang and MSVC can compile this fine!

Question #1: who is correct in this case? I expect it to be gcc, but the fact that two other unrelated compilers give a consistently different result here makes me wonder whether I'm missing something in the Standard, and things are different for operators when they're not invoked using function syntax.

Also note that if you only uncomment one of the using declarations, but not the other, then all three compilers will fail to compile, because they will only consider the function brought in by using during overload resolution, and thus one of the calls will fail due to type mismatch. Remember this; we'll get back to it later.

Now consider the following code:

#include <stdio.h>

auto print_int = [](int x) {
    printf("int %d\n", x);
};
typedef decltype(print_int) foo_int;

auto print_str = [](const char* x) {
    printf("str %s\n", x);
};
typedef decltype(print_str) foo_str;

struct foo : foo_int, foo_str {
    //using foo_int::operator();
    //using foo_str::operator();
    foo(): foo_int(print_int), foo_str(print_str) {}
};

int main() {
    foo f;
    f(123);
    f("foo");
}

Again, same as before, except now we don't define operator() explicitly, but instead get it from a lambda type. Again, you'd expect the results to be consistent with the previous snippet; and this is true for the case where both using declarations are commented out, or if both are uncommented. But if you only comment out one but not the other, things are suddenly different again: now only MSVC complains as I would expect it to, while Clang and gcc both think it's fine - and use both inherited members for overload resolution, despite only one being brought in by using!

Question #2: who is correct in this case? Again, I'd expect it to be MSVC, but then why do both Clang and gcc disagree? And, more importantly, why this is different from the previous snippet? I would expect the lambda type to behave exactly the same as a manually defined type with overloaded operator()...


问:
Should I use libc::c_char or std::os::raw::c_char?
I am writing a FFI wrapper for Rust. I have seen usages of both libc::c_char and std::os::raw::c_char. My knowledge of C is very minimal and I wonder if there is any difference. What should I use if I would like to expose a string to Python via cffi?

答:
I can't answer which is more idiomatic, but I can say that they are the same on 64-bit Linux (the default platform for most online hosted documentation):

std::os::raw::c_char:

```<code>type c_char = i8;
</code>```

libc::c_char:

```<code>type c_char = i8;
</code>```

Looking more broadly across different platforms is a bit more complicated. The standard library tightly groups all the definitions for c_char, but libc groups them by platform. Considering how fundamental this type is, I'd expect them to be the same on all platforms.

Practically speaking, neither of these definitions are likely to ever change, so there's probably not any stability difference.

My opinion would be to use the one from the standard library version until I needed to use something specific from libc, in which case I'd probably switch all the types to the libc variants, just to be consistent.

Body:
I can't answer which is more idiomatic, but I can say that they are the same on 64-bit Linux (the default platform for most online hosted documentation):

std::os::raw::c_char:

type c_char = i8;

libc::c_char:

type c_char = i8;

Looking more broadly across different platforms is a bit more complicated. The standard library tightly groups all the definitions for c_char, but libc groups them by platform. Considering how fundamental this type is, I'd expect them to be the same on all platforms.

Practically speaking, neither of these definitions are likely to ever change, so there's probably not any stability difference.

My opinion would be to use the one from the standard library version until I needed to use something specific from libc, in which case I'd probably switch all the types to the libc variants, just to be consistent.


问:
Linq statements need optimizing
I have written the following code:

```<code>//get the user from the DB
var tmpuser = _db.aspnet_Users.First(q => q.UserName == user.Identity.Name);

//list the direct connections to Verbond
List<Verbond> verb1 = tmpuser.UsersVerbondens
                             .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                             .Select(q => q.Verbond)
                             .ToList();

//list the connected Facturatieverbonden
List<FacturatieVerbonden> verb2 = tmpuser.UsersFacturatieVerbondens
                                         .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                                         .Select(q => q.FacturatieVerbonden)
                                         .ToList();

//loop through the facturatieverbonden and add their verbonds to the first list
foreach (FacturatieVerbonden v in verb2) {
    verb1.AddRange(v.Verbonds);
}

//make a distinct list
List<Verbond> test = verb1.Distinct().ToList();
</code>```

So, Users can be connected to 0 or more facturatieverbonden and also can be connected to verbond.

A facturatieverbonden can have one or more verbond's under itself.

What I need is a list of all the verbond's the user is connected to, directly, or indirectly via the facturatieverbonden.

My code works but I don't think it's very efficient. Any hints on making it cleaner?

答:
Your performance problem is here.  Each AddRange call will enumerate v.Verbonds, and each will be a database roundtrip.

```<code>//loop through the facturatieverbonden and add their verbonds to the first list
foreach (FacturatieVerbonden v in verb2) {
    verb1.AddRange(v.Verbonds);
}
</code>```

To fix it:

```<code>//query the connected Facturatieverbonden
IQueryable<FacturatieVerbonden> verbQuery2 = tmpuser.UsersFacturatieVerbondens
  .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
  .Select(q => q.FacturatieVerbonden);

verb1.AddRange(verbQuery2.SelectMany(fv => fv.Verbonds));
</code>```

There's still plenty of room to tighten the performance, but at least this address the gross problem.  You could easily observe a 10 times speed up.

ContentLicense: CC BY-SA 2.5

Title: Linq statements need optimizing

Body:
I have written the following code:

//get the user from the DB
var tmpuser = _db.aspnet_Users.First(q => q.UserName == user.Identity.Name);

//list the direct connections to Verbond
List<Verbond> verb1 = tmpuser.UsersVerbondens
                             .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                             .Select(q => q.Verbond)
                             .ToList();

//list the connected Facturatieverbonden
List<FacturatieVerbonden> verb2 = tmpuser.UsersFacturatieVerbondens
                                         .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                                         .Select(q => q.FacturatieVerbonden)
                                         .ToList();

//loop through the facturatieverbonden and add their verbonds to the first list
foreach (FacturatieVerbonden v in verb2) {
    verb1.AddRange(v.Verbonds);
}

//make a distinct list
List<Verbond> test = verb1.Distinct().ToList();

So, Users can be connected to 0 or more facturatieverbonden and also can be connected to verbond.

A facturatieverbonden can have one or more verbond's under itself.

What I need is a list of all the verbond's the user is connected to, directly, or indirectly via the facturatieverbonden.

My code works but I don't think it's very efficient. Any hints on making it cleaner?

Body:
Your performance problem is here.  Each AddRange call will enumerate v.Verbonds, and each will be a database roundtrip.

//loop through the facturatieverbonden and add their verbonds to the first list
foreach (FacturatieVerbonden v in verb2) {
    verb1.AddRange(v.Verbonds);
}

To fix it:

//query the connected Facturatieverbonden
IQueryable<FacturatieVerbonden> verbQuery2 = tmpuser.UsersFacturatieVerbondens
  .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
  .Select(q => q.FacturatieVerbonden);

verb1.AddRange(verbQuery2.SelectMany(fv => fv.Verbonds));

There's still plenty of room to tighten the performance, but at least this address the gross problem.  You could easily observe a 10 times speed up.


问:
Access parent's application.properties from dependent project in spring boot
I am developing a multi-module project in Spring Boot where the project structure is as follows:

```<code>com.app.parent  <- parent pom with version numbers and common dependencies (POM)
com.app.core    <- repository and service layer, models, DTOs (JAR)
com.app.rest    <- rest API (WAR)
com.app.soap    <- soap API (WAR)
</code>```

The pom.xml file for the parent project is:

```<code><artifactId>app-parent</artifactId>
<packaging>pom</packaging>
<name>app-parent</name>

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

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

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

The pom.xml file for the core project is:

```<code><artifactId>app-core</artifactId>
<packaging>jar</packaging>
<name>app-core</name>

<parent>
    <groupId>com.app</groupId>
    <artifactId>app-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath>../app-parent/pom.xml</relativePath>
</parent>

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

The pom.xml for the rest project is:

```<code><artifactId>app-rest</artifactId>
<packaging>war</packaging>
<name>app-rest</name>

<parent>
    <groupId>com.app</groupId>
    <artifactId>app-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath>../app-parent/pom.xml</relativePath>
</parent>

<dependencies>
    <dependency>
        <groupId>com.app</groupId>
        <artifactId>app-core</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
</code>```

The entry point for the app-core project is:

```<code>@SpringBootApplication
public class CoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(CoreApplication.class, args);
    }
}
</code>```

The entry point for the app-rest project looks exactly the same.

I have created an application.properties file within core/src/main/resources/ which contains database config etc. and I can compile/test the app-core project just fine. However, when I try to run or test the app-rest project I get errors related to the absence of application.properties file

Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.

How do I get the child project to load the parent's application.properties file? Do I have to create a symlink to the parent file, or do I expressly load the parent's property file via @PropertySource? What do others do in this scenario?

答:
Create another module for configurations (let's say config) and put your application.properties in config/src/main/resources/.

Add the config module as dependency to any module which use the same configs and there you go.

Body:
I am developing a multi-module project in Spring Boot where the project structure is as follows:

com.app.parent  <- parent pom with version numbers and common dependencies (POM)
com.app.core    <- repository and service layer, models, DTOs (JAR)
com.app.rest    <- rest API (WAR)
com.app.soap    <- soap API (WAR)

The pom.xml file for the parent project is:

<artifactId>app-parent</artifactId>
<packaging>pom</packaging>
<name>app-parent</name>

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

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

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

The pom.xml file for the core project is:

<artifactId>app-core</artifactId>
<packaging>jar</packaging>
<name>app-core</name>

<parent>
    <groupId>com.app</groupId>
    <artifactId>app-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath>../app-parent/pom.xml</relativePath>
</parent>

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

The pom.xml for the rest project is:

<artifactId>app-rest</artifactId>
<packaging>war</packaging>
<name>app-rest</name>

<parent>
    <groupId>com.app</groupId>
    <artifactId>app-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath>../app-parent/pom.xml</relativePath>
</parent>

<dependencies>
    <dependency>
        <groupId>com.app</groupId>
        <artifactId>app-core</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

The entry point for the app-core project is:

@SpringBootApplication
public class CoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(CoreApplication.class, args);
    }
}

The entry point for the app-rest project looks exactly the same.

I have created an application.properties file within core/src/main/resources/ which contains database config etc. and I can compile/test the app-core project just fine. However, when I try to run or test the app-rest project I get errors related to the absence of application.properties file

Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.

How do I get the child project to load the parent's application.properties file? Do I have to create a symlink to the parent file, or do I expressly load the parent's property file via @PropertySource? What do others do in this scenario?


问:
How do you specify variables to be final in C?
I am aware that it is possible to declare constants using the #define macro. With this, it would be simple to define integer, floating point or character literals to be constants.

But, for more complicated data structures, such as an array, or a struct, say for example:

```<code>typedef struct {
    int name;
    char* phone_number;
} person;
</code>```

I want to be able to initialise this just once and then make it a non-editable struct.

In object oriented languages, there exists the final keyword to do this easily, but there is no such thing in C. One workaround I've thought of is to use setjmp and longjmp to simulate try-catch braces and do a rollback if a change is detected. You'd need to store a backup in a file/in memory object, which can get  little messy if you have many such objects you want to protect from accidental alteration.

Q: Is it possible to effectively represent such a pattern in C? If yes, how can it be done?

答:
Use const as keyword for variable. This is a way how to prevent value to be modified later.

```<code>const int a = 5;
a = 7; //Error, you cannot modify it!
</code>```

For example, in embedded systems where you have flash memory, this variable may be put to flash by linker, if available. But it is not necessary the case.

Body:
I am aware that it is possible to declare constants using the #define macro. With this, it would be simple to define integer, floating point or character literals to be constants.

But, for more complicated data structures, such as an array, or a struct, say for example:

typedef struct {
    int name;
    char* phone_number;
} person;

I want to be able to initialise this just once and then make it a non-editable struct.

In object oriented languages, there exists the final keyword to do this easily, but there is no such thing in C. One workaround I've thought of is to use setjmp and longjmp to simulate try-catch braces and do a rollback if a change is detected. You'd need to store a backup in a file/in memory object, which can get  little messy if you have many such objects you want to protect from accidental alteration.

Q: Is it possible to effectively represent such a pattern in C? If yes, how can it be done?

Body:
Use const as keyword for variable. This is a way how to prevent value to be modified later.

const int a = 5;
a = 7; //Error, you cannot modify it!

For example, in embedded systems where you have flash memory, this variable may be put to flash by linker, if available. But it is not necessary the case.

ContentLicense: CC BY-SA 4.0


问:
No layout found when accessing /sitecore. I am trying to access it for the first time
No layout found when accessing mylocalwebsite.local/sitecore. I am trying to run it for the first time, restored DBs, granted permission to AppPool etc.

I get a redirect to 404 and the url changes to:

```<code>/no-layout?item=%2fsitecore&layout=%7b00000000-0000-0000-0000-000000000000%7d&device=Default
no layout
</code>```

Please note, I am on Sitecore 6.5

答: Make sure you have the correct Sitecore, Sitecore modules and sitecore_files folders. In my case the total size of combined folders was only 11MB, so I copied the original folders from a new Sitecore 6.5 (12009) instance, which combined was > 140MB  in size

Body:
No layout found when accessing mylocalwebsite.local/sitecore. I am trying to run it for the first time, restored DBs, granted permission to AppPool etc.

I get a redirect to 404 and the url changes to:

/no-layout?item=%2fsitecore&layout=%7b00000000-0000-0000-0000-000000000000%7d&device=Default
no layout

Please note, I am on Sitecore 6.5


问:
double dash webkit prefix --webkit in chrome, single not working
Have I stumbled upon something new?

My existing css with -webkit-transform (for example) is crossed over (disabled) when I inspect in chrome desktop v58 but when I add a dash to --webkit-transform- the css tag works.

Is this something new, I dont find anything about this when searching online

答: The term is active and working but is listed as crossed over in chrome


问:
How to install mysql-connector via pip
I use sqlalchemy to access MySQL in my Python project. sqlalchemy's conf is like this:

```<code>dialect=mysql
driver=mysqlconnector
</code>```

So I need to install the Python module mysql connector via pip. Any help?

答:
If loading via pip install mysql-connector and leads an error Unable to find Protobuf include directory then this would be useful pip install mysql-connector==2.1.4

mysql-connector is obsolete, so use pip install mysql-connector-python. Same here

Title: How to install mysql-connector via pip

Body:
I use sqlalchemy to access MySQL in my Python project. sqlalchemy's conf is like this:

dialect=mysql
driver=mysqlconnector

So I need to install the Python module mysql connector via pip. Any help?


问:
How to launch the activity for user to key in information once only in android?
This is my login activity code. I just want to launch my user information for user to key in their information once only after that next time when user login will straight open to main activity. Can anyone help me or teach me?

```<code>public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;

private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Boolean session_tag = prefs.getBoolean("session", false);
    if(session_tag)
    {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));

    }

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){

                        //start the profle activity
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}
</code>```

}

答:
```<code>public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences();

    Boolean session_tag = prefs.getBoolean("session", false);
         if(session_tag)
       {
          startActivity(new Intent(getApplicationContext(),MainActivity.class));
       }
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){
                        //start the profle activity
                       prefs.edit().putBoolean("session", true).apply();
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}

}
</code>```

if you want check boolean variable then here i wrote some code:

```<code>prefs.edit().putBoolean("session", true).apply();
</code>```

to get value Boolean

```<code>session_tag = prefs.getBoolean("session", false);
</code>```

Body:
This is my login activity code. I just want to launch my user information for user to key in their information once only after that next time when user login will straight open to main activity. Can anyone help me or teach me?

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;

private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Boolean session_tag = prefs.getBoolean("session", false);
    if(session_tag)
    {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));

    }

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){

                        //start the profle activity
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}

}

Body:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

private Button buttonSignIn;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    firebaseAuth = FirebaseAuth.getInstance();

    if(firebaseAuth.getCurrentUser() !=null){
        //profile activity here
    }

    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    textViewSignup = (TextView) findViewById(R.id.textViewSignUp);
    buttonSignIn = (Button) findViewById(R.id.buttonSignin);

    progressDialog = new ProgressDialog(this);
    buttonSignIn.setOnClickListener(this);
    textViewSignup.setOnClickListener(this);

    prefs = PreferenceManager.getDefaultSharedPreferences();

    Boolean session_tag = prefs.getBoolean("session", false);
         if(session_tag)
       {
          startActivity(new Intent(getApplicationContext(),MainActivity.class));
       }
}

private void userLogin(){
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        //email is empty
        Toast.makeText(this,"Please enter email", Toast.LENGTH_SHORT).show();
        //stopping the function execction further
        return;
    }

    if(TextUtils.isEmpty(password)){
        //password is empty
        Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        //stopping the function execution further
        return;
    }
    //if validations are ok

    progressDialog.setMessage("Logging In...");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();

                    if(task.isSuccessful()){
                        //start the profle activity
                       prefs.edit().putBoolean("session", true).apply();
                        finish();
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                    }else{
                        Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_SHORT).show();
                    }
                }

            });
}

@Override
public void onClick(View view) {
    if(view == buttonSignIn){
        userLogin();

    }
    if (view == textViewSignup){
        finish();
        startActivity(new Intent(this,RegisterActivity.class));

    }
}

}

if you want check boolean variable then here i wrote some code:

prefs.edit().putBoolean("session", true).apply();

to get value Boolean

session_tag = prefs.getBoolean("session", false);


答: The equivalent keyword in C is const.

Title: How do you specify variables to be final in C?

Body: The equivalent keyword in C is const.


Body:
how do i split the unstructured data and insert it into a table

the below data represents unstructured data which i need to format in a set of different column and insert it in a table,

ABB0512  709023378812005327020220953171        025336141992033270207033123002663270200401ABC02055       ABC02055CBL MURARJIPET,MALAD MAlAD      MHIN3270204     ABC                                                          333000000000050000000000000050000000000000000000333000000000050000000000000000000000000000000000   000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000

ABB0222  709023378812005327020220953171    025222141992033270207033123002663270200401PQR02055       PQR02055CBL MURARJIPET,THANE THANE      MHIN3270204     PQR                                                          222000000000010000000000000010000000000000000000222000000000010000000000000000000000000000000000   000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000

The structure of the data after formatting will be as show below :

----a---------b------------c---------------------d-----e
========================================================================
ABC02055    ABC02055    CBL MURARJIPET,MALAD    MAlAD   MHIN

PQR02055    PQR02055    CBL MURARJIPET,THANE    THANE   MHIN

The below query gives the expected result for just the first string

Declare @variablestring varchar(max)
set @variablestring = substring(@strval,0,407)
print @variablestring
INSERT INTO tbldummyEntries(A, B, C,D,E,F)
values( CAST(SUBSTRING(@variablestring, 84, 15) AS Varchar(MAX)) ,
    CAST(SUBSTRING(@variablestring, 99, 8) AS Varchar(MAX)) ,
    CAST(SUBSTRING(@variablestring, 107, 22) AS Varchar(MAX)),
    CAST (SUBSTRING(@variablestring, 130, 13) AS Varchar(MAX)),
    CAST (SUBSTRING (@variablestring, 143, 5) AS Varchar(MAX)),
    CAST (SUBSTRING(@variablestring , 148 , 261) AS Varchar(MAX)))
set @strval=REPLACE(@strval,@variablestring,'')

How do i replicate it for the entries following after the first one?

Any help would be appreciated.

Body:
I tried as follows:(Keep the length in loop as per your format)

Declare @variablestring varchar(max),@strval varchar(max)
set @strval='ABB0512  709023378812005327020220953171        025336141992033270207033123002663270200401ABC02055       ABC02055CBL MURARJIPET,MALAD MAlAD      MHIN3270204     ABC                                                          333000000000050000000000000050000000000000000000333000000000050000000000000000000000000000000000   000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000

ABB0222  709023378812005327020220953171    025222141992033270207033123002663270200401PQR02055       PQR02055CBL MURARJIPET,THANE THANE      MHIN3270204     PQR                                                          222000000000010000000000000010000000000000000000222000000000010000000000000000000000000000000000   000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000'
set @variablestring = substring(@strval,0,407)
while len(@strval)>406
begin
INSERT INTO tbldummyEntries(A, B, C,D,E,F) values
select CAST(SUBSTRING(@variablestring, 84, 15) AS Varchar(MAX)) ,
    CAST(SUBSTRING(@variablestring, 99, 8) AS Varchar(MAX)) ,
    CAST(SUBSTRING(@variablestring, 107, 22) AS Varchar(MAX)),
    CAST (SUBSTRING(@variablestring, 130, 13) AS Varchar(MAX)),
    CAST (SUBSTRING (@variablestring, 143, 5) AS Varchar(MAX)),
    CAST (SUBSTRING(@variablestring , 148 , 261) AS Varchar(MAX))
set @strval=REPLACE(@strval,@variablestring,'')
set @variablestring = substring(@strval,0,407)
    end


问:
Permission dialogs
In my AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

But when I have installed my App-APK, I must setting up the permissions in my Android OS in the settings manually (Settings > Apps > myApp > Permissions > Storage).

How can I get that the permissions setting up automatically. Or the user of my App must confirm it in a dialog?

答:
I guess you want like this:

i want to give simple solution as :

Add Library in your Gradle file dependencies {} section :

```<code>compile 'com.karumi:dexter:4.1.0'
</code>```

am customize some changes in your code and that changes are very easy to understand.If you have any query,feeling freely to ask me.

```<code>  private void checkwriteStoragePermission()
{

    new android.support.v7.app.AlertDialog.Builder(this)
            .setTitle(R.string.permissions_title)
            .setMessage(R.string.read_ext_permissions_message)
            .setPositiveButton(R.string.btn_continue, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Dexter.withActivity(MultipleBranchesActivity.this)
                            .withPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .withListener(new PermissionListener() {
                                @Override
                                public void onPermissionGranted(PermissionGrantedResponse response) {
                                    Toast.makeText(MultipleBranchesActivity.this, "Permisson Granted", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onPermissionDenied(PermissionDeniedResponse response) {
                                    Toast.makeText(MultipleBranchesActivity.this, "Permisson Denied", Toast.LENGTH_SHORT).show();

                                }

                                @Override
                                public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
                            }).check();

                }
            })
            .setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setCancelable(false)
            .show();

}
</code>```

and call your method.

Title: Permission dialogs

Body:
In my AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

But when I have installed my App-APK, I must setting up the permissions in my Android OS in the settings manually (Settings > Apps > myApp > Permissions > Storage).

How can I get that the permissions setting up automatically. Or the user of my App must confirm it in a dialog?

Body:
I guess you want like this:

i want to give simple solution as :

Add Library in your Gradle file dependencies {} section :

compile 'com.karumi:dexter:4.1.0'

am customize some changes in your code and that changes are very easy to understand.If you have any query,feeling freely to ask me.

  private void checkwriteStoragePermission()
{

    new android.support.v7.app.AlertDialog.Builder(this)
            .setTitle(R.string.permissions_title)
            .setMessage(R.string.read_ext_permissions_message)
            .setPositiveButton(R.string.btn_continue, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Dexter.withActivity(MultipleBranchesActivity.this)
                            .withPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .withListener(new PermissionListener() {
                                @Override
                                public void onPermissionGranted(PermissionGrantedResponse response) {
                                    Toast.makeText(MultipleBranchesActivity.this, "Permisson Granted", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onPermissionDenied(PermissionDeniedResponse response) {
                                    Toast.makeText(MultipleBranchesActivity.this, "Permisson Denied", Toast.LENGTH_SHORT).show();

                                }

                                @Override
                                public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
                            }).check();

                }
            })
            .setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setCancelable(false)
            .show();

}

and call your method.


问:
Tomcat vs Weblogic JNDI Lookup
The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds".

For development (localhost), we might be running Tomcat and when declared in the <context> section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree.

Problem: in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config ... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments.

Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great.

答: JndiLocatorSupport has a property resourceRef. When setting this true, "java:comp/env/" prefix will be prepended automatically. So I believe it would be correct to differentiate this parameter when moving from Tomcat to Weblogic.

OwnerDisplayName: Luther Baker

Title: Tomcat vs Weblogic JNDI Lookup

OwnerDisplayName: martsraits


问:
Why is an extra pixel added to firefox elements when I use `line-height: 1` in my reset?
I use this reset.

```<code>* {
    font-family: Arial, Helvetica, sans-serif;
    outline: 0;
    padding: 0;
    margin: 0;
    border: 0;
    text-decoration: none;
    vertical-align: baseline;
    white-space: normal;
    line-height: 1;
}
hr {display: none}
blockquote:before, blockquote:after, q:before, q:after {content: ''}
blockquote, q {quotes: "" ""}
ul {list-style-type: none}
ol {list-style-type: decimal}
a {text-decoration: none}

.clear {clear: both}
</code>```

The problem is that as long as I use line-height: 1 I see an extra pixel that does not go away no matter what I do in my block links even I tried setting height, line-height, font-size for it. nothing works. Please tell me what's going on with firefox line-height.

This is my css.

```<code>.tag {
    display: block;
    font-size: 11px;
    background: #fff;
    border: 1px solid #aaa;
    color: #555;
    text-transform: lowercase;
        padding: 3px 6px;
}
</code>```

Pretty simple yea? Seems not. Firefox will create a pixel on top of text I can clearly see it its not balanced even though I set top and bottom padding the same. Someone tell me why this happens, if I remove the line-height: 1 from my reset a whole lot of other things get screwed up.

答:
I don't get it, I see no space using your CSS above, im using firefox 3.6.13

Maybe see if you can recreate a mock up of your issue on JSbin?

http://jsbin.com/ajinu3

Body:
I use this reset.

* {
    font-family: Arial, Helvetica, sans-serif;
    outline: 0;
    padding: 0;
    margin: 0;
    border: 0;
    text-decoration: none;
    vertical-align: baseline;
    white-space: normal;
    line-height: 1;
}
hr {display: none}
blockquote:before, blockquote:after, q:before, q:after {content: ''}
blockquote, q {quotes: "" ""}
ul {list-style-type: none}
ol {list-style-type: decimal}
a {text-decoration: none}

.clear {clear: both}

The problem is that as long as I use line-height: 1 I see an extra pixel that does not go away no matter what I do in my block links even I tried setting height, line-height, font-size for it. nothing works. Please tell me what's going on with firefox line-height.

This is my css.

.tag {
    display: block;
    font-size: 11px;
    background: #fff;
    border: 1px solid #aaa;
    color: #555;
    text-transform: lowercase;
        padding: 3px 6px;
}

Pretty simple yea? Seems not. Firefox will create a pixel on top of text I can clearly see it its not balanced even though I set top and bottom padding the same. Someone tell me why this happens, if I remove the line-height: 1 from my reset a whole lot of other things get screwed up.


问:
arduino write and reading
I am working with C# and arduino. I am still a newbie on this. I wish someone can help me. So my project is to send some code to Arduino. Then apply delay on Arduino and send back some string/char back to C#. I gave a textbox on C# to show the result of reading. This is my code:
C# code

```<code>Public form1()
{
    initializeComponent();
    Serialport1.Open();
}

public void Read()
{
    while (Serialport1.IsOpen)
    {
        try
        {
            string message = SerialPort1.ReadLine();
            textbox1.text = message;
        }
        catch (timeoutException)
        {
        }
    }
}
private void button1_click(object sender, eventargs e)
{
    SerialPort1.write("A");
    read();
}
</code>```

arduino code:

```<code>int data;
void setup()
{
    Serial.begin(9600);
    Serial.print("START\n");
}

void loop()
{
    if(Serial.available())
    {
        data = Serial.read();
        if(data=='A')
        {
            delay(3000);
            Serial.print("B");
        }
    }
}
</code>```

What I wish is textbox result write B, but nothing is come and the textbox keep blank. What did I do wrong? I hope someone can explain to me. Thank you

答:
ReadLine is a method that according to documentation

returns the contents of the input buffer up to the first occurrence of a NewLine value.

  ....

  By default, the ReadLine method will block until a line is received. If this behavior is undesirable, set the ReadTimeout property to any non-zero value to force the ReadLine method to throw a TimeoutException if a line is not available on the port.

So if you look at what the arduino is sending it is just a "B". Either you should add a newline to the message: "B\n" or use the println method which would add automatically a new line.

But the main problem is actually that you never return from you method Read so the GUI will never be updated, and even if you receive something you will not see it.

Furthermore, in your while-loop it would be advisable to only read when data is in the buffer. You can use the BytesToRead property to check whether it is worth to read from the port:

```<code>while (Serialport1.IsOpen)
{
    if (Serialport1.BytesToRead > 0)
    {
        try
        {
            string message = Serialport1.ReadLine();
            textbox1.text = message;
            // break out the while loop here so that you can see the content of the textbox
            break;
        }
        catch (Exception ex)
        {
            textbox1.text = "ERROR: " + ex.Message;
        }
    }
}
</code>```

Also it is a bad habit to catch an expection and don't do anything with this information. Because quite often it allows you to grasp the nature of the error. Up to now you are just masking it.

Title: arduino write and reading

Body:
I am working with C# and arduino. I am still a newbie on this. I wish someone can help me. So my project is to send some code to Arduino. Then apply delay on Arduino and send back some string/char back to C#. I gave a textbox on C# to show the result of reading. This is my code:
C# code

Public form1()
{
    initializeComponent();
    Serialport1.Open();
}

public void Read()
{
    while (Serialport1.IsOpen)
    {
        try
        {
            string message = SerialPort1.ReadLine();
            textbox1.text = message;
        }
        catch (timeoutException)
        {
        }
    }
}
private void button1_click(object sender, eventargs e)
{
    SerialPort1.write("A");
    read();
}

arduino code:

int data;
void setup()
{
    Serial.begin(9600);
    Serial.print("START\n");
}

void loop()
{
    if(Serial.available())
    {
        data = Serial.read();
        if(data=='A')
        {
            delay(3000);
            Serial.print("B");
        }
    }
}

What I wish is textbox result write B, but nothing is come and the textbox keep blank. What did I do wrong? I hope someone can explain to me. Thank you

Body:
ReadLine is a method that according to documentation

returns the contents of the input buffer up to the first occurrence of a NewLine value.

  ....

  By default, the ReadLine method will block until a line is received. If this behavior is undesirable, set the ReadTimeout property to any non-zero value to force the ReadLine method to throw a TimeoutException if a line is not available on the port.

So if you look at what the arduino is sending it is just a "B". Either you should add a newline to the message: "B\n" or use the println method which would add automatically a new line.

But the main problem is actually that you never return from you method Read so the GUI will never be updated, and even if you receive something you will not see it.

Furthermore, in your while-loop it would be advisable to only read when data is in the buffer. You can use the BytesToRead property to check whether it is worth to read from the port:

while (Serialport1.IsOpen)
{
    if (Serialport1.BytesToRead > 0)
    {
        try
        {
            string message = Serialport1.ReadLine();
            textbox1.text = message;
            // break out the while loop here so that you can see the content of the textbox
            break;
        }
        catch (Exception ex)
        {
            textbox1.text = "ERROR: " + ex.Message;
        }
    }
}

Also it is a bad habit to catch an expection and don't do anything with this information. Because quite often it allows you to grasp the nature of the error. Up to now you are just masking it.


问:
convert text file into dictionary -Python
I am given a .txt file which looks like this..

2:rain
3:odd
5:yes
6:go

I need to convert it into a dictionary.

This is what I have done so far.

```<code> words_dict = {}
 file = open(filename, "r")
 for word in file:
      k, v = word.split(":")
      words_dict[k.strip()] = v.strip()
 file.close()
 return words_dict
</code>```

However, when i go and print the dictionary it does not match my expected output of {2: 'rain', 3: 'odd', 5: 'yes', 6: 'go'}

答:
```<code>list_ = [x for x in open('text.txt').read().split()]

dict_ = {k: v for k, v in [x.split(':') for x in list_]}

# list_ = ['2:rain', '3:odd', '5:yes', '6:go']
# dict_ = {'2': 'rain', '3': 'odd', '5': 'yes', '6': 'go'}
</code>```

Body:
I am given a .txt file which looks like this..

2:rain
3:odd
5:yes
6:go

I need to convert it into a dictionary.

This is what I have done so far.

 words_dict = {}
 file = open(filename, "r")
 for word in file:
      k, v = word.split(":")
      words_dict[k.strip()] = v.strip()
 file.close()
 return words_dict

However, when i go and print the dictionary it does not match my expected output of {2: 'rain', 3: 'odd', 5: 'yes', 6: 'go'}


问:
Restrict Regex to be 8 to 15 characters long
I have the following regex checking password complexity.

```<code>^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])){8,15}.+$
</code>```

At least one lowercase

At least one Uppercase

At least one Symb0l

At least 1 number

But I also want to restrict it to only allow all the above plus length. Valid length would be anything between 8 and 15.

I've tried doing that by adding the {8,15}, but that doesn't seem to work! What am I doing wrong?

答:
You misplaced the quantifier:

```<code>^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\W]).{8,15}$
                                           ^^^^^^
</code>```

Also, (_|[^\w]) is the same as [_\W].

See the regex demo.

Details:

^ - start of string

(?=.*[a-z]) - at least 1 lowercase ASCII letter

(?=.*[A-Z]) - at least 1 uppercase ASCII letter

(?=.*\d) - at least 1  digit

(?=.*[_\W]) -  at least 1 "special", non-alphanumeric, char

.{8,15} - any 8 to 15 chars other than line break chars

$ - end of string.

Body:
I have the following regex checking password complexity.

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])){8,15}.+$

At least one lowercase

At least one Uppercase

At least one Symb0l

At least 1 number

But I also want to restrict it to only allow all the above plus length. Valid length would be anything between 8 and 15.

I've tried doing that by adding the {8,15}, but that doesn't seem to work! What am I doing wrong?

Body:
You misplaced the quantifier:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\W]).{8,15}$
                                           ^^^^^^

Also, (_|[^\w]) is the same as [_\W].

See the regex demo.

Details:

^ - start of string

(?=.*[a-z]) - at least 1 lowercase ASCII letter

(?=.*[A-Z]) - at least 1 uppercase ASCII letter

(?=.*\d) - at least 1  digit

(?=.*[_\W]) -  at least 1 "special", non-alphanumeric, char

.{8,15} - any 8 to 15 chars other than line break chars

$ - end of string.


问:
Gamemaker variable using porals
I am remaking portal in gamemaker for my semester final, I was wondering how you find an object, if I have one portal down, and go into it, the game crashes, as the 2nd portal isn't placed, and it can't get its .x,.y pos. How do I set a variable to fix this? </p>

答:
I assume that in some event you have a piece of code that does the teleporting. You just have to place this piece of code in an "if" statement that verifies if the second portal exists. This way, you will attempt teleportation only if the needed exit instance exists. You can use the "instance_exists" function

for example :

```<code>if ( instance_exists( exit_portal_or_whatever_you_name_it ) )
{
    your_teleportation_code;
}
</code>```

Title: Gamemaker variable using porals

Body:
I assume that in some event you have a piece of code that does the teleporting. You just have to place this piece of code in an "if" statement that verifies if the second portal exists. This way, you will attempt teleportation only if the needed exit instance exists. You can use the "instance_exists" function

for example :

if ( instance_exists( exit_portal_or_whatever_you_name_it ) )
{
    your_teleportation_code;
}


问:
PHP - Has anyway to encrypt/decrpyt hash in PHP?
I'm interested to encrypt/decrpyt hash in PHP.

But as I know hash can be encoding only with md5, sha1, sha256.

However, is it possible to make encrypt/decrpyt in PHP by another hash like ripemd160, haval256,5 or ripemd256?

Thank

答:
Hashing algorithms are not encryption algorithms. Hashing algorithms have the following principles:

Specific input produces always the same output

The input cannot be resolved based on the output

Any change to input will produce different output

Technically the last one is not true, because you have limited amount of possible outputs but basically unlimited amount of possible inputs. Therefore there will be other inputs that produces the same output, but for strong hashing algorithms finding those collisions takes VERY long time as @delboy1978uk explained.

MD5 is an example of a weak hashing algorithm that you should not use for secure hashes. Collision attacks against MD5 are cheap. On the other hand hashing algorithms in SHA2 family can be considered secure (take SHA256 for example).

Encryption algorithms require a key or multiple keys to allow you to do decryption on the cipher text.

The short answer to your questions is no.


问:
how to insert an ads into $text?
i have this code :

```<code> <?php include("Hedar.php"); ?>

<?php
    $q=mysql_query("select * from news2 where id = $news2_id ");
    list($news2_ides,$news_id,$name,$text,$stext,$ktext,$dtext,$date,$vews,$path)=mysql_fetch_array($q);
    ?>
        <img src="upload1/<?php echo $path ?>"/>
         <h2 class="_title"><?php echo $name ?></h2>
         <?php echo $text ?>
        <?php include("Footers.php"); ?>

------------
</code>```

so as you can see i have a site in PHP code
so i want to insert 2 adsense code into $text
i tried to separat this $text to many
 but i fail with it
so anyone can help me to separate this  ( <?php echo $text ?> )
thanks a lot
Regards

答:
If am right you want to display adsense code with the $text variable
so you do:

```<code><?php
$text.=$adsense
echo $text;
?>
</code>```

If you are storing your adsense code in $adsense variable

Title: how to insert an ads into $text?

Body:
i have this code :

 <?php include("Hedar.php"); ?>

<?php
    $q=mysql_query("select * from news2 where id = $news2_id ");
    list($news2_ides,$news_id,$name,$text,$stext,$ktext,$dtext,$date,$vews,$path)=mysql_fetch_array($q);
    ?>
        <img src="upload1/<?php echo $path ?>"/>

<?php echo $name ?>

         <?php echo $text ?>
        <?php include("Footers.php"); ?>

------------

so as you can see i have a site in PHP code
so i want to insert 2 adsense code into $text
i tried to separat this $text to many
 but i fail with it
so anyone can help me to separate this  ( <?php echo $text ?> )
thanks a lot
Regards

Body:
If am right you want to display adsense code with the $text variable
so you do:

<?php
$text.=$adsense
echo $text;
?>

If you are storing your adsense code in $adsense variable


问:
Laravel - hasMany() and belongsTo() not working correctly for me in @foreach loop
I got following error when I try to use this on my page

Trying to get property of non-object

I have two tables:

```<code>cvicenis
  id
  title
  body
  category_id
categories
  id
  name
</code>```

My Cviceni model:

```<code>namespace App;
use Illuminate\Database\Eloquent\Model;

class Cviceni extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category', 'id');
    }
}
</code>```

My Category model:

```<code>namespace App;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function cviceni()
    {
        return $this->hasMany('App\Cviceni', 'category_id');
    }
}
</code>```

My controller:

```<code>public function index()
{
    $cviceni = Cviceni::all();
    return view('excercises.index', compact('cviceni'));
}
</code>```

My index.blade:

```<code>@extends('layouts.app')

@section('content')
    <div class="row">
        <div class="col-sm-6 col-md-6 col-lg-3">
            <h1>Přehled cvičení</h1>
            @if(count($cviceni) > 0)
            <ul>
                @foreach ($cviceni as $c)
                    <li> {{ $c->category->name }}</li>
                @endforeach
            </ul>
            @else
                <h2>There is nothing to display</h2>
            @endif
        </div><!-- end of column -->
    </div><!-- end of row -->
@endsection
</code>```

If I use in my controller Cviceni::find(1) then I can get the value from $cviceni->category->name
But not when I use a foreach loop.
Can somebody help me please?

答:
In the Cviceni model, I think you set up the foreign key is wrong. Your foreign key in the table is category_id, while you set up the relationship with foreign key is id. Try to replace the category() relationship with follow </p>

```<code>public function category()
{
    return $this->belongsTo('App\Category', 'category_id');
}
</code>```

Body:
I got following error when I try to use this on my page

Trying to get property of non-object

I have two tables:

cvicenis
  id
  title
  body
  category_id
categories
  id
  name

My Cviceni model:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Cviceni extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category', 'id');
    }
}

My Category model:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function cviceni()
    {
        return $this->hasMany('App\Cviceni', 'category_id');
    }
}

My controller:

public function index()
{
    $cviceni = Cviceni::all();
    return view('excercises.index', compact('cviceni'));
}

My index.blade:

@extends('layouts.app')

@section('content')

Přehled cvičení

            @if(count($cviceni) > 0)

                @foreach ($cviceni as $c)

 {{ $c->category->name }}

                @endforeach

            @else

There is nothing to display

            @endif

@endsection

If I use in my controller Cviceni::find(1) then I can get the value from $cviceni->category->name
But not when I use a foreach loop.
Can somebody help me please?

Body:
In the Cviceni model, I think you set up the foreign key is wrong. Your foreign key in the table is category_id, while you set up the relationship with foreign key is id. Try to replace the category() relationship with follow

public function category()
{
    return $this->belongsTo('App\Category', 'category_id');
}


问:
String to phrase replacement python
I have a text string and I want to replace two words with a single word. E.g. if the word is artificial intelligence, I want to replace it with artificial_intelligence. This needs to be done for a list of 200 words and on a text file of size 5 mb.
I tried string.replace but it can work only for one element, not for the list.

Example

Text='Artificial intelligence is useful for us in every situation of deep learning.'

```<code>List a : list b
Artificial intelligence: artificial_intelligence
Deep learning: deep_ learning
...
</code>```

Text.replace('Artificial intelligence','Artificial_intelligence') is working.
But

```<code>For I in range(len(Lista)):
 Text=Text.replace(Lista[I],List b[I])
</code>```

doesn't work.

答:
Since you have a case problem between your list entries and your string, you could use the re.sub() function with IGNORECASE flag to obtain what you want:

```<code>import re

list_a = ['Artificial intelligence', 'Deep learning']
list_b = ['artificial_intelligence', 'deep_learning']
text = 'Artificial intelligence is useful for us in every situation of deep learning.'

for from_, to in zip(list_a, list_b):
    text = re.sub(from_, to, text, flags=re.IGNORECASE)

print(text)
# artificial_intelligence is useful for us in every situation of deep_learning.
</code>```

Note the use of the zip() function wich allows to iterate over the two lists in the same time.

Also note that Christian is right, a dict would be more suitable for your substitution data. The previous code would then be the following for the exact same result:

```<code>import re

subs = {'Artificial intelligence': 'artificial_intelligence',
        'Deep learning': 'deep_learning'}
text = 'Artificial intelligence is useful for us in every situation of deep learning.'

for from_, to in subs.items():
    text = re.sub(from_, to, text, flags=re.IGNORECASE)

print(text)
</code>```

Title: String to phrase replacement python

Body:
I have a text string and I want to replace two words with a single word. E.g. if the word is artificial intelligence, I want to replace it with artificial_intelligence. This needs to be done for a list of 200 words and on a text file of size 5 mb.
I tried string.replace but it can work only for one element, not for the list.

Example

Text='Artificial intelligence is useful for us in every situation of deep learning.'

List a : list b
Artificial intelligence: artificial_intelligence
Deep learning: deep_ learning
...

Text.replace('Artificial intelligence','Artificial_intelligence') is working.
But

For I in range(len(Lista)):
 Text=Text.replace(Lista[I],List b[I])

doesn't work.

Body:
Since you have a case problem between your list entries and your string, you could use the re.sub() function with IGNORECASE flag to obtain what you want:

import re

list_a = ['Artificial intelligence', 'Deep learning']
list_b = ['artificial_intelligence', 'deep_learning']
text = 'Artificial intelligence is useful for us in every situation of deep learning.'

for from_, to in zip(list_a, list_b):
    text = re.sub(from_, to, text, flags=re.IGNORECASE)

print(text)
# artificial_intelligence is useful for us in every situation of deep_learning.

Note the use of the zip() function wich allows to iterate over the two lists in the same time.

Also note that Christian is right, a dict would be more suitable for your substitution data. The previous code would then be the following for the exact same result:

import re

subs = {'Artificial intelligence': 'artificial_intelligence',
        'Deep learning': 'deep_learning'}
text = 'Artificial intelligence is useful for us in every situation of deep learning.'

for from_, to in subs.items():
    text = re.sub(from_, to, text, flags=re.IGNORECASE)

print(text)