问:
Activity not opening after signing in
I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.

```<code>{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}
</code>```

But while using the app, it does not go to the mainActivity.
This is the login class:-

```<code>public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;

EditText mEdtEmail , mEdtPassword ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Answers(), new Crashlytics());
    setContentView(R.layout.activity_login);

    login1 = (Button) findViewById(R.id.button);
    mEdtEmail = (EditText) findViewById(R.id.phone_number);
    mEdtPassword = (EditText) findViewById(R.id.password);

    session = new Session(login.this);

    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(login.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

   // sign_in();

    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String mobile = mEdtEmail.getText().toString().trim();
            String password = mEdtPassword.getText().toString().trim();

            status = checkInternetConnection();

            if (status) {

                if (mobile.length() == 0) {
                    mEdtEmail.setError("Required");
                } else if (mobile.length() < 10) {
                    mEdtEmail.setError("Mobile no must be 10 char. long");
                } else if (password.length() == 0) {
                    mEdtPassword.setError("Required");
                } else {

                    new UserLoginTask(mobile, password, login.this).execute();

                }
            }
            else
            {
                Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
                //  Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
            }
        }
    });
}

private class UserLoginTask extends AsyncTask<String, Void, String> {

    private String mUserName;
    private String mPassword;
    String msg ;
    ProgressDialog progressDialog;

    Boolean loginStatus = false;
    private Activity activity;
    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;

    UserLoginTask(String userName, String password, Activity activity) {
        mUserName = userName;
        mPassword = password;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
        Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            String result= WebService.postHttpResponse(mUserName, mPassword, activity);

            JSONObject jsonObject = new JSONObject(result);
          //  Log.d("Json Array", "doInBackground: "+jsonObject);
           String status = jsonObject.optString("error");
         //   msg = jsonObject.optString("msg");
           // Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
            if(status.equals("0")){

                loginStatus = true ;

                session.setLogin(true);

                JSONArray jsonarray = jsonObject.getJSONArray("data");
                JSONObject jsonObject1=jsonarray.getJSONObject(0);

                status = jsonObject1.getString("msg");
                Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));

                Driver driver = new Driver();

                driver.setId(jsonObject1.getString("id"));
                driver.setDriver_name(jsonObject1.getString("driver_name"));
                driver.setDriver_lat(jsonObject1.getString("driver_lat"));
                driver.setDriver_long(jsonObject1.getString("driver_long"));
                driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
                driver.setDriver_token(jsonObject1.getString("driver_token"));
                driver.setCreated_at(jsonObject1.getString("created_at"));
                driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));

                sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedpreferences.edit();

                editor.putString("driver_name",jsonObject1.getString("driver_name"));
                editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
                editor.putString("id", jsonObject1.getString("id"));
                editor.putString("driver_token", jsonObject1.getString("driver_token"));
                editor.putString("driver_image", jsonObject1.getString("driver_image"));
                editor.putString("current_order_no", "");

                editor.commit();
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));

                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                finish();

            }

            else {
            }

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

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

        }

        return msg ;

    }

    @Override
    protected void onPostExecute(String msg) {
        super.onPostExecute(msg);

        progressDialog.dismiss();
        Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();

    }
}

/*public void sign_in(){
    login1=(Button)findViewById(R.id.button);
    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();

            startActivity(intent);
        }
    });
}*/
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce){
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true ;
    Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false ;
        }
    }, 2000);

    /*Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    System.exit(0);*/

}

public boolean checkInternetConnection()
{

    ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null)
    {
        NetworkInfo[] inf = connectivity.getAllNetworkInfo();
        if (inf != null)
            for (int i = 0; i < inf.length; i++)
                if (inf[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
}
}
</code>```

Please Help!
Thanks!!

EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!

答:
Here you are getting JSONObject in response from server.

This object contains three values:

error

data

msg

error contains error code in integer format.

data contains JSONArray which contain the details of the driver.

msg contains the message in String format.

So you need to write

```<code>JSONObject jsonObject = new JSONObject(result);
int code = jsonObject.getString("error");
if (code == 0) {
    JSONArray jsonarray = jsonObject.getJSONArray("data");
    JSONObject data = jsonarray.getJSONObject(0);
    String msg = jsonObject.getString("msg");
    driver = new Driver();
    ...
}
</code>```

and remove this from doInBackground method

```<code>Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
</code>```

and write this code in onPostExecute method after displaying Toast

```<code>...
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
...
</code>```

You need to declare Driver in UserLoginTask after ProgressDialog like

```<code>...
ProgressDialog progressDialog;
Driver driver;
</code>```

Title: Activity not opening after signing in

Body:
I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.

{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}

But while using the app, it does not go to the mainActivity.
This is the login class:-

public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;

EditText mEdtEmail , mEdtPassword ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Answers(), new Crashlytics());
    setContentView(R.layout.activity_login);

    login1 = (Button) findViewById(R.id.button);
    mEdtEmail = (EditText) findViewById(R.id.phone_number);
    mEdtPassword = (EditText) findViewById(R.id.password);

    session = new Session(login.this);

    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(login.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

   // sign_in();

    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String mobile = mEdtEmail.getText().toString().trim();
            String password = mEdtPassword.getText().toString().trim();

            status = checkInternetConnection();

            if (status) {

                if (mobile.length() == 0) {
                    mEdtEmail.setError("Required");
                } else if (mobile.length() < 10) {
                    mEdtEmail.setError("Mobile no must be 10 char. long");
                } else if (password.length() == 0) {
                    mEdtPassword.setError("Required");
                } else {

                    new UserLoginTask(mobile, password, login.this).execute();

                }
            }
            else
            {
                Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
                //  Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
            }
        }
    });
}

private class UserLoginTask extends AsyncTask<String, Void, String> {

    private String mUserName;
    private String mPassword;
    String msg ;
    ProgressDialog progressDialog;

    Boolean loginStatus = false;
    private Activity activity;
    public static final String MyPREFERENCES = "MyPrefs" ;
    SharedPreferences sharedpreferences;

    UserLoginTask(String userName, String password, Activity activity) {
        mUserName = userName;
        mPassword = password;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
        Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            String result= WebService.postHttpResponse(mUserName, mPassword, activity);

            JSONObject jsonObject = new JSONObject(result);
          //  Log.d("Json Array", "doInBackground: "+jsonObject);
           String status = jsonObject.optString("error");
         //   msg = jsonObject.optString("msg");
           // Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
            if(status.equals("0")){

                loginStatus = true ;

                session.setLogin(true);

                JSONArray jsonarray = jsonObject.getJSONArray("data");
                JSONObject jsonObject1=jsonarray.getJSONObject(0);

                status = jsonObject1.getString("msg");
                Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));

                Driver driver = new Driver();

                driver.setId(jsonObject1.getString("id"));
                driver.setDriver_name(jsonObject1.getString("driver_name"));
                driver.setDriver_lat(jsonObject1.getString("driver_lat"));
                driver.setDriver_long(jsonObject1.getString("driver_long"));
                driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
                driver.setDriver_token(jsonObject1.getString("driver_token"));
                driver.setCreated_at(jsonObject1.getString("created_at"));
                driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));

                sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedpreferences.edit();

                editor.putString("driver_name",jsonObject1.getString("driver_name"));
                editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
                editor.putString("id", jsonObject1.getString("id"));
                editor.putString("driver_token", jsonObject1.getString("driver_token"));
                editor.putString("driver_image", jsonObject1.getString("driver_image"));
                editor.putString("current_order_no", "");

                editor.commit();
                startActivity(intent);
                activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));

                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                finish();

            }

            else {
            }

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

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

        }

        return msg ;

    }

    @Override
    protected void onPostExecute(String msg) {
        super.onPostExecute(msg);

        progressDialog.dismiss();
        Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();

    }
}

/*public void sign_in(){
    login1=(Button)findViewById(R.id.button);
    login1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();

            startActivity(intent);
        }
    });
}*/
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce){
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true ;
    Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false ;
        }
    }, 2000);

    /*Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    System.exit(0);*/

}

public boolean checkInternetConnection()
{

    ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null)
    {
        NetworkInfo[] inf = connectivity.getAllNetworkInfo();
        if (inf != null)
            for (int i = 0; i < inf.length; i++)
                if (inf[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
}
}

Please Help!
Thanks!!

EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!

Body:
Here you are getting JSONObject in response from server.

This object contains three values:

error

data

msg

error contains error code in integer format.

data contains JSONArray which contain the details of the driver.

msg contains the message in String format.

So you need to write

JSONObject jsonObject = new JSONObject(result);
int code = jsonObject.getString("error");
if (code == 0) {
    JSONArray jsonarray = jsonObject.getJSONArray("data");
    JSONObject data = jsonarray.getJSONObject(0);
    String msg = jsonObject.getString("msg");
    driver = new Driver();
    ...
}

and remove this from doInBackground method

Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();

and write this code in onPostExecute method after displaying Toast

...
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
...

You need to declare Driver in UserLoginTask after ProgressDialog like

...
ProgressDialog progressDialog;
Driver driver;


来源: stackexchange

问:
Why do we need a default no argument constructor in Java?
Why do we need a default no argument constructor in many Java related APIs? Like as a general rule all java bean classes or entity classes (JPA etc) or JAX-WS implementation classes require a explicit no argument constructor.

If by default Java provides a no argument constructor then why most of these standards require a explicit constructor?

答:
Java only provides a default no-argument constructor if no other constructors are defined. Thus, if you have other constructors you must explicitly define a no-arg constructor yourself.

These frameworks use the reflection API and look at method names to determine how to set properties. The arguments of a constructor can only be found by type, not by name, so there is no way for the  framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.

Some frameworks may support @ConstructorProperties as an alternative.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to display total number of records using smart table in AngularJS
I am using smart-table for displaying the records.
Using custom pagination to display the records 20 per page.

I want to display pagination like :  1 - 20 of 25 Records
How can I accomplish this ?
- I tried using (num of pages * total pages), but this will round the result.

答:
First of all your should create Directive

```<code>ticketsApp.directive('stSummary', function () {

    return {
    restrict: 'E',
    require: '^stTable',
    template:'<span><b>[[pagination.start ]]  of [[pagination.totalItemCount]] items</b></span>',
    scope: {},
    link: function (scope, element, attr, ctrl) {
      var listener = function (val) {
        scope.pagination = ctrl.tableState().pagination;
        scope.to = Math.min(scope.pagination.start + scope.pagination.number, scope.total || 0);
      };
      scope.$watch(ctrl.tableState(), listener, true);
    }
  }
});`
</code>```

After that you should use "stSummary"  Tag in your view.
Ex :

```<code><st-summary st-items-by-page="10"
            class="pull-right"
            class="pagination-info itemCountnumber">
</st-summary>`
</code>```

Body:
First of all your should create Directive

ticketsApp.directive('stSummary', function () {

    return {
    restrict: 'E',
    require: '^stTable',
    template:'<span><b>[[pagination.start ]]  of [[pagination.totalItemCount]] items</b></span>',
    scope: {},
    link: function (scope, element, attr, ctrl) {
      var listener = function (val) {
        scope.pagination = ctrl.tableState().pagination;
        scope.to = Math.min(scope.pagination.start + scope.pagination.number, scope.total || 0);
      };
      scope.$watch(ctrl.tableState(), listener, true);
    }
  }
});`

After that you should use "stSummary"  Tag in your view.
Ex :

<st-summary st-items-by-page="10"
            class="pull-right"
            class="pagination-info itemCountnumber">
</st-summary>`


问:
gettext or font issue?
I have just moved a website from one host to another and I am having an issue with displaying other languages.  It was working perfectly on the old server but I'm not sure where to start looking for the problem.

As you can see the fonts display fine in the select box but not in the main page.  I am using a font I have used many times before and never had issues with it.

Any suggestions on were to start looking for the problem?

答:
OK found the solution on another website not sure why but on this new server I needed an extra piece of code to make gettext work correctly.

```<code>bind_textdomain_codeset($domain, 'UTF-8');
</code>```

Previously I only had,

```<code>bindtextdomain($domain, "Locale");
textdomain($domain);
</code>```

but for some reason this new server required the extra line?  For interest's sake if anyone can explain the difference I would love to hear.

Title: gettext or font issue?

Body:
OK found the solution on another website not sure why but on this new server I needed an extra piece of code to make gettext work correctly.

bind_textdomain_codeset($domain, 'UTF-8');

Previously I only had,

bindtextdomain($domain, "Locale");
textdomain($domain);

but for some reason this new server required the extra line?  For interest's sake if anyone can explain the difference I would love to hear.


问:
How can I import Swift code to Objective-C?
I have written a library in Swift and I wasn't able to import it to my current project, written in Objective-C.

Are there any ways to import it?

```<code>#import "SCLAlertView.swift" - 'SCLAlertView.swift' file not found
</code>```

答:
Importing Swift file inside Objective-c can cause this error, if it doesn't import properly.

NOTE: You don't have to import Swift files externally, you just have to import one file which takes care of swift files.

When you Created/Copied Swift file inside Objective-C project. It would've created a bridging header automatically.

Check Objective-C Generated Interface Header Name at Targets -> Build Settings.

Based on above, I will import KJExpandable-Swift.h as it is.

Your's will be TargetName-Swift.h, Where TargetName differs based on your project name or another target your might have added and running on it.

As below my target is KJExpandable, so it's KJExpandable-Swift.h

Body:
I have written a library in Swift and I wasn't able to import it to my current project, written in Objective-C.

Are there any ways to import it?

#import "SCLAlertView.swift" - 'SCLAlertView.swift' file not found


问:
Unmarshaller and schema in JAXB
I have application that can save file in various formats (all of them is xml). So I should solve problem with determination in what format file have been saved. So, I see 2 solutions

different formats have different schemas, so I could determine it by them.
I set schemas in way that I get from here

marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "bla-bla.xsd");

so I suppose I can get it using unmarshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION)

but it throwing

javax.xml.bind.PropertyException:
  jaxb.noNamespaceSchemaLocation

and getSchema()  return null
So, how can I get schema location?

Specifying different adapters for different beans using  setAdapter(Class type, A adapter) method

What way is preferable? If first, then how can I get schema location label?

upd code example
suppose we have bean

```<code>@XmlRootElement
public class Foo{
    String bar;
    public String getBar() {return bar; }
    public void setBar(String bar) {this.bar = bar;}
}
</code>```

and code that generates schema, saves Foo's instances and loads then.

```<code>public class Test {
    final static String schemaLoc = "fooschema.xsd";

    public static void write(File file, Foo foo, Schema schema) throws Throwable {
        XMLEventWriter xsw = null;
        try{
            JAXBContext context = JAXBContext.newInstance(Foo.class);
            XMLOutputFactory xof = XMLOutputFactory.newInstance();
            OutputStream out = new FileOutputStream(file);
            xsw = xof.createXMLEventWriter(out);
            Marshaller m = context.createMarshaller();
            m.setSchema(schema);    //schema setted
            System.out.println(">>>marchal : " + m.getSchema());    //check it
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, schemaLoc);
            m.marshal(foo, xsw);
        } finally{
             xsw.close();
        }
    }

    public static Foo load(File file) throws Throwable {
        JAXBContext context = JAXBContext.newInstance(Foo.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        System.out.println("unmarshaller schema:" + unmarshaller.getSchema());  //I need get it here
    //  System.out.println("schema_prop:" + unmarshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION));

        InputStreamReader in = new InputStreamReader(new FileInputStream(file));
        XMLEventReader xer = XMLInputFactory.newInstance()
                .createXMLEventReader(in);
        return Foo.class.cast(unmarshaller.unmarshal(xer));
    }

    private static File createSchema(String schemaLocation) throws Throwable{
        final File target = new File(schemaLocation);
        if(!target.exists()){
            JAXBContext jaxbContext = JAXBContext.newInstance(Foo.class);
            SchemaOutputResolver sor = new SchemaOutputResolver() {
                public Result createOutput(String namespaceURI, String suggestedFileName)
                throws IOException {
                    StreamResult result = new StreamResult(target);
                    result.setSystemId(target.toURI().toURL().toString());
                    return result;
                }
            };
            jaxbContext.generateSchema(sor);
        }
        return target;
    }

    public static void main(String[] args) throws Throwable {
        createSchema(schemaLoc);
        File file = new File("temp.xml");
        Foo foo = new Foo();
        foo.setBar("test bar");
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(createSchema(schemaLoc));
        write(file, foo, schema);
        System.out.println("result " + load(file).getBar());
    }

}
</code>```

schema that generates

```<code>      <xs:element name="foo" type="foo"/>

      <xs:complexType name="foo">
        <xs:sequence>
          <xs:element name="bar" type="xs:string" minOccurs="0"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
</code>```

our temp file

```<code><?xml version="1.0"?>
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="fooschema.xsd">
<bar>test bar</bar></foo>
</code>```

as we see, there is

xsi:noNamespaceSchemaLocation="fooschema.xsd"

How I can get this text using JAXB?

答:
I would leverage a StAX parser to get this information (see example below).  Create an XMLStreamReader on the input.  Advance the XMLStreamReader to the root element using the nextTag() method.  Then grab the noNamespaceSchemaLocation attribute of the root element.  Then pass the XMLStreamReader to the unmarshal(XMLStreamReader) method on Unmarshaller.

```<code>import java.io.FileInputStream;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(Categories.class);

        XMLInputFactory xif = XMLInputFactory.newInstance();
        FileInputStream fis = new FileInputStream("input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);
        xsr.nextTag();
        String noNamespaceSchemaLocation = xsr.getAttributeValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "noNamespaceSchemaLocation");
        System.out.println(noNamespaceSchemaLocation);

        Unmarshaller um = context.createUnmarshaller();
        Categories response = (Categories) um.unmarshal(xsr);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Unmarshaller and schema in JAXB

Body:
I have application that can save file in various formats (all of them is xml). So I should solve problem with determination in what format file have been saved. So, I see 2 solutions

different formats have different schemas, so I could determine it by them.
I set schemas in way that I get from here

marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "bla-bla.xsd");

so I suppose I can get it using unmarshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION)

but it throwing

javax.xml.bind.PropertyException:
  jaxb.noNamespaceSchemaLocation

and getSchema()  return null
So, how can I get schema location?

Specifying different adapters for different beans using  setAdapter(Class type, A adapter) method

What way is preferable? If first, then how can I get schema location label?

upd code example
suppose we have bean

@XmlRootElement
public class Foo{
    String bar;
    public String getBar() {return bar; }
    public void setBar(String bar) {this.bar = bar;}
}

and code that generates schema, saves Foo's instances and loads then.

public class Test {
    final static String schemaLoc = "fooschema.xsd";

    public static void write(File file, Foo foo, Schema schema) throws Throwable {
        XMLEventWriter xsw = null;
        try{
            JAXBContext context = JAXBContext.newInstance(Foo.class);
            XMLOutputFactory xof = XMLOutputFactory.newInstance();
            OutputStream out = new FileOutputStream(file);
            xsw = xof.createXMLEventWriter(out);
            Marshaller m = context.createMarshaller();
            m.setSchema(schema);    //schema setted
            System.out.println(">>>marchal : " + m.getSchema());    //check it
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, schemaLoc);
            m.marshal(foo, xsw);
        } finally{
             xsw.close();
        }
    }

    public static Foo load(File file) throws Throwable {
        JAXBContext context = JAXBContext.newInstance(Foo.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        System.out.println("unmarshaller schema:" + unmarshaller.getSchema());  //I need get it here
    //  System.out.println("schema_prop:" + unmarshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION));

        InputStreamReader in = new InputStreamReader(new FileInputStream(file));
        XMLEventReader xer = XMLInputFactory.newInstance()
                .createXMLEventReader(in);
        return Foo.class.cast(unmarshaller.unmarshal(xer));
    }

    private static File createSchema(String schemaLocation) throws Throwable{
        final File target = new File(schemaLocation);
        if(!target.exists()){
            JAXBContext jaxbContext = JAXBContext.newInstance(Foo.class);
            SchemaOutputResolver sor = new SchemaOutputResolver() {
                public Result createOutput(String namespaceURI, String suggestedFileName)
                throws IOException {
                    StreamResult result = new StreamResult(target);
                    result.setSystemId(target.toURI().toURL().toString());
                    return result;
                }
            };
            jaxbContext.generateSchema(sor);
        }
        return target;
    }

    public static void main(String[] args) throws Throwable {
        createSchema(schemaLoc);
        File file = new File("temp.xml");
        Foo foo = new Foo();
        foo.setBar("test bar");
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(createSchema(schemaLoc));
        write(file, foo, schema);
        System.out.println("result " + load(file).getBar());
    }

}

schema that generates

      <xs:element name="foo" type="foo"/>

      <xs:complexType name="foo">
        <xs:sequence>
          <xs:element name="bar" type="xs:string" minOccurs="0"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>

our temp file

<?xml version="1.0"?>
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="fooschema.xsd">
<bar>test bar</bar></foo>

as we see, there is

xsi:noNamespaceSchemaLocation="fooschema.xsd"

How I can get this text using JAXB?

Body:
I would leverage a StAX parser to get this information (see example below).  Create an XMLStreamReader on the input.  Advance the XMLStreamReader to the root element using the nextTag() method.  Then grab the noNamespaceSchemaLocation attribute of the root element.  Then pass the XMLStreamReader to the unmarshal(XMLStreamReader) method on Unmarshaller.

import java.io.FileInputStream;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(Categories.class);

        XMLInputFactory xif = XMLInputFactory.newInstance();
        FileInputStream fis = new FileInputStream("input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);
        xsr.nextTag();
        String noNamespaceSchemaLocation = xsr.getAttributeValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "noNamespaceSchemaLocation");
        System.out.println(noNamespaceSchemaLocation);

        Unmarshaller um = context.createUnmarshaller();
        Categories response = (Categories) um.unmarshal(xsr);
    }
}


问:
Why after the use "free()" the value of the memory adress is always 0?
I have this code:

```<code>int * m = (int *)malloc(sizeof(int));
printf("%p %i\n", m, *m);
(*m) = 6;
printf("%p %i\n", m, *m);
free(m);
printf("%p %i\n", m, *m);
</code>```

I run it on Linux. Why the value of the memory address is always 0?

Why if I run it on Windows this value changes?

答:
Let us see the C11 standard, chapter §7.22.3.3.

The free function causes the space pointed to by ptr to be deallocated, that is, made
  available for further allocation. [....]

So, that means, the pointer which was passed to free() is no longer a "valid" pointer in your program context. Thereby, attempting to access the pointer, you're essentially accessing an invalid memory which causes undefined behavior.

Now, what actually happens to the memory location and to the content of the memory location, is depending on the memory manager or the OS. It could just be left as-is, unless it is required to be allocated again by some further calls, it could either be zeroed-out, anything...that is beyond the C standard specification.

Then, I'm not preaching for the coding style, but I personally find it handy to set any free-d pointer to NULL immediately after free(). "Most of the time", this will prevent any further use of the pointer (via a segfault), as NULL is definitely an invalid pointer in all context.

That said, some points regarding your code snippet,

Please see this discussion on why not to cast the return value of malloc() and family in C..

You must cast the argument to %p to void * as printf() is a variadic function and there's no default argument promotion applicable.

Body:
I have this code:

int * m = (int *)malloc(sizeof(int));
printf("%p %i\n", m, *m);
(*m) = 6;
printf("%p %i\n", m, *m);
free(m);
printf("%p %i\n", m, *m);

I run it on Linux. Why the value of the memory address is always 0?

Why if I run it on Windows this value changes?


问:
Why doesn't hadoop allows to use VIM to edit files?
Why doesn't hadoop allows to use VIM to edit files. I want to edit modify files using an editor using HDFS command line.</p>

答:
you can copy this 5 line script and them use

```<code>hvim <your filename>
</code>```

And the script code:

```<code>hadoop fs -text $1>hvim.txt
vim hvim.txt
hadoop fs -rm -skipTrash $1
hadoop fs -copyFromLocal hvim.txt $1
rm hvim.txt
</code>```

Body:
you can copy this 5 line script and them use

hvim <your filename>

And the script code:

hadoop fs -text $1>hvim.txt
vim hvim.txt
hadoop fs -rm -skipTrash $1
hadoop fs -copyFromLocal hvim.txt $1
rm hvim.txt


问:
wp_remote_get() not passing authentication
I've been trying to use wp_remote_get for the first time and having some troubles.

So far I'm testing the response with this code:

```<code><?php
                    $url      = "https://webapieu3.filefinderanywhere.com/SeussConsultingTestWebportAPI/xml/AllActive";
                    $username = 'username';
                    $password = 'password';
                    $headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ), "sslverify" => false );
                    $response = wp_remote_get($url, $headers);

                    if (is_wp_error($response)){
                        echo $response->get_error_message();
                    }else{
                        print_r($response);
                    }

                 ?>
</code>```

Prior to adding the sslverify param, is_wp_error returned true, but now it's returning false, however I'm getting the following response:

```<code>Array (
    [headers] => Array (
        [cache-control] => no-cache
        [pragma] => no-cache
        [content-type] => application/json; charset=utf-8
        [expires] => -1
        [server] => Microsoft-IIS/7.5
        [www-authenticate] => Basic
        [x-aspnet-version] => 4.0.30319
        [x-powered-by] => ASP.NET
        [date] => Mon, 30 Nov 2015 00:56:09 GMT
        [connection] => close [content-length] => 61 )

    [body] => {"Message":"Authorization has been denied for this request."}
    [response] => Array (
        [code] => 401
        [message] => Unauthorized )

    [cookies] => Array ( )
    [filename] => )
</code>```

Why is there a 401 error after I've already passed authentication? And how do I pass authentication?

答:
```<code>$wp_request_headers = array(
    'Authorization' => 'Basic ' . base64_encode( 'username:password' )
);

$wp_request_url = 'http://localserver/wordpress-api/wp-json/wp/v2/posts/52';

$wp_delete_post_response = wp_remote_request(
    $wp_request_url,
    array(
        'method'    => 'DELETE',
        'headers'   => $wp_request_headers
    )
);

echo wp_remote_retrieve_response_code( $wp_delete_post_response ) . ' ' . wp_remote_retrieve_response_message( $wp_delete_post_response );
</code>```

Body:
I've been trying to use wp_remote_get for the first time and having some troubles.

So far I'm testing the response with this code:

<?php
                    $url      = "https://webapieu3.filefinderanywhere.com/SeussConsultingTestWebportAPI/xml/AllActive";
                    $username = 'username';
                    $password = 'password';
                    $headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ), "sslverify" => false );
                    $response = wp_remote_get($url, $headers);

                    if (is_wp_error($response)){
                        echo $response->get_error_message();
                    }else{
                        print_r($response);
                    }

                 ?>

Prior to adding the sslverify param, is_wp_error returned true, but now it's returning false, however I'm getting the following response:

Array (
    [headers] => Array (
        [cache-control] => no-cache
        [pragma] => no-cache
        [content-type] => application/json; charset=utf-8
        [expires] => -1
        [server] => Microsoft-IIS/7.5
        [www-authenticate] => Basic
        [x-aspnet-version] => 4.0.30319
        [x-powered-by] => ASP.NET
        [date] => Mon, 30 Nov 2015 00:56:09 GMT
        [connection] => close [content-length] => 61 )

    [body] => {"Message":"Authorization has been denied for this request."}
    [response] => Array (
        [code] => 401
        [message] => Unauthorized )

    [cookies] => Array ( )
    [filename] => )

Why is there a 401 error after I've already passed authentication? And how do I pass authentication?


问:
Can you use an Azure Function to trigger an Azure Logic App?
The time triggers within Logic Apps aren't really specific enough to meet my scheduling requirements, but using the scheduler looks overly expensive for our needs.

I see that functions can use CRON for timed triggering, so wondered if functions can actually be used to call Logic Apps, and hence have the Logic Apps triggered by the CRON time schedules?

答:
Yes, this should be possible. You can invoke the flow from an Azure Function. You will have to call the Logic App endpoint workflow from the Azure Function. To start with look at this blogpost: Invoking Flows from another Logic App

In your Azure function you can use HttpWebRequest or other mechanisms to call the Logic App endpoint.


问:
dynamic_cast to derived type with unknown template argument
I would like to dynamic_cast to a templated derived type, with unknown template argument:

```<code>struct A {
    virtual void f() { };
};

template <std::size_t N>
struct B : public A { };
</code>```

With the known template argument the cast can be performed as:

```<code>const A& base_ref = B<N>();
const B<N>& ref = dynamic_cast<const B<N>&>(base_ref);
</code>```

My question is about the case where the value of the template argument (N) is not known.

I was wondering if there is a way to obtain the object type, in this case B<N> from the base class pointer/reference, such that the dynamic_cast template parameter can be inferred automatically?

P.S. In the considered case the template argument is an integer type, and is used as a template parameter for an std::array.

答:
If you have just a few possible values of N, then you can try dynamic_cast'ing to each of them. Otherwise, the answer is:

No. As a compile time constant, no. If you don't need a compile time constant, then you can do this:

```<code>struct AWithN {
  int n;

  AWithN(int n_) : n(n_) { }
};

template <std::size_t N>
struct B: public AWithN {
  B() : AWithN(N) { }
};
</code>```

And you can dynamic_cast to AWithN, from where you can get n.

Body:
I would like to dynamic_cast to a templated derived type, with unknown template argument:

struct A {
    virtual void f() { };
};

template <std::size_t N>
struct B : public A { };

With the known template argument the cast can be performed as:

const A& base_ref = B<N>();
const B<N>& ref = dynamic_cast<const B<N>&>(base_ref);

My question is about the case where the value of the template argument (N) is not known.

I was wondering if there is a way to obtain the object type, in this case B<N> from the base class pointer/reference, such that the dynamic_cast template parameter can be inferred automatically?

P.S. In the considered case the template argument is an integer type, and is used as a template parameter for an std::array.

Body:
If you have just a few possible values of N, then you can try dynamic_cast'ing to each of them. Otherwise, the answer is:

No. As a compile time constant, no. If you don't need a compile time constant, then you can do this:

struct AWithN {
  int n;

  AWithN(int n_) : n(n_) { }
};

template <std::size_t N>
struct B: public AWithN {
  B() : AWithN(N) { }
};

And you can dynamic_cast to AWithN, from where you can get n.


问:
CoreData/Entity error does not disappear even though there is no more entity
I am facing a CoreData related issue, and keep getting this error message:

```<code>Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

More precisely, before the message above is displayed, I can see these details:

```<code><unknown>:0: error: filename "NiceEntity+CoreDataProperties.swift" used twice: '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift' and '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name
</code>```

I know I made some wrong manipulations when first setting up the entity NiceEntity, but I have removed everything that I could see related to this entity. That is I removed the entity NiceEntity from the data model and I erased the DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht folder. And yet the error has not disappeared.

Anyone has an idea on how to solve that?

In case this may be useful, I am using Xcode Version 8.3.2.

答:
My suggestion you "Reset Content and Settings" again in the simulator to make sure you have a clean foundation again.
Also Clean Build Folder.

Hope it helps,
Cheers glnj

Body:
I am facing a CoreData related issue, and keep getting this error message:

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

More precisely, before the message above is displayed, I can see these details:

<unknown>:0: error: filename "NiceEntity+CoreDataProperties.swift" used twice: '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift' and '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name

I know I made some wrong manipulations when first setting up the entity NiceEntity, but I have removed everything that I could see related to this entity. That is I removed the entity NiceEntity from the data model and I erased the DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht folder. And yet the error has not disappeared.

Anyone has an idea on how to solve that?

In case this may be useful, I am using Xcode Version 8.3.2.


问:
How to create an observableCollection Sortable and multithreading
Here is my problem , I have created a SortableCollection : ObservableCollection
and added a sort method (sort colors).
When I sort The collection with the principal Thread , it works every thing is fine and works
But When I try to sort this customCollection by using an item in the collection  I have an expetion : (The calling thread cannot access this object because a different thread owns it).
I have looked in web and I found several solution , One Solution

This type of solution put the collection multithread for insertion , removing moving operation.
But not for the custom sort.
Thanks for help,

答:
WPF classes have thread affinity.  What this means is that all changes to those objects must be in the same thread where they were created.  It truly is difficult to create a user interface API that is thread-safe, so Microsoft chose to keep it singlethreaded and force run-time checking to make sure of it.

That said, there are a few options you have to perform your sort in a background thread, and then apply it in the UI thread.  The first option is to copy your SortableCollection into a plain old List or Array and perform the sort in the background.  Once the background thread is complete, you use a Dispatcher to execute code in the UI thread.  Every UI element in WPF extends System.Windows.Threading.DispatcherObject and most extend System.Windows.Freezable.  The DispatcherObject is where you get the Dispatcher to execute code in the UI thread.

Logically, the execution would be something like this:

```<code>public void BackgroundSort()
{
    List<T> items = new List<T>(this.ToArray());
    BackgroundSortDelegate del = Sort;

    del.BeginInvoke(SortCompleted, del);
}

private void SortCompleted(IAsyncResult result)
{
    BackgroundSortDelegate del = result.AsyncState as BackgroundSortDelegate;

    List<T> items = del.EndInvoke(result);
    this.Dispatcher.Invoke(()=>{this.Collection = items;});
}
</code>```

The short explanation of what happened is that the background worker/delegate is using a copy of the items in this list.  Once the sort is complete, we are calling the Dispatcher object and invoking an action.  In that action we are assigning the new sorted list back to our object.

The key to assigning the result of any background work within the UI thread is to use the UI's Dispatcher object.  There's actually probably a half dozen ways to invoke a background worker in C#, but the approach to get your work in a background thread into the UI thread is the same.

Body:
WPF classes have thread affinity.  What this means is that all changes to those objects must be in the same thread where they were created.  It truly is difficult to create a user interface API that is thread-safe, so Microsoft chose to keep it singlethreaded and force run-time checking to make sure of it.

That said, there are a few options you have to perform your sort in a background thread, and then apply it in the UI thread.  The first option is to copy your SortableCollection into a plain old List or Array and perform the sort in the background.  Once the background thread is complete, you use a Dispatcher to execute code in the UI thread.  Every UI element in WPF extends System.Windows.Threading.DispatcherObject and most extend System.Windows.Freezable.  The DispatcherObject is where you get the Dispatcher to execute code in the UI thread.

Logically, the execution would be something like this:

public void BackgroundSort()
{
    List<T> items = new List<T>(this.ToArray());
    BackgroundSortDelegate del = Sort;

    del.BeginInvoke(SortCompleted, del);
}

private void SortCompleted(IAsyncResult result)
{
    BackgroundSortDelegate del = result.AsyncState as BackgroundSortDelegate;

    List<T> items = del.EndInvoke(result);
    this.Dispatcher.Invoke(()=>{this.Collection = items;});
}

The short explanation of what happened is that the background worker/delegate is using a copy of the items in this list.  Once the sort is complete, we are calling the Dispatcher object and invoking an action.  In that action we are assigning the new sorted list back to our object.

The key to assigning the result of any background work within the UI thread is to use the UI's Dispatcher object.  There's actually probably a half dozen ways to invoke a background worker in C#, but the approach to get your work in a background thread into the UI thread is the same.


问:
minimize a list of items to one item in Ionic
I have a form.There's different parts in that form.Every part is separated by a heading.What i want to achieve is when i click on the heading,the items under it will disappear.
i'll show what i want to do

wanted design

As you see there's a minimize button.when clicked the button will change to a maximize button.A plus sign

Here's what i made so far
my design

I really don't know how to make this.i suppose some kind of css

Thank you for any help

答:
Solved it by using jquery SlideToggle

```<code>  $(".buttonh").click(function(){
if($(this).html() == "-"){
    $(this).html("+");
}
else{
    $(this).html("-");
}
$("#ion-item2").slideToggle();
});
</code>```

You'll need to add jquery in index.html

Body:
Solved it by using jquery SlideToggle

  $(".buttonh").click(function(){
if($(this).html() == "-"){
    $(this).html("+");
}
else{
    $(this).html("-");
}
$("#ion-item2").slideToggle();
});

You'll need to add jquery in index.html


问:
Tkinter - How to use option 'foreground' for some text in Entry widget?
Here is my code:

```<code>from tkinter import *
root = Tk()
root.title("Punctured Convolution Encoder dan Viterbi Decoder")
root.geometry("1350x655+0+0")

frame_input = LabelFrame(root, text="Input")
frame_input.place(x=20, y=10, width=400, height=200)

# input#
lbl_in = Label(frame_input, text="Input", font=("Arial", 16))
lbl_in.place(x=10, y=20)
bin_in = Entry(frame_input, font=('Gill Sans MT', 16))
bin_in.place(x=130, y=20, width=240)

def klik_proses():
    bin_in.selection_range(1,2)
    bin_in.config(foreground="red")
    bin_in.selection_range(4,5)
    bin_in.config(foreground="red")

btn_proses = Button(frame_input, text="test", width=12, command=klik_proses)
btn_proses.place(x=140, y=100)

root.mainloop()
</code>```

The result is the color of the whole text in entry widget was changed, when I pressed the button.
How can I change color for some text in the entry widget?

e.g:
I enter 123456789 in the entry box, then I want to change text color for number 2 and 5.
So, there are 2 numbers have red color and the others have black color.

答:
It is not possible to change the color of only part of the text in an Entry, but it is possible in a Text widget using tags. So I suggest you to create a one line Text widget.

Here is an example:

```<code>import tkinter as tk

def change_color():
    entry.tag_add('red', '1.1')
    entry.tag_add('red', '1.4')

root = tk.Tk()

entry = tk.Text(root, height=1, width=20)
entry.tag_configure('red', foreground='red')
entry.bind('<Return>', lambda e: "break")  # prevent newlines
entry.insert('1.0', '123456789')

entry.pack()
tk.Button(root, text='Change color', command=change_color).pack()
root.mainloop()
</code>```

You can find more information about the Text widget on this website .

Body:
Here is my code:

from tkinter import *
root = Tk()
root.title("Punctured Convolution Encoder dan Viterbi Decoder")
root.geometry("1350x655+0+0")

frame_input = LabelFrame(root, text="Input")
frame_input.place(x=20, y=10, width=400, height=200)

# input#
lbl_in = Label(frame_input, text="Input", font=("Arial", 16))
lbl_in.place(x=10, y=20)
bin_in = Entry(frame_input, font=('Gill Sans MT', 16))
bin_in.place(x=130, y=20, width=240)

def klik_proses():
    bin_in.selection_range(1,2)
    bin_in.config(foreground="red")
    bin_in.selection_range(4,5)
    bin_in.config(foreground="red")

btn_proses = Button(frame_input, text="test", width=12, command=klik_proses)
btn_proses.place(x=140, y=100)

root.mainloop()

The result is the color of the whole text in entry widget was changed, when I pressed the button.
How can I change color for some text in the entry widget?

e.g:
I enter 123456789 in the entry box, then I want to change text color for number 2 and 5.
So, there are 2 numbers have red color and the others have black color.

Body:
It is not possible to change the color of only part of the text in an Entry, but it is possible in a Text widget using tags. So I suggest you to create a one line Text widget.

Here is an example:

import tkinter as tk

def change_color():
    entry.tag_add('red', '1.1')
    entry.tag_add('red', '1.4')

root = tk.Tk()

entry = tk.Text(root, height=1, width=20)
entry.tag_configure('red', foreground='red')
entry.bind('<Return>', lambda e: "break")  # prevent newlines
entry.insert('1.0', '123456789')

entry.pack()
tk.Button(root, text='Change color', command=change_color).pack()
root.mainloop()

You can find more information about the Text widget on this website .


问:
Rest Api Best practice - Passing date as query param
I am writing a rest service using NodeJs and express middleware. I have below questions -

I have to take userid and token for authentication in every service irrespective of the method type i.e. GET, POST, PUT and DELETE. What is the best way to take these two param i.e  as request header or query param? I don't want to take it as body params since the get requests wouldn't have the body.

I want to write a service with method type GET for data retrieval, the params for this call are string and a date. How shoule I pass the params as query parameter for this, specifically the date param should i pass it as js date or any other format?

```<code>GET - https://localhost:someport/<objectid>/<createddate>
headers - x-user-id:someid
          x-access-token:sometoken
</code>```

if this then which format the created date should be passed.

or should I use the below one?

```<code>GET - https://localhost:someport/
headers - x-user-id:someid
          x-access-token:sometoken
          x-object-id:someid
          x-created-date:somedate
</code>```

答:
Request header is the best place to send those kind of sensitive information. Header is common in all method of http request. Therefor you don't want to worry about the method like GET, POST, PUT. if you use query parameters, it will we more ugly in the urls.
 Additionally, I have no idea of the usage of UserID with token. Because in restful server we use the token to identify the user also. Therefor in general we don't send user id.

Body:
I am writing a rest service using NodeJs and express middleware. I have below questions -

I have to take userid and token for authentication in every service irrespective of the method type i.e. GET, POST, PUT and DELETE. What is the best way to take these two param i.e  as request header or query param? I don't want to take it as body params since the get requests wouldn't have the body.

I want to write a service with method type GET for data retrieval, the params for this call are string and a date. How shoule I pass the params as query parameter for this, specifically the date param should i pass it as js date or any other format?

GET - https://localhost:someport/<objectid>/<createddate>
headers - x-user-id:someid
          x-access-token:sometoken

if this then which format the created date should be passed.

or should I use the below one?

GET - https://localhost:someport/
headers - x-user-id:someid
          x-access-token:sometoken
          x-object-id:someid
          x-created-date:somedate


问:
How to compare elements consisting of two values? (pareto optimum)
I am pretty new to Python and I want to perform some sort of Pareto optimum. It is somewhat difficult to explain, so I hope my question will be clear enough to understand.

I have the following model which consists of a list of 5 doors (list: ‘doors’) and each door contains two costs (shown in dictionary ‘cost’): [travel distance, delay]. I would like to compare the costs of each door with the costs of another door. However, there is no dominant cost. This means I want a list of doors with the best solution (minimize cost) for both costs.

```<code>doors = ['D1', 'D2', 'D3', 'D4', 'D5']

# cost: [travel distance, delay]
cost = {
'D1': [150, 0],
'D2': [160, 0],
'D3': [170, 1],
'D4': [140, 2],
'D5': [150, 0]
}

def test(doors):
    for s in doors:
        for d in doors:
            if s != d:
                if cost[s][0] < cost[d][0] and cost[s][1] < cost[d][1]:
                    doors.remove(d)
    return doors

print(test(doors))
</code>```

For instance: D1, D2, D5 both have delay cost of 0. If I would only look for the door with minimum delay cost all three doors will do. However, D2 has a travel distance of 160 which is bigger than 150. Therefore, you would never choose D2 (compared to D1 and D5), since it consists of the same delay value and a worse travel distance value. So we would like D2 to be removed from the list.

For travel distance cost, you would choose D4 since it has the lowest travel distance: 140. Although it has the highest delay, there is no door which outperforms D4 due to the low travel distance.

So eventually I want a list with doors for which one of the cost is minimum with the best value for the other cost.
Based on this, I would like to have the following output:

best_doors = [‘D1’, ‘D4’,  ‘D5’].

In my model, I try to compare both costs for two different doors and remove a door if both costs are higher than the costs of the other door, but it does not give me the output I want.

I understand that my function is probably too simple to solve this problem but I don’t know how to solve this otherwise. Does someone have any idea how to solve this? I already looked on the internet to several websites, but nothing seems to really solve my problem.

Your help would be really appreciated!

答:
Easiest would be to make a Door class

Doors class

```<code>class Door():
    def __init__(self, name, distance, delay):
        self.name = name
        self.distance = distance
        self.delay = delay

    def __gt__(self, other):
        return (self.distance > other.distance and self.delay >= other.delay) or \
    (self.distance >= other.distance and self.delay > other.delay)

    def __repr__(self):
        return 'Door(name=%s, distance=%i, delay=%i'% (self.name, self.distance, self.delay)
</code>```

Note the double comparison  (>, >=) and (>=, >). With only (>, >) there would be no difference between D1 and D2

generating the samples

Here I use a set, a dict would work too with slight adaptations

```<code>doors_orig = set()
for d, c in cost.items():
    doors_orig.add(Door(d, *c))
</code>```

doors_orig

```<code>{Door(name=D4, distance=140, delay=2,
 Door(name=D1, distance=150, delay=0,
 Door(name=D5, distance=150, delay=0,
 Door(name=D2, distance=160, delay=0,
 Door(name=D3, distance=170, delay=1}
</code>```

The actual comparisons

Then you can use itertools.permutations to generate all possible combinations. Check whether that combination is still a subset of the possible best doors and compare them. Discard of it is absolutely larger.

```<code>doors_perm = doors_orig.copy()
comb = itertools.permutations(doors_perm, 2)

for d1, d2 in comb:
    if {d1, d2} <= doors_perm and (d1 > d2):
        doors_perm.discard(d1)
</code>```

doors_perm

```<code>{Door(name=D4, distance=140, delay=2,
 Door(name=D1, distance=150, delay=0,
 Door(name=D5, distance=150, delay=0}
</code>```

Whether the {d1, d2} <= doors_perm is necessary depends on the relative performance of the subset check and the comparison.

Body:
I am pretty new to Python and I want to perform some sort of Pareto optimum. It is somewhat difficult to explain, so I hope my question will be clear enough to understand.

I have the following model which consists of a list of 5 doors (list: ‘doors’) and each door contains two costs (shown in dictionary ‘cost’): [travel distance, delay]. I would like to compare the costs of each door with the costs of another door. However, there is no dominant cost. This means I want a list of doors with the best solution (minimize cost) for both costs.

doors = ['D1', 'D2', 'D3', 'D4', 'D5']

# cost: [travel distance, delay]
cost = {
'D1': [150, 0],
'D2': [160, 0],
'D3': [170, 1],
'D4': [140, 2],
'D5': [150, 0]
}

def test(doors):
    for s in doors:
        for d in doors:
            if s != d:
                if cost[s][0] < cost[d][0] and cost[s][1] < cost[d][1]:
                    doors.remove(d)
    return doors

print(test(doors))

For instance: D1, D2, D5 both have delay cost of 0. If I would only look for the door with minimum delay cost all three doors will do. However, D2 has a travel distance of 160 which is bigger than 150. Therefore, you would never choose D2 (compared to D1 and D5), since it consists of the same delay value and a worse travel distance value. So we would like D2 to be removed from the list.

For travel distance cost, you would choose D4 since it has the lowest travel distance: 140. Although it has the highest delay, there is no door which outperforms D4 due to the low travel distance.

So eventually I want a list with doors for which one of the cost is minimum with the best value for the other cost.
Based on this, I would like to have the following output:

best_doors = [‘D1’, ‘D4’,  ‘D5’].

In my model, I try to compare both costs for two different doors and remove a door if both costs are higher than the costs of the other door, but it does not give me the output I want.

I understand that my function is probably too simple to solve this problem but I don’t know how to solve this otherwise. Does someone have any idea how to solve this? I already looked on the internet to several websites, but nothing seems to really solve my problem.

Your help would be really appreciated!

Body:
Easiest would be to make a Door class

Doors class

class Door():
    def __init__(self, name, distance, delay):
        self.name = name
        self.distance = distance
        self.delay = delay

    def __gt__(self, other):
        return (self.distance > other.distance and self.delay >= other.delay) or \
    (self.distance >= other.distance and self.delay > other.delay)

    def __repr__(self):
        return 'Door(name=%s, distance=%i, delay=%i'% (self.name, self.distance, self.delay)

Note the double comparison  (>, >=) and (>=, >). With only (>, >) there would be no difference between D1 and D2

generating the samples

Here I use a set, a dict would work too with slight adaptations

doors_orig = set()
for d, c in cost.items():
    doors_orig.add(Door(d, *c))

doors_orig

{Door(name=D4, distance=140, delay=2,
 Door(name=D1, distance=150, delay=0,
 Door(name=D5, distance=150, delay=0,
 Door(name=D2, distance=160, delay=0,
 Door(name=D3, distance=170, delay=1}

The actual comparisons

Then you can use itertools.permutations to generate all possible combinations. Check whether that combination is still a subset of the possible best doors and compare them. Discard of it is absolutely larger.

doors_perm = doors_orig.copy()
comb = itertools.permutations(doors_perm, 2)

for d1, d2 in comb:
    if {d1, d2} <= doors_perm and (d1 > d2):
        doors_perm.discard(d1)

doors_perm

{Door(name=D4, distance=140, delay=2,
 Door(name=D1, distance=150, delay=0,
 Door(name=D5, distance=150, delay=0}

Whether the {d1, d2} <= doors_perm is necessary depends on the relative performance of the subset check and the comparison.


问:
Hiding DIVs using Jquery is not working in Safari (iOS)
I have written a fairly basic script that hides various field on an HTML form on document ready. This works just fine on my desktop machine and on my Kindle, but when trialling it on an iPad using Safari, none of the elements are hidden.

```<code>$(document).ready(function()
{
    //Hide the editable field DIVs
    $("#form_location_edit").hide();
    $("#form_bin_no_edit").hide();
    $("#form_area_edit").hide();
    $("#form_quantity_edit").hide();
    $("#form_denomination_edit").hide();
    $("#form_comments_edit").hide();
    $("#form_responsible_edit").hide();
}
</code>```

What am I doing wrong?

答:
Some versions of Safari doesn't support hide() function. You can use CSS + addClass() function instead of it.

See: Hide and show function not working in Safari

Body:
I have written a fairly basic script that hides various field on an HTML form on document ready. This works just fine on my desktop machine and on my Kindle, but when trialling it on an iPad using Safari, none of the elements are hidden.

$(document).ready(function()
{
    //Hide the editable field DIVs
    $("#form_location_edit").hide();
    $("#form_bin_no_edit").hide();
    $("#form_area_edit").hide();
    $("#form_quantity_edit").hide();
    $("#form_denomination_edit").hide();
    $("#form_comments_edit").hide();
    $("#form_responsible_edit").hide();
}

What am I doing wrong?


问:
Generics with optional multiple bounds, e.g. List<? extends Integer OR String>
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

```<code>map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error
</code>```

It is not possible to declare a Map as below (to enforce compile time check).

```<code>void setProperties(Map<String, ? extends Integer || String> properties)
</code>```

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

```<code>void setProperties(Map<String, ?> properties)
</code>```

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.

答:
Define two overloads:

```<code>void setIntegerProperties(Map<String, Integer> properties)

void setStringProperties(Map<String, String> properties)
</code>```

They have to be called different things, because you can't have two methods with the same erasure.

Body:
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error

It is not possible to declare a Map as below (to enforce compile time check).

void setProperties(Map<String, ? extends Integer || String> properties)

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

void setProperties(Map<String, ?> properties)

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.

Body:
Define two overloads:

void setIntegerProperties(Map<String, Integer> properties)

void setStringProperties(Map<String, String> properties)

They have to be called different things, because you can't have two methods with the same erasure.


问:
Power Bi: Embedding Report into MVC Site
I have created a power bi report. I want to embed this report to my MVC site. Here is my code:-

```<code> private static readonly string ClientID = ConfigurationManager.AppSettings["ClientID"];
 private static readonly string ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
 private static readonly string RedirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
 private static readonly string AADAuthorityUri = ConfigurationManager.AppSettings["AADAuthorityUri"];
 private static readonly string PowerBiAPI = ConfigurationManager.AppSettings["PowerBiAPI"];
 private static readonly string PowerBiDataset = ConfigurationManager.AppSettings["PowerBiDataset"];
 private static readonly string baseUri = PowerBiDataset;
 private static string accessToken = string.Empty;
 public class PBIReports
 {
     public PBIReport[] value { get; set; }
 }
 public class PBIReport
 {
     public string id { get; set; }
     public string name { get; set; }
     public string webUrl { get; set; }
     public string embedUrl { get; set; }
 }

 public ReportController()
 {
     try
     {
         if (Request.Params.Get("code") != null)
         {

             Session["AccessToken"] = GetAccessToken(
                 HttpContext.Request["code"],
                 ClientID,
                 ClientSecret,
                 RedirectUrl);
         }
         if (Session["AccessToken"] != null)
         {
             accessToken = Session["AccessToken"].ToString();
             GetReport(0);
         }
     }
     catch(Exception ex)
     {

     }
 }

 public string GetAccessToken(string authorizationCode, string clientID, string clientSecret, string redirectUri)
 {
     TokenCache TC = new TokenCache();
     string authority = AADAuthorityUri;
     AuthenticationContext AC = new AuthenticationContext(authority, TC);
     ClientCredential cc = new ClientCredential(clientID, clientSecret);
     return AC.AcquireTokenByAuthorizationCodeAsync(
         authorizationCode,
         new Uri(redirectUri), cc).Result.AccessToken;
 }
 protected void GetReport(int index)
 {
     System.Net.WebRequest request = System.Net.WebRequest.Create(
         String.Format("{0}/Reports",
         baseUri)) as System.Net.HttpWebRequest;

     request.Method = "GET";
     request.ContentLength = 0;
     request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
     using (var response = request.GetResponse() as System.Net.HttpWebResponse)
     {
         using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
         {
             PBIReports Reports = JsonConvert.DeserializeObject<PBIReports>(reader.ReadToEnd());
             if (Reports.value.Length > 0)
             {
                 var report = Reports.value[index];

                 ViewBag["ReportId"] = report.id;
                 ViewBag["EmbedUrl"] = report.embedUrl;
                 ViewBag["ReportName"] = report.name;
                 ViewBag["WebUrl"] = report.webUrl;
             }
         }
     }
 }

 public void GetAuthorizationCode()
 {
     var @params = new NameValueCollection
     {
         {"response_type", "code"},
         {"client_id", ClientID},
         {"resource", PowerBiAPI},
         { "redirect_uri", RedirectUrl}
     };

     var queryString = HttpUtility.ParseQueryString(string.Empty);
     queryString.Add(@params);
     Response.Redirect(String.Format(AADAuthorityUri + "?{0}", queryString));
 }

 public ActionResult Index()
 {
     GetAuthorizationCode();
     return View();
 }
</code>```

On Redirecting to "Report Page", it goes for power bi login page and after I sign in it redirects back to this page (as homepage and redirect url are same). But Request.Params.Get("code") != null is null. HttpContext.Request is also null. Why? Is there anything wrong in the code?

答:
In the constructor of a controller you don't have the this.HttpContext object to your disposal yet. You might have HttpContext.Current, but I am not sure of that.

What you should do is move that code to an action (for example your GetReport action), where you can make your checks.

Body:
I have created a power bi report. I want to embed this report to my MVC site. Here is my code:-

 private static readonly string ClientID = ConfigurationManager.AppSettings["ClientID"];
 private static readonly string ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
 private static readonly string RedirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
 private static readonly string AADAuthorityUri = ConfigurationManager.AppSettings["AADAuthorityUri"];
 private static readonly string PowerBiAPI = ConfigurationManager.AppSettings["PowerBiAPI"];
 private static readonly string PowerBiDataset = ConfigurationManager.AppSettings["PowerBiDataset"];
 private static readonly string baseUri = PowerBiDataset;
 private static string accessToken = string.Empty;
 public class PBIReports
 {
     public PBIReport[] value { get; set; }
 }
 public class PBIReport
 {
     public string id { get; set; }
     public string name { get; set; }
     public string webUrl { get; set; }
     public string embedUrl { get; set; }
 }

 public ReportController()
 {
     try
     {
         if (Request.Params.Get("code") != null)
         {

             Session["AccessToken"] = GetAccessToken(
                 HttpContext.Request["code"],
                 ClientID,
                 ClientSecret,
                 RedirectUrl);
         }
         if (Session["AccessToken"] != null)
         {
             accessToken = Session["AccessToken"].ToString();
             GetReport(0);
         }
     }
     catch(Exception ex)
     {

     }
 }

 public string GetAccessToken(string authorizationCode, string clientID, string clientSecret, string redirectUri)
 {
     TokenCache TC = new TokenCache();
     string authority = AADAuthorityUri;
     AuthenticationContext AC = new AuthenticationContext(authority, TC);
     ClientCredential cc = new ClientCredential(clientID, clientSecret);
     return AC.AcquireTokenByAuthorizationCodeAsync(
         authorizationCode,
         new Uri(redirectUri), cc).Result.AccessToken;
 }
 protected void GetReport(int index)
 {
     System.Net.WebRequest request = System.Net.WebRequest.Create(
         String.Format("{0}/Reports",
         baseUri)) as System.Net.HttpWebRequest;

     request.Method = "GET";
     request.ContentLength = 0;
     request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
     using (var response = request.GetResponse() as System.Net.HttpWebResponse)
     {
         using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
         {
             PBIReports Reports = JsonConvert.DeserializeObject<PBIReports>(reader.ReadToEnd());
             if (Reports.value.Length > 0)
             {
                 var report = Reports.value[index];

                 ViewBag["ReportId"] = report.id;
                 ViewBag["EmbedUrl"] = report.embedUrl;
                 ViewBag["ReportName"] = report.name;
                 ViewBag["WebUrl"] = report.webUrl;
             }
         }
     }
 }

 public void GetAuthorizationCode()
 {
     var @params = new NameValueCollection
     {
         {"response_type", "code"},
         {"client_id", ClientID},
         {"resource", PowerBiAPI},
         { "redirect_uri", RedirectUrl}
     };

     var queryString = HttpUtility.ParseQueryString(string.Empty);
     queryString.Add(@params);
     Response.Redirect(String.Format(AADAuthorityUri + "?{0}", queryString));
 }

 public ActionResult Index()
 {
     GetAuthorizationCode();
     return View();
 }

On Redirecting to "Report Page", it goes for power bi login page and after I sign in it redirects back to this page (as homepage and redirect url are same). But Request.Params.Get("code") != null is null. HttpContext.Request is also null. Why? Is there anything wrong in the code?


问:
How to parse multiline ELK based on Timestamp
My logs are

```<code>2017-07-04 10:19:52,896 - [INFO] - from application in ForkJoinPool-3-worker-1

Resolving database...

2017-07-04 10:19:52,897 - [INFO] - from application in ForkJoinPool-3-worker-1

Resolving database...

2017-07-04 10:19:52,897 - [DEBUG] - from application in ForkJoinPool-3-worker-1

Json Body : {"took":2,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]},"aggregations":{"fp":{"doc_count_error_upper_bound":0,"sum_other_doc_count":0,"buckets":[]}}}

2017-07-04 10:19:52,898 - [DEBUG] - from application in application-akka.actor.default-dispatcher-53

Successfully updated the transaction.

2017-07-04 10:19:52,899 - [INFO] - from application in ForkJoinPool-3-worker-1

Resolving database...

2017-07-04 10:19:52,901 - [DEBUG] - from application in application-akka.actor.default-dispatcher-54

Successfully updated the transaction.
</code>```

I want to group all logs between two timestamp together match them with
GREEDYDATA.
I am using filebeat with ELK

答:
I have solved it via following configuration

-

```<code>  paths:
    - /var/www/aspserver/logs/application.log
  document_type: asp
  input_type: log
  multiline:
    pattern: '^[0-9]'
    negate: true
    match: after
</code>```

Matchin all line after a line starting with number and merging them together.

```<code>logstash filter :
filter {
  if [type] == "asp" {
    grok {
      patterns_dir => "/etc/logstash/conf.d/patterns"
      match => { "message" => "%{JAVASTACKTRACEPART}" }
    }
  }
}
</code>```

Gobble up all the logs

Body:
My logs are

2017-07-04 10:19:52,896 - [INFO] - from application in ForkJoinPool-3-worker-1

Resolving database...

2017-07-04 10:19:52,897 - [INFO] - from application in ForkJoinPool-3-worker-1

Resolving database...

2017-07-04 10:19:52,897 - [DEBUG] - from application in ForkJoinPool-3-worker-1

Json Body : {"took":2,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]},"aggregations":{"fp":{"doc_count_error_upper_bound":0,"sum_other_doc_count":0,"buckets":[]}}}

2017-07-04 10:19:52,898 - [DEBUG] - from application in application-akka.actor.default-dispatcher-53

Successfully updated the transaction.

2017-07-04 10:19:52,899 - [INFO] - from application in ForkJoinPool-3-worker-1

Resolving database...

2017-07-04 10:19:52,901 - [DEBUG] - from application in application-akka.actor.default-dispatcher-54

Successfully updated the transaction.

I want to group all logs between two timestamp together match them with
GREEDYDATA.
I am using filebeat with ELK

Body:
I have solved it via following configuration

-

  paths:
    - /var/www/aspserver/logs/application.log
  document_type: asp
  input_type: log
  multiline:
    pattern: '^[0-9]'
    negate: true
    match: after

Matchin all line after a line starting with number and merging them together.

logstash filter :
filter {
  if [type] == "asp" {
    grok {
      patterns_dir => "/etc/logstash/conf.d/patterns"
      match => { "message" => "%{JAVASTACKTRACEPART}" }
    }
  }
}

Gobble up all the logs


问:
How should a list be represented in XML?
In XML, how should a list be represented?

With an enclosing list entity:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>
</code>```

Or without:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>
</code>```

答: The first one would work pretty well for simple lists, but what if the list contained a nested list itself?! What if an element had a couple different lists? To keep things consistent I prefer an element for the list and using an <item> tag or something for child data. This will help using a generic function to parse all lists.

OwnerDisplayName: Mat

Body:
In XML, how should a list be represented?

With an enclosing list entity:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>

Or without:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>

OwnerDisplayName: Mehrdad Afshari


问:
How to view the variable values in release builds
I want to be able to see the variable values while debugging a release application.
I have set the compiler option as Z7 and given a /DEBUG and /PDB: linker option. Now I have a pdb for the application.

With this set up I am able to put a break point (Windbg) inside the code and it hits properly. But I am not able to see the variable values.

The Locals window only shows the pointer value but I cant see the contents of the same. For instance if I have a pointer to a structure that has an int inside it, it just shows the value of the pointer. If I expand the same by clicking + in the tree, I see the variable name with the value as <Memory access error>

How should I make the release builds show the variable values?

答: Many times, you cannot see them because they don't exist. If you look at the optimized assembly code, you will find that many intermediate variables are completely removed in favor of performance. That is most likely what you're seeing, and the only way around it is to follow the disassembly and watch the right memory locations / registers.</p>


问:
Rails check if HABTM association is changed
I have a roles table

```<code>select * from roles;

 id |   name
----+----------
  1 | admin
  2 | user
  3 | author
  4 | guest
  5 | manager
</code>```

and another table user_roles

```<code>select * from user_roles;

 role_id | user_id
---------+---------
       3 |       1
       3 |       2
       3 |       3
       4 |       5
       3 |       6
       5 |       7
       5 |       8
       1 |       9
       1 |      11

#role.rb

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, join_table: 'user_roles', class_name: user_class.to_s
end
</code>```

I am trying to do some actions when a user's role is updated say, from guest to author

```<code>#user.rb

class Use < ActiveRecord::Base
  after_update :print_role_updated if: :user_roles_changed?
  .
  .

  private

  def user_roles_changed?
    user_roles.any? { |role| role.changed? }
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end
</code>```

But it is not working as expected (.changed? is checking whether the value in role table is updated ?).

How do I run print_role_updated method whenever user roles get updated to a diffrent one?

edit

I tried Doctor's answer but role_updated? is returning false even though the record is being updated

```<code>class Use < ActiveRecord::Base
  has_many :user_roles
  after_update :print_role_updated if: role_updated?
  .
  .

  private

  def role_updated?
    user_roles.any? {|a| a.changed?}
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end
</code>```

答:
try below code in model:

user.rb

```<code>class User < ActiveRecord::Base
  after_update :print_role_updated if: :user_roles_changed?
  .
  .

  private

  def print_role_updated
    puts "User role changed"
  end

  def user_roles_changed?
    u = User.find(self.id)
    u.role != self.role # it check existing role and role saved in db
  end
end
</code>```

Body:
I have a roles table

select * from roles;

 id |   name
----+----------
  1 | admin
  2 | user
  3 | author
  4 | guest
  5 | manager

and another table user_roles

select * from user_roles;

 role_id | user_id
---------+---------
       3 |       1
       3 |       2
       3 |       3
       4 |       5
       3 |       6
       5 |       7
       5 |       8
       1 |       9
       1 |      11

#role.rb

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, join_table: 'user_roles', class_name: user_class.to_s
end

I am trying to do some actions when a user's role is updated say, from guest to author

#user.rb

class Use < ActiveRecord::Base
  after_update :print_role_updated if: :user_roles_changed?
  .
  .

  private

  def user_roles_changed?
    user_roles.any? { |role| role.changed? }
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end

But it is not working as expected (.changed? is checking whether the value in role table is updated ?).

How do I run print_role_updated method whenever user roles get updated to a diffrent one?

edit

I tried Doctor's answer but role_updated? is returning false even though the record is being updated

class Use < ActiveRecord::Base
  has_many :user_roles
  after_update :print_role_updated if: role_updated?
  .
  .

  private

  def role_updated?
    user_roles.any? {|a| a.changed?}
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end

Body:
try below code in model:

user.rb

class User < ActiveRecord::Base
  after_update :print_role_updated if: :user_roles_changed?
  .
  .

  private

  def print_role_updated
    puts "User role changed"
  end

  def user_roles_changed?
    u = User.find(self.id)
    u.role != self.role # it check existing role and role saved in db
  end
end


问:
TimelineMax reverse tweens once
I'm wondering if there is a way to reverse tweens inside a timeline once they finished animating. I want to scale elements and change their color. After that I want to reverse the animation.
I tried with yoyo() but that method unfortunately plays the animations 3 times even when I set repeat: 1 (it animates 1-2-3-3-2-1-1-2-3-3-2-1).

```<code>    introTimeline.append(  TweenMax.to($(".Element"), 1, {scale: 2,
    fill: "red", ease: Power2.easeIn, repeat: 1, yoyo:
    true})  );
</code>```

All I need is 1-2-3-3-2-1 for each tween in the timeline …

Is timeline the wrong way to approach this?

Come on does really know an answer to such a simple question … ?

答:
You can just reverse the animation once the tween is complete. Use the following code:</p>

```<code>var tl = new TimelineMax({
  onComplete:complete,
});

tl.to("img", 3, {rotation:360, transformOrigin:"150px 150px", ease:Linear.easeNone});

function complete(tl) {
  tl.restart(); // 0 sets the playhead at the end of the animation
}
</code>```

Title: TimelineMax reverse tweens once

Body:
I'm wondering if there is a way to reverse tweens inside a timeline once they finished animating. I want to scale elements and change their color. After that I want to reverse the animation.
I tried with yoyo() but that method unfortunately plays the animations 3 times even when I set repeat: 1 (it animates 1-2-3-3-2-1-1-2-3-3-2-1).

    introTimeline.append(  TweenMax.to($(".Element"), 1, {scale: 2,
    fill: "red", ease: Power2.easeIn, repeat: 1, yoyo:
    true})  );

All I need is 1-2-3-3-2-1 for each tween in the timeline …

Is timeline the wrong way to approach this?

Come on does really know an answer to such a simple question … ?

Body:
You can just reverse the animation once the tween is complete. Use the following code:

var tl = new TimelineMax({
  onComplete:complete,
});

tl.to("img", 3, {rotation:360, transformOrigin:"150px 150px", ease:Linear.easeNone});

function complete(tl) {
  tl.restart(); // 0 sets the playhead at the end of the animation
}


问:
Batch - Count string appearance between two patterns
This question is pretty similar to this question.

I've been stuck trying to count how many a string appears between brackets. Consider the follow text file(although it looks like a .bat script)

```<code>(
echo a
echo b
echo c
)
echo z
</code>```

In the file above, we can see 4 echo, but I only want to count the ones inside the brackets(the result should be 3)

```<code>for /f "delims=][  tokens=2" %%H in ('FART.exe -c -i -p %File% ^( a') do set /a count+=1
</code>```

This code works, but only counts 1, because I couldn't figure out how to count multiple appearances. Please help me, any help will be appreciated.

Edit - 5/7/17

You can assume

There would be only 1 echo on each line.

Parentheses are not nested

echo would not appear on the same line as parentheses

Bonus if you can make your script count the echo on the same line of parentheses

答:
For those expecting a batch-file, who have more respect for the rules than SteveFest, here is a basic example, (probably not the most efficient, but hey this sort of task wouldn't be designed for huge files anyhow):

@Echo Off
For /F "Tokens=1*Delims=:" %%A In ('FindStr/N $ "%~n0.txt"') Do (
    If "%%B"=="(" If Not Defined FL Set/A FL=%%A+1
    If "%%B"==")" If Not Defined LL Set/A LL=%%A-1)
Set "i=0"
If FL LEq LL For /L %%A In (%FL%,1,%LL%) Do For /F "Tokens=1*Delims=:" %%B In (
    'FindStr/N $ "%~n0.txt"') Do If "%%B"=="%%A" If Not "(%%C"=="(" Set/A i+=1
Echo( [%i%]
Timeout -1
```

Body:
This question is pretty similar to this question.

I've been stuck trying to count how many a string appears between brackets. Consider the follow text file(although it looks like a .bat script)

(
echo a
echo b
echo c
)
echo z

In the file above, we can see 4 echo, but I only want to count the ones inside the brackets(the result should be 3)

for /f "delims=][  tokens=2" %%H in ('FART.exe -c -i -p %File% ^( a') do set /a count+=1

This code works, but only counts 1, because I couldn't figure out how to count multiple appearances. Please help me, any help will be appreciated.

Edit - 5/7/17

You can assume

There would be only 1 echo on each line.

Parentheses are not nested

echo would not appear on the same line as parentheses

Bonus if you can make your script count the echo on the same line of parentheses


问:
Replacing byte in file
I'm trying to replace certain bytes from a file with some other specific bytes, but have a problem with my binary writer replacing too many bytes. What is wrong in my code?

```<code>using (BinaryWriter bw =
    new BinaryWriter(File.Open(fileName,
        FileMode.Open)))
{
    bw.BaseStream.Position = 0x3;
    bw.Write(0x50);
}
</code>```

This was supposed to change the letter "E" (hex 0x45) with the letter "P", but instead changes that byte and 3 more bytes; from "45 30 31 FF" to "50 00 00 00". I would like to keep the "30 31 FF", only change "45" to "50".

答: Because method Write actually write int (4 bytes). You should convert your value to byte type. bw.Write((byte)0x50);

Title: Replacing byte in file

Body:
I'm trying to replace certain bytes from a file with some other specific bytes, but have a problem with my binary writer replacing too many bytes. What is wrong in my code?

using (BinaryWriter bw =
    new BinaryWriter(File.Open(fileName,
        FileMode.Open)))
{
    bw.BaseStream.Position = 0x3;
    bw.Write(0x50);
}

This was supposed to change the letter "E" (hex 0x45) with the letter "P", but instead changes that byte and 3 more bytes; from "45 30 31 FF" to "50 00 00 00". I would like to keep the "30 31 FF", only change "45" to "50".