问:
REST Service WebHttpBinding with Http and Https
I have a REST service. This service need to be work with http and https.
I've tried to add two endpoint in my web.config file. But i get this error when i try to browse my service over http:

Could not find a base address that matches scheme https for the
  endpoint with binding WebHttpBinding. Registered base address schemes
  are [http].

and i get this error when i try to browse over https:

Could not find a base address that matches scheme http for the endpoint with binding WebHttpBinding. Registered base address schemes are [https].

If i remove one of endpoint from my config file, the both http and https services works fine.
I checked this link: WebHttpBinding with Http and Https
But when i remove endpoints from my config file, the both http and https services runs without any errors on web browser. But when i try to call one of my methods (over a rest client tool) in this service it gets:

500 Internal Server Error.

How can i run this service over http and https without any errors?

My config file is like this:

```<code> <system.serviceModel>
<protocolMapping>
  <add scheme="http" binding="webHttpBinding" bindingConfiguration="webHttpBinding"/>
  <add scheme="https" binding="webHttpBinding" bindingConfiguration="webHttpsBinding"/>
</protocolMapping>
<bindings>
  <webHttpBinding>
    <binding name="webHttpBinding">
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None" />
      </security>
    </binding>
    <binding name="webHttpsBinding">
      <security mode="Transport">
        <transport clientCredentialType="None" proxyCredentialType="None" />
      </security>
    </binding>
  </webHttpBinding>
</bindings>
<services>
  <service name="MyProject.MyService" behaviorConfiguration="serviceBehavior">
    <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" bindingConfiguration="webHttpBinding" contract="MyProject.IMyService" />
    <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" bindingConfiguration="webHttpsBinding" contract="MyProject.IMyService" />
    <!--<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />-->
    <!--<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>-->
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="serviceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
      <serviceAuthorization serviceAuthorizationManagerType="MyProject.RestAuthorizationManager, MyProject"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</code>```

```<code>  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</code>```

答:
here is a sample web.config in order to have both http and https support. i hope solve your problem:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="SoapBinding" />
      </basicHttpBinding>
      <basicHttpsBinding>
        <binding name="SecureSoapBinding" />
      </basicHttpsBinding>

      <webHttpBinding>
        <binding name="RestBinding" />
        <binding name="SecureRestBinding">
          <security mode="Transport" />
        </binding>
      </webHttpBinding>

      <mexHttpBinding>
        <binding name="MexBinding" />
      </mexHttpBinding>
      <mexHttpsBinding>
        <binding name="SecureMexBinding" />
      </mexHttpsBinding>
    </bindings>

    <client />

    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Interface.Core">
        <endpoint address="soap" binding="basicHttpBinding" bindingConfiguration="SoapBinding" name="Soap" contract="Interface.ICore" />
        <endpoint address="soap" binding="basicHttpsBinding" bindingConfiguration="SecureSoapBinding" name="SecureSoap" contract="Interface.ICore" />
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="RestBinding" name="Rest" contract="Interface.ICore" />
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="SecureRestBinding" name="SecureRest" contract="Interface.ICore" />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="MexBinding" name="Mex" contract="IMetadataExchange" />
        <endpoint address="mex" binding="mexHttpsBinding" bindingConfiguration="SecureMexBinding" name="SecureMex" contract="IMetadataExchange" />
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="Web">
          <webHttp helpEnabled="true" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <directoryBrowse enabled="false" />
  </system.webServer>

</configuration>
</code>```

Body:
I have a REST service. This service need to be work with http and https.
I've tried to add two endpoint in my web.config file. But i get this error when i try to browse my service over http:

Could not find a base address that matches scheme https for the
  endpoint with binding WebHttpBinding. Registered base address schemes
  are [http].

and i get this error when i try to browse over https:

Could not find a base address that matches scheme http for the endpoint with binding WebHttpBinding. Registered base address schemes are [https].

If i remove one of endpoint from my config file, the both http and https services works fine.
I checked this link: WebHttpBinding with Http and Https
But when i remove endpoints from my config file, the both http and https services runs without any errors on web browser. But when i try to call one of my methods (over a rest client tool) in this service it gets:

500 Internal Server Error.

How can i run this service over http and https without any errors?

My config file is like this:

 <system.serviceModel>
<protocolMapping>
  <add scheme="http" binding="webHttpBinding" bindingConfiguration="webHttpBinding"/>
  <add scheme="https" binding="webHttpBinding" bindingConfiguration="webHttpsBinding"/>
</protocolMapping>
<bindings>
  <webHttpBinding>
    <binding name="webHttpBinding">
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None" />
      </security>
    </binding>
    <binding name="webHttpsBinding">
      <security mode="Transport">
        <transport clientCredentialType="None" proxyCredentialType="None" />
      </security>
    </binding>
  </webHttpBinding>
</bindings>
<services>
  <service name="MyProject.MyService" behaviorConfiguration="serviceBehavior">
    <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" bindingConfiguration="webHttpBinding" contract="MyProject.IMyService" />
    <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" bindingConfiguration="webHttpsBinding" contract="MyProject.IMyService" />

  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="serviceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
      <serviceAuthorization serviceAuthorizationManagerType="MyProject.RestAuthorizationManager, MyProject"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

Body:
here is a sample web.config in order to have both http and https support. i hope solve your problem:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="SoapBinding" />
      </basicHttpBinding>
      <basicHttpsBinding>
        <binding name="SecureSoapBinding" />
      </basicHttpsBinding>

      <webHttpBinding>
        <binding name="RestBinding" />
        <binding name="SecureRestBinding">
          <security mode="Transport" />
        </binding>
      </webHttpBinding>

      <mexHttpBinding>
        <binding name="MexBinding" />
      </mexHttpBinding>
      <mexHttpsBinding>
        <binding name="SecureMexBinding" />
      </mexHttpsBinding>
    </bindings>

    <client />

    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Interface.Core">
        <endpoint address="soap" binding="basicHttpBinding" bindingConfiguration="SoapBinding" name="Soap" contract="Interface.ICore" />
        <endpoint address="soap" binding="basicHttpsBinding" bindingConfiguration="SecureSoapBinding" name="SecureSoap" contract="Interface.ICore" />
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="RestBinding" name="Rest" contract="Interface.ICore" />
        <endpoint address="" behaviorConfiguration="Web" binding="webHttpBinding" bindingConfiguration="SecureRestBinding" name="SecureRest" contract="Interface.ICore" />
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="MexBinding" name="Mex" contract="IMetadataExchange" />
        <endpoint address="mex" binding="mexHttpsBinding" bindingConfiguration="SecureMexBinding" name="SecureMex" contract="IMetadataExchange" />
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="Web">
          <webHttp helpEnabled="true" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <directoryBrowse enabled="false" />
  </system.webServer>

</configuration>


来源: stackexchange

问:
Showing correct response in Postman but wrong response in Android app
I have a Registration page in android where user enters his/her name, email, phone and password. When I register any new user from the app, the response I am getting is always E/Json response: {"success":false,"msg":"User already Exists"}even when the user does not exists. But when I hit the same query through Postman, I am getting proper response like

```<code>{
  "success": true,
  "msg": "Confirmation Link to activate your account has been sent to your email address",
  "data": {
    "studentId": 8
  }
}
</code>```

If I register with new users through Postman I am getting correct response but from app it is always showing "User already Exists".

Here is my Register Activity :

```<code>public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {

    private EditText password, phone, email;
    public static EditText name;
    ServerRequests serverRequests;
    JSONParser jsonParser;
    private Button registerButton;
    TextView alreadyMember;

    Editor editor;
    UserSession session;
    SharedPreferences sharedPreferences;

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

        jsonParser = new JSONParser();
        serverRequests = new ServerRequests(getApplicationContext());
        serverRequests.setRegistereponse(this);

        alreadyMember = (TextView) findViewById(R.id.alreadyMember);

        name = (EditText) findViewById(R.id.FName);
        phone = (EditText) findViewById(R.id.PhoneNum);
        email = (EditText) findViewById(R.id.mail);
        password = (EditText) findViewById(R.id.password);
        registerButton = (Button) findViewById(R.id.email_sign_in_button);

        sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
        editor = sharedPreferences.edit();

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CharSequence temp_emailID = email.getText().toString();
                if (name.getText().toString().length() == 0) {
                    name.setError("Please enter your name");
                    name.requestFocus();

                } else if (phone.getText().toString().length() == 0) {
                    phone.setError("Please enter your phone number");
                    phone.requestFocus();

                } else if (!isValidEmail(temp_emailID)) {
                    email.setError("Please enter valid email");
                    email.requestFocus();

                } else if (password.getText().toString().length() == 0) {
                    password.setError("Please enter password");
                    password.requestFocus();

                } else {

                    try {
                        String Name = name.getText().toString();
                        String Email = email.getText().toString();
                        String Password = password.getText().toString();
                        String Phone = phone.getText().toString();

                        JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
                        Log.e("final Json", obj.toString());
                        serverRequests.register(obj);

                        editor.putString("name", Name);
                        editor.putString("email", Email);
                        editor.putString("password", Password);
                        editor.putString("phone", Phone);
                        editor.commit();
                        //    Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();

                    } catch (Exception e) {

                    }
                }

                //   startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

            }
        });

        alreadyMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

    }

    @Override
    public void onRegsiterReposne(JSONObject object) {
        Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();

    }

    public final static boolean isValidEmail(CharSequence target) {
        if (TextUtils.isEmpty(target)) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }

}
</code>```

Here is my Server Request class :

```<code>public void setRegistereponse(Registereponse registereponse) {
        this.registereponse = registereponse;
    }

    private Registereponse registereponse;

    public interface Registereponse {
        void onRegsiterReposne(JSONObject object);
    }

    public void register(JSONObject jsonObject) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("Json response", "" + response);
                            boolean b = response.getBoolean("success");

                            if (registereponse != null) {
                                registereponse.onRegsiterReposne(response);

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error ", "" + error);
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }
</code>```

Here is my JSON Parser class :

```<code>public class JSONParser {

    //----------For Register

    public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {

        JSONObject object = new JSONObject();

        object.put("name", name);
        object.put("email", email);
        object.put("password", password);
        object.put("phone", phone);
        // if its in array------
       /*JSONObject finalObject=new JSONObject();
       finalObject.put("request",object);
       return finalObject;*/
        return object;
    }
</code>```

Server Side :
I have done coding in Php using codeigniter framework:

This is my controller method:

```<code>public function register_post()
    {
        $data['name']       = $this->post('name');
        $data['email']      = $this->post('email');
        $data['phone']      = $this->post('phone');
        $data['password']   = $this->post('password');

        if (isset($data['name']) && !empty($data['name']) && isset($data['email']) && !empty($data['email']) && isset($data['phone']) && !empty($data['phone']) && isset($data['password']) && !empty($data['password']))
        {

            $model_response=$this->api_model->register_user($data);

            if($model_response == "E101"){
                $data_result['success'] = false;
                $data_result['msg'] = "User already Exists";
            }

            if($model_response == "E103" || $model_response == "E102"){
                $data_result['success'] = false;
                $data_result['msg'] = "Record Not Inserted";
            }
            else
                {
                    $name = $data['name'];
                    $emailid = $data['email'];
                    $link = "<a href=''>Verification Link</a>";
                    $mail = new PHPMailer;
                    $mail->isSMTP();
                    $mail->Debugoutput = 'html';
                    $mail->Host = "dash.dash.in";
                    $mail->Port = 25;
                    $mail->SMTPAuth = true;
                    $mail->isHTML(true);
                    $mail->Username = "dash@dash.in";
                    $mail->Password = "******";
                    $mail->setFrom('dash@dash.in','Training App');
                    $mail->addAddress($emailid, 'Registration');
                    $mail->Subject = 'Registration - Training App';
                    $mail->Body = "<p>Hi $name,<br/><br/>You are successfully registered with us.<br/><br/> Please Click below link to activate your account<br/> Link - $link<br/><br/>If you have any queries or encounter any problems in logging in, please contact us on :<br>dash@dash.com <br/><br/> Thank you.</p>";
                    if($mail->send()){

                        $data_result['success'] = true;
                        $data_result['msg'] = "Confirmation Link to activate your account has been sent to your email address";
                        $data_result['data'] = array('studentId' => $model_response);
                    }else{
                        $data_result['success'] = false;
                        $data_result["msg"] = "Failed to send mail.";
                    }
                }

        }
        else{
            $data_result['success'] = false;
            $data_result['msg'] = "Please Check Your Request";
        }
        $this->response($data_result);
    }
</code>```

This is my model Code:

```<code>public function register_user($data)
        {
            $email = $data['email'];
            $this->db->select('username as email');
            $this->db->where('username',$email);
            $query = $this->db->get('tbl_login');

            if($query->row() > 0)
            {
                return "E101";
            }else{
                $data_l = array(
                'username'  => $data['email'],
                'role'      => 2,
                'password'  => md5($data['password'])
                );
                $this->db->insert('tbl_login', $data_l);
                if ($this->db->affected_rows() == 1) {
                    $loginId = $this->db->insert_id();
                    $data_s = array(
                    'name'  => $data['name'],
                    'email' => $data['email'],
                    'phone' => $data['phone'],
                    'loginId' => $loginId
                    );
                    $this->db->insert('student', $data_s);
                    if ($this->db->affected_rows() == 1) {
                        $studentId = $this->db->insert_id();
                        return $studentId;
                    } else {
                        return "E102";
                    }
                }else {
                    return "E103";
                }
            }
        }
</code>```

I dont know where am I going wrong.

答: I found another solution for it. It worked for me using Async task, but still didn't understand why the error came when I am using Volley.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a Registration page in android where user enters his/her name, email, phone and password. When I register any new user from the app, the response I am getting is always E/Json response: {"success":false,"msg":"User already Exists"}even when the user does not exists. But when I hit the same query through Postman, I am getting proper response like

{
  "success": true,
  "msg": "Confirmation Link to activate your account has been sent to your email address",
  "data": {
    "studentId": 8
  }
}

If I register with new users through Postman I am getting correct response but from app it is always showing "User already Exists".

Here is my Register Activity :

public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {

    private EditText password, phone, email;
    public static EditText name;
    ServerRequests serverRequests;
    JSONParser jsonParser;
    private Button registerButton;
    TextView alreadyMember;

    Editor editor;
    UserSession session;
    SharedPreferences sharedPreferences;

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

        jsonParser = new JSONParser();
        serverRequests = new ServerRequests(getApplicationContext());
        serverRequests.setRegistereponse(this);

        alreadyMember = (TextView) findViewById(R.id.alreadyMember);

        name = (EditText) findViewById(R.id.FName);
        phone = (EditText) findViewById(R.id.PhoneNum);
        email = (EditText) findViewById(R.id.mail);
        password = (EditText) findViewById(R.id.password);
        registerButton = (Button) findViewById(R.id.email_sign_in_button);

        sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
        editor = sharedPreferences.edit();

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CharSequence temp_emailID = email.getText().toString();
                if (name.getText().toString().length() == 0) {
                    name.setError("Please enter your name");
                    name.requestFocus();

                } else if (phone.getText().toString().length() == 0) {
                    phone.setError("Please enter your phone number");
                    phone.requestFocus();

                } else if (!isValidEmail(temp_emailID)) {
                    email.setError("Please enter valid email");
                    email.requestFocus();

                } else if (password.getText().toString().length() == 0) {
                    password.setError("Please enter password");
                    password.requestFocus();

                } else {

                    try {
                        String Name = name.getText().toString();
                        String Email = email.getText().toString();
                        String Password = password.getText().toString();
                        String Phone = phone.getText().toString();

                        JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
                        Log.e("final Json", obj.toString());
                        serverRequests.register(obj);

                        editor.putString("name", Name);
                        editor.putString("email", Email);
                        editor.putString("password", Password);
                        editor.putString("phone", Phone);
                        editor.commit();
                        //    Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();

                    } catch (Exception e) {

                    }
                }

                //   startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

            }
        });

        alreadyMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

    }

    @Override
    public void onRegsiterReposne(JSONObject object) {
        Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();

    }

    public final static boolean isValidEmail(CharSequence target) {
        if (TextUtils.isEmpty(target)) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }

}

Here is my Server Request class :

public void setRegistereponse(Registereponse registereponse) {
        this.registereponse = registereponse;
    }

    private Registereponse registereponse;

    public interface Registereponse {
        void onRegsiterReposne(JSONObject object);
    }

    public void register(JSONObject jsonObject) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("Json response", "" + response);
                            boolean b = response.getBoolean("success");

                            if (registereponse != null) {
                                registereponse.onRegsiterReposne(response);

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error ", "" + error);
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }

Here is my JSON Parser class :

public class JSONParser {

    //----------For Register

    public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {

        JSONObject object = new JSONObject();

        object.put("name", name);
        object.put("email", email);
        object.put("password", password);
        object.put("phone", phone);
        // if its in array------
       /*JSONObject finalObject=new JSONObject();
       finalObject.put("request",object);
       return finalObject;*/
        return object;
    }

Server Side :
I have done coding in Php using codeigniter framework:

This is my controller method:

public function register_post()
    {
        $data['name']       = $this->post('name');
        $data['email']      = $this->post('email');
        $data['phone']      = $this->post('phone');
        $data['password']   = $this->post('password');

        if (isset($data['name']) && !empty($data['name']) && isset($data['email']) && !empty($data['email']) && isset($data['phone']) && !empty($data['phone']) && isset($data['password']) && !empty($data['password']))
        {

            $model_response=$this->api_model->register_user($data);

            if($model_response == "E101"){
                $data_result['success'] = false;
                $data_result['msg'] = "User already Exists";
            }

            if($model_response == "E103" || $model_response == "E102"){
                $data_result['success'] = false;
                $data_result['msg'] = "Record Not Inserted";
            }
            else
                {
                    $name = $data['name'];
                    $emailid = $data['email'];
                    $link = "Verification Link";
                    $mail = new PHPMailer;
                    $mail->isSMTP();
                    $mail->Debugoutput = 'html';
                    $mail->Host = "dash.dash.in";
                    $mail->Port = 25;
                    $mail->SMTPAuth = true;
                    $mail->isHTML(true);
                    $mail->Username = "dash@dash.in";
                    $mail->Password = "******";
                    $mail->setFrom('dash@dash.in','Training App');
                    $mail->addAddress($emailid, 'Registration');
                    $mail->Subject = 'Registration - Training App';
                    $mail->Body = "
Hi $name,

You are successfully registered with us.

 Please Click below link to activate your account
 Link - $link

If you have any queries or encounter any problems in logging in, please contact us on :
dash@dash.com

 Thank you.
";
                    if($mail->send()){

                        $data_result['success'] = true;
                        $data_result['msg'] = "Confirmation Link to activate your account has been sent to your email address";
                        $data_result['data'] = array('studentId' => $model_response);
                    }else{
                        $data_result['success'] = false;
                        $data_result["msg"] = "Failed to send mail.";
                    }
                }

        }
        else{
            $data_result['success'] = false;
            $data_result['msg'] = "Please Check Your Request";
        }
        $this->response($data_result);
    }

This is my model Code:

public function register_user($data)
        {
            $email = $data['email'];
            $this->db->select('username as email');
            $this->db->where('username',$email);
            $query = $this->db->get('tbl_login');

            if($query->row() > 0)
            {
                return "E101";
            }else{
                $data_l = array(
                'username'  => $data['email'],
                'role'      => 2,
                'password'  => md5($data['password'])
                );
                $this->db->insert('tbl_login', $data_l);
                if ($this->db->affected_rows() == 1) {
                    $loginId = $this->db->insert_id();
                    $data_s = array(
                    'name'  => $data['name'],
                    'email' => $data['email'],
                    'phone' => $data['phone'],
                    'loginId' => $loginId
                    );
                    $this->db->insert('student', $data_s);
                    if ($this->db->affected_rows() == 1) {
                        $studentId = $this->db->insert_id();
                        return $studentId;
                    } else {
                        return "E102";
                    }
                }else {
                    return "E103";
                }
            }
        }

I dont know where am I going wrong.


问:
Laravel - belongsToMany with multiple tables
I created 3 Database Tables:

users
 - id
 - username
 - ...

messages
 - id
 - title
 - message

messages_user
 - messages_id
 - user_id
 - receive_user_id

The fields in messages_user are set as foreign key to the according tables.

The function I want to archieve is:
I want to get all messages of a user, be it the one he created himself or he just received.

Current status:
I am able to get all messages a user created by using a inside my User-Model:

```<code>return $this->belongsToMany('App\Messages', 'messages_user');
</code>```

My problem currently is that I'm not able to get the received messages as well with one query. I could start a second query, but I'm sure their is a way to archieve that in another way.

Is that possible and if, how? :)

Thanks in advance!

答:
Please try this

Model users.php

```<code>class Users extends Model    {
   // Relation with messages_user table
      public function messages_user() {
         return $this->hasMany('App\Messages_user','id');
      }
}
</code>```

Model messages.php

```<code>class Messages extends Model    {
   // Relation with messages_user table
      public function messages_user() {
         return $this->hasMany('App\Messages_user','id');
      }
}
</code>```

Model messages_user.php

```<code> class Messages_user extends Model    {
   // Relation with users table
      public function send_user() {
         return $this->belongsTo('App\Users','user_id');
      }

      public function receive_user() {
         return $this->belongsTo('App\Users','receive_user_id');
      }
     // Relation with messages table
      public function messages() {
         return $this->belongsTo('App\Messages','messages_id');
      }

}
</code>```

In controller

```<code>   public function user_all_messages($id) {
      $data = Messages_user::with('send_user')
          ->with('receive_user')
          ->where('user_id', $id)
          ->orWhere('receive_user_id', $id)
          ->get();
   }
</code>```

Body:
I created 3 Database Tables:

users
 - id
 - username
 - ...

messages
 - id
 - title
 - message

messages_user
 - messages_id
 - user_id
 - receive_user_id

The fields in messages_user are set as foreign key to the according tables.

The function I want to archieve is:
I want to get all messages of a user, be it the one he created himself or he just received.

Current status:
I am able to get all messages a user created by using a inside my User-Model:

return $this->belongsToMany('App\Messages', 'messages_user');

My problem currently is that I'm not able to get the received messages as well with one query. I could start a second query, but I'm sure their is a way to archieve that in another way.

Is that possible and if, how? :)

Thanks in advance!

Body:
Please try this

Model users.php

class Users extends Model    {
   // Relation with messages_user table
      public function messages_user() {
         return $this->hasMany('App\Messages_user','id');
      }
}

Model messages.php

class Messages extends Model    {
   // Relation with messages_user table
      public function messages_user() {
         return $this->hasMany('App\Messages_user','id');
      }
}

Model messages_user.php

 class Messages_user extends Model    {
   // Relation with users table
      public function send_user() {
         return $this->belongsTo('App\Users','user_id');
      }

      public function receive_user() {
         return $this->belongsTo('App\Users','receive_user_id');
      }
     // Relation with messages table
      public function messages() {
         return $this->belongsTo('App\Messages','messages_id');
      }

}

In controller

   public function user_all_messages($id) {
      $data = Messages_user::with('send_user')
          ->with('receive_user')
          ->where('user_id', $id)
          ->orWhere('receive_user_id', $id)
          ->get();
   }

ContentLicense: CC BY-SA 4.0


问:
Best practise for declaring submodules using NgModule
I feel as if I have searched high and low for a reasonable answer to a question which must have been explained many times. Nonetheless, I am trying to find any way to declare module dependencies without needing to place it all within the app.module.ts file.

By declaring all dependencies within one file, it forces large applications to get unwieldy very quickly.

Is there a better way do this by declaring specific modules dependencies within a module?

Example of my current app.module.ts file

```<code>    import { NgModule } from '@angular/core';
    import { UniversalModule } from 'angular2-universal';
    import { ReactiveFormsModule, FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppComponent } from './components/app/app.component'
    import { NavMenuComponent } from './components/navmenu/navmenu.component';
    import { HomeComponent } from './components/home/home.component';
    import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
    import { CounterComponent } from './components/counter/counter.component';
    import { HeroDetailComponent } from './components/hero/hero-detail.component';
    import { HeroListComponent } from './components/hero/hero-list.component';
    import { HeroService } from './components/hero/hero.service';
    import { HeroDashboardComponent } from './components/hero/hero-dashboard.component';
    import { HeroMainComponent } from './components/hero/hero-main.component';
    import { HeroFormComponent } from './components/form/hero-form.component';
    import { HeroFormReactiveComponent } from './components/form-reactive/form-reactive.component';
    import { HeroFormReactiveMainComponent } from './components/form-reactive/form-main.component';
    import { ReactiveListComponent } from './components/form-reactive/hero-list.component';
    import { DataService } from './components/form-reactive/data.service';
    import { CoreTrackingMainComponent } from './components/core/coreTrackingMain.component';
    import { AppRoutingModule } from './app.routes'

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        HeroDetailComponent,
        HeroListComponent,
        HeroDashboardComponent,
        HeroMainComponent,
        HeroFormComponent,
        HeroFormReactiveComponent,
        HeroFormReactiveMainComponent,
        ReactiveListComponent,
        CoreTrackingMainComponent],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        HttpModule,
        FormsModule,
        AppRoutingModule,
        ReactiveFormsModule
    ],
    providers: [HeroService, DataService]
})
</code>```

Is it possible to declare some dependencies within these modules for example.

```<code>import { Component, NgModule } from '@angular/core';
import { CoreTrackingCriteriaComponent } from './coreTrackingCriteria.component';

@NgModule({
    declarations: [CoreTrackingCriteriaComponent],
    exports: [CoreTrackingCriteriaComponent]
})

@Component({
    selector: 'my-app',
    templateUrl: './coreTrackingMain.component.html'
})
export class CoreTrackingMainComponent { }
</code>```

I just cant seem to make it work without needing to declare everything within the module.app.ts

答:
If i read your question correctly what you are looking for is lazy loading modules:
https://angular.io/docs/ts/latest/guide/ngmodule.html#!#lazy-load

you define all your dependencies within that module and then in router load that module lazily.
nothing about it in root module.

Body:
I feel as if I have searched high and low for a reasonable answer to a question which must have been explained many times. Nonetheless, I am trying to find any way to declare module dependencies without needing to place it all within the app.module.ts file.

By declaring all dependencies within one file, it forces large applications to get unwieldy very quickly.

Is there a better way do this by declaring specific modules dependencies within a module?

Example of my current app.module.ts file

    import { NgModule } from '@angular/core';
    import { UniversalModule } from 'angular2-universal';
    import { ReactiveFormsModule, FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppComponent } from './components/app/app.component'
    import { NavMenuComponent } from './components/navmenu/navmenu.component';
    import { HomeComponent } from './components/home/home.component';
    import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
    import { CounterComponent } from './components/counter/counter.component';
    import { HeroDetailComponent } from './components/hero/hero-detail.component';
    import { HeroListComponent } from './components/hero/hero-list.component';
    import { HeroService } from './components/hero/hero.service';
    import { HeroDashboardComponent } from './components/hero/hero-dashboard.component';
    import { HeroMainComponent } from './components/hero/hero-main.component';
    import { HeroFormComponent } from './components/form/hero-form.component';
    import { HeroFormReactiveComponent } from './components/form-reactive/form-reactive.component';
    import { HeroFormReactiveMainComponent } from './components/form-reactive/form-main.component';
    import { ReactiveListComponent } from './components/form-reactive/hero-list.component';
    import { DataService } from './components/form-reactive/data.service';
    import { CoreTrackingMainComponent } from './components/core/coreTrackingMain.component';
    import { AppRoutingModule } from './app.routes'

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        HeroDetailComponent,
        HeroListComponent,
        HeroDashboardComponent,
        HeroMainComponent,
        HeroFormComponent,
        HeroFormReactiveComponent,
        HeroFormReactiveMainComponent,
        ReactiveListComponent,
        CoreTrackingMainComponent],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        HttpModule,
        FormsModule,
        AppRoutingModule,
        ReactiveFormsModule
    ],
    providers: [HeroService, DataService]
})

Is it possible to declare some dependencies within these modules for example.

import { Component, NgModule } from '@angular/core';
import { CoreTrackingCriteriaComponent } from './coreTrackingCriteria.component';

@NgModule({
    declarations: [CoreTrackingCriteriaComponent],
    exports: [CoreTrackingCriteriaComponent]
})

@Component({
    selector: 'my-app',
    templateUrl: './coreTrackingMain.component.html'
})
export class CoreTrackingMainComponent { }

I just cant seem to make it work without needing to declare everything within the module.app.ts


问:
Github, binding an issue to another issue to trigger next issue movement to a column
How can I bind an issue to another issue, such that it will trigger the other issue to do something?

In the upper example, when "explicit device" issue is moved to "finished" column, I want the "error handling"(leftmost) issue to move to "in progress" column automatically. Because I may not remember which needs what and what was which, needing to check all issues whenever an issue is finished and would become tiring after some point.

Even better, building an issue tree, finishing from ground up without stopping by all issues for just finding the closest root of an issue, isn't an option?

Another example:

add method is written: "issue1" complete

multiply method is written: "issue2" complete

suddenly, a multiply-add method as "issue3" pops in the beginning column or if it is already there, it moves to right by 1 column.

答:
The notion of project board presented in GitHub Universe 2016 is still lacking in term of fine-grained issue management.

That is why you have so many third-party integrations, including ZenHub (free for small teams and public account), which does have more features.

The point is: look for third-party integration (with a free offer) for your feature.


问:
How can i create a Multi-Dimensional array as the following in php?
Hi guys i am  trying to create a multi dimensional array as the format bellow but i am struggling to do so, any help would be appreciated. Thank you.

```<code>    $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
    $movies[] = $result;
    }

    foreach($movies as $k => $v){
    unset($movies[$k]);
    $movies[$v['Username']] = $v;
    }
    foreach($movies as $k => $v){
    unset($movies[$k]['Username']);
    }

    print_r($movies);
</code>```

This is what i am currently getting:

```<code>     [user1] => Array ( [Video_title] => Snakes on the Plane,
                                         Superman Returns,
                                         The Night Listner,
                                         Lady in the Water,
                                         Just my Luck,
                                         You me and Dupree
                         [Rating] => 3.5,
                                     3.5,
                                     3,
                                     2.5,
                                     3,
                                     2.5
                     ) )
</code>```

But i am aiming to output it in the following format:

```<code> 'user1' =>
          array('Lady in the Water' => 2.5,
                'Snakes on a Plane' => 3.5,
                'Just My Luck' => 3.0,
                'Superman Returns' => 3.5,
                'You, Me and Dupree' => 2.5,
                'The Night Listener' => 3.0
               )
</code>```

答:
Try this code for your aiming result:        </p>

```<code>    $movies = array();
    $sql = "

    SELECT u.username AS Username, v.title AS Video_title, r.rate AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
        $movies[$result['Username']][$result['Video_title']] = $result['Rating'];
    }

    print_r($movies);
</code>```

Body:
Hi guys i am  trying to create a multi dimensional array as the format bellow but i am struggling to do so, any help would be appreciated. Thank you.

    $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
    $movies[] = $result;
    }

    foreach($movies as $k => $v){
    unset($movies[$k]);
    $movies[$v['Username']] = $v;
    }
    foreach($movies as $k => $v){
    unset($movies[$k]['Username']);
    }

    print_r($movies);

This is what i am currently getting:

     [user1] => Array ( [Video_title] => Snakes on the Plane,
                                         Superman Returns,
                                         The Night Listner,
                                         Lady in the Water,
                                         Just my Luck,
                                         You me and Dupree
                         [Rating] => 3.5,
                                     3.5,
                                     3,
                                     2.5,
                                     3,
                                     2.5
                     ) )

But i am aiming to output it in the following format:

 'user1' =>
          array('Lady in the Water' => 2.5,
                'Snakes on a Plane' => 3.5,
                'Just My Luck' => 3.0,
                'Superman Returns' => 3.5,
                'You, Me and Dupree' => 2.5,
                'The Night Listener' => 3.0
               )

Body:
Try this code for your aiming result:

    $movies = array();
    $sql = "

    SELECT u.username AS Username, v.title AS Video_title, r.rate AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
        $movies[$result['Username']][$result['Video_title']] = $result['Rating'];
    }

    print_r($movies);


问:
Get last entered record for each item from mysql
how to join t_detail and t_header mysql, by group by item, by taking the last data record ?

```<code>id | doc | item | price
1  | 002 | asz  | 1200
2  | 002 | aqw  | 3000
3  | 002 | qwe  | 1300
4  | 005 | qwe  | 1000
5  | 005 | aqw  | 2000
</code>```

output

```<code>id | doc | item | price
1  | 002 | asz  | 1200
4  | 005 | qwe  | 1000
5  | 005 | aqw  | 2000
</code>```

答:
Try this,</p>

```<code>SELECT * FROM table WHERE id IN (SELECT MAX(id) FROM table GROUP BY item)
</code>```

Body:
how to join t_detail and t_header mysql, by group by item, by taking the last data record ?

id | doc | item | price
1  | 002 | asz  | 1200
2  | 002 | aqw  | 3000
3  | 002 | qwe  | 1300
4  | 005 | qwe  | 1000
5  | 005 | aqw  | 2000

output

id | doc | item | price
1  | 002 | asz  | 1200
4  | 005 | qwe  | 1000
5  | 005 | aqw  | 2000

Body:
Try this,

SELECT * FROM table WHERE id IN (SELECT MAX(id) FROM table GROUP BY item)


问:
Taking a line from a text file and putting them into a dictionary in python
I have a line in the following format:

```<code>Liam "!#123121" 32 "University of Southern California" "1312azasdas"
</code>```

I want to split this line in python such that for each line in a file, there is a name, age and university. In the above example, '32' is the age, 'Liam' is the name and 'University...' is the University name. What could be the best way to do this?

答:
Regular Expressions! They're a little confusing to get your head around to start with, but they're awesome. Too much to explain in full here, but a brief demo on your specific example:

```<code>import re

t = 'Liam "!#123121" 32 "University of Southern California" "1312azasdas"'

nau = re.match('([A-Za-z]+) ".*" ([0-9]+) "([A-Za-z ]+)" .*', t)
nau.groups()

>> ('Liam', '32', 'University of Southern California')
</code>```

Very brief breakdown of the regular expression:

Anything within round brackets is a 'group' - i.e. the bits you're interested in.

Anything in square brackets denotes a character set - which means 'match any of these characters', and the hyphen in A-Z means 'anything upper case between A and Z'.

The '+' after square brackets means that it's looking for 1 or more of the characters in the set, and only stops when it finds a character not in the set.

'.*' means match anything, but you'll notice that none of the .*'s I've used are in the groups - they're just used to skip irrelevant stuff between the groups.

Hoppe that helps!

Body:
I have a line in the following format:

Liam "!#123121" 32 "University of Southern California" "1312azasdas"

I want to split this line in python such that for each line in a file, there is a name, age and university. In the above example, '32' is the age, 'Liam' is the name and 'University...' is the University name. What could be the best way to do this?

Body:
Regular Expressions! They're a little confusing to get your head around to start with, but they're awesome. Too much to explain in full here, but a brief demo on your specific example:

import re

t = 'Liam "!#123121" 32 "University of Southern California" "1312azasdas"'

nau = re.match('([A-Za-z]+) ".*" ([0-9]+) "([A-Za-z ]+)" .*', t)
nau.groups()

>> ('Liam', '32', 'University of Southern California')

Very brief breakdown of the regular expression:

Anything within round brackets is a 'group' - i.e. the bits you're interested in.

Anything in square brackets denotes a character set - which means 'match any of these characters', and the hyphen in A-Z means 'anything upper case between A and Z'.

The '+' after square brackets means that it's looking for 1 or more of the characters in the set, and only stops when it finds a character not in the set.

'.*' means match anything, but you'll notice that none of the .*'s I've used are in the groups - they're just used to skip irrelevant stuff between the groups.

Hoppe that helps!


问:
Self calculated RGB values aren't matching with actual RGB values
I am working on a program where I take a portion of an image and calculate the average RGB of that image. When I calculate it I get totally different values as if I was to use the built in function. When I test my numbers and put them in an RGB color chart they are off while the built in function is very accurate. The problem with using the built in function is that it has literally no functionality. It just prints out what I calculate but I can't use that data. link to function called dump()

```<code>public void readSquares(Mat img){

    int width = 20;
    int height = 20;
    int rSum = 0;
    int gSum = 0;
    int bSum = 0;
    int rAvg = 0;
    int gAvg = 0;
    int bAvg = 0;

    Imgproc.cvtColor(img, img, Imgproc.COLOR_BGR2RGB);
    int channels = img.channels();

    int totalBytes = (int)(img.total() * img.channels());

    byte buff[] = new byte[totalBytes];
    img.get(0, 0, buff);

    for (int i=0; i< height; i++) {
        //stride is the number of bytes in a row of smallImg
        int stride = channels * width;
        for (int j=0; j<stride; j+=channels) {
            int r = buff[(i * stride) + j];
            int g = buff[(i * stride) + j + 1];
            int b = buff[(i * stride) + j + 2];

            if(r < 0 || g < 0 || b < 0){
                r = Math.abs(r);
                g = Math.abs(g);
                b = Math.abs(b);
            }

            rSum += r;
            gSum += g;
            bSum += b;

        }
    }

    rAvg = (int) (rSum / img.total()); //total pixels in picture
    gAvg = (int) (gSum / img.total());
    bAvg = (int) (bSum / img.total());
    System.out.println("R: " + rAvg);
    System.out.println("G: " + gAvg);
    System.out.println("B: " + bAvg);
</code>```

This below prints out the accurate values but I can't get the separate channels or find the average RGB it just spits everything out as a string which I can't utilize.

```<code>System.out.println(img.dump());
}
</code>```

Here is an example; I read Red image for pixels this was the output:

My Calculated

```<code>R:18
G:27
B:64
</code>```

The function
The first number represents the R second the G and third the B. It does that for every pixel in the image.

```<code>[237,  24,  60, 236,  23,  59, 236,  26,  56, 234,  25,  55, 238,  27,  62, 238,  27,  62, 238,  27,  62, 236,  25,  60, 234,  24,  59, 233,  23,  57, 234,  24,  59, 234,  24,  59, 235,  22,  59, 235,  22,  59, 237,  21,  59, 235,  20,  58, 237,  19,  56, 237,  19,  56, 239,  19,  52, 237,  18,  51;
 236,  24,  55, 237,  25,  56, 237,  25,  54, 237,  25,  54, 236,  26,  56, 237,  27,  57, 238,  28,  58, 239,  29,  59, 238,  27,  62, 234,  24,  59, 237,  24,  62, 237,  24,  62, 238,  22,  63, 237,  20,  61, 235,  20,  58, 235,  20,  58, 237,  19,  58, 239,  21,  61, 237,  19,  56, 236,  18,  55;
 238,  26,  57, 238,  26,  57, 234,  25,  53, 232,  23,  50, 236,  26,  54, 237,  27,  55, 237,  27,  55, 237,  27,  55, 237,  26,  61, 236,  25,  60, 237,  24,  62, 237,  24,  62, 238,  22,  63, 237,  20,  61, 238,  22,  63, 238,  22,  63, 238,  20,  61, 238,  20,  61, 237,  19,  56, 236,  18,  55;
 242,  30,  60, 240,  27,  58, 235,  24,  49, 233,  21,  47, 234,  22,  48, 237,  26,  52, 236,  25,  50, 237,  26,  52, 238,  26,  57, 237,  25,  56, 239,  23,  62, 239,  23,  62, 238,  22,  63, 238,  22,  63, 238,  19,  63, 239,  20,  65, 238,  20,  61, 239,  21,  63, 238,  20,  59, 236,  18,  57;
 240,  27,  62, 236,  23,  59, 236,  24,  53, 236,  24,  53, 235,  23,  51, 234,  22,  50, 235,  23,  51, 236,  24,  53, 237,  24,  60, 236,  23,  59, 237,  24,  64, 237,  24,  64, 237,  24,  64, 236,  22,  63, 238,  22,  63, 238,  22,  63, 237,  20,  61, 237,  20,  61, 237,  21,  59, 235,  20,  58;
 238,  25,  61, 237,  24,  60, 237,  24,  60, 237,  24,  60, 235,  22,  57, 236,  23,  59, 235,  22,  57, 235,  22,  57, 234,  21,  56, 236,  23,  59, 237,  24,  62, 236,  23,  61, 237,  20,  61, 237,  20,  61, 238,  21,  65, 238,  21,  65, 238,  22,  63, 237,  20,  61, 235,  22,  59, 235,  22,  59;
 238,  27,  62, 237,  26,  61, 237,  24,  60, 236,  23,  59, 236,  24,  55, 236,  24,  55, 236,  24,  55, 234,  22,  52, 237,  22,  53, 237,  22,  53, 237,  21,  57, 237,  21,  57, 237,  21,  59, 237,  21,  59, 237,  20,  61, 237,  20,  61, 236,  22,  63, 236,  22,  63, 236,  22,  63, 235,  21,  61;
 237,  26,  63, 236,  25,  62, 237,  24,  62, 237,  24,  62, 238,  25,  63, 237,  24,  62, 237,  21,  57, 238,  22,  59, 237,  21,  57, 237,  21,  57, 235,  20,  56, 235,  20,  56, 235,  20,  56, 237,  21,  57, 237,  21,  57, 238,  22,  59, 235,  23,  53, 236,  24,  55, 236,  24,  53, 236,  24,  53;
 236,  29,  69, 235,  28,  68, 238,  26,  70, 239,  27,  71, 240,  25,  68, 238,  24,  67, 237,  24,  64, 236,  22,  63, 237,  20,  61, 235,  19,  60, 237,  19,  58, 236,  18,  57, 237,  21,  59, 237,  21,  59, 238,  22,  59, 240,  25,  61, 237,  25,  56, 236,  24,  55, 236,  24,  53, 237,  25,  54;
 235,  28,  66, 235,  28,  66, 237,  25,  65, 240,  29,  68, 241,  27,  67, 238,  25,  65, 239,  23,  64, 238,  22,  63, 237,  19,  58, 237,  19,  58, 237,  17,  57, 237,  17,  57, 240,  20,  57, 241,  21,  59, 238,  21,  53, 239,  22,  55, 240,  26,  55, 238,  23,  53, 237,  22,  51, 237,  22,  51;
 237,  25,  69, 237,  25,  69, 239,  27,  73, 239,  27,  73, 240,  25,  70, 241,  26,  71, 239,  22,  66, 237,  20,  63, 238,  20,  61, 237,  18,  60, 236,  17,  59, 237,  18,  60, 238,  20,  59, 239,  21,  61, 238,  22,  59, 238,  22,  59, 239,  25,  54, 237,  22,  51, 237,  23,  49, 235,  22,  48;
 237,  25,  65, 238,  27,  66, 238,  27,  66, 238,  27,  66, 238,  27,  66, 237,  25,  65, 236,  22,  63, 235,  21,  61, 235,  22,  59, 235,  22,  59, 234,  18,  57, 237,  21,  59, 238,  22,  61, 238,  22,  61, 238,  22,  59, 238,  22,  59, 238,  20,  57, 238,  20,  57, 237,  20,  52, 237,  20,  52;
 236,  25,  60, 236,  25,  60, 238,  27,  62, 239,  29,  63, 237,  26,  61, 236,  25,  60, 237,  26,  61, 236,  25,  60, 236,  23,  59, 235,  22,  57, 236,  23,  59, 235,  22,  57, 237,  24,  60, 236,  23,  59, 238,  22,  59, 237,  21,  57, 237,  21,  57, 235,  20,  56, 236,  18,  55, 235,  17,  54;
 237,  25,  56, 238,  26,  57, 237,  27,  57, 237,  27,  57, 236,  26,  56, 237,  27,  57, 238,  28,  58, 237,  27,  57, 237,  27,  57, 238,  28,  58, 240,  27,  58, 237,  25,  56, 236,  23,  59, 236,  23,  59, 237,  21,  57, 237,  21,  57, 235,  20,  58, 235,  20,  58, 236,  18,  55, 236,  18,  55;
 237,  25,  54, 237,  25,  54, 237,  25,  54, 235,  23,  51, 237,  25,  56, 240,  27,  58, 237,  26,  61, 236,  25,  60, 237,  26,  63, 237,  26,  63, 238,  27,  66, 236,  24,  64, 237,  24,  64, 236,  22,  63, 237,  20,  61, 235,  19,  60, 236,  17,  59, 236,  17,  59, 236,  18,  57, 235,  16,  56;
 237,  25,  56, 237,  25,  56, 236,  23,  59, 238,  25,  61, 237,  24,  62, 238,  25,  63, 237,  24,  64, 238,  25,  65, 240,  25,  68, 238,  24,  67, 237,  23,  66, 237,  23,  66, 238,  21,  65, 238,  21,  65, 237,  20,  63, 237,  20,  63, 235,  19,  62, 235,  19,  62, 235,  19,  60, 235,  19,  60;
 237,  25,  56, 237,  25,  56, 237,  24,  60, 237,  24,  60, 237,  24,  64, 234,  20,  60, 237,  23,  66, 238,  24,  67, 238,  24,  69, 237,  23,  68, 236,  23,  70, 234,  22,  69, 236,  22,  67, 233,  18,  63, 236,  22,  65, 235,  21,  63, 236,  22,  63, 234,  20,  60, 235,  22,  59, 235,  22,  59;
 238,  27,  55, 238,  27,  55, 239,  24,  56, 241,  27,  58, 237,  24,  62, 237,  24,  62, 237,  23,  66, 238,  24,  67, 237,  24,  71, 237,  24,  71, 236,  23,  72, 234,  22,  71, 231,  19,  65, 236,  23,  70, 236,  24,  68, 236,  24,  68, 237,  24,  62, 236,  23,  61, 236,  24,  55, 238,  26,  57;
 239,  29,  63, 236,  25,  60, 236,  25,  62, 236,  25,  62, 236,  24,  64, 237,  25,  65, 234,  27,  67, 232,  26,  66, 238,  31,  74, 236,  29,  71, 234,  26,  71, 231,  24,  69, 232,  25,  70, 234,  26,  71, 236,  29,  71, 238,  31,  74, 235,  28,  68, 232,  26,  66, 237,  26,  63, 236,  25,  62;
 237,  24,  60, 237,  24,  60, 237,  26,  61, 236,  25,  60, 233,  22,  59, 234,  24,  61, 232,  26,  62, 234,  28,  63, 234,  27,  65, 234,  27,  65, 234,  26,  69, 234,  26,  69, 234,  26,  73, 234,  26,  73, 237,  29,  79, 238,  30,  80, 236,  29,  71, 234,  26,  69, 237,  26,  63, 238,  27,  64]
</code>```

答:
Strictly speaking, the Java Language Specification states that a byte data type has the range −128 - 127 and that's how Java will interpret a byte. If for instance a byte is promoted or cast to an int Java will interpret the first bit as a sign and use sign extension. There's no language support to help you interpret a byte differently. (There's, for instance, no unsigned keyword in Java.)

That being said, nothing prevents you from viewing a byte as an 8-bit value and interpret those bits as unsigned. Just keep in mind that there's nothing you can do to force your interpretation upon someone else's method. If a method accepts a byte, then that method accepts a value between −128 and 127 unless explicitly stated otherwise.

```<code>    public static int unsignedToBytes(byte b) {
        return b & 0xFF;
    }
</code>```

This method does what you asked. Hope this helps !!!

Edit: There are plenty of good answers on Stack Overflow and elsewhere. I would recommend you to try finding the answer before posting the question. Thanks.

Body:
I am working on a program where I take a portion of an image and calculate the average RGB of that image. When I calculate it I get totally different values as if I was to use the built in function. When I test my numbers and put them in an RGB color chart they are off while the built in function is very accurate. The problem with using the built in function is that it has literally no functionality. It just prints out what I calculate but I can't use that data. link to function called dump()

public void readSquares(Mat img){

    int width = 20;
    int height = 20;
    int rSum = 0;
    int gSum = 0;
    int bSum = 0;
    int rAvg = 0;
    int gAvg = 0;
    int bAvg = 0;

    Imgproc.cvtColor(img, img, Imgproc.COLOR_BGR2RGB);
    int channels = img.channels();

    int totalBytes = (int)(img.total() * img.channels());

    byte buff[] = new byte[totalBytes];
    img.get(0, 0, buff);

    for (int i=0; i< height; i++) {
        //stride is the number of bytes in a row of smallImg
        int stride = channels * width;
        for (int j=0; j<stride; j+=channels) {
            int r = buff[(i * stride) + j];
            int g = buff[(i * stride) + j + 1];
            int b = buff[(i * stride) + j + 2];

            if(r < 0 || g < 0 || b < 0){
                r = Math.abs(r);
                g = Math.abs(g);
                b = Math.abs(b);
            }

            rSum += r;
            gSum += g;
            bSum += b;

        }
    }

    rAvg = (int) (rSum / img.total()); //total pixels in picture
    gAvg = (int) (gSum / img.total());
    bAvg = (int) (bSum / img.total());
    System.out.println("R: " + rAvg);
    System.out.println("G: " + gAvg);
    System.out.println("B: " + bAvg);

This below prints out the accurate values but I can't get the separate channels or find the average RGB it just spits everything out as a string which I can't utilize.

System.out.println(img.dump());
}

Here is an example; I read Red image for pixels this was the output:

My Calculated

R:18
G:27
B:64

The function
The first number represents the R second the G and third the B. It does that for every pixel in the image.

[237,  24,  60, 236,  23,  59, 236,  26,  56, 234,  25,  55, 238,  27,  62, 238,  27,  62, 238,  27,  62, 236,  25,  60, 234,  24,  59, 233,  23,  57, 234,  24,  59, 234,  24,  59, 235,  22,  59, 235,  22,  59, 237,  21,  59, 235,  20,  58, 237,  19,  56, 237,  19,  56, 239,  19,  52, 237,  18,  51;
 236,  24,  55, 237,  25,  56, 237,  25,  54, 237,  25,  54, 236,  26,  56, 237,  27,  57, 238,  28,  58, 239,  29,  59, 238,  27,  62, 234,  24,  59, 237,  24,  62, 237,  24,  62, 238,  22,  63, 237,  20,  61, 235,  20,  58, 235,  20,  58, 237,  19,  58, 239,  21,  61, 237,  19,  56, 236,  18,  55;
 238,  26,  57, 238,  26,  57, 234,  25,  53, 232,  23,  50, 236,  26,  54, 237,  27,  55, 237,  27,  55, 237,  27,  55, 237,  26,  61, 236,  25,  60, 237,  24,  62, 237,  24,  62, 238,  22,  63, 237,  20,  61, 238,  22,  63, 238,  22,  63, 238,  20,  61, 238,  20,  61, 237,  19,  56, 236,  18,  55;
 242,  30,  60, 240,  27,  58, 235,  24,  49, 233,  21,  47, 234,  22,  48, 237,  26,  52, 236,  25,  50, 237,  26,  52, 238,  26,  57, 237,  25,  56, 239,  23,  62, 239,  23,  62, 238,  22,  63, 238,  22,  63, 238,  19,  63, 239,  20,  65, 238,  20,  61, 239,  21,  63, 238,  20,  59, 236,  18,  57;
 240,  27,  62, 236,  23,  59, 236,  24,  53, 236,  24,  53, 235,  23,  51, 234,  22,  50, 235,  23,  51, 236,  24,  53, 237,  24,  60, 236,  23,  59, 237,  24,  64, 237,  24,  64, 237,  24,  64, 236,  22,  63, 238,  22,  63, 238,  22,  63, 237,  20,  61, 237,  20,  61, 237,  21,  59, 235,  20,  58;
 238,  25,  61, 237,  24,  60, 237,  24,  60, 237,  24,  60, 235,  22,  57, 236,  23,  59, 235,  22,  57, 235,  22,  57, 234,  21,  56, 236,  23,  59, 237,  24,  62, 236,  23,  61, 237,  20,  61, 237,  20,  61, 238,  21,  65, 238,  21,  65, 238,  22,  63, 237,  20,  61, 235,  22,  59, 235,  22,  59;
 238,  27,  62, 237,  26,  61, 237,  24,  60, 236,  23,  59, 236,  24,  55, 236,  24,  55, 236,  24,  55, 234,  22,  52, 237,  22,  53, 237,  22,  53, 237,  21,  57, 237,  21,  57, 237,  21,  59, 237,  21,  59, 237,  20,  61, 237,  20,  61, 236,  22,  63, 236,  22,  63, 236,  22,  63, 235,  21,  61;
 237,  26,  63, 236,  25,  62, 237,  24,  62, 237,  24,  62, 238,  25,  63, 237,  24,  62, 237,  21,  57, 238,  22,  59, 237,  21,  57, 237,  21,  57, 235,  20,  56, 235,  20,  56, 235,  20,  56, 237,  21,  57, 237,  21,  57, 238,  22,  59, 235,  23,  53, 236,  24,  55, 236,  24,  53, 236,  24,  53;
 236,  29,  69, 235,  28,  68, 238,  26,  70, 239,  27,  71, 240,  25,  68, 238,  24,  67, 237,  24,  64, 236,  22,  63, 237,  20,  61, 235,  19,  60, 237,  19,  58, 236,  18,  57, 237,  21,  59, 237,  21,  59, 238,  22,  59, 240,  25,  61, 237,  25,  56, 236,  24,  55, 236,  24,  53, 237,  25,  54;
 235,  28,  66, 235,  28,  66, 237,  25,  65, 240,  29,  68, 241,  27,  67, 238,  25,  65, 239,  23,  64, 238,  22,  63, 237,  19,  58, 237,  19,  58, 237,  17,  57, 237,  17,  57, 240,  20,  57, 241,  21,  59, 238,  21,  53, 239,  22,  55, 240,  26,  55, 238,  23,  53, 237,  22,  51, 237,  22,  51;
 237,  25,  69, 237,  25,  69, 239,  27,  73, 239,  27,  73, 240,  25,  70, 241,  26,  71, 239,  22,  66, 237,  20,  63, 238,  20,  61, 237,  18,  60, 236,  17,  59, 237,  18,  60, 238,  20,  59, 239,  21,  61, 238,  22,  59, 238,  22,  59, 239,  25,  54, 237,  22,  51, 237,  23,  49, 235,  22,  48;
 237,  25,  65, 238,  27,  66, 238,  27,  66, 238,  27,  66, 238,  27,  66, 237,  25,  65, 236,  22,  63, 235,  21,  61, 235,  22,  59, 235,  22,  59, 234,  18,  57, 237,  21,  59, 238,  22,  61, 238,  22,  61, 238,  22,  59, 238,  22,  59, 238,  20,  57, 238,  20,  57, 237,  20,  52, 237,  20,  52;
 236,  25,  60, 236,  25,  60, 238,  27,  62, 239,  29,  63, 237,  26,  61, 236,  25,  60, 237,  26,  61, 236,  25,  60, 236,  23,  59, 235,  22,  57, 236,  23,  59, 235,  22,  57, 237,  24,  60, 236,  23,  59, 238,  22,  59, 237,  21,  57, 237,  21,  57, 235,  20,  56, 236,  18,  55, 235,  17,  54;
 237,  25,  56, 238,  26,  57, 237,  27,  57, 237,  27,  57, 236,  26,  56, 237,  27,  57, 238,  28,  58, 237,  27,  57, 237,  27,  57, 238,  28,  58, 240,  27,  58, 237,  25,  56, 236,  23,  59, 236,  23,  59, 237,  21,  57, 237,  21,  57, 235,  20,  58, 235,  20,  58, 236,  18,  55, 236,  18,  55;
 237,  25,  54, 237,  25,  54, 237,  25,  54, 235,  23,  51, 237,  25,  56, 240,  27,  58, 237,  26,  61, 236,  25,  60, 237,  26,  63, 237,  26,  63, 238,  27,  66, 236,  24,  64, 237,  24,  64, 236,  22,  63, 237,  20,  61, 235,  19,  60, 236,  17,  59, 236,  17,  59, 236,  18,  57, 235,  16,  56;
 237,  25,  56, 237,  25,  56, 236,  23,  59, 238,  25,  61, 237,  24,  62, 238,  25,  63, 237,  24,  64, 238,  25,  65, 240,  25,  68, 238,  24,  67, 237,  23,  66, 237,  23,  66, 238,  21,  65, 238,  21,  65, 237,  20,  63, 237,  20,  63, 235,  19,  62, 235,  19,  62, 235,  19,  60, 235,  19,  60;
 237,  25,  56, 237,  25,  56, 237,  24,  60, 237,  24,  60, 237,  24,  64, 234,  20,  60, 237,  23,  66, 238,  24,  67, 238,  24,  69, 237,  23,  68, 236,  23,  70, 234,  22,  69, 236,  22,  67, 233,  18,  63, 236,  22,  65, 235,  21,  63, 236,  22,  63, 234,  20,  60, 235,  22,  59, 235,  22,  59;
 238,  27,  55, 238,  27,  55, 239,  24,  56, 241,  27,  58, 237,  24,  62, 237,  24,  62, 237,  23,  66, 238,  24,  67, 237,  24,  71, 237,  24,  71, 236,  23,  72, 234,  22,  71, 231,  19,  65, 236,  23,  70, 236,  24,  68, 236,  24,  68, 237,  24,  62, 236,  23,  61, 236,  24,  55, 238,  26,  57;
 239,  29,  63, 236,  25,  60, 236,  25,  62, 236,  25,  62, 236,  24,  64, 237,  25,  65, 234,  27,  67, 232,  26,  66, 238,  31,  74, 236,  29,  71, 234,  26,  71, 231,  24,  69, 232,  25,  70, 234,  26,  71, 236,  29,  71, 238,  31,  74, 235,  28,  68, 232,  26,  66, 237,  26,  63, 236,  25,  62;
 237,  24,  60, 237,  24,  60, 237,  26,  61, 236,  25,  60, 233,  22,  59, 234,  24,  61, 232,  26,  62, 234,  28,  63, 234,  27,  65, 234,  27,  65, 234,  26,  69, 234,  26,  69, 234,  26,  73, 234,  26,  73, 237,  29,  79, 238,  30,  80, 236,  29,  71, 234,  26,  69, 237,  26,  63, 238,  27,  64]

Body:
Strictly speaking, the Java Language Specification states that a byte data type has the range −128 - 127 and that's how Java will interpret a byte. If for instance a byte is promoted or cast to an int Java will interpret the first bit as a sign and use sign extension. There's no language support to help you interpret a byte differently. (There's, for instance, no unsigned keyword in Java.)

That being said, nothing prevents you from viewing a byte as an 8-bit value and interpret those bits as unsigned. Just keep in mind that there's nothing you can do to force your interpretation upon someone else's method. If a method accepts a byte, then that method accepts a value between −128 and 127 unless explicitly stated otherwise.

    public static int unsignedToBytes(byte b) {
        return b & 0xFF;
    }

This method does what you asked. Hope this helps !!!

Edit: There are plenty of good answers on Stack Overflow and elsewhere. I would recommend you to try finding the answer before posting the question. Thanks.


问:
How do you pass a value to an API in Swift?
I am pretty much a beginner in Swift and I am trying to pass a value to make a call to an API with the value being from an input field.
The API is given below. How do I write code to pass value for ZIP_CODE from a text field?

https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/ZIP_CODE/JSON

```<code>@IBOutlet var zipLabel: UILabel!
@IBOutlet var zipInput: UITextField!
@IBOutlet var jsondataLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    getJSON()
}

@IBAction func btnAction() {
    zipLabel.text = zipInput.text
}

func getJSON(){
    let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON")
    let request = URLRequest(url: url as! URL )
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request){(data, response, error ) -> Void in
        if error == nil{
            DispatchQueue.main.async(execute: {
                let jsondata = JSON(data : data!)

                print(jsondata)
                print("-----")
                print(jsondata[0]["UV_INDEX"])

                let result =  jsondata[0]["UV_INDEX"].stringValue

                self.jsondataLabel.text = result
            })
        }else{
            print("There was an error")
        }
    }
    task.resume()
}
</code>```

答:
```<code>func getJSON(_ zipcode : Int){

            let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/\(zipcode)/JSON")

            let request = URLRequest(url: url as! URL )

            let config = URLSessionConfiguration.default

            let session = URLSession(configuration: config)

            let task = session.dataTask(with: request){(data, response, error ) -> Void in

                if error == nil{

                    DispatchQueue.main.async(execute: {

                        let jsondata = JSON(data : data!)

                        print(jsondata)

                        print("-----")

                        print(jsondata[0]["UV_INDEX"])

                        let result =  jsondata[0]["UV_INDEX"].stringValue

                        self.jsondataLabel.text = result
                    })

                }else{

                    print("There was an error")
                }

            }
            task.resume()
    }
</code>```

Body:
I am pretty much a beginner in Swift and I am trying to pass a value to make a call to an API with the value being from an input field.
The API is given below. How do I write code to pass value for ZIP_CODE from a text field?

https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/ZIP_CODE/JSON

@IBOutlet var zipLabel: UILabel!
@IBOutlet var zipInput: UITextField!
@IBOutlet var jsondataLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    getJSON()
}

@IBAction func btnAction() {
    zipLabel.text = zipInput.text
}

func getJSON(){
    let url = NSURL(string :"https://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/10001/JSON")
    let request = URLRequest(url: url as! URL )
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request){(data, response, error ) -> Void in
        if error == nil{
            DispatchQueue.main.async(execute: {
                let jsondata = JSON(data : data!)

                print(jsondata)
                print("-----")
                print(jsondata[0]["UV_INDEX"])

                let result =  jsondata[0]["UV_INDEX"].stringValue

                self.jsondataLabel.text = result
            })
        }else{
            print("There was an error")
        }
    }
    task.resume()
}


问:
Updating to latest Swift version problems
I just updated to the latest version of Swift and I am getting issues with a breakpoint error. There are no errors in the console.

```<code>backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height))
self.view.addSubview(backgroundsetting)
</code>```

Then after the update it wanted me to set the backgroundsetting.frame as! CGRect and it crashes the app when I open that part of the app. Why is this occurring? Here is the after code:

```<code>backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height)) as! CGRect
self.view.addSubview(backgroundsetting)
</code>```

答:
If you are using constraint for your view and then use height:self.view.frame.size.height and width:self.view.frame.size.width , it will not show proper height and width as compare to your iPhone screen.

For that its better to use UIScreen size i.e      UIScreen.main.bounds.height and UIScreen.main.bounds.width , it will always show original width and height of your iPhone.

```<code>    backgroundsetting.frame = CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) as! CGRect
    self.view.addSubview(backgroundsetting)
</code>```

Body:
I just updated to the latest version of Swift and I am getting issues with a breakpoint error. There are no errors in the console.

backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height))
self.view.addSubview(backgroundsetting)

Then after the update it wanted me to set the backgroundsetting.frame as! CGRect and it crashes the app when I open that part of the app. Why is this occurring? Here is the after code:

backgroundsetting.innerColor = UIColor.rgb(fromHex: 0xB0E7D7)

backgroundsetting.outterColor = UIColor.rgb(fromHex: 0x005E7D)

backgroundsetting.frame = (frame: CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:self.view.frame.size.width, height: self.view.frame.size.height)) as! CGRect
self.view.addSubview(backgroundsetting)

Body:
If you are using constraint for your view and then use height:self.view.frame.size.height and width:self.view.frame.size.width , it will not show proper height and width as compare to your iPhone screen.

For that its better to use UIScreen size i.e      UIScreen.main.bounds.height and UIScreen.main.bounds.width , it will always show original width and height of your iPhone.

    backgroundsetting.frame = CGRect(x: self.view.frame.size.width * 0, y: self.view.frame.size.height * 0, width:UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) as! CGRect
    self.view.addSubview(backgroundsetting)


问:
Converting ES5 Mixins to Higher Order Components
In my project I'm trying to get rid of all the mixins and replace them with HOCs. I am stuck using ES5 at the moment.

```<code>export default React.createClass({
  mixins: [SomeAsyncMixin],
  data: {
    item1: {
      params: ({params, query}) => {
        params: ({params, query}) => {
          if (!query.p) {
              return null;
          }
          const status = someTernaryResult
          return {
              groups: query.groups,
              status,
              subject: params.subject,
          };
        },
        promise: query => query && query.subject && api(makeUrl(`/some/endpoint`, query))
      },

    item2: {
        params: ({params, query}) => {
          //same as before
        },
        promise: ({subject, query}) =>
          // same as before
    }

    render() {
      // some stuff

      return(
        // some jsx
      );
    }
}
</code>```

Inside of the mixin, it has a componentWillMount and a componentWillUpdate that runs an update function that will loop through each key on data and update the props/state.

In React's docs about removing mixins, their mixins hold the data, not the component.

There are MANY components in my project that have a data object and use this mixin to update their props/state. How do I make a reusable component to handle this data object?

Also, how do I even access this data object from within the component? In the component this.data is null. Inside of the mixin this.data is the data object from inside the component.. why?

答:
Your higher order component and mixin will look very similar. The main difference will be how data, props, and state are shared/passed. In the mixin case, you are altering your component's definition with the mixin's behavior, so the state and props are all in the one resulting component.

In the higher order component case, you are creating a new component that wraps around your other component. Thus, the shared state/behavior is entirely contained within wrapping component, and any data that needs to be used within the wrapped component can be passed via props.

So from what you have in your example, your higher order component would be something like

```<code>const someAsync = (data) => (WrappedComponent) => {
    class SomeAsyncComponent extends React.Component {
        constructor(...args) {
            super(...args)

            this.state = {
                ...
            }
        }

        componentWillMount() {
            // Make use of data, props, state, etc
            ...
        }

        componentWillUpdate() {
            ...
        }

        render() {
            // May filter out some props/state, depending on what is needed
            // Can also pass data through if the WrappedComponent needs it.
            return (
                <WrappedComponent
                    { ...this.props }
                    { ...this.state }
                />
            )
        }
    }

    return SomeAsyncComponent
}
</code>```

And then your usage of it

```<code>export default someAsync(dataConfig)(WrappedComponent)
</code>```

Body:
In my project I'm trying to get rid of all the mixins and replace them with HOCs. I am stuck using ES5 at the moment.

export default React.createClass({
  mixins: [SomeAsyncMixin],
  data: {
    item1: {
      params: ({params, query}) => {
        params: ({params, query}) => {
          if (!query.p) {
              return null;
          }
          const status = someTernaryResult
          return {
              groups: query.groups,
              status,
              subject: params.subject,
          };
        },
        promise: query => query && query.subject && api(makeUrl(`/some/endpoint`, query))
      },

    item2: {
        params: ({params, query}) => {
          //same as before
        },
        promise: ({subject, query}) =>
          // same as before
    }

    render() {
      // some stuff

      return(
        // some jsx
      );
    }
}

Inside of the mixin, it has a componentWillMount and a componentWillUpdate that runs an update function that will loop through each key on data and update the props/state.

In React's docs about removing mixins, their mixins hold the data, not the component.

There are MANY components in my project that have a data object and use this mixin to update their props/state. How do I make a reusable component to handle this data object?

Also, how do I even access this data object from within the component? In the component this.data is null. Inside of the mixin this.data is the data object from inside the component.. why?

Body:
Your higher order component and mixin will look very similar. The main difference will be how data, props, and state are shared/passed. In the mixin case, you are altering your component's definition with the mixin's behavior, so the state and props are all in the one resulting component.

In the higher order component case, you are creating a new component that wraps around your other component. Thus, the shared state/behavior is entirely contained within wrapping component, and any data that needs to be used within the wrapped component can be passed via props.

So from what you have in your example, your higher order component would be something like

const someAsync = (data) => (WrappedComponent) => {
    class SomeAsyncComponent extends React.Component {
        constructor(...args) {
            super(...args)

            this.state = {
                ...
            }
        }

        componentWillMount() {
            // Make use of data, props, state, etc
            ...
        }

        componentWillUpdate() {
            ...
        }

        render() {
            // May filter out some props/state, depending on what is needed
            // Can also pass data through if the WrappedComponent needs it.
            return (
                <WrappedComponent
                    { ...this.props }
                    { ...this.state }
                />
            )
        }
    }

    return SomeAsyncComponent
}

And then your usage of it

export default someAsync(dataConfig)(WrappedComponent)


问:
"GetLatest" with Powershell doesn't download files on new TFS workspace
I'm trying to create a Powershell script that will setup a brand new workspace in a temporary location, do a GetLatest on selected solutions/projects, and download the source code so that I can then trigger further build/versioning operations.

I think I have the script more or less right, but the problem is every time I run this, it tells me there were 0 operations... i.e. I already have the latest versions. This results in nothing at all being downloaded.

Can anyone see what I'm doing wrong?

```<code>$subfolder = [System.Guid]::NewGuid().ToString()
$tfsServer = "http://tfsserver:8080/tfs"
$projectsAndWorkspaces = @(
    @("$/Client1/Project1","D:\Builds\$subfolder\Client1\Project1"),
    @("$/Client1/Project2","D:\Builds\$subfolder\Client1\Project2"),
)

$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$tfsVersionCtrl = $tfsCollection.GetService([type] "Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer")
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthorizedUser)

Write-Host "Operations:"

foreach ($projectAndWs in $projectsAndWorkspaces)
{
    if (-not(Test-Path $projectAndWs[1]))
    {
        New-Item -ItemType Directory -Force -Path $projectAndWs[1] | Out-Null
    }

    $tfsWorkspace.Map($projectAndWs[0], $projectAndWs[1])
    $recursion = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
    $itemSpecFullTeamProj = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectAndWs[0], $recursion)
    $fileRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($itemSpecFullTeamProj, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
    $getStatus = $tfsWorkspace.Get($fileRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite)
    Write-Host ("[{0}] {1}" -f $getStatus.NumOperations, ($projectAndWs[0].Substring($projectAndWs[0].LastIndexOf("/") + 1)))
}

Write-Host "Finished"
</code>```

答: The $tfsServer = "http://tfsserver:8080/tfs" should be $tfsServer = "http://tfsserver:8080/tfs/nameOfACollection"

Body:
I'm trying to create a Powershell script that will setup a brand new workspace in a temporary location, do a GetLatest on selected solutions/projects, and download the source code so that I can then trigger further build/versioning operations.

I think I have the script more or less right, but the problem is every time I run this, it tells me there were 0 operations... i.e. I already have the latest versions. This results in nothing at all being downloaded.

Can anyone see what I'm doing wrong?

$subfolder = [System.Guid]::NewGuid().ToString()
$tfsServer = "http://tfsserver:8080/tfs"
$projectsAndWorkspaces = @(
    @("$/Client1/Project1","D:\Builds\$subfolder\Client1\Project1"),
    @("$/Client1/Project2","D:\Builds\$subfolder\Client1\Project2"),
)

$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$tfsVersionCtrl = $tfsCollection.GetService([type] "Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer")
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthorizedUser)

Write-Host "Operations:"

foreach ($projectAndWs in $projectsAndWorkspaces)
{
    if (-not(Test-Path $projectAndWs[1]))
    {
        New-Item -ItemType Directory -Force -Path $projectAndWs[1] | Out-Null
    }

    $tfsWorkspace.Map($projectAndWs[0], $projectAndWs[1])
    $recursion = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
    $itemSpecFullTeamProj = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectAndWs[0], $recursion)
    $fileRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($itemSpecFullTeamProj, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
    $getStatus = $tfsWorkspace.Get($fileRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite)
    Write-Host ("[{0}] {1}" -f $getStatus.NumOperations, ($projectAndWs[0].Substring($projectAndWs[0].LastIndexOf("/") + 1)))
}

Write-Host "Finished"


问:
How to change Action Bar/Title Bar font?
Not sure if this is called the action bar or the title bar but I need to change the font to a font I have in my assets folder. How do I do this?

答:
You can try the following :-

ActionBar actionBar=getSupportActionBar();

actionBar.setTitle("New Title");