问:
Conditionally create an object in c++
I am writing a program that has the option to visualize the output of an algorithm I am working on - this is done by changing a const bool VISUALIZE_OUTPUT variable defined in a header file. In the main file, I want to have this kind of pattern:

```<code>if(VISUALIZE_OUTPUT) {
    VisualizerObject vis_object;
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.initscene(objects_here);
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.drawScene(objects_here);
}
</code>```

However, this clearly won't compile since vis_object goes out of scope. I don't want to declare the object before the condition since it is a big object and it needs to available for multiple points in the code (I can't just have one conditional statement where everything is done).

What is the preferred way of doing this?

Declare the object on the heap and refer to it by using a pointer (or
unique_ptr)?

Declare the object on the heap and make a reference to it
since it won't ever change?

Some other alternative?

答:
I'll give a few options.   All have upsides and downsides.

If it is NOT possible to modify VisualizerObject, as I noted in comments, the effect could be achieved by using the preprocessor, since the preprocessor does not respect scope, and the question specifically seeks controlling lifetime of an object in a manner that crosses scope boundaries.

```<code>#ifdef VISUALIZE_OUTPUT
   VisualizerObject vis_object;
#endif

#ifdef VISUALIZE_OUTPUT
    vis_object.initscene(objects_here);
#endif
</code>```

The compiler will diagnose any usage of vis_object that are not in #ifdef/#endif.

The big criticism, of course, is that use of the preprocessor is considered poor practice in C++.   The advantage is that the approach can be used even if it is not possible to modify the VisualizerObject class (e.g. because it is in a third-party library without source code provided).

However, this is the only option that has the feature requested by the OP of object lifetime crossing scope boundaries.

If it is possible to modify the VisualizerObject class, make it a template with two specialisations

```<code>template<bool visualise> struct VisualizerObject
{
     // implement all member functions required to do nothing and have no members

     VisualizerObject() {};
     void initscene(types_here) {};
};

template<> struct VisualizerObject<true>    // heavyweight implementation with lots of members
{
     VisualizerObject(): heavy1(), heavy2() {};
     void initscene(types_here) { expensive_operations_here();};

     HeavyWeight1 heavy1;
     HeavyWeight2 heavy2;
};

int main()
{
      VisualizerObject<VISUALIZE_OUTPUT> vis_object;
      ...
      vis_object.initscene(objects_here);
      ...
      vis_object.drawScene(objects_here);
}
</code>```

The above will work in all C++ versions.   Essentially, it works by either instantiating a lightweight object with member functions that do nothing, or instantiating the heavyweight version.

It would also be possible to use the above approach to wrap a VisualizerObject.

```<code> template<bool visualise> VisualizerWrapper
 {
      //  implement all required member functions to do nothing
      //   don't supply any members either
 }

 template<> VisualizerWrapper<true>
 {
      VisualizerWrapper() : object() {};

       //  implement all member functions as forwarders

     void initscene(types_here) { object.initscene(types_here);};

      VisualizerObject object;
 }

int main()
{
      VisualizerWrapper<VISUALIZE_OUTPUT> vis_object;
      ...
      vis_object.initscene(objects_here);
      ...
      vis_object.drawScene(objects_here);
}
</code>```

The disadvantage of both of the template approaches is maintenance - when adding a member function to one class (template specialisation) it is necessary to add a function with the same signature to the other.   In large team settings, it is likely that testing/building will be mostly done with one setting of VISUALIZE_OUTPUT or the other - so it is easy to get one version out of alignment (different interface) to the other.    Problems of that (e.g. a failed build on changing the setting) are likely to emerge at inconvenient times - such as when there is a tight deadline to deliver a different version of the product.

Pedantically, the other downside of the template options is that they don't comply with the desired "kind of pattern"  i.e. the if is not required in

```<code> if(VISUALIZE_OUTPUT)
 {
    vis_object.initscene(objects_here);
 }
</code>```

and object lifetimes do not cross scope boundaries.

Title: Conditionally create an object in c++

Body:
I am writing a program that has the option to visualize the output of an algorithm I am working on - this is done by changing a const bool VISUALIZE_OUTPUT variable defined in a header file. In the main file, I want to have this kind of pattern:

if(VISUALIZE_OUTPUT) {
    VisualizerObject vis_object;
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.initscene(objects_here);
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.drawScene(objects_here);
}

However, this clearly won't compile since vis_object goes out of scope. I don't want to declare the object before the condition since it is a big object and it needs to available for multiple points in the code (I can't just have one conditional statement where everything is done).

What is the preferred way of doing this?

Declare the object on the heap and refer to it by using a pointer (or
unique_ptr)?

Declare the object on the heap and make a reference to it
since it won't ever change?

Some other alternative?

Body:
I'll give a few options.   All have upsides and downsides.

If it is NOT possible to modify VisualizerObject, as I noted in comments, the effect could be achieved by using the preprocessor, since the preprocessor does not respect scope, and the question specifically seeks controlling lifetime of an object in a manner that crosses scope boundaries.

#ifdef VISUALIZE_OUTPUT
   VisualizerObject vis_object;
#endif

#ifdef VISUALIZE_OUTPUT
    vis_object.initscene(objects_here);
#endif

The compiler will diagnose any usage of vis_object that are not in #ifdef/#endif.

The big criticism, of course, is that use of the preprocessor is considered poor practice in C++.   The advantage is that the approach can be used even if it is not possible to modify the VisualizerObject class (e.g. because it is in a third-party library without source code provided).

However, this is the only option that has the feature requested by the OP of object lifetime crossing scope boundaries.

If it is possible to modify the VisualizerObject class, make it a template with two specialisations

template<bool visualise> struct VisualizerObject
{
     // implement all member functions required to do nothing and have no members

     VisualizerObject() {};
     void initscene(types_here) {};
};

template<> struct VisualizerObject<true>    // heavyweight implementation with lots of members
{
     VisualizerObject(): heavy1(), heavy2() {};
     void initscene(types_here) { expensive_operations_here();};

     HeavyWeight1 heavy1;
     HeavyWeight2 heavy2;
};

int main()
{
      VisualizerObject<VISUALIZE_OUTPUT> vis_object;
      ...
      vis_object.initscene(objects_here);
      ...
      vis_object.drawScene(objects_here);
}

The above will work in all C++ versions.   Essentially, it works by either instantiating a lightweight object with member functions that do nothing, or instantiating the heavyweight version.

It would also be possible to use the above approach to wrap a VisualizerObject.

 template<bool visualise> VisualizerWrapper
 {
      //  implement all required member functions to do nothing
      //   don't supply any members either
 }

 template<> VisualizerWrapper<true>
 {
      VisualizerWrapper() : object() {};

       //  implement all member functions as forwarders

     void initscene(types_here) { object.initscene(types_here);};

      VisualizerObject object;
 }

int main()
{
      VisualizerWrapper<VISUALIZE_OUTPUT> vis_object;
      ...
      vis_object.initscene(objects_here);
      ...
      vis_object.drawScene(objects_here);
}

The disadvantage of both of the template approaches is maintenance - when adding a member function to one class (template specialisation) it is necessary to add a function with the same signature to the other.   In large team settings, it is likely that testing/building will be mostly done with one setting of VISUALIZE_OUTPUT or the other - so it is easy to get one version out of alignment (different interface) to the other.    Problems of that (e.g. a failed build on changing the setting) are likely to emerge at inconvenient times - such as when there is a tight deadline to deliver a different version of the product.

Pedantically, the other downside of the template options is that they don't comply with the desired "kind of pattern"  i.e. the if is not required in

 if(VISUALIZE_OUTPUT)
 {
    vis_object.initscene(objects_here);
 }

and object lifetimes do not cross scope boundaries.


来源: stackexchange

问:
Protractor - Change Browser Capabilities at RunTime
Is there a way to change the browser capabilities within beforeEach of the protractor suite. I need to set the Capabilities.name attribute before each spec execution.</p>

答:
You can't change the capabilities in beforeEach() (Jasmine hook) or onPrepare() (Protractor conf.js) because the browser instance has already been created and webdriver session has been started with the capabilities already sent to the Selenium server.

Desired capabilities are set in the conf.js under Capabilities or Multicapabilities.  You could set them at runtime by getting a variable before exporting in conf.js.

One common way to do this is to set the capability using an environment variable, for example:

```<code>Capabilities: {
  browserName: process.env.SELENIUM_BROWSER
}
</code>```

You can set variables to be used in capabilities in beforeLaunch() but this executes one time only, before any specs are read.

There is an excellent summary of the Protractor / Jasmine hooks here:

http://timothymartin.azurewebsites.net/protractor-before-and-afters/

I have not yet identified a way (without modifying Protractor source) to change capabilities dynamically on a per-spec or per-suite basis.

ContentLicense: CC BY-SA 3.0

Body:
You can't change the capabilities in beforeEach() (Jasmine hook) or onPrepare() (Protractor conf.js) because the browser instance has already been created and webdriver session has been started with the capabilities already sent to the Selenium server.

Desired capabilities are set in the conf.js under Capabilities or Multicapabilities.  You could set them at runtime by getting a variable before exporting in conf.js.

One common way to do this is to set the capability using an environment variable, for example:

Capabilities: {
  browserName: process.env.SELENIUM_BROWSER
}

You can set variables to be used in capabilities in beforeLaunch() but this executes one time only, before any specs are read.

There is an excellent summary of the Protractor / Jasmine hooks here:

http://timothymartin.azurewebsites.net/protractor-before-and-afters/

I have not yet identified a way (without modifying Protractor source) to change capabilities dynamically on a per-spec or per-suite basis.


问:
How to change connection to the database on acts as taggable on
I have used rails and gem(acts as taggable on).
I want to change acts as taggable on's database setting.
so,I set as below

-database.yml

```<code>default: &default
    adapter: mysql2
    database: my_db1
    host: localhost
    username: root
    password: pass

development:
    <<: *default

my_db2:
    <<: *default
    database: my_db2
</code>```

-user_model.rb

```<code>class User < ActiveRecord::Base
    acts_as_taggable
    establish_connection :my_db2
end
</code>```

and, execute as below

```<code>User.find(1)
//this line result is connection to my_db2

User.find(1).tag_list
//this line result is connection to my_db1
//i want to connect to my_db2 in this code(by acts as taggable on)
</code>```

I don't know how to resolve this problem.

Thanks.

答:
I also had to add the Tagging class to Mohammed's answer.</p>

```<code>module ActsAsTaggableOn
  class Tag
    establish_connection :my_db2
  end
  class Tagging
    establish_connection :my_db2
  end
end
</code>```

Body:
I have used rails and gem(acts as taggable on).
I want to change acts as taggable on's database setting.
so,I set as below

-database.yml

default: &default
    adapter: mysql2
    database: my_db1
    host: localhost
    username: root
    password: pass

development:
    <<: *default

my_db2:
    <<: *default
    database: my_db2

-user_model.rb

class User < ActiveRecord::Base
    acts_as_taggable
    establish_connection :my_db2
end

and, execute as below

User.find(1)
//this line result is connection to my_db2

User.find(1).tag_list
//this line result is connection to my_db1
//i want to connect to my_db2 in this code(by acts as taggable on)

I don't know how to resolve this problem.

Thanks.

Body:
I also had to add the Tagging class to Mohammed's answer.

module ActsAsTaggableOn
  class Tag
    establish_connection :my_db2
  end
  class Tagging
    establish_connection :my_db2
  end
end


问:
ASP.net Page_Load does not seems to be called
I am new to asp.net. My login.aspx page has this line:

<%@ Page Language="C#"  AutoEventWireup="true" CodeBehind="Users.aspx.cs" %>

and my Users.aspx.cs file has following lines of code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;

public partial class Users : System.Web.UI.Page
{

    protected void LoginButton_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            LoginButton.Text = "My form is valid!";
        }
    }

}
</code>```

On the login.aspx page I am using

RequiredFieldValidator and
  RegularExpressionValidator

to validate Email and Password fields.

Now, I have to make sure that the validation is complete and do further stuffs. But, my code is not being friendly here; it's not caling any of those two functions. As a matter of fact, I feel like it's not even getting into the .cs page. I know I am making some silly mistake here.
Thank you!

P.S. Validation is working fine, it's returning error messages correctly.

Edit: Login.aspx page looks like below:

```<code><%@ Page Language="C#"  AutoEventWireup="true" CodeBehind="Users.aspx.cs" %>

                <div class="card text-white bg-info mb-3 toHide" id="loginBlock">
                    <div class="card-header"><b>Login To Pay Your Bills Online</b></div>
                    <div class="card-body">

                            <div class="form-group">
                                <label for="emailToLogin">Email address<b class="text-danger">*</b></label>
                                <asp:TextBox id="emailToLogin" ValidationGroup="Login" runat="server" placeholder="Enter email" CssClass="form-control"  />
                                <asp:RequiredFieldValidator id="emailToLogin1" EnableClientScript="false" ValidationGroup="Login" CssClass="small text-danger" Display="Dynamic" runat="server" controltovalidate="emailToLogin" errormessage="Please enter your email!" />
                            </div>
                            <div class="form-group">
                                <label for="passwordToLogin">Password<b class="text-danger">*</b></label>
                                <asp:TextBox id="passwordToLogin" ValidationGroup="Login" TextMode="password" runat="server" placeholder="Password" CssClass="form-control"  />
                                <asp:RequiredFieldValidator id="passwordToLogin1" EnableClientScript="false" ValidationGroup="Login" CssClass="small text-danger" Display="Dynamic" runat="server" controltovalidate="passwordToLogin" errormessage="Please enter your password!" />

                            </div>
                            <div>

                            </div>
                            <asp:Button id="LoginButton" ValidationGroup="Login" runat="server" OnClientClick="LoginButton_Click" Text="User Login" CssClass="btn btn-warning"  />

                    </div>
                </div>
</code>```

答:
OnClick will work on server side , OnClientClick will execute on client side before control passed to server.
So, Either you need to define OnClientClick function ClientSide or change OnClientClick to OnClick.

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick(VS.80).aspx

Body:
I am new to asp.net. My login.aspx page has this line:

<%@ Page Language="C#"  AutoEventWireup="true" CodeBehind="Users.aspx.cs" %>

and my Users.aspx.cs file has following lines of code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;

public partial class Users : System.Web.UI.Page
{

    protected void LoginButton_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            LoginButton.Text = "My form is valid!";
        }
    }

}

On the login.aspx page I am using

RequiredFieldValidator and
  RegularExpressionValidator

to validate Email and Password fields.

Now, I have to make sure that the validation is complete and do further stuffs. But, my code is not being friendly here; it's not caling any of those two functions. As a matter of fact, I feel like it's not even getting into the .cs page. I know I am making some silly mistake here.
Thank you!

P.S. Validation is working fine, it's returning error messages correctly.

Edit: Login.aspx page looks like below:

<%@ Page Language="C#"  AutoEventWireup="true" CodeBehind="Users.aspx.cs" %>

Login To Pay Your Bills Online

                                Email address*
                                <asp:TextBox id="emailToLogin" ValidationGroup="Login" runat="server" placeholder="Enter email" CssClass="form-control"  />
                                <asp:RequiredFieldValidator id="emailToLogin1" EnableClientScript="false" ValidationGroup="Login" CssClass="small text-danger" Display="Dynamic" runat="server" controltovalidate="emailToLogin" errormessage="Please enter your email!" />

                                Password*
                                <asp:TextBox id="passwordToLogin" ValidationGroup="Login" TextMode="password" runat="server" placeholder="Password" CssClass="form-control"  />
                                <asp:RequiredFieldValidator id="passwordToLogin1" EnableClientScript="false" ValidationGroup="Login" CssClass="small text-danger" Display="Dynamic" runat="server" controltovalidate="passwordToLogin" errormessage="Please enter your password!" />

                            <asp:Button id="LoginButton" ValidationGroup="Login" runat="server" OnClientClick="LoginButton_Click" Text="User Login" CssClass="btn btn-warning"  />


问:
Creating a Morse Code translator for my programming class,having troubles with the output
this is my first post on this platform ,im kinda new to this java programing and also not that good at english :p

My teacher asked for a morse code translator that does morse to letters and vice versa

Here's the code i came up with:

```<code>import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";

frase=frase.toLowerCase();
String[] paraletras=frase.split("");
String[]paraMorse=frase.split(" ");
for(int i=0;i< paraletras.length;i++){
    for(int j=0;j< letras.length ;j++){
     if (paraletras[i].equals(letras[j])){
    resp=resp+ MORSE[j]+" ";}
    }
}
for(int k=0;k<paraMorse.length;k++){
     for (int l=0;l<MORSE.length;l++){
          if(paraMorse[k].equals(MORSE[l])){
    resp=resp+letras[l]+ " ";}}
    }

System.out.print(resp);}

    }
</code>```

The class compiles fine but im having some issues with my output,more specifically the order of the output:

e.g My input " a b -.- c "
    What i wanted ".- -... k -.-."
    What i got ".- -... -.-. k"
I believe that's because i used 2 for cycles instead of 1 but i cant really tell how to do it.Would apreciate some help
Also when the user writes an impossible character like "*" im suppossed to put an "?" in that position and im also strugling on that i dont know if i should use a if else cycle or what

Please help me and thank you everybody ^^

答:
You have to evaluate every group or chars to guess if it is morse or not.

```<code>Example:
First group: 'a'
  is morse -> no
  is a letter -> yes -> then convert to morse
Second group: 'b'
  is morse -> no
  is a letter -> yes -> then convert to morse
Third group: '-.-'
  is morse -> yes -> then convert to letter
</code>```

This code could be more efficient, but I think it is easy to understand. I hope this help you to improve your programming skills.

```<code>import java.util.Scanner;

public class Morse2 {

    public static void main(String[] args) {

        String[] LETRAS = {
                "a", "b", "c", "d", "e", "f",
                "g", "h", "i", "j", "k", "l",
                "m", "n", "o", "p", "q", "r",
                "s", "t", "u", "v", "w", "x",
                "y", "z" };

        String[] MORSE = {
                ".-", "-...", "-.-.", "-..", ".", "..-.",
                "--.", "....", "..", ".---", "-.-", ".-..",
                "--", "-.", "---", ".--.", "--.-", ".-.",
                "...", "-", "..-", "...-", ".--", "-..-",
                "-.--", "--.." };

        System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
        Scanner in=new Scanner(System.in);
        String frase =in.nextLine();
        String resp = "";

        frase = frase.trim().toLowerCase();
        String[] chars = frase.split(" ");

        for (int i = 0; i < chars.length; i++) {

            String group = chars[i];

            String newChar = null;

            for (int j = 0; j < LETRAS.length; j++) {
                if (LETRAS[j].equals(group)) {
                    newChar =  MORSE[j];
                    break;
                }
            }

            if (newChar == null) {
                for (int j = 0; j < MORSE.length; j++) {
                    if (MORSE[j].equals(group)) {
                        newChar =  LETRAS[j];
                        break;
                    }
                }
            }

            if (newChar == null) {
                System.out.println("Group not found: "+group);
                continue;
            }
            resp += newChar + " ";

        }
        System.out.print(resp);
        in.close();
    }

}
</code>```

Body:
this is my first post on this platform ,im kinda new to this java programing and also not that good at english :p

My teacher asked for a morse code translator that does morse to letters and vice versa

Here's the code i came up with:

import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";

frase=frase.toLowerCase();
String[] paraletras=frase.split("");
String[]paraMorse=frase.split(" ");
for(int i=0;i< paraletras.length;i++){
    for(int j=0;j< letras.length ;j++){
     if (paraletras[i].equals(letras[j])){
    resp=resp+ MORSE[j]+" ";}
    }
}
for(int k=0;k<paraMorse.length;k++){
     for (int l=0;l<MORSE.length;l++){
          if(paraMorse[k].equals(MORSE[l])){
    resp=resp+letras[l]+ " ";}}
    }

System.out.print(resp);}

    }

The class compiles fine but im having some issues with my output,more specifically the order of the output:

e.g My input " a b -.- c "
    What i wanted ".- -... k -.-."
    What i got ".- -... -.-. k"
I believe that's because i used 2 for cycles instead of 1 but i cant really tell how to do it.Would apreciate some help
Also when the user writes an impossible character like "*" im suppossed to put an "?" in that position and im also strugling on that i dont know if i should use a if else cycle or what

Please help me and thank you everybody ^^

Body:
You have to evaluate every group or chars to guess if it is morse or not.

Example:
First group: 'a'
  is morse -> no
  is a letter -> yes -> then convert to morse
Second group: 'b'
  is morse -> no
  is a letter -> yes -> then convert to morse
Third group: '-.-'
  is morse -> yes -> then convert to letter

This code could be more efficient, but I think it is easy to understand. I hope this help you to improve your programming skills.

import java.util.Scanner;

public class Morse2 {

    public static void main(String[] args) {

        String[] LETRAS = {
                "a", "b", "c", "d", "e", "f",
                "g", "h", "i", "j", "k", "l",
                "m", "n", "o", "p", "q", "r",
                "s", "t", "u", "v", "w", "x",
                "y", "z" };

        String[] MORSE = {
                ".-", "-...", "-.-.", "-..", ".", "..-.",
                "--.", "....", "..", ".---", "-.-", ".-..",
                "--", "-.", "---", ".--.", "--.-", ".-.",
                "...", "-", "..-", "...-", ".--", "-..-",
                "-.--", "--.." };

        System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
        Scanner in=new Scanner(System.in);
        String frase =in.nextLine();
        String resp = "";

        frase = frase.trim().toLowerCase();
        String[] chars = frase.split(" ");

        for (int i = 0; i < chars.length; i++) {

            String group = chars[i];

            String newChar = null;

            for (int j = 0; j < LETRAS.length; j++) {
                if (LETRAS[j].equals(group)) {
                    newChar =  MORSE[j];
                    break;
                }
            }

            if (newChar == null) {
                for (int j = 0; j < MORSE.length; j++) {
                    if (MORSE[j].equals(group)) {
                        newChar =  LETRAS[j];
                        break;
                    }
                }
            }

            if (newChar == null) {
                System.out.println("Group not found: "+group);
                continue;
            }
            resp += newChar + " ";

        }
        System.out.print(resp);
        in.close();
    }

}


问:
Error:No such property: zipAlignEnabled for class: com.android.build.gradle.internal.variant.ApplicationVariantData
I am getting this error continuously when I try to build my old project in Android Studio 3.0

Here's my gradle file:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.github.triplet.gradle:play-publisher:1.1.4'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'com.google.guava:guava:19.0'
        classpath 'me.tatarka:gradle-retrolambda:3.3.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        flatDir {
            dirs 'libs'
        }
    }
}
</code>```

答:
Because AS 3.0 uses gradle 4.1，but gradle 4.1 removed the property-- ApplicationVariantData.

So, you can downgrade your AS or set

```<code>dependencies {
  classpath 'com.android.tools.build:gradle:2.3.3'
}
</code>```

on your root .gradle file

Maybe you can see this http://dev.qq.com/topic/5a0cfef91d8190380176e74d
or this http://dev.qq.com/topic/59b272d9e0a78ea25114ed2a

Body:
I am getting this error continuously when I try to build my old project in Android Studio 3.0

Here's my gradle file:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.github.triplet.gradle:play-publisher:1.1.4'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'com.google.guava:guava:19.0'
        classpath 'me.tatarka:gradle-retrolambda:3.3.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        flatDir {
            dirs 'libs'
        }
    }
}

Body:
Because AS 3.0 uses gradle 4.1，but gradle 4.1 removed the property-- ApplicationVariantData.

So, you can downgrade your AS or set

dependencies {
  classpath 'com.android.tools.build:gradle:2.3.3'
}

on your root .gradle file

Maybe you can see this http://dev.qq.com/topic/5a0cfef91d8190380176e74d
or this http://dev.qq.com/topic/59b272d9e0a78ea25114ed2a


问:
PyYAML find line of incorrect YAML syntax error
I'm reading in a YAML file. If there's a syntax mistake that causes an exception, I send the exception to a logger. What is a way to identify in my logging message which line of the YAML file contains the syntax error?</p>

```<code>try:
    with open(input_path, "r") as yaml_file:
        yaml_dict = yaml.load(yaml_file)
except FileNotFoundError:
    logger.error("YAML file {} does not exist".format(input_path), exc_info=True)
    sys.exit(1)
except:
    logger.critical("Error in reading or parsing YAML file {}".format(input_path), exc_info=True)
    sys.exit(1)
</code>```

答:
Have a look at the PyYAMLDocumentation, look for YAMLError():

```<code>try:
    yaml.load("unbalanced blackets: ][")
except yaml.YAMLError, exc:
    if hasattr(exc, 'problem_mark'):
        mark = exc.problem_mark
        print "Error position: (%s:%s)" % (mark.line+1, mark.column+1)

Error position: (1:22)
</code>```

Body:
I'm reading in a YAML file. If there's a syntax mistake that causes an exception, I send the exception to a logger. What is a way to identify in my logging message which line of the YAML file contains the syntax error?

try:
    with open(input_path, "r") as yaml_file:
        yaml_dict = yaml.load(yaml_file)
except FileNotFoundError:
    logger.error("YAML file {} does not exist".format(input_path), exc_info=True)
    sys.exit(1)
except:
    logger.critical("Error in reading or parsing YAML file {}".format(input_path), exc_info=True)
    sys.exit(1)

Body:
Have a look at the PyYAMLDocumentation, look for YAMLError():

try:
    yaml.load("unbalanced blackets: ][")
except yaml.YAMLError, exc:
    if hasattr(exc, 'problem_mark'):
        mark = exc.problem_mark
        print "Error position: (%s:%s)" % (mark.line+1, mark.column+1)

Error position: (1:22)


问:
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

```<code>#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}
</code>```

答:
In the constructor of C you have

```<code>    b = B();
</code>```

what this does is:

construct temporary object of type B

assign this object to b by the use of default assignment operator

destroy the temporary object

To fix this use initialization list in the constructor of C like this:

```<code>    C() : b()
    { }
</code>```

or just leave the constructor empty, that way it will use the default constructor.

ContentLicense: CC BY-SA 2.5

Title: C++ unwanted destruction

Body:
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}

Body:
In the constructor of C you have

    b = B();

what this does is:

construct temporary object of type B

assign this object to b by the use of default assignment operator

destroy the temporary object

To fix this use initialization list in the constructor of C like this:

    C() : b()
    { }

or just leave the constructor empty, that way it will use the default constructor.


问:
Changing table's cell background color using PHP while loop
I need to change the background color of cells with freezing temperature (32F, 0C) to #bff9ff but have some difficulties. I tried to print CSS class inside  but seems it just doesn't work properly inside the loop and being printed at the same time.

However, it's half a problem. How can I identify those cells with freezing temp and below not manually but using PHP?

```<code><html>
<head>
    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>

        <style>
            table {
                font-family: arial, sans-serif;
                border-collapse: collapse;
                width: 100%;
            }

            tr:hover {
                background-color:#bff9ff;
                }

            td, th {
                border: 1px solid #dddddd;
                text-align: left;
                padding: 8px;``
            }
            .cell {
                background-color: #00bfff;
                }

        </style>

</head>
<body>

    <table border="1" cellpadding="3">

        <thead>
            <th>Fahrenheit</th>
            <th>Celsius</th>
        </thead>

        <?php
        $fahrenheit = 50;

        while ($fahrenheit >= -50) {

            $celsius = ($fahrenheit - 32) * 5 / 9;

            print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

            $fahrenheit -= 5;
            $celsius -= 5;

        } ?>

    </table>

</body>
</html>
</code>```

答:
Create a CSS class called "freezing".  Use an if add the freezing class, e.g.,

```<code>"<td class='$freezing'></td>"
</code>```

Basically evaluate this:

```<code>if (32 <= $farenheit || 0 <= $celcius) {
  $freezing = "freezing";
}
</code>```

Edit: CSS

```<code>.freezing {
  background-color: #bff9ff;
}
</code>```

Body:
I need to change the background color of cells with freezing temperature (32F, 0C) to #bff9ff but have some difficulties. I tried to print CSS class inside  but seems it just doesn't work properly inside the loop and being printed at the same time.

However, it's half a problem. How can I identify those cells with freezing temp and below not manually but using PHP?

    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>

            Fahrenheit
            Celsius

        <?php
        $fahrenheit = 50;

        while ($fahrenheit >= -50) {

            $celsius = ($fahrenheit - 32) * 5 / 9;

            print "
$fahrenheit	$celsius
";

            $fahrenheit -= 5;
            $celsius -= 5;

        } ?>

Body:
Create a CSS class called "freezing".  Use an if add the freezing class, e.g.,

"<td class='$freezing'></td>"

Basically evaluate this:

if (32 <= $farenheit || 0 <= $celcius) {
  $freezing = "freezing";
}

Edit: CSS

.freezing {
  background-color: #bff9ff;
}


问:
Merging JVM and the code into a single file
I would like to merge Java Virtual Machine and my .java code (or compiled .class files) into a single executable binary. How can I do this?</p>

答: GCJ basically works like that, but depends on the GNU classpath libraries and is not fully compatible with the Java standard (may not support some language features and parts of the standard API).</p>


问:
How to test a Asterisk Sign
I need to test the asterisk sign (required Field) using appium for Android .
.getText is not working. what other method should i use to grab the asterisk sign so that i can validate it is a required field. please see the image below.

Thanks

答:
I suggest to call driver.getPageSource() and inspect the source XML. The XML format is different in UIAutomator and UIAutomator2, so if you are testing on Android 5 you should try both automationName capabilities.

If you will be able to find element with * text or just element most likely representing asterisk next to password android.widget.EditText input, then you can search for it and validate if its present.

However, if asterisk symbol is part of password android.widget.EditText input element (most likely), then you probably won't get it: in my case I don't get dots that hides password as well - empty text in Appium Desktop inspector.

If its critical, you need to ask developers to put it in separate element, but I doubt it makes any sense to focus on it so much

Title: How to test a Asterisk Sign


问:
inconsistencies in colors when drawing
I have a UIImageView and I draw to it using UIColor orangeColor. Now, I have a function that is supposed to detect the pixelColor of a pixel tapped on.

R: 1.000000 G: 0.501961 B: 0.000000

That's the RGB value I receive when attempting to detect the pixelColor for UIOrange

It should be.

R: 1.000000 G: 0.5 B: 0.000000

Here's my function

```<code>- (UIColor *)colorAtPixel:(CGPoint)point {
    // Cancel if point is outside image coordinates
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, _overlay_imageView.frame.size.width, _overlay_imageView.frame.size.height), point)) {
        return nil;
    }

    // Create a 1x1 pixel byte array and bitmap context to draw the pixel into.
    // Reference: http://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage
    NSInteger pointX = trunc(point.x);
    NSInteger pointY = trunc(point.y);
    CGImageRef cgImage = _overlay_imageView.image.CGImage;
    NSUInteger width = CGImageGetWidth(cgImage);
    NSUInteger height = CGImageGetHeight(cgImage);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = { 0, 0, 0, 0 };
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 1,
                                                 1,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);

    // Draw the pixel we are interested in onto the bitmap context
    CGContextTranslateCTM(context, -pointX, -pointY);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    CGContextRelease(context);

    // Convert color values [0..255] to floats [0.0..1.0]
    CGFloat red   = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue  = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
</code>```

Any ideas?

I must mention, my UIImageView has a clearBackground, and its ontop of a black canvas. Is that maybe the issue?

答:
There's nothing wrong with your function.  This is a a result of floating point math.  Half of an integer 255 (the max value of an unsigned byte) is either 127/255.0 or 128/255.0 depending on how you round.  Neither one of those is 0.5.  They are 0.498039215686275 and 0.501960784313725 respectively.

EDIT: I guess I should add that the colors in the CGImage are stored as bytes, not floats.  So when you create your orange with a float in UIColor its getting truncated to R:255, G:128, B:0 A:255.  When you read this back as a float you get 1.0 0.501961 B: 0.0 A: 1.0

Title: inconsistencies in colors when drawing

Body:
I have a UIImageView and I draw to it using UIColor orangeColor. Now, I have a function that is supposed to detect the pixelColor of a pixel tapped on.

R: 1.000000 G: 0.501961 B: 0.000000

That's the RGB value I receive when attempting to detect the pixelColor for UIOrange

It should be.

R: 1.000000 G: 0.5 B: 0.000000

Here's my function

- (UIColor *)colorAtPixel:(CGPoint)point {
    // Cancel if point is outside image coordinates
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, _overlay_imageView.frame.size.width, _overlay_imageView.frame.size.height), point)) {
        return nil;
    }

    // Create a 1x1 pixel byte array and bitmap context to draw the pixel into.
    // Reference: http://stackoverflow.com/questions/1042830/retrieving-a-pixel-alpha-value-for-a-uiimage
    NSInteger pointX = trunc(point.x);
    NSInteger pointY = trunc(point.y);
    CGImageRef cgImage = _overlay_imageView.image.CGImage;
    NSUInteger width = CGImageGetWidth(cgImage);
    NSUInteger height = CGImageGetHeight(cgImage);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = { 0, 0, 0, 0 };
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 1,
                                                 1,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);

    // Draw the pixel we are interested in onto the bitmap context
    CGContextTranslateCTM(context, -pointX, -pointY);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    CGContextRelease(context);

    // Convert color values [0..255] to floats [0.0..1.0]
    CGFloat red   = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue  = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

Any ideas?

I must mention, my UIImageView has a clearBackground, and its ontop of a black canvas. Is that maybe the issue?


问:
Python3: regex code with carret or dollar sign doesn't match anything
Does anyone have an idea why a regex code that works perfectly finding
shutil.move() does not find anything if I add the carret and dollar sign at the beginning and end of the regex code?

```<code>exampleRegex = re.compile (r'(shutil[.])(.*)(\)\s)') --> finds all shutil functions

exampleRegex = re.compile (r'^(shutil[.])(.*)(\)\s)$') --> doesn't find anything
</code>```

Thanks!

答:
Because your string probably isn't just shutil.move().

I suggest you read up on regex and how they work. Here is a decent place to start https://github.com/zeeshanu/learn-regex/blob/master/README.md.

Body:
Does anyone have an idea why a regex code that works perfectly finding
shutil.move() does not find anything if I add the carret and dollar sign at the beginning and end of the regex code?

exampleRegex = re.compile (r'(shutil[.])(.*)(\)\s)') --> finds all shutil functions

exampleRegex = re.compile (r'^(shutil[.])(.*)(\)\s)$') --> doesn't find anything

Thanks!


问:
Write pixel data to FITS file Cfitsio
I am trying to write and fill the image with pixel data to new fits file using cfitsio. I am not sure where I am doing wrong but all of the data are not being written to the fits file. I used binary vi to check out the data and image data is not properly created. I used the second image HST WFPC 2 fits file from NASA website. This is the code that I wrote:

```<code>#include <string.h>
#include <stdio.h>
#include "fitsio.h"

int main() {
    fitsfile *fptr;
    int status = 0, i;

    fits_open_file(&fptr, "WFPC2ASSNu5780205bx.fits", READONLY, &status);
    long naxes[2];
    fits_get_img_size(fptr, 3, naxes, &status);

    fitsfile *ofptr;
    fits_create_file(&ofptr, "o_nasa.fits", &status);
    fits_copy_header(fptr, ofptr, &status);

    long fp[2] = {1, 1};
    long nelements = naxes[0];

    float arr[nelements];
    for (i = 0; i < nelements; i++) {
        arr[i] = 100;
    }

    int ii, jj, kk;
    for (ii = 1; ii <= naxes[0]; ii++) {
        for (jj = 1; jj <= naxes[1]; jj++) {
            fits_write_pix(ofptr, TFLOAT, fp, nelements, arr, &status); // this is not working
        }
    }
    fits_close_file(ofptr, &status);
    fits_close_file(fptr, &status);

    return status;
}
</code>```

答:
I found out what is wrong with the code. I just posted the answer since there doesn't seem to be a lot of community working on CFITSIO. The code is wrong in the lines in the double for loop with variables ii, jj. I thought fp, the first pixel array to point where the image array starts writing, is used once where to start the whole iterations but instead write_pix uses it throughout the iterations to know where to write. My code is also trying to write/update the 1, 1 pixel and it seems to be NULL. The correct code is:

```<code>for (fp[1] = 1; fp[1] <= naxes[0]; fp[1]++) {
    for (fp[0] = 1; fp[0] <= naxes[1]; fp[0]++) {
        fits_write_pix(ofptr, TFLOAT, fp, nelements, arr, &status);
    }
}
</code>```

Title: Write pixel data to FITS file Cfitsio

Body:
I am trying to write and fill the image with pixel data to new fits file using cfitsio. I am not sure where I am doing wrong but all of the data are not being written to the fits file. I used binary vi to check out the data and image data is not properly created. I used the second image HST WFPC 2 fits file from NASA website. This is the code that I wrote:

#include <string.h>
#include <stdio.h>
#include "fitsio.h"

int main() {
    fitsfile *fptr;
    int status = 0, i;

    fits_open_file(&fptr, "WFPC2ASSNu5780205bx.fits", READONLY, &status);
    long naxes[2];
    fits_get_img_size(fptr, 3, naxes, &status);

    fitsfile *ofptr;
    fits_create_file(&ofptr, "o_nasa.fits", &status);
    fits_copy_header(fptr, ofptr, &status);

    long fp[2] = {1, 1};
    long nelements = naxes[0];

    float arr[nelements];
    for (i = 0; i < nelements; i++) {
        arr[i] = 100;
    }

    int ii, jj, kk;
    for (ii = 1; ii <= naxes[0]; ii++) {
        for (jj = 1; jj <= naxes[1]; jj++) {
            fits_write_pix(ofptr, TFLOAT, fp, nelements, arr, &status); // this is not working
        }
    }
    fits_close_file(ofptr, &status);
    fits_close_file(fptr, &status);

    return status;
}

Body:
I found out what is wrong with the code. I just posted the answer since there doesn't seem to be a lot of community working on CFITSIO. The code is wrong in the lines in the double for loop with variables ii, jj. I thought fp, the first pixel array to point where the image array starts writing, is used once where to start the whole iterations but instead write_pix uses it throughout the iterations to know where to write. My code is also trying to write/update the 1, 1 pixel and it seems to be NULL. The correct code is:

for (fp[1] = 1; fp[1] <= naxes[0]; fp[1]++) {
    for (fp[0] = 1; fp[0] <= naxes[1]; fp[0]++) {
        fits_write_pix(ofptr, TFLOAT, fp, nelements, arr, &status);
    }
}


问:
Custom widget throws a NullPointerException on setRequestedViewSize
Good morning folks,

I'm working on an Android app and I've run into a bit of a problem. I have created a new class that extends View.  I have overridden the appropriate methods (the Constructor, onDraw, onMeasure) and am instantiating the View through the applications layout XML (which is called main.xml).

Within the source code of my app I have the following code:

```<code>public class CustomViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

/* I *think* I need to setContentView before I actually can use any of the widgets on the form. */
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.button);

        b.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
// my new widget
newWidget s = (newWidget)findViewById(R.id.testWidget);
s.setRequestedViewSize(300);
   }

        });

    }
}
</code>```

the problem here, is that s.setRequestedViewSize(300) throws a NullPointerException. Has anyone run into this before or can lend me some advice?

[EDIT]
The main.XML looks like this:

It returning null, but the XML looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.testing.CustomViewTest02.newWidget
        android:id="@+id/testWidget"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ></Button>
</LinearLayout>
</code>```

Thanks you!
Sam

答: You have no view with the R.id.testWidget ID: it's not about nonstatic methods. Since findViewById() returns null, the next line throws an exception.

Body:
Good morning folks,

I'm working on an Android app and I've run into a bit of a problem. I have created a new class that extends View.  I have overridden the appropriate methods (the Constructor, onDraw, onMeasure) and am instantiating the View through the applications layout XML (which is called main.xml).

Within the source code of my app I have the following code:

public class CustomViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

/* I *think* I need to setContentView before I actually can use any of the widgets on the form. */
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.button);

        b.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
// my new widget
newWidget s = (newWidget)findViewById(R.id.testWidget);
s.setRequestedViewSize(300);
   }

        });

    }
}

the problem here, is that s.setRequestedViewSize(300) throws a NullPointerException. Has anyone run into this before or can lend me some advice?

[EDIT]
The main.XML looks like this:

It returning null, but the XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.testing.CustomViewTest02.newWidget
        android:id="@+id/testWidget"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ></Button>
</LinearLayout>

Thanks you!
Sam


问:
Android EditText data entry in lowercase determined at runtime
I was rather surprised that this was not a native function of EditText, but I can't find any mechanism that will convert inputs to lower case as they are entered into an EditText field. The EditText field determines whether to be lowercase at runtime, so I can't have this in the XML, it needs to be fired as I allocate the EditText. I have tried:

1) Negating the ALL Caps:

```<code> mEntry.setInputType(InputType.TYPE_CLASS_TEXT |  ~InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
</code>```

2) Creating a listener:

private TextWatcher textWatcher = new TextWatcher() {

```<code>@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (!Utilities.stringIsBlank(mField.getFormat()) && Field.LOWER.equalsIgnoreCase(mField.getFormat())) {
        if (!Utilities.stringIsBlank(s.toString()) && !s.toString().equals(s.toString().toLowerCase()) ) {
            mEntry.setText(s.toString().toLowerCase());
            mEntry.setSelection(start+1);
        }
    }
}
</code>```

}

The problem with this is that when I call the setText() it recursively calls back to the onTextChange event, which messes with the location of cursor, depending on what it is changing.

Anyone have a simple solution that I have somehow missed?

答:
You can use a filter.  Below is a modified AllCaps filter to convert everything to lowercase in stead of uppercase.

```<code>/**
 * This filter will lower case all the capitalized letters that are added
 * through edits.
 */
public static class NoCapsFilter implements InputFilter {

    public CharSequence filter(CharSequence source, int start, int end,
        Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; i++) {
            if (Character.isUpperCase(source.charAt(i))) {
                char[] v = new char[end - start];
                TextUtils.getChars(source, start, end, v, 0);
                String s = new String(v).toLowerCase();

                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(s);
                    TextUtils.copySpansFrom((Spanned) source,
                                            start, end, null, sp, 0);
                    return sp;
                }
                else {
                    return s;
                }
            }
        }

        return null; // keep original
    }
}
</code>```

Then just set the filter on your EditText.

```<code>mEntry.setFilters(new InputFilter[]{new NoCapsFilter()});
</code>```

Body:
I was rather surprised that this was not a native function of EditText, but I can't find any mechanism that will convert inputs to lower case as they are entered into an EditText field. The EditText field determines whether to be lowercase at runtime, so I can't have this in the XML, it needs to be fired as I allocate the EditText. I have tried:

1) Negating the ALL Caps:

 mEntry.setInputType(InputType.TYPE_CLASS_TEXT |  ~InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);

2) Creating a listener:

private TextWatcher textWatcher = new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

    if (!Utilities.stringIsBlank(mField.getFormat()) && Field.LOWER.equalsIgnoreCase(mField.getFormat())) {
        if (!Utilities.stringIsBlank(s.toString()) && !s.toString().equals(s.toString().toLowerCase()) ) {
            mEntry.setText(s.toString().toLowerCase());
            mEntry.setSelection(start+1);
        }
    }
}

}

The problem with this is that when I call the setText() it recursively calls back to the onTextChange event, which messes with the location of cursor, depending on what it is changing.

Anyone have a simple solution that I have somehow missed?

Body:
You can use a filter.  Below is a modified AllCaps filter to convert everything to lowercase in stead of uppercase.

/**
 * This filter will lower case all the capitalized letters that are added
 * through edits.
 */
public static class NoCapsFilter implements InputFilter {

    public CharSequence filter(CharSequence source, int start, int end,
        Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; i++) {
            if (Character.isUpperCase(source.charAt(i))) {
                char[] v = new char[end - start];
                TextUtils.getChars(source, start, end, v, 0);
                String s = new String(v).toLowerCase();

                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(s);
                    TextUtils.copySpansFrom((Spanned) source,
                                            start, end, null, sp, 0);
                    return sp;
                }
                else {
                    return s;
                }
            }
        }

        return null; // keep original
    }
}

Then just set the filter on your EditText.

mEntry.setFilters(new InputFilter[]{new NoCapsFilter()});


问:
Ansible route53_zone doesn't create private and public hosted zones
I want to create two hosted zones 1 private and 1 public hosted zones. I have already created a vpc. Somehow when I run my ansible script it only creates 1 hosted zone. If the public zone task is first it will create a public zone and if the private zone task is first it will create a private zone only. I don't know if there is a bug in the module or I am doing something wrong.

```<code>    ---
    - name: Create private hosted Zone
      route53_zone:
      zone: "{{ private_hosted_zone_name }}"
      state: present
      vpc_id: "{{ vpc_id }}"
      vpc_region: "{{ vpc_region }}"
      register: private_hosted_zone

    - name: Print private zone id
      debug:
      msg: "{{ private_hosted_zone.set.zone_id }}"

   - name: Set private zone ID in a variable
     set_fact:
     private_zone_id: "{{ private_hosted_zone.set.zone_id }}"

  - name: Create public hosted Zone
    route53_zone:
    zone: "{{ public_hosted_zone_name }}"
    state: present
    register: public_hosted_zone

  - name: Print public zone id
    debug:
    msg: "{{ public_hosted_zone.set.zone_id }}"

  - name: Set public zone ID in a variable
    set_fact:
    public_zone_id: "{{ public_hosted_zone.set.zone_id }}"
</code>```

My code for hosted zone is here:

```<code>    ---
    - name: Create private hosted Zone
      route53_zone:
      zone: "{{ private_hosted_zone_name }}"
      state: present
      vpc_id: "{{ vpc_id }}"
      vpc_region: "{{ vpc_region }}"
      register: private_hosted_zone

   - name: Print private zone id
     debug:
     msg: "{{ private_hosted_zone.set.zone_id }}"

  - name: Set private zone ID in a variable
    set_fact:
    private_zone_id: "{{ private_hosted_zone.set.zone_id }}"

 - name: Create public hosted Zone
   route53_zone:
   zone: "{{ public_hosted_zone_name }}"
   state: present
   register: public_hosted_zone

- name: Print public zone id
  debug:
   msg: "{{ public_hosted_zone.set.zone_id }}"
</code>```

- name: Set public zone ID in a variable
     set_fact:
     public_zone_id: "{{ public_hosted_zone.set.zone_id }}"

Any help will be highly appreciated.

答: I think there’s an issue with your yaml. I’d use yamllint to make sure it’s standard then try again. Notably, your indentations look inconsistent. </p>

Body:
I want to create two hosted zones 1 private and 1 public hosted zones. I have already created a vpc. Somehow when I run my ansible script it only creates 1 hosted zone. If the public zone task is first it will create a public zone and if the private zone task is first it will create a private zone only. I don't know if there is a bug in the module or I am doing something wrong.

    ---
    - name: Create private hosted Zone
      route53_zone:
      zone: "{{ private_hosted_zone_name }}"
      state: present
      vpc_id: "{{ vpc_id }}"
      vpc_region: "{{ vpc_region }}"
      register: private_hosted_zone

    - name: Print private zone id
      debug:
      msg: "{{ private_hosted_zone.set.zone_id }}"

   - name: Set private zone ID in a variable
     set_fact:
     private_zone_id: "{{ private_hosted_zone.set.zone_id }}"

  - name: Create public hosted Zone
    route53_zone:
    zone: "{{ public_hosted_zone_name }}"
    state: present
    register: public_hosted_zone

  - name: Print public zone id
    debug:
    msg: "{{ public_hosted_zone.set.zone_id }}"

  - name: Set public zone ID in a variable
    set_fact:
    public_zone_id: "{{ public_hosted_zone.set.zone_id }}"

My code for hosted zone is here:

    ---
    - name: Create private hosted Zone
      route53_zone:
      zone: "{{ private_hosted_zone_name }}"
      state: present
      vpc_id: "{{ vpc_id }}"
      vpc_region: "{{ vpc_region }}"
      register: private_hosted_zone

   - name: Print private zone id
     debug:
     msg: "{{ private_hosted_zone.set.zone_id }}"

  - name: Set private zone ID in a variable
    set_fact:
    private_zone_id: "{{ private_hosted_zone.set.zone_id }}"

 - name: Create public hosted Zone
   route53_zone:
   zone: "{{ public_hosted_zone_name }}"
   state: present
   register: public_hosted_zone

- name: Print public zone id
  debug:
   msg: "{{ public_hosted_zone.set.zone_id }}"

- name: Set public zone ID in a variable
     set_fact:
     public_zone_id: "{{ public_hosted_zone.set.zone_id }}"

Any help will be highly appreciated.


问:
Retrieving data with angularfire2 and angular 4
My database is given
here. I want to retrieve the total data tree of Post with the key under Post

I have tried with the code given below. but this provides me a list with 0 1 2 3 instead of original key ( KxZPLJh9k4ldXqz3gNF ) under Post

```<code>this.db.list('/post', ref => ref.orderByChild('course').equalTo("che101f")).valueChanges();
</code>```

Is there any way to have my desired data tree ? If so how ?

答:
valueChanges() strips the metadata, it's only intended for simple access to your JSON tree.

You should use snapshotChanges() if you want to access anything other than the JSON tree, such as pushIds.

Check out the docs here.

Body:
My database is given
here. I want to retrieve the total data tree of Post with the key under Post

I have tried with the code given below. but this provides me a list with 0 1 2 3 instead of original key ( KxZPLJh9k4ldXqz3gNF ) under Post

this.db.list('/post', ref => ref.orderByChild('course').equalTo("che101f")).valueChanges();

Is there any way to have my desired data tree ? If so how ?


问:
Converting from UTF8 To ASCII in Java
I have written a code to read data from a text file. I would like to know how to convert from UTF8 to ASCII after loading the data from the file. Below is part of the code that I have written but need to find the way to do the conversion. As I said in my previous questions I'm very new to Java, please give me a hand.</p>

```<code>public static List<String> readFile(String filename) throws Exception {
    String line = null;
    List<String> records = new ArrayList<String>();

    BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));

    while ((line = bufferedReader.readLine()) != null) {
        records.add(line.trim());
    }

    bufferedReader.close();
    return records;
}
</code>```

答:
Here's your original code:

```<code>public static List<String> readFile(String filename) throws Exception {
String line = null;
List<String> records = new ArrayList<String>();

BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));

while ((line = bufferedReader.readLine()) != null) {
    records.add(line.trim());
}

bufferedReader.close();
return records;
}
</code>```

change it to:

```<code>public static List<String> readFile(String filename) throws Exception {
   return Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
}
</code>```

remember to import the relevant java.nio packages or your program will give you a compilation error.

Here's a fully working program:

```<code>

    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.List;

    public class Tests {
        public static void main(String[] args) {
            String filename = "C:\\Users\\username\\Desktop\\test.txt";
            try {
                for(String s : readFile(filename)) {
                    System.out.println(s);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public static List readFile(String filename) throws Exception {
            return Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
        }
    }

</code>```

Title: Converting from UTF8 To ASCII in Java

Body:
I have written a code to read data from a text file. I would like to know how to convert from UTF8 to ASCII after loading the data from the file. Below is part of the code that I have written but need to find the way to do the conversion. As I said in my previous questions I'm very new to Java, please give me a hand.

public static List<String> readFile(String filename) throws Exception {
    String line = null;
    List<String> records = new ArrayList<String>();

    BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));

    while ((line = bufferedReader.readLine()) != null) {
        records.add(line.trim());
    }

    bufferedReader.close();
    return records;
}

Body:
Here's your original code:

public static List<String> readFile(String filename) throws Exception {
String line = null;
List<String> records = new ArrayList<String>();

BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));

while ((line = bufferedReader.readLine()) != null) {
    records.add(line.trim());
}

bufferedReader.close();
return records;
}

change it to:

public static List<String> readFile(String filename) throws Exception {
   return Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
}

remember to import the relevant java.nio packages or your program will give you a compilation error.

Here's a fully working program:

    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.List;

    public class Tests {
        public static void main(String[] args) {
            String filename = "C:\\Users\\username\\Desktop\\test.txt";
            try {
                for(String s : readFile(filename)) {
                    System.out.println(s);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public static List readFile(String filename) throws Exception {
            return Files.readAllLines(Paths.get(filename), StandardCharsets.US_ASCII);
        }
    }


问:
Facebook SDK conflicts with the android support 26.+ library
im trying to implement login with Facebook i followed the guide lines in here
https://developers.facebook.com/docs/facebook-login/android
but every time i get the following error

```<code>Error:Execution failed for task ':app:processDebugManifest'.
</code>```

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com.android.support:appcompat-v7:26.0.0-alpha1] AndroidManifest.xml:27:9-38
      is also present at [com.android.support:cardview-v7:25.3.1] AndroidManifest.xml:24:9-31 value=(25.3.1).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:25:5-27:41 to override.

and this is my Build.gradle dependencies

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.jakewharton:butterknife:8.7.0'
    compile 'com.android.support:design:26.+'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.android.support:support-v4:26.+'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

    compile 'com.facebook.android:facebook-android-sdk:4.+'
}
</code>```

i tried ass suggested to add tools:value

```<code>   <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:25.3.1">
</code>```

What can i do to solve this conflict without downgrading my compile SDK to 25 ?

答:
You may not need this anymore, but someone may need it.

This fixed the problem for me:

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

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "your.package"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    // FB compatibility. Consider removing them when upgrading FB SDK
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:customtabs:26.1.0'
    implementation 'com.android.support:support-annotations:26.1.0'
    implementation 'com.android.support:support-core-utils:26.1.0'
    implementation('com.facebook.android:facebook-android-sdk:4.28.0') {
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'appcompat-v7'
        exclude group: 'com.android.support', module: 'cardview-v7'
        exclude group: 'com.android.support', module: 'customtabs'
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.android.support', module: 'support-core-utils'
    }

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

Body:
im trying to implement login with Facebook i followed the guide lines in here
https://developers.facebook.com/docs/facebook-login/android
but every time i get the following error

Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com.android.support:appcompat-v7:26.0.0-alpha1] AndroidManifest.xml:27:9-38
      is also present at [com.android.support:cardview-v7:25.3.1] AndroidManifest.xml:24:9-31 value=(25.3.1).
      Suggestion: add 'tools:replace="android:value"' to  element at AndroidManifest.xml:25:5-27:41 to override.

and this is my Build.gradle dependencies

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.jakewharton:butterknife:8.7.0'
    compile 'com.android.support:design:26.+'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.android.support:support-v4:26.+'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

    compile 'com.facebook.android:facebook-android-sdk:4.+'
}

i tried ass suggested to add tools:value

   <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:25.3.1">

What can i do to solve this conflict without downgrading my compile SDK to 25 ?

Body:
You may not need this anymore, but someone may need it.

This fixed the problem for me:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "your.package"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    // FB compatibility. Consider removing them when upgrading FB SDK
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support:customtabs:26.1.0'
    implementation 'com.android.support:support-annotations:26.1.0'
    implementation 'com.android.support:support-core-utils:26.1.0'
    implementation('com.facebook.android:facebook-android-sdk:4.28.0') {
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'appcompat-v7'
        exclude group: 'com.android.support', module: 'cardview-v7'
        exclude group: 'com.android.support', module: 'customtabs'
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.android.support', module: 'support-core-utils'
    }

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}


答:
Try

```<code>var B01 = document.getElementsByClassName("block_matrix")[0];
</code>```

or

```<code>var B01 = document.getElementsByClassName("block_matrix")[0].outerHTML;
</code>```

This will solve your current problem, but then you will meet another problem because you are using document.write()

Title: javascript output [object HTMLCollection]

Body:
Since i've got no clue after doing research i got to the point to ask.

So The Following code is supposed to output the inside of the array as divs more precise as a simple block.
For some reason every "B01" will be output as [object HTMLCollection] , instead as a block as defined in css.
So how does that happen and how can I fix it?

var B01 = document.getElementsByClassName("block_matrix");

var level = [B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01,
    B01, B01, B01,B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01, B01 , B01];

  document.write(level);

body, html{
 margin:0;
 border:0;
 width:100%;
 height:100%;
 background-color: grey;
}
#game{
 width:90%;
 height: 90%;
 margin: 0 auto;

}

.block_matrix{
 width:5%;
 height:5%;
 background-color:orange;
 z-index:1;
 position:absolute;
}

<!DOCTYPE HTML>

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="gfx/style.css" media="screen" />

Body:
Try

var B01 = document.getElementsByClassName("block_matrix")[0];

or

var B01 = document.getElementsByClassName("block_matrix")[0].outerHTML;

This will solve your current problem, but then you will meet another problem because you are using document.write()


问:
JPA Design of User and Roles
I have a User class and a Role class.  Both of these classes are JPA entities, and hence stored in a Person table and a Role table, as well as a corresponding link table Person_Role used for joins, since the association is many to many. A user may have many roles, and a role may be assigned to many users.

```<code>@Entity
@Table(name="role")
public class Role implements Comparable<Role>
{
   // data members
   @Id @GeneratedValue
   private int    id;              // primary key
   private String name;            // name of the role
   private String description;     // description of the role

   ...
}

@Entity
@Table(name="person")
public class Person implements Comparable<Person>
{
   // data members
   @Id @GeneratedValue
   protected int       id;          // the primary key
   protected String    username;    // the user's unique user name
   protected String    firstName;   // the user's first name
   protected String    lastName;    // the user's last  name
   protected String    email;       // the user's work e-mail address
   @Transient
   protected String    history;     // chronological list of changes to the person
                                    // don't want to load this unless an explicit call to getHistory() is made
   @Transient
   protected Set<Role> roles;       // list of roles assigned to the user
                                    // don't want to load this unless an explicit call to getRoles() is made

   ...
}
</code>```

The User entity is used extensively throughout the application, as it is a shared reference for many objects, and is used in many, many  searches.  99.99% of the time, the user's roles and history are not needed.  I'm new to JPA, and have been reading the "Java Persistence with Hibernate" book in order to learn.  As I understand lazy fetching, it will load all the corresponding User data from the database when any getXXX() method is called.

Ex: user.getFirstName() would cause a database hit and load all the data, including roles and history, for the user.

I want to avoid this at all costs.  Its just needless in 99.99% of the use cases.  So, what's the best way to handle this?

My initial thought is to mark the Set<Role> roles and Set<String> history in the User class as @Transient and manually query for the roles and history only when the user.getRoles() or user.getHistory() method is called.

Thanks for any suggestions.

答:
As I understand lazy fetching, it will load all the corresponding User
  data from the database when any getXXX() method is called.

You can force JPA to be eager or lazy while fetching data from the database but first and foremost it depends on JPA provider. As described in JPA 2.1 specification, chapter 11.1.6:

The FetchType enum defines strategies for fetching data from the
  database:

```<code>public enum FetchType { LAZY, EAGER };
</code>```

The EAGER strategy is a requirement on the persistence provider
  runtime that data must be eagerly fetched. The LAZY strategy is a
  hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to
  eagerly fetch data for which the LAZY strategy hint has been
  specified. In particular, lazy fetching might only be available for
  Basic mappings for which property-based access is used.

A nice presentation on how fetching strategies work and how performant they are in real-life scenarios you can find here.

Ex: user.getFirstName() would cause a database hit and load all the
  data, including roles and history, for the user.

Data are retrieved either directly from the persistence context (usually it has a short lifespan) or indirectly from the underlying database (when it's not found in the transactional/shared caches). If entity manager is requested to get your entity object and it does not exist in the persistence context it needs to go deeper - into the database in the worst scenario.

I want to avoid this at all costs. Its just needless in 99.99% of the
  use cases. So, what's the best way to handle this?

An example approach:

```<code>@Entity
@NamedQuery(name="Person.getNameById",
            query="SELECT p.name FROM Person p WHERE p.id = :id")
public class Person
{
   @Id @GeneratedValue
   protected int id;

   private String name; //the sole attribute to be requested

   @ManyToMany //fetch type is lazy by default
   @JoinTable
   protected Set<Role> roles; //not loaded until referenced or accessed
   ...
}
</code>```

Usually the best way to go is the find method. It's perfect when you want to retrieve all non-relationship attributes at once:

```<code>Person p = em.find(Person.class, id)
</code>```

An alternative for you would be to use named query. It's useful when you need a single attribute or a small subset of attributes:

```<code>String name = em.createNamedQuery("Person.getNameById", String.class)
                 .setParameter("id", id)
                 .getSingleResult()
</code>```

My initial thought is to mark the Set roles and Set history in the
  User class as @Transient and manually query for the roles and history
  only when the user.getRoles() or user.getHistory() method is called.

Transient attributes are not persisted in a database. Whatever you will set to these attributes it will stay in memory only. I would prefer JPA doing it lazily.

Title: JPA Design of User and Roles

Body:
I have a User class and a Role class.  Both of these classes are JPA entities, and hence stored in a Person table and a Role table, as well as a corresponding link table Person_Role used for joins, since the association is many to many. A user may have many roles, and a role may be assigned to many users.

@Entity
@Table(name="role")
public class Role implements Comparable<Role>
{
   // data members
   @Id @GeneratedValue
   private int    id;              // primary key
   private String name;            // name of the role
   private String description;     // description of the role

   ...
}

@Entity
@Table(name="person")
public class Person implements Comparable<Person>
{
   // data members
   @Id @GeneratedValue
   protected int       id;          // the primary key
   protected String    username;    // the user's unique user name
   protected String    firstName;   // the user's first name
   protected String    lastName;    // the user's last  name
   protected String    email;       // the user's work e-mail address
   @Transient
   protected String    history;     // chronological list of changes to the person
                                    // don't want to load this unless an explicit call to getHistory() is made
   @Transient
   protected Set<Role> roles;       // list of roles assigned to the user
                                    // don't want to load this unless an explicit call to getRoles() is made

   ...
}

The User entity is used extensively throughout the application, as it is a shared reference for many objects, and is used in many, many  searches.  99.99% of the time, the user's roles and history are not needed.  I'm new to JPA, and have been reading the "Java Persistence with Hibernate" book in order to learn.  As I understand lazy fetching, it will load all the corresponding User data from the database when any getXXX() method is called.

Ex: user.getFirstName() would cause a database hit and load all the data, including roles and history, for the user.

I want to avoid this at all costs.  Its just needless in 99.99% of the use cases.  So, what's the best way to handle this?

My initial thought is to mark the Set<Role> roles and Set<String> history in the User class as @Transient and manually query for the roles and history only when the user.getRoles() or user.getHistory() method is called.

Thanks for any suggestions.

Body:
As I understand lazy fetching, it will load all the corresponding User
  data from the database when any getXXX() method is called.

You can force JPA to be eager or lazy while fetching data from the database but first and foremost it depends on JPA provider. As described in JPA 2.1 specification, chapter 11.1.6:

The FetchType enum defines strategies for fetching data from the
  database:

public enum FetchType { LAZY, EAGER };

The EAGER strategy is a requirement on the persistence provider
  runtime that data must be eagerly fetched. The LAZY strategy is a
  hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to
  eagerly fetch data for which the LAZY strategy hint has been
  specified. In particular, lazy fetching might only be available for
  Basic mappings for which property-based access is used.

A nice presentation on how fetching strategies work and how performant they are in real-life scenarios you can find here.

Ex: user.getFirstName() would cause a database hit and load all the
  data, including roles and history, for the user.

Data are retrieved either directly from the persistence context (usually it has a short lifespan) or indirectly from the underlying database (when it's not found in the transactional/shared caches). If entity manager is requested to get your entity object and it does not exist in the persistence context it needs to go deeper - into the database in the worst scenario.

I want to avoid this at all costs. Its just needless in 99.99% of the
  use cases. So, what's the best way to handle this?

An example approach:

@Entity
@NamedQuery(name="Person.getNameById",
            query="SELECT p.name FROM Person p WHERE p.id = :id")
public class Person
{
   @Id @GeneratedValue
   protected int id;

   private String name; //the sole attribute to be requested

   @ManyToMany //fetch type is lazy by default
   @JoinTable
   protected Set<Role> roles; //not loaded until referenced or accessed
   ...
}

Usually the best way to go is the find method. It's perfect when you want to retrieve all non-relationship attributes at once:

Person p = em.find(Person.class, id)

An alternative for you would be to use named query. It's useful when you need a single attribute or a small subset of attributes:

String name = em.createNamedQuery("Person.getNameById", String.class)
                 .setParameter("id", id)
                 .getSingleResult()

My initial thought is to mark the Set roles and Set history in the
  User class as @Transient and manually query for the roles and history
  only when the user.getRoles() or user.getHistory() method is called.

Transient attributes are not persisted in a database. Whatever you will set to these attributes it will stay in memory only. I would prefer JPA doing it lazily.


问:
react-native-beacons-manager Not showing any beacons on Android
Using https://github.com/MacKentoch/react-native-beacons-manager

Works lovely on iOS, however, on Android, after I begin ranging beacons, the beacon array shows up with nothing in it (there are 6 beacons next to me and they all show up on iOS).

Here's what I'm doing:

```<code>componentDidMount() {

 // Start detecting all iBeacons in the nearby
Beacons.detectIBeacons();

Beacons.startRangingBeaconsInRegion('Estimotes', 'B9407F30-F5F8-466E-AFF9-25556B57FE6D').then((data)=>{

    console.log(data);

}).catch((reason) => {

    console.log(reason);

});

// Print a log of the detected iBeacons (1 per second)
DeviceEventEmitter.addListener('beaconsDidRange', (data) => {

    console.log(data);

});

}
</code>```

In my console, I get this:

```<code>{beacons: Array(0), uuid: "b9407f30-f5f8-466e-aff9-25556b57fe6d", identifier: "Estimotes"}
</code>```

I left the UUID of the Estimotes as default so this should work. Using a Samsung Galaxy S8+ for testing. Am I doing anything wrong coding wise here? Are there additional permissions on Android that I am missing? Bluetooth and Location services are on.

答:
Alright, I figured it out. Newer versions of android require additional permissions. In your Manifest, throw this guy in there:

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

.... if you're using react-native-kontaktio (which is better than react-native-beacons-manager imo) you'll also need to throw this in your Manifest in the  <application> section:

```<code><service android:name="com.kontakt.sdk.android.ble.service.ProximityService"/>
</code>```

Then in your app.js you'll need to request the permission like () make sure you

```<code>import PermissionsAndroid
from 'react-native'
</code>```

:

```<code>componentDidMount() {

    try {
        const granted = PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
                'title': 'Location Permission',
                'message': 'Activeev needs to access your location.'
            }
        )
        console.log('here', granted);
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log("Location Permitted")
        } else {
            console.log("Location permission denied")
        }
    } catch (err) {
        console.warn(err)
    }
}
</code>```

Working like a charm now. Hope this helps someone else.

Body:
Using https://github.com/MacKentoch/react-native-beacons-manager

Works lovely on iOS, however, on Android, after I begin ranging beacons, the beacon array shows up with nothing in it (there are 6 beacons next to me and they all show up on iOS).

Here's what I'm doing:

componentDidMount() {

 // Start detecting all iBeacons in the nearby
Beacons.detectIBeacons();

Beacons.startRangingBeaconsInRegion('Estimotes', 'B9407F30-F5F8-466E-AFF9-25556B57FE6D').then((data)=>{

    console.log(data);

}).catch((reason) => {

    console.log(reason);

});

// Print a log of the detected iBeacons (1 per second)
DeviceEventEmitter.addListener('beaconsDidRange', (data) => {

    console.log(data);

});

}

In my console, I get this:

{beacons: Array(0), uuid: "b9407f30-f5f8-466e-aff9-25556b57fe6d", identifier: "Estimotes"}

I left the UUID of the Estimotes as default so this should work. Using a Samsung Galaxy S8+ for testing. Am I doing anything wrong coding wise here? Are there additional permissions on Android that I am missing? Bluetooth and Location services are on.

Body:
Alright, I figured it out. Newer versions of android require additional permissions. In your Manifest, throw this guy in there:

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

.... if you're using react-native-kontaktio (which is better than react-native-beacons-manager imo) you'll also need to throw this in your Manifest in the  <application> section:

<service android:name="com.kontakt.sdk.android.ble.service.ProximityService"/>

Then in your app.js you'll need to request the permission like () make sure you

import PermissionsAndroid
from 'react-native'

:

componentDidMount() {

    try {
        const granted = PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
                'title': 'Location Permission',
                'message': 'Activeev needs to access your location.'
            }
        )
        console.log('here', granted);
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log("Location Permitted")
        } else {
            console.log("Location permission denied")
        }
    } catch (err) {
        console.warn(err)
    }
}

Working like a charm now. Hope this helps someone else.


问:
setState not updating when set to boolean
I have the following method in a react component:

```<code>handleCheckBoxClick() {
  var checkbox = document.getElementById("boldCheckbox").checked;
  this.setState({ischecked : checkbox});
  if(this.state.ischecked) {
    this.setState({weight:'bold'});
  } else {
    this.setState({weight:'normal'});
  }
}
</code>```

but if I change the if statement to:

```<code>if(checkbox) {
  this.setState({weight:'bold'});
} else {
  this.setState({weight:'normal'});
}
</code>```

it works fine but I can't figure out why the first way doesn't work.

答:
The method setState() is asynchronous, and updates are often batched together. In your case, ischecked is updated together with the weight, so when you set the weight you still refer to the old value.

One solution is to use setState()'s callback that will be called after the state is updated.

Note: to get the checkbox checked state, use the event object e passed to the handler instead of querying the DOM.

```<code>handleCheckBoxClick(e){
   var checked = e.target.checked;
   this.setState({ischecked : checked}, function() {
     if(this.state.ischecked){
        this.setState({weight:'bold'});
     }else{
        this.setState({weight:'normal'});
     }
   });
}
</code>```

A better solution is to update both properties because you know if the checkbox is checked:

```<code>handleCheckBoxClick(e){
   var checked = e.target.checked;

   this.setState({
    ischecked : checked,
    weight: checked ? 'bold' : 'normal'
   });
}
</code>```

Body:
I have the following method in a react component:

handleCheckBoxClick() {
  var checkbox = document.getElementById("boldCheckbox").checked;
  this.setState({ischecked : checkbox});
  if(this.state.ischecked) {
    this.setState({weight:'bold'});
  } else {
    this.setState({weight:'normal'});
  }
}

but if I change the if statement to:

if(checkbox) {
  this.setState({weight:'bold'});
} else {
  this.setState({weight:'normal'});
}

it works fine but I can't figure out why the first way doesn't work.

Body:
The method setState() is asynchronous, and updates are often batched together. In your case, ischecked is updated together with the weight, so when you set the weight you still refer to the old value.

One solution is to use setState()'s callback that will be called after the state is updated.

Note: to get the checkbox checked state, use the event object e passed to the handler instead of querying the DOM.

handleCheckBoxClick(e){
   var checked = e.target.checked;
   this.setState({ischecked : checked}, function() {
     if(this.state.ischecked){
        this.setState({weight:'bold'});
     }else{
        this.setState({weight:'normal'});
     }
   });
}

A better solution is to update both properties because you know if the checkbox is checked:

handleCheckBoxClick(e){
   var checked = e.target.checked;

   this.setState({
    ischecked : checked,
    weight: checked ? 'bold' : 'normal'
   });
}