问:
How to use jess in Android
I'm trying to use JESS in and Android project. I tried using Jess 6 which is working fine on a web application on netbeans, but it's giving errors. It seems like the version of the jar file is not compatible.
I need help on how to integrate jess with an Android project.

The error is generated from a line of code:

```<code>Rete engine = new Rete();
</code>```

See the error trail below:

```<code> 2593-2593/com.example.modupe.tryjessapp E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.modupe.tryjessapp, PID: 2593
 java.lang.NoClassDefFoundError: Failed resolution of: Ljava/applet/Applet;
     at jess.Rete.getApplet(Unknown Source)
     at jess.Batch.batch(Unknown Source)
     at jess.Rete.if(Unknown Source)
     at jess.Rete.<init>(Unknown Source)
     at jess.Rete.<init>(Unknown Source)
     at jess.Rete.<init>(Unknown Source)
     at com.example.modupe.tryjessapp.MainActivity.<init>(MainActivity.java:17)
     at java.lang.Class.newInstance(Native Method)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
     at android.app.ActivityThread.-wrap12(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6119)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
  Caused by: java.lang.ClassNotFoundException: Didn't find class "java.applet.Applet" on path: DexPathList[[zip file "/data/app/com.example.modupe.tryjessapp-1/base.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.modupe.tryjessapp-1/lib/x86, /system/lib, /vendor/lib]]
....
</code>```

答: Jess uses a number of Java APIs that are not supported on Dalvik, Applet being one, but more importantly, java.beans.Introspector. An android-capable version of Jess is available as an alpha build to source licensees only; it hasn't been released.</p>

Title: How to use jess in Android

Body:
I'm trying to use JESS in and Android project. I tried using Jess 6 which is working fine on a web application on netbeans, but it's giving errors. It seems like the version of the jar file is not compatible.
I need help on how to integrate jess with an Android project.

The error is generated from a line of code:

Rete engine = new Rete();

See the error trail below:

 2593-2593/com.example.modupe.tryjessapp E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.modupe.tryjessapp, PID: 2593
 java.lang.NoClassDefFoundError: Failed resolution of: Ljava/applet/Applet;
     at jess.Rete.getApplet(Unknown Source)
     at jess.Batch.batch(Unknown Source)
     at jess.Rete.if(Unknown Source)
     at jess.Rete.<init>(Unknown Source)
     at jess.Rete.<init>(Unknown Source)
     at jess.Rete.<init>(Unknown Source)
     at com.example.modupe.tryjessapp.MainActivity.<init>(MainActivity.java:17)
     at java.lang.Class.newInstance(Native Method)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
     at android.app.ActivityThread.-wrap12(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6119)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
  Caused by: java.lang.ClassNotFoundException: Didn't find class "java.applet.Applet" on path: DexPathList[[zip file "/data/app/com.example.modupe.tryjessapp-1/base.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.modupe.tryjessapp-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.modupe.tryjessapp-1/lib/x86, /system/lib, /vendor/lib]]
....


来源: stackexchange

问:
Where to place constant attributes?
I want to write clean code in java and I am very insecure where to place my attriutes.

I often cannot decide, if I place them on top of the class, in a constructor or directly in the method. Are there some rules out there? The only logic one for me is, to place attributes on top of the class when these attributes are used in more than one method.

Can you evaluate this code in terms of clean code? Should I place the constant currency attributes in the constructor? Can I also put some of the class attributes in a method? Thanks for the advice

```<code>public class CsvFileReader  {
    private SimpleDateFormatStringToDate formatter = new SimpleDateFormatStringToDate();
    private IataExchangeRateDataSet exchangeRateDataSet= new IataExchangeRateDataSet();
    private final String SEMICOLON_DELIMITER = ";";

    // Currency attributes index
    private final int CURRENCY_VALUE = 1;
    private final int CURRENCY_ISO_CODE = 2;
    private final int CURRENCY_PERIOD_START = 3;
    private final int CURRENCY_PERIOD_END = 4;

    public CsvFileReader(IataExchangeRateDataSet exchangeRateDataSet) {
        this.exchangeRateDataSet = exchangeRateDataSet;
    }

    public void readCsvFile(String fileName, final int maxLengthOfColumn) {

        BufferedReader fileReader = null;
        try {
            String line = "";
            fileReader = new BufferedReader(new FileReader(fileName));

            while ((line = fileReader.readLine()) != null) {

                String[] tokens = line.split(SEMICOLON_DELIMITER);

                //TODO: Noch auf Vollständigkeit der Zeile, Korrektheit der Datumsformate und ähnliches überprüfen
                if ( tokens.length== maxLengthOfColumn && DateFormat.checkDateFormat(tokens[CURRENCY_PERIOD_START]) && DateFormat.checkDateFormat(tokens[CURRENCY_PERIOD_END])) {

                    //format currency value in csv
                    tokens[CURRENCY_VALUE]=tokens[CURRENCY_VALUE].replace(",", ".");

                    IataExchangeRateData iataExchangeRateData = new IataExchangeRateData(
                            new BigDecimal(tokens[CURRENCY_VALUE]), tokens[CURRENCY_ISO_CODE],
                            formatter.parseStringToDate(tokens[CURRENCY_PERIOD_START]),
                            formatter.parseStringToDate(tokens[CURRENCY_PERIOD_END]));

                    exchangeRateDataSet.getExchangeRateDataSet().add(iataExchangeRateData);
                }
            }
        }

        catch (Exception e) {
            System.out.println("Error in CsvFileReader");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error while closing fileReader !!!");
                e.printStackTrace();
            }
        }
    }
}
</code>```

答:
If any attribute is used for calculation or manipulation inside a method then use that attribute inside only the method.

If any attribute is being used such that any method can refer it then use it at the top of all the methods.

If any attribute does not depend on the class specifically like counting the number of threads of a particular object then use it as a class variable by making it static.

ContentLicense: CC BY-SA 3.0

Title: Where to place constant attributes?

Body:
I want to write clean code in java and I am very insecure where to place my attriutes.

I often cannot decide, if I place them on top of the class, in a constructor or directly in the method. Are there some rules out there? The only logic one for me is, to place attributes on top of the class when these attributes are used in more than one method.

Can you evaluate this code in terms of clean code? Should I place the constant currency attributes in the constructor? Can I also put some of the class attributes in a method? Thanks for the advice

public class CsvFileReader  {
    private SimpleDateFormatStringToDate formatter = new SimpleDateFormatStringToDate();
    private IataExchangeRateDataSet exchangeRateDataSet= new IataExchangeRateDataSet();
    private final String SEMICOLON_DELIMITER = ";";

    // Currency attributes index
    private final int CURRENCY_VALUE = 1;
    private final int CURRENCY_ISO_CODE = 2;
    private final int CURRENCY_PERIOD_START = 3;
    private final int CURRENCY_PERIOD_END = 4;

    public CsvFileReader(IataExchangeRateDataSet exchangeRateDataSet) {
        this.exchangeRateDataSet = exchangeRateDataSet;
    }

    public void readCsvFile(String fileName, final int maxLengthOfColumn) {

        BufferedReader fileReader = null;
        try {
            String line = "";
            fileReader = new BufferedReader(new FileReader(fileName));

            while ((line = fileReader.readLine()) != null) {

                String[] tokens = line.split(SEMICOLON_DELIMITER);

                //TODO: Noch auf Vollständigkeit der Zeile, Korrektheit der Datumsformate und ähnliches überprüfen
                if ( tokens.length== maxLengthOfColumn && DateFormat.checkDateFormat(tokens[CURRENCY_PERIOD_START]) && DateFormat.checkDateFormat(tokens[CURRENCY_PERIOD_END])) {

                    //format currency value in csv
                    tokens[CURRENCY_VALUE]=tokens[CURRENCY_VALUE].replace(",", ".");

                    IataExchangeRateData iataExchangeRateData = new IataExchangeRateData(
                            new BigDecimal(tokens[CURRENCY_VALUE]), tokens[CURRENCY_ISO_CODE],
                            formatter.parseStringToDate(tokens[CURRENCY_PERIOD_START]),
                            formatter.parseStringToDate(tokens[CURRENCY_PERIOD_END]));

                    exchangeRateDataSet.getExchangeRateDataSet().add(iataExchangeRateData);
                }
            }
        }

        catch (Exception e) {
            System.out.println("Error in CsvFileReader");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error while closing fileReader !!!");
                e.printStackTrace();
            }
        }
    }
}


问:
Full repository queue manager as Multi Instance
Why it is not recommended to have full repository queue manager in a cluster as multi-instance?

Recommendation is from the in webcast presentation "Implementation Considerations for Multi-Instance Queue Managers in WebSphere MQ Cluster Environment".

答:
The webcast presentation "Implementation Considerations for Multi-Instance Queue Managers in WebSphere MQ Cluster Environment" referenced was from 2010.

Two limitations that contribute to the recommendation are given earlier in the presentation:

Page 16:

Pre - 7.0.1 repositories will have to have a channel to both machines that Multi-Instance queue manager is using

Stuck messages on SYSTEM.CLUSTER.TRANSMIT.QUEUE

Page 17:

z/OS

CONNAME attribute 48 character limit

Long hostnames may not fit

Given that the last version of MQ prior to 7.0.1 went out of support September 30th 2012, the first limitation above should no longer be a consideration however at the time the presentation was given there was still more than two years of support left for v6.

The second limitation above would only be a concern if you have z/OS (Mainframe) MQ partial repositories connecting to a distributed full repository.

While those two limitations above may not apply to you now, there may be no reason to make them MI since you already have  redundancy with the recommended two Full repositories for a cluster.


问:
How to POST data to an HTTP endpoint using NodeJs
I am New to AWS Lambda

I was trying to POST a simple data from AWS data to HTTP endpoint, but i am unable to do that.

I was using NodeJs language.
And I want the POST method to be done using http module not using request module.
How to solve this.

答:
I'm assuming you want to us the native HTTP module because you don't know how to include an external module. Since this is probably the case, take the time to read this article by AWS Creating a Deployment Package (Node.js).

It should help you understand how to work with AWS Lambda, NodeJS and external modules.


问:
String manipulation in C#. Inserting "+" between words
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

```<code>    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }
</code>```

Desired output

```<code>word1+word2+word3
</code>```

where the number of words are not fixed.

答: Use String.Join to concatenate the strings together.

ContentLicense: CC BY-SA 2.5

Body:
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }

Desired output

word1+word2+word3

where the number of words are not fixed.


问:
How to pass object through activities by reference?
this is my first post here so be gentle :p
Here is the thing, I'm facing a really though issue and after several research i did not manage to figure out a clean solution. Let me explain:

I'm actually developing an android app for restaurant management.
In activity A, i'm able to create some articles with different parameters (picture, name, price ..).
I can also create a menu in which i indicate which articles are included. To do so i run Activity B that contains a dynamic list of the available articles (the ones i created) to be chosen. After picking up some of them the customised chosen objects are sent to Activity A through Parcel. And the chosen article list is updated in the menu.
But here is the thing, as far as i know, using Parcels create another instance of the object. As a result, if i modify or delete an article, the article list included in the menu does not change, and obviously i would like the list in the menu to be automatically updated.

Is there a way to simply pass customised objects through activities by reference?
What could be a clean solution to make the article list in the menu dynamic?

Here is some code:

In Activity A, in the menu interface i click + button to add an article, which run Activity B (the extras is the list of articles already included in the menu before, so in the beginning it's empty).

```<code>//Add article
    FloatingActionButton addArticleButton = (FloatingActionButton)parentActivity.findViewById(R.id.addArticleButton);
    addArticleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showMenuDetails(menuListView,menuAdapter,currentMenu);
            parentActivity.startActivityForResult(new Intent(parentActivity.getApplicationContext(),ChooseArticleActivity.class).putParcelableArrayListExtra("menuArticleList",currentMenu.getArticles()),PICK_ARTICLES);
        }
    });
</code>```

In activity B: I select Articles in a list of available Articles (the ones i created). After picking up i press OK button to put the list of chosen articles in result Intent as Parcelable Extras

```<code>protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.choose_article_layout);
    initializeLists();

    this.resultIntent = new Intent();
}

private void initializeLists(){
    final ListView articleToChoose = (ListView)findViewById(R.id.articleToChoose);
    final ListView articleChosen = (ListView)findViewById(R.id.articleChosen);

    final ArrayList<Article> articleToChooseList = (ArrayList<Article>)MainActivity.model.getArticleList().getArticleList().clone();
    final ArrayList<Parcelable> articleChosenListParcelable = (ArrayList<Parcelable>)this.getIntent().getParcelableArrayListExtra("menuArticleList");
    final ArticleAdapter articleToChooseAdapter = new ArticleAdapter(getApplicationContext(), articleToChooseList);
    articleToChoose.setAdapter(articleToChooseAdapter);

    ArrayList<Article> articleChosenListTemp = new ArrayList<>();
    ArrayList<Article> articleToRemove = new ArrayList<>();
    for(Parcelable a:articleChosenListParcelable){
        articleChosenListTemp.add((Article)a);
        for(Article article:articleToChooseList){
            if(article.getName().equals(((Article) a).getName())){
                articleToRemove.add(article);
            }
        }
    }
    articleToChooseList.removeAll(articleToRemove);
    articleToChooseAdapter.notifyDataSetChanged();

    final ArrayList<Article> articleChosenList = articleChosenListTemp;

    final ArticleAdapter articleChosenAdapter = new ArticleAdapter(getApplicationContext(),articleChosenList);

    articleChosen.setAdapter(articleChosenAdapter);

    articleChosen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleChosenAdapter.getItem(position);
            articleChosenList.remove(articleClicked);
            articleToChooseList.add(articleClicked);
            articleChosenAdapter.notifyDataSetChanged();
            articleToChooseAdapter.notifyDataSetChanged();
        }
    });

    articleToChoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleToChooseAdapter.getItem(position);
            if(!articleChosenList.contains(articleClicked)){
                articleChosenList.add(articleClicked);
                articleToChooseList.remove(articleClicked);
                articleToChooseAdapter.notifyDataSetChanged();
                articleChosenAdapter.notifyDataSetChanged();
            }
        }
    });

    Button okButton = (Button)findViewById(R.id.okButton);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chosenArticleListAttr = articleChosenList;
            resultIntent.putParcelableArrayListExtra("articleList",chosenArticleListAttr);
            setResult(RESULT_OK,resultIntent);
            finish();
        }
    });

    Button cancelButton = (Button)findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}
</code>```

In activity A, in onActivityResult i catch the result and update the list, but the added Articles here are not the same instance as the article list in the model

```<code>if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
        ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();

        ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
        gestionMenusLayout.getCurrentMenu().getArticles().clear();
        for(Parcelable a:chosenArticleList){
            gestionMenusLayout.getCurrentMenu().addArticle((Article)a);
        }
        articleAdapter.notifyDataSetChanged();
    }
</code>```

答:
I figured it out with a quite easy and simple solution finally.

I keep passing my Article objects through intents by parcels.
But as it creates a new instance, instead of adding this instance i add the original one (the one from the model) after an equality key check (the name of the article). By doing so i keep the reference on my Article.

Thank you for helping!

Edit:
Here is the code:

```<code>if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
        ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();

        ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
        gestionMenusLayout.getCurrentMenu().getArticles().clear();
        ArrayList<Article> modelArticles = MainActivity.model.getArticleList().getArticleList();
        for(Parcelable a:chosenArticleList){
            for(Article modelArticle:modelArticles){
                if(((Article)a).getName().equals(modelArticle.getName())){
                    gestionMenusLayout.getCurrentMenu().addArticle(modelArticle);
                }
            }
        }
        articleAdapter.notifyDataSetChanged();
    }
</code>```

Body:
this is my first post here so be gentle :p
Here is the thing, I'm facing a really though issue and after several research i did not manage to figure out a clean solution. Let me explain:

I'm actually developing an android app for restaurant management.
In activity A, i'm able to create some articles with different parameters (picture, name, price ..).
I can also create a menu in which i indicate which articles are included. To do so i run Activity B that contains a dynamic list of the available articles (the ones i created) to be chosen. After picking up some of them the customised chosen objects are sent to Activity A through Parcel. And the chosen article list is updated in the menu.
But here is the thing, as far as i know, using Parcels create another instance of the object. As a result, if i modify or delete an article, the article list included in the menu does not change, and obviously i would like the list in the menu to be automatically updated.

Is there a way to simply pass customised objects through activities by reference?
What could be a clean solution to make the article list in the menu dynamic?

Here is some code:

In Activity A, in the menu interface i click + button to add an article, which run Activity B (the extras is the list of articles already included in the menu before, so in the beginning it's empty).

//Add article
    FloatingActionButton addArticleButton = (FloatingActionButton)parentActivity.findViewById(R.id.addArticleButton);
    addArticleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showMenuDetails(menuListView,menuAdapter,currentMenu);
            parentActivity.startActivityForResult(new Intent(parentActivity.getApplicationContext(),ChooseArticleActivity.class).putParcelableArrayListExtra("menuArticleList",currentMenu.getArticles()),PICK_ARTICLES);
        }
    });

In activity B: I select Articles in a list of available Articles (the ones i created). After picking up i press OK button to put the list of chosen articles in result Intent as Parcelable Extras

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.choose_article_layout);
    initializeLists();

    this.resultIntent = new Intent();
}

private void initializeLists(){
    final ListView articleToChoose = (ListView)findViewById(R.id.articleToChoose);
    final ListView articleChosen = (ListView)findViewById(R.id.articleChosen);

    final ArrayList
 articleToChooseList = (ArrayList
)MainActivity.model.getArticleList().getArticleList().clone();
    final ArrayList<Parcelable> articleChosenListParcelable = (ArrayList<Parcelable>)this.getIntent().getParcelableArrayListExtra("menuArticleList");
    final ArticleAdapter articleToChooseAdapter = new ArticleAdapter(getApplicationContext(), articleToChooseList);
    articleToChoose.setAdapter(articleToChooseAdapter);

    ArrayList
 articleChosenListTemp = new ArrayList<>();
    ArrayList
 articleToRemove = new ArrayList<>();
    for(Parcelable a:articleChosenListParcelable){
        articleChosenListTemp.add((Article)a);
        for(Article article:articleToChooseList){
            if(article.getName().equals(((Article) a).getName())){
                articleToRemove.add(article);
            }
        }
    }
    articleToChooseList.removeAll(articleToRemove);
    articleToChooseAdapter.notifyDataSetChanged();

    final ArrayList
 articleChosenList = articleChosenListTemp;

    final ArticleAdapter articleChosenAdapter = new ArticleAdapter(getApplicationContext(),articleChosenList);

    articleChosen.setAdapter(articleChosenAdapter);

    articleChosen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleChosenAdapter.getItem(position);
            articleChosenList.remove(articleClicked);
            articleToChooseList.add(articleClicked);
            articleChosenAdapter.notifyDataSetChanged();
            articleToChooseAdapter.notifyDataSetChanged();
        }
    });

    articleToChoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Article articleClicked = articleToChooseAdapter.getItem(position);
            if(!articleChosenList.contains(articleClicked)){
                articleChosenList.add(articleClicked);
                articleToChooseList.remove(articleClicked);
                articleToChooseAdapter.notifyDataSetChanged();
                articleChosenAdapter.notifyDataSetChanged();
            }
        }
    });

    Button okButton = (Button)findViewById(R.id.okButton);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chosenArticleListAttr = articleChosenList;
            resultIntent.putParcelableArrayListExtra("articleList",chosenArticleListAttr);
            setResult(RESULT_OK,resultIntent);
            finish();
        }
    });

    Button cancelButton = (Button)findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

In activity A, in onActivityResult i catch the result and update the list, but the added Articles here are not the same instance as the article list in the model

if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
        ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();

        ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
        gestionMenusLayout.getCurrentMenu().getArticles().clear();
        for(Parcelable a:chosenArticleList){
            gestionMenusLayout.getCurrentMenu().addArticle((Article)a);
        }
        articleAdapter.notifyDataSetChanged();
    }

Body:
I figured it out with a quite easy and simple solution finally.

I keep passing my Article objects through intents by parcels.
But as it creates a new instance, instead of adding this instance i add the original one (the one from the model) after an equality key check (the name of the article). By doing so i keep the reference on my Article.

Thank you for helping!

Edit:
Here is the code:

if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
        ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();

        ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
        gestionMenusLayout.getCurrentMenu().getArticles().clear();
        ArrayList<Article> modelArticles = MainActivity.model.getArticleList().getArticleList();
        for(Parcelable a:chosenArticleList){
            for(Article modelArticle:modelArticles){
                if(((Article)a).getName().equals(modelArticle.getName())){
                    gestionMenusLayout.getCurrentMenu().addArticle(modelArticle);
                }
            }
        }
        articleAdapter.notifyDataSetChanged();
    }


问:
Add or Remove multiple records without manual comparision
I have three tables: Person, Books and PersonBook. Person and Books are the main tables and PersonBook is a "mapping table" between them.

The logic is very simple: Each person has multiple books. In the Add / Remove Book Screen, the Person can Add a new book or remove the existing book.

Note: I depicted only the limited column for easy understanding, but
  the actual table has large number of columns and much more constrains.

Person:

```<code>PersonId    FirstName    LastName
_____________________________________
1           Emma         Watsan
2           John         Peter
3           Albert       Einsten
(....)
</code>```

Book:

```<code>BookId      BookName                ISBN           Author
___________________________________________________________
1           Beautiful Darkness
2           Bones Never Lies
3           The Lion
(...)
</code>```

PersonBook:

```<code>Id    PersonId     BookId
___________________________
1     1            1
2     2            3
3     3            3
(...)
</code>```

I have a list PersonBook, and I need to update it in the table using Entity State.

I'm currently doing the following:

```<code>Context.PersonBook.RemoveRange(Context.PersonBook.Where(m => m.PersonId == PersonId));
Context.PersonBook.AddRange(ListOfBooks);
</code>```

Here I give a simple condition:

```<code>Context.PersonBook.Where(m => m.PersonId == PersonId)
</code>```

But in reality, I have many checks.

My Requirement is to remove only the records which do not exist in the local collection ListOfBooks and add the records which do not exist in the DbSet.

Note: Each Person has 1K+ Books. In each edit request, comparing of
  all the records leads to performance degradation and what I am doing
  currently is better than that comparison, but it increases the
  primary key (auto Incremental Key PersonBook.Id) value to very large numbers.

答:
You were almost there, use contains to see if something is in the list and then exclude it if it is:  </p>

```<code>Context.PersonBook.RemoveRange(
            Contect.PersonBook.where(m => m.PersonId == PersonId
                                    && !ListOfBooks.Contains(m)));

Context.PersonBook.AddRange(ListOfBooks.Where(r => !Context.PersonBook.Contains(r))));
</code>```

Body:
I have three tables: Person, Books and PersonBook. Person and Books are the main tables and PersonBook is a "mapping table" between them.

The logic is very simple: Each person has multiple books. In the Add / Remove Book Screen, the Person can Add a new book or remove the existing book.

Note: I depicted only the limited column for easy understanding, but
  the actual table has large number of columns and much more constrains.

Person:

PersonId    FirstName    LastName
_____________________________________
1           Emma         Watsan
2           John         Peter
3           Albert       Einsten
(....)

Book:

BookId      BookName                ISBN           Author
___________________________________________________________
1           Beautiful Darkness
2           Bones Never Lies
3           The Lion
(...)

PersonBook:

Id    PersonId     BookId
___________________________
1     1            1
2     2            3
3     3            3
(...)

I have a list PersonBook, and I need to update it in the table using Entity State.

I'm currently doing the following:

Context.PersonBook.RemoveRange(Context.PersonBook.Where(m => m.PersonId == PersonId));
Context.PersonBook.AddRange(ListOfBooks);

Here I give a simple condition:

Context.PersonBook.Where(m => m.PersonId == PersonId)

But in reality, I have many checks.

My Requirement is to remove only the records which do not exist in the local collection ListOfBooks and add the records which do not exist in the DbSet.

Note: Each Person has 1K+ Books. In each edit request, comparing of
  all the records leads to performance degradation and what I am doing
  currently is better than that comparison, but it increases the
  primary key (auto Incremental Key PersonBook.Id) value to very large numbers.

Body:
You were almost there, use contains to see if something is in the list and then exclude it if it is:

Context.PersonBook.RemoveRange(
            Contect.PersonBook.where(m => m.PersonId == PersonId
                                    && !ListOfBooks.Contains(m)));

Context.PersonBook.AddRange(ListOfBooks.Where(r => !Context.PersonBook.Contains(r))));


问:
ui-router child state not able to access parent state data
A child state component in ui-router is having issues reading it's parents data. When logging the $stateParams it displays the correct information. This data is passed as parameters to the ui-sref attribute, which should result in the correct information being displayed to the user, but it isn't.

Here is the items id being logged (depending on which item is clicked on).

Why is the child state patents.patent failing to read the data from parent state patents?

```<code>var app = angular.module('myApp', ['ui.router']);

app.config(['$stateProvider', function($stateProvider) {

    var states = [
        {
            name: 'patents',
            url: '/patents',
            component: 'patents',
            resolve: {
                patents: function(patentsService) {
                    return patentsService.fetchAllPatents();
                }
            }
        },
        {
            name: 'patents.patent',
            url: '/{patentId}',
            component: 'patent',
            resolve: {
                patent: function(patents, $stateParams) {
                    return patents.find(function(patent){
                        return patent.id === $stateParams.patentId;
                    })
                }
            }
        }
    ]

    states.forEach(function(state) {
        $stateProvider.state(state);
    });

}]);
</code>```

```<code>app.service('patentsService', function($http) {

    var service = {

        fetchAllPatents: function() {
        return $http.get('http://localhost:8080/Sprint002b/restpatent/', {cache: true}).then(function(resp){
                    return resp.data
            });

        }
    };

    return service;

});
</code>```

components

```<code>angular.module('myApp').component('patents', {
    bindings: { patents: '<' },
    template: ' <div>' +
                    '<div>' +
                        '<table>' +
                            '<thead>' +
                                '<tr>' +
                                    '<td>Application No. </td>' +
                                    '<td>Client Ref</td>' +
                                    '<td>Cost now</td>' +
                                    '<td>Cost band end</td>' +
                                    '<td>Cost next</td>' +
                                    '<td>Renewal Date</td>' +
                                '</tr>' +
                            '</thead>' +
                            '<tbody>' +
                                '<tr ng-repeat="patent in $ctrl.patents">' +
                                    '<td><a ui-sref="patents.patent({patentId: patent.id})" ng-bind="patent.applicationNumber"></a></td>' +
                                    '<td ng-bind="patent.clientRef"></td>' +
                                    '<td ng-bind="patent.currentRenewalCost">$</td>' +
                                    '<td ng-bind="patent.costBandEndDate"></td>' +
                                    '<td ng-bind="patent.renewalCostNextStage"></td>' +
                                    '<td ng-bind="patent.renewalDueDate"></td>' +
                                '</tr>' +
                            '</tbody>' +
                        '</table>' +
                        '<div ui-view></div>' +
                    '</div>' +
                '</div>'
});
</code>```

```<code>angular.module('myApp').component('patent', {
  bindings: { patent: '<' },
  template: '<h3>A patent!</h3>' +

            '<div><p>Name: {{$ctrl.patent.id}}</p></div>' +
            '<div><p>Id: {{$ctrl.patent.applicationNumber}}</p></div>' +
            '<div><p>Company: {{$ctrl.patent.clientRef}}</p></div>' +

            '<button ui-sref="people">Close</button>'
});
</code>```

UPDATE

I managed to populate the child state with data, but only the first item within the JSON object.

I changed the data returned within my resolve property in my config file. Data is being loaded, but isn't changing when item is selected.

Any ideas on what I should do? This is all working in a plunkr https://plnkr.co/edit/jbZgIg?p=preview

```<code>{
   name: 'patents.patent',
   url: '/{patentId}',
   component: 'patent',
   resolve: {
       patent: function(patents, $stateParams) {
       return patents.find(function(patent){
       return $stateParams; // changed from patent.id === $stateParams.patentId
      })
    }
  }
}
</code>```

答:
It was down to using a strict equality operator rather than equal to. So the code is now:</p>

```<code>{
  name: 'patents.patent',
  url: '/{patentId}',
  component: 'patent',
  resolve: {
    patent: function(patents, $stateParams) {
    return patents.find(function(patent){
        return patent.id == $stateParams.patentId; //not === operator
      })
    }
  }
}
</code>```

Body:
A child state component in ui-router is having issues reading it's parents data. When logging the $stateParams it displays the correct information. This data is passed as parameters to the ui-sref attribute, which should result in the correct information being displayed to the user, but it isn't.

Here is the items id being logged (depending on which item is clicked on).

Why is the child state patents.patent failing to read the data from parent state patents?

var app = angular.module('myApp', ['ui.router']);

app.config(['$stateProvider', function($stateProvider) {

    var states = [
        {
            name: 'patents',
            url: '/patents',
            component: 'patents',
            resolve: {
                patents: function(patentsService) {
                    return patentsService.fetchAllPatents();
                }
            }
        },
        {
            name: 'patents.patent',
            url: '/{patentId}',
            component: 'patent',
            resolve: {
                patent: function(patents, $stateParams) {
                    return patents.find(function(patent){
                        return patent.id === $stateParams.patentId;
                    })
                }
            }
        }
    ]

    states.forEach(function(state) {
        $stateProvider.state(state);
    });

}]);

app.service('patentsService', function($http) {

    var service = {

        fetchAllPatents: function() {
        return $http.get('http://localhost:8080/Sprint002b/restpatent/', {cache: true}).then(function(resp){
                    return resp.data
            });

        }
    };

    return service;

});

components

angular.module('myApp').component('patents', {
    bindings: { patents: '<' },
    template: '
' +
                    '
' +
                        '
' +
                            '
' +
                                '
' +
                                    'Application No. 	' +
                                    'Client Ref	' +
                                    'Cost now	' +
                                    'Cost band end	' +
                                    'Cost next	' +
                                    'Renewal Date	' +
                                '
' +
                            '
' +
                            '
' +
                                '
' +
                                    '	' +
                                    '	' +
                                    '$	' +
                                    '	' +
                                    '	' +
                                    '	' +
                                '
' +
                            '
' +
                        '
' +
                        '

' +
                    '
' +
                '
'
});

angular.module('myApp').component('patent', {
  bindings: { patent: '<' },
  template: '
A patent!
' +

            '

Name: {{$ctrl.patent.id}}

' +
            '

Id: {{$ctrl.patent.applicationNumber}}

' +
            '

Company: {{$ctrl.patent.clientRef}}

' +

            '<button ui-sref="people">Close</button>'
});

UPDATE

I managed to populate the child state with data, but only the first item within the JSON object.

I changed the data returned within my resolve property in my config file. Data is being loaded, but isn't changing when item is selected.

Any ideas on what I should do? This is all working in a plunkr https://plnkr.co/edit/jbZgIg?p=preview

{
   name: 'patents.patent',
   url: '/{patentId}',
   component: 'patent',
   resolve: {
       patent: function(patents, $stateParams) {
       return patents.find(function(patent){
       return $stateParams; // changed from patent.id === $stateParams.patentId
      })
    }
  }
}

Body:
It was down to using a strict equality operator rather than equal to. So the code is now:

{
  name: 'patents.patent',
  url: '/{patentId}',
  component: 'patent',
  resolve: {
    patent: function(patents, $stateParams) {
    return patents.find(function(patent){
        return patent.id == $stateParams.patentId; //not === operator
      })
    }
  }
}


问:
Matplotlib: How to make a stacked plot of count of values in a Numpy array
Hey I have the following problem. I have a array like this:

```<code> arr1=
[[4 4 4]
 [4 4 6]
 [4 3 4]
 [4 4 7]
 [4 4 3]
 [4 4 1]
 [3 4 7]
 [4 3 7]
 [4 4 5]
 [4 3 6]]
</code>```

Now i want to get a stacked bar plot(histogram), that shows the number of different elements,, like this:

My frist approach was to bincount the elements, fill the arrays up, but then i dont know what to do.

```<code>arr2=
    [[0 0 0]
     [0 0 1]
     [0 0 0]
     [1 3 1]
     [9 7 2]
     [0 0 1]
     [0 0 2]
     [0 0 3]]
</code>```

答:
Here is the output

and the code to generate the same

```<code>import numpy as np
import pandas as pd
data = np.array([[4, 4, 4],
 [4, 4, 6],
 [4, 3, 4],
 [4, 4, 7],
 [4, 4, 3],
 [4, 4, 1],
 [3, 4, 7],
 [4, 3, 7],
 [4, 4, 5],
 [4, 3, 6]])

columns = ['Col1', 'Col2', 'Col3']
df = pd.DataFrame(data, columns=columns)
out = {}
for column in columns:
    out[column] = pd.value_counts(df[column])

uniq_df = pd.DataFrame(out).fillna(0)

uniq_df.T.plot(kind="bar", stacked=True)
</code>```

Body:
Hey I have the following problem. I have a array like this:

 arr1=
[[4 4 4]
 [4 4 6]
 [4 3 4]
 [4 4 7]
 [4 4 3]
 [4 4 1]
 [3 4 7]
 [4 3 7]
 [4 4 5]
 [4 3 6]]

Now i want to get a stacked bar plot(histogram), that shows the number of different elements,, like this:

My frist approach was to bincount the elements, fill the arrays up, but then i dont know what to do.

arr2=
    [[0 0 0]
     [0 0 1]
     [0 0 0]
     [1 3 1]
     [9 7 2]
     [0 0 1]
     [0 0 2]
     [0 0 3]]

Body:
Here is the output

and the code to generate the same

import numpy as np
import pandas as pd
data = np.array([[4, 4, 4],
 [4, 4, 6],
 [4, 3, 4],
 [4, 4, 7],
 [4, 4, 3],
 [4, 4, 1],
 [3, 4, 7],
 [4, 3, 7],
 [4, 4, 5],
 [4, 3, 6]])

columns = ['Col1', 'Col2', 'Col3']
df = pd.DataFrame(data, columns=columns)
out = {}
for column in columns:
    out[column] = pd.value_counts(df[column])

uniq_df = pd.DataFrame(out).fillna(0)

uniq_df.T.plot(kind="bar", stacked=True)


问:
How to join three tables with eloquent using a model
I've never studied Eloquent.  I am studying APIs and I want to get some data as kickly as possible, without writing sql, what is I usually do.

I have the tables: "house" related to "announcement" (one to one) and the "announcement" table is related to "advertiser" (one to many).

When I tried

```<code>       $house = \App\House::where('house_id', $id)->with('announcement', 'advertiser')->first();
</code>```

I get the error:  announcement undefined method.
I think I set up the relationship on the models correctly so I didn't include them here. I want to join using the model House because I am not using the default connection when using Eloquent.

答:
for a nested relationship use dot like announcement.advertiser

$house = App\House::with(['announcement', 'announcement.advertiser'])->where('house_id', $id)->first();

Body:
I've never studied Eloquent.  I am studying APIs and I want to get some data as kickly as possible, without writing sql, what is I usually do.

I have the tables: "house" related to "announcement" (one to one) and the "announcement" table is related to "advertiser" (one to many).

When I tried

       $house = \App\House::where('house_id', $id)->with('announcement', 'advertiser')->first();

I get the error:  announcement undefined method.
I think I set up the relationship on the models correctly so I didn't include them here. I want to join using the model House because I am not using the default connection when using Eloquent.


问:
Android App Compile Not Generating Package Resources
When attempting to compile my Xamarin.Android app I get the compile error:

Error 3   The file "obj\Debug\android\bin\packaged_resources" does not exist. MyApp.UI.Droid

This error occurred after I made some changes (added some new classes - cannot remember what it was). But I didn't change any project settings, nor go delete actual files in the obj folder.

What is the cause of this error and how can I fix this?

Some information that may be useful:

The project is a Cross-Platform PCL project - Core, Android, and iOS Projects

The project uses MVVM Cross

答:
Got this error in Visual Studio 2017 Xamarin android project on Windows.
After lot of experiments with resource's files I found, that filename length and extension of image file in the drawable folder affect the result of compillation!

drawable/abcde.png - compilled ok

drawable/abcdef.png - error, "obj\Debug\android\bin\packaged_resources" does not exist

If rename image to file without .png extension, compilled without errors.

Spended a lot of time and was confused :-/


问:
Different way of Model object creation in laravel
There are following ways in which we can create model objects in controller and insert records to database.

First Approach

```<code>$object1 = new Model;
$object1->column = $val;

...
...

$object1->save();
</code>```

Second Approach

```<code>$object2 = new Model();
$object2->column = $val;

...
...

$object2->save();
</code>```

Both of these work without any problem. I have checked and searched on Internet. But, I don't understand that these two way are exactly same or something else.

And another thing is if I just want to save records to a database table which one is correct and best practice ?

Can anyone describe ?

Thanks,

答:
I found this post on stackoverflow : Instantiate a class with or without parentheses?

Here is a part of the answer :

While both ways are fine, I personally would prefer using new Car(); because usually, a method is being called here, and function/method calls in PHP require (). Also, it's more consistent with instantiations that have parameters.

So there is no negligible differences between those two approaches. So choose the one that is the most relevant to you.
But keep using the same approach !

ContentLicense: CC BY-SA 4.0

Body:
There are following ways in which we can create model objects in controller and insert records to database.

First Approach

$object1 = new Model;
$object1->column = $val;

...
...

$object1->save();

Second Approach

$object2 = new Model();
$object2->column = $val;

...
...

$object2->save();

Both of these work without any problem. I have checked and searched on Internet. But, I don't understand that these two way are exactly same or something else.

And another thing is if I just want to save records to a database table which one is correct and best practice ?

Can anyone describe ?

Thanks,


问:
What input should I give to crc16 Method
This my Mod bus crc_16 embedded code. I have run this code in code block many Times. There is no error but I am not getting actual crc value. I should get crc 05C8 and I am getting 8512 right now.

I think I giving wrong input while calling CRC method. I am passing string and its length. So please help me.

```<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define POLY 0x8005
    unsigned int ModRTU_CRC(unsigned char * mod_data,unsigned int length)
    {
    unsigned int CRC16 = 0xFFFF;

    unsigned int pos=0,i=0;

    for(pos=0;pos<length;pos++)
    {
    CRC16 ^= (unsigned int) mod_data[pos];

    for(i=0;i<8;i++)
    {
        if((CRC16 & 0x0001)!=0)
        {
            CRC16 >>=1;
            CRC16^=0xA001;
        }
        else
        {
            CRC16 >>=1;
        }
    }

    }

   return CRC16;

    }

   int main()
   {

    //char *frame = "010600081388";
   //  char *frame = "010300080001";

   char frame[7];
        frame[0]=0x01;
       frame[1]=0x03;
       frame[2]=0x00;
       frame[3]=0x08;
       frame[4]=0x00;
       frame[5]=0x01;
       frame[6]='\0';

     printf("%x\n",frame);
     int len = strlen(frame);
     unsigned int  crcv = ModRTU_CRC(frame,len);
    printf("%x\n",crcv);
   return 0;
       }
</code>```

答:
```<code>#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define POLY 0x8005
unsigned int ModRTU_CRC(unsigned char * mod_data,unsigned int length)
{
unsigned int CRC16 = 0xFFFF;

unsigned int pos=0,i=0;

for(pos=0;pos<length;pos++)
{
    CRC16 ^= (unsigned int) mod_data[pos];

    for(i=0;i<8;i++)
    {
        if((CRC16 & 0x0001)!=0)
        {
            CRC16 >>=1;
            CRC16^=0xA001;
        }
        else
        {
            CRC16 >>=1;
        }
    }

  }

  return CRC16;

 }

 int main()
 {

        uint8_t message[80] = { // 6-byte test vector
  0x01, 0x03, 0x00, 0x08, 0x00, 0x01
};
int message_length = 6;
 printf("%x\n",message);
// int len = strlen(message);
 uint16_t the_CRC = ModRTU_CRC(message,message_length);
 printf("%x\n",the_CRC);
        return 0;
   }

 `
</code>```

Body:
This my Mod bus crc_16 embedded code. I have run this code in code block many Times. There is no error but I am not getting actual crc value. I should get crc 05C8 and I am getting 8512 right now.

I think I giving wrong input while calling CRC method. I am passing string and its length. So please help me.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define POLY 0x8005
    unsigned int ModRTU_CRC(unsigned char * mod_data,unsigned int length)
    {
    unsigned int CRC16 = 0xFFFF;

    unsigned int pos=0,i=0;

    for(pos=0;pos<length;pos++)
    {
    CRC16 ^= (unsigned int) mod_data[pos];

    for(i=0;i<8;i++)
    {
        if((CRC16 & 0x0001)!=0)
        {
            CRC16 >>=1;
            CRC16^=0xA001;
        }
        else
        {
            CRC16 >>=1;
        }
    }

    }

   return CRC16;

    }

   int main()
   {

    //char *frame = "010600081388";
   //  char *frame = "010300080001";

   char frame[7];
        frame[0]=0x01;
       frame[1]=0x03;
       frame[2]=0x00;
       frame[3]=0x08;
       frame[4]=0x00;
       frame[5]=0x01;
       frame[6]='\0';

     printf("%x\n",frame);
     int len = strlen(frame);
     unsigned int  crcv = ModRTU_CRC(frame,len);
    printf("%x\n",crcv);
   return 0;
       }


问:
Extract given columns from a matrix based on a vector in Matlab
I have this matrix:

```<code>A = [2 3 5; 1 7 8; 4 9 1; 6 2 6]
</code>```

and this vector:

```<code>b = [1 0 1 0]
</code>```

And I would like to get this matrix:

```<code>C = [2 3 5; 4 9 1]
</code>```

Thanks for your answers.

答:
This will do the job:</p>

```<code>C=A(b==1,:)
</code>```

Body:
I have this matrix:

A = [2 3 5; 1 7 8; 4 9 1; 6 2 6]

and this vector:

b = [1 0 1 0]

And I would like to get this matrix:

C = [2 3 5; 4 9 1]

Thanks for your answers.

Body:
This will do the job:

C=A(b==1,:)


问:
Improve SQL query performance
I have three tables where I store actual person data (person), teams (team) and entries (athlete). The schema of the three tables is:

In each team there might be two or more athletes.

I'm trying to create a query to produce the most frequent pairs, meaning people who play in teams of two. I came up with the following query:

```<code>SELECT p1.surname, p1.name, p2.surname, p2.name, COUNT(*) AS freq
FROM person p1, athlete a1, person p2, athlete a2
WHERE
    p1.id = a1.person_id AND
    p2.id = a2.person_id AND
    a1.team_id = a2.team_id AND
    a1.team_id IN
          ( SELECT team.id
            FROM team, athlete
            WHERE team.id = athlete.team_id
            GROUP BY team.id
            HAVING COUNT(*) = 2 )
GROUP BY p1.id
ORDER BY freq DESC
</code>```

Obviously this is a resource consuming query. Is there a way to improve it?

答:
Here, Some tips to improve SQL select query performance like:

Use SET NOCOUNT ON it is help to decrease network traffic thus
improve performance.

Use fully qualified procedure name (e.g.
database.schema.objectname)

Use sp_executesql instead of execute for dynamic query

Don't use select * use select column1,column2,.. for IF EXISTS
or SELECT operation

Avoid naming user Stored Procedure like sp_procedureName Becouse,
If we use Stored Procedure name start with sp_ then SQL first
search in master db. so it can down query performance.

Title: Improve SQL query performance

Body:
I have three tables where I store actual person data (person), teams (team) and entries (athlete). The schema of the three tables is:

In each team there might be two or more athletes.

I'm trying to create a query to produce the most frequent pairs, meaning people who play in teams of two. I came up with the following query:

SELECT p1.surname, p1.name, p2.surname, p2.name, COUNT(*) AS freq
FROM person p1, athlete a1, person p2, athlete a2
WHERE
    p1.id = a1.person_id AND
    p2.id = a2.person_id AND
    a1.team_id = a2.team_id AND
    a1.team_id IN
          ( SELECT team.id
            FROM team, athlete
            WHERE team.id = athlete.team_id
            GROUP BY team.id
            HAVING COUNT(*) = 2 )
GROUP BY p1.id
ORDER BY freq DESC

Obviously this is a resource consuming query. Is there a way to improve it?


问:
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery
In my web application I get the following error:

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping
  for 'jquery'. Please add a ScriptResourceMapping named
  jquery(case-sensitive).

Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: WebForms
  UnobtrusiveValidationMode requires a ScriptResourceMapping for
  'jquery'. Please add a ScriptResourceMapping named
  jquery(case-sensitive).

How can I solve it?

答:
To fix this problem on specific page need to set some validation settings when page loading. Write code below in Page_Load() method:

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
    }
</code>```

Its work for me in .NET 4.5

Body:
To fix this problem on specific page need to set some validation settings when page loading. Write code below in Page_Load() method:

protected void Page_Load(object sender, EventArgs e)
    {
        ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
    }

Its work for me in .NET 4.5


问:
Why does a C++ friend class need a forward declaration only in other namespaces?
Suppose I have a class F that should be friend to the classes G (in the global namespace) and C (in namespace A).

to be friend to A::C, F must be forward declared.

to be friend to G, no forward declaration of F is necessary.

likewise, a class A::BF can be friend to A::C without forward declaration

The following code illustrates this and compiles with GCC 4.5, VC++ 10 and at least with one other compiler.

```<code>class G {
    friend class F;
    int g;
};

// without this forward declaration, F can't be friend to A::C
class F;

namespace A {

class C {
    friend class ::F;
    friend class BF;
    int c;
};

class BF {
public:
    BF() { c.c = 2; }
private:
    C c;
};

} // namespace A

class F {
public:
    F() { g.g = 3; c.c = 2; }
private:
    G g;
    A::C c;
};

int main()
{
    F f;
}
</code>```

To me this seems inconsistent. Is there a reason for this or is it just a design decision of the standard?

答:
C++ Standard ISO/IEC 14882:2003(E)

7.3.1.2  Namespace member definitions

Paragraph 3

Every name first declared in a
  namespace is a member of that
  namespace.  If a friend declaration in
  a non-local class first declares a
  class or function
  (this implies that the name of the class or function is unqualified) the friend class
  or function is a member of the
  innermost enclosing namespace.

```<code>// Assume f and g have not yet been defined.
void h(int);
template <class T> void f2(T);
namespace A {
   class X {
   friend void f(X);  //  A::f(X) is a friend
      class Y {
         friend void g();  //  A::g is a friend
         friend void h(int);  //  A::h is a friend
         //  ::h not considered
         friend void f2<>(int);  //  ::f2<>(int) is a friend
      };
   };
   //  A::f, A::g and A::h are not visible here
   X x;
   void g() { f(x); }  // definition of A::g
   void f(X) { /* ... */}  // definition of A::f
   void h(int) { /* ... */ }  // definition of A::h
   //  A::f, A::g and A::h are visible here and known to be friends
}
</code>```

Your friend class BF; is a declaration of A::BF in namespace A rather than global namespace. You need the global prior declaration to avoid this new declaration.

Body:
Suppose I have a class F that should be friend to the classes G (in the global namespace) and C (in namespace A).

to be friend to A::C, F must be forward declared.

to be friend to G, no forward declaration of F is necessary.

likewise, a class A::BF can be friend to A::C without forward declaration

The following code illustrates this and compiles with GCC 4.5, VC++ 10 and at least with one other compiler.

class G {
    friend class F;
    int g;
};

// without this forward declaration, F can't be friend to A::C
class F;

namespace A {

class C {
    friend class ::F;
    friend class BF;
    int c;
};

class BF {
public:
    BF() { c.c = 2; }
private:
    C c;
};

} // namespace A

class F {
public:
    F() { g.g = 3; c.c = 2; }
private:
    G g;
    A::C c;
};

int main()
{
    F f;
}

To me this seems inconsistent. Is there a reason for this or is it just a design decision of the standard?

Body:
C++ Standard ISO/IEC 14882:2003(E)

7.3.1.2  Namespace member definitions

Paragraph 3

Every name first declared in a
  namespace is a member of that
  namespace.  If a friend declaration in
  a non-local class first declares a
  class or function
  (this implies that the name of the class or function is unqualified) the friend class
  or function is a member of the
  innermost enclosing namespace.

// Assume f and g have not yet been defined.
void h(int);
template <class T> void f2(T);
namespace A {
   class X {
   friend void f(X);  //  A::f(X) is a friend
      class Y {
         friend void g();  //  A::g is a friend
         friend void h(int);  //  A::h is a friend
         //  ::h not considered
         friend void f2<>(int);  //  ::f2<>(int) is a friend
      };
   };
   //  A::f, A::g and A::h are not visible here
   X x;
   void g() { f(x); }  // definition of A::g
   void f(X) { /* ... */}  // definition of A::f
   void h(int) { /* ... */ }  // definition of A::h
   //  A::f, A::g and A::h are visible here and known to be friends
}

Your friend class BF; is a declaration of A::BF in namespace A rather than global namespace. You need the global prior declaration to avoid this new declaration.


问:
XUnit, RhinoMocks, or TestDriven.Net Issue
Having some issues wrapping my head around class instantiation and TestDriven.Net(v4.0.3478) or XUnit(v2.2.0), RhinoMocks(v3.6.1), and structuremap.automocking(v4.0.0.315).

Given this code:

```<code>public class Tests1
{
    [Fact]
    public void passing_test()
    {
        var mocker = new RhinoAutoMocker<Subject>();
        mocker.Get<IData>().Stub(x => x.Strings).Return(new List<string> {""});

        var result = mocker.ClassUnderTest.GetStrings();

        result.Count().ShouldEqual(1);
    }
}

public class Tests2
{
    [Fact]
    public void passing_test()
    {
        var mocker = new RhinoAutoMocker<Subject>();
        mocker.Get<IData>().Stub(x => x.Strings).Return(new List<string> {""});

        var result = mocker.ClassUnderTest.GetStrings();

        result.Count().ShouldEqual(1);
    }
}

public class Subject
{
    private readonly IData _data;

    public Subject(IData data)
    {
        _data = data;
    }

    public IEnumerable<string> GetStrings()
    {
        return _data.Strings;
    }
}

public interface IData
{
    IEnumerable<string> Strings { get; set; }
}
</code>```

All tests run fine when I right click -> Run Test(s) on specific test method or a specific class definition.

Tests fail when I right click on project, folder containing tests or the namespace definition of the class above.

The errors are NullReferenceException, when doing asserts, it seems to be the stub's data. It's random, sometimes Tests1.passing_test fails, sometimes Tests2.passing_test fails. Never both.

Thinking it has to with RhinoAutoMocker and/or the MockRepository not being reset between test fixtures?

UPDATE: simplified the code to show the problem, also given code is complete, using NUnit [Test] instead of XUnit [Fact] attributes works, everything behaves as normal.

答:
In your example, you have two separate test classes.
By default, xUnit v2 will run these tests in parallel.

I have experienced the same issue, but in my case using the static MockRepository.GenerateMock.
The static class being used across the parallel tests results in exceptions.
The seeming randomness of the test failures depends on which tests run first.

There are two alternatives I can see.
1. Tests in a single class - not really workable
2. Use the XUnit Collection attribute to place all tests classes in the same collection - this worked for me.

see: http://xunit.github.io/docs/running-tests-in-parallel.html

Another alternative is to turn off parallelism for xUnit using the following attribute in your test assembly

[assembly: CollectionBehavior(DisableTestParallelization = true)]

Body:
Having some issues wrapping my head around class instantiation and TestDriven.Net(v4.0.3478) or XUnit(v2.2.0), RhinoMocks(v3.6.1), and structuremap.automocking(v4.0.0.315).

Given this code:

public class Tests1
{
    [Fact]
    public void passing_test()
    {
        var mocker = new RhinoAutoMocker<Subject>();
        mocker.Get<IData>().Stub(x => x.Strings).Return(new List<string> {""});

        var result = mocker.ClassUnderTest.GetStrings();

        result.Count().ShouldEqual(1);
    }
}

public class Tests2
{
    [Fact]
    public void passing_test()
    {
        var mocker = new RhinoAutoMocker<Subject>();
        mocker.Get<IData>().Stub(x => x.Strings).Return(new List<string> {""});

        var result = mocker.ClassUnderTest.GetStrings();

        result.Count().ShouldEqual(1);
    }
}

public class Subject
{
    private readonly IData _data;

    public Subject(IData data)
    {
        _data = data;
    }

    public IEnumerable<string> GetStrings()
    {
        return _data.Strings;
    }
}

public interface IData
{
    IEnumerable<string> Strings { get; set; }
}

All tests run fine when I right click -> Run Test(s) on specific test method or a specific class definition.

Tests fail when I right click on project, folder containing tests or the namespace definition of the class above.

The errors are NullReferenceException, when doing asserts, it seems to be the stub's data. It's random, sometimes Tests1.passing_test fails, sometimes Tests2.passing_test fails. Never both.

Thinking it has to with RhinoAutoMocker and/or the MockRepository not being reset between test fixtures?

UPDATE: simplified the code to show the problem, also given code is complete, using NUnit [Test] instead of XUnit [Fact] attributes works, everything behaves as normal.


问:
jQuery autohide element after 5 seconds
Is it possible to automatically hide an element in a web page 5 seconds after the form loads using jQuery?

Basically, I've got

```<code><div id="successMessage">Project saved successfully!</div>
</code>```

that I'd like to disappear after 5 seconds. I've looked at jQuery UI and the hide effect but I'm having a little trouble getting it work the way I want it to.

```<code><script type="text/javascript">
        $(function() {
            function runEffect() {

                var selectedEffect = 'blind';

                var options = {};

                $("#successMessage").hide(selectedEffect, options, 500);
            };

            $("#successMessage").click(function() {
                runEffect();
                return false;
            });
        });
    </script>
</code>```

I'd like the click function to be removed and add a timeout method that calls the runEffect() after 5 seconds.

答:
This is how you can set the timeout after you click.

```<code>$(".selectorOnWhichEventCapture").on('click', function() {
    setTimeout(function(){
        $(".selector").doWhateverYouWantToDo();
    }, 5000);
});
</code>```

//5000 = 5sec = 5000 milisec

OwnerDisplayName: Chris Conway

Title: jQuery autohide element after 5 seconds

Body:
Is it possible to automatically hide an element in a web page 5 seconds after the form loads using jQuery?

Basically, I've got

Project saved successfully!

that I'd like to disappear after 5 seconds. I've looked at jQuery UI and the hide effect but I'm having a little trouble getting it work the way I want it to.

I'd like the click function to be removed and add a timeout method that calls the runEffect() after 5 seconds.

Body:
This is how you can set the timeout after you click.

$(".selectorOnWhichEventCapture").on('click', function() {
    setTimeout(function(){
        $(".selector").doWhateverYouWantToDo();
    }, 5000);
});

//5000 = 5sec = 5000 milisec


问:
How to use data from the localstorage in angular 2
How to use data from the localstorage for the another component. Localstorage in service are:

localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success,res:res.data}));

I want to use id, username etc from the data in another component How it possible

答:
currentUser = JSON.parse(localStorage.getItem('currentUser'));
    userid=  (this.currentUser.res.id);</p>


问:
Add Multiple URLs to this PowerShell Script?
I am using a script to call URLs, get the output, and save the output to a text file. It all works great. However, when I need to call multiple URLs in succession it causes CPU spikes because it is starting/stopping powershell.exe so many times. Is there a whay I could use a for each technique for each URL while still saving the output? Here is my script:

```<code>$content = Get-Content $PSScriptRoot\urls.txt

echo "Testing for $content"

(Invoke-WebRequest -Uri "$content").Content |
    Out-File -FilePath "$PSScriptRoot\out.txt"

$status = Get-Content $PSScriptRoot\out.txt
</code>```

Note that the two echo are just for debugging purposes, don't really matter.

答:
Is this Something that you wanted to do?

```<code>$contents = Get-Content $PSScriptRoot\urls.txt
foreach($content in $contents){
(Invoke-WebRequest -Uri "$content").Content |Out-File -FilePath $PSScriptRoot\out.txt -Append
}
</code>```

I Wrote a urls.txt with 7-8 urls,And it worked fine for me.

Body:
I am using a script to call URLs, get the output, and save the output to a text file. It all works great. However, when I need to call multiple URLs in succession it causes CPU spikes because it is starting/stopping powershell.exe so many times. Is there a whay I could use a for each technique for each URL while still saving the output? Here is my script:

$content = Get-Content $PSScriptRoot\urls.txt

echo "Testing for $content"

(Invoke-WebRequest -Uri "$content").Content |
    Out-File -FilePath "$PSScriptRoot\out.txt"

$status = Get-Content $PSScriptRoot\out.txt

Note that the two echo are just for debugging purposes, don't really matter.

Body:
Is this Something that you wanted to do?

$contents = Get-Content $PSScriptRoot\urls.txt
foreach($content in $contents){
(Invoke-WebRequest -Uri "$content").Content |Out-File -FilePath $PSScriptRoot\out.txt -Append
}

I Wrote a urls.txt with 7-8 urls,And it worked fine for me.


问:
String comparison is too slow in R language
there

String comparison is too slow in R language.
it will take 3 minutes, it is too slow; if the string is longer, it will take more time. Are there any ways to fast compare strings? Thanks!

```<code>    date()
    strArray1<-rep("1234567890",10000)
    strArray2<-rep("1234567890",10000)
    tt<-0
    for(xx in 1:10000)
    {
        for(yy in 1:10000)
        {
            if(strArray1[xx]==strArray2[yy])
            {
                tt<-tt+1
            }

        }

    }
    date()
</code>```

UPDATE:
In fact, I have two files, say a.txt and b.txt as follows:

```<code>a.txt (>10000 lines):
abc00001
abc00035
abc15747
....
</code>```

b.txt(>50000 lines):

```<code>abc00001 blablabla...
abc00002 blablabla...
abc00003 blablabla...
abc00004 blablabla...
....
abc60000  blablabla...
</code>```

What I want to do is to extract rows from b.txt. The rows which contain a.txt's IDs are to be extracted. This will compare thousands of strings and take long time.

答:
String comparisons per se are not terribly slow:

```<code>> v <- rep("1234567890",100)
> microbenchmark(v=="1234567890")
Unit: nanoseconds
              expr min  lq    mean median  uq   max neval
 v == "1234567890"   0 355 1006.05    355 709 39639   100
</code>```

The expression v == "1234567890" requires 100 string comparisons to evaluate. The mean time to do so is 1000 nanoseconds which implies that (on my machine) it takes an average of 10 nanoseconds for such a comparison. That is reasonably quick for strings of length 10. On the other hand for loops in R are notoriously slow. You need to find a way to vectorize the code (which will run the implicit loops in optimized C rather than interpreted R).

For example, the following vectorized code (which computes the same value of tt as your code) runs in less than 1 second:

```<code>print(date())
strArray1<-rep("1234567890",10000)
strArray2<-rep("1234567890",10000)
tt<-sum(sapply(strArray1,function(s){sum(strArray2 == s)}))
print(tt)
print(date())
</code>```

Doubtless it could be improved even better since solutions which use sapply are frequently suboptimal.

Body:
there

String comparison is too slow in R language.
it will take 3 minutes, it is too slow; if the string is longer, it will take more time. Are there any ways to fast compare strings? Thanks!

    date()
    strArray1<-rep("1234567890",10000)
    strArray2<-rep("1234567890",10000)
    tt<-0
    for(xx in 1:10000)
    {
        for(yy in 1:10000)
        {
            if(strArray1[xx]==strArray2[yy])
            {
                tt<-tt+1
            }

        }

    }
    date()

UPDATE:
In fact, I have two files, say a.txt and b.txt as follows:

a.txt (>10000 lines):
abc00001
abc00035
abc15747
....

b.txt(>50000 lines):

abc00001 blablabla...
abc00002 blablabla...
abc00003 blablabla...
abc00004 blablabla...
....
abc60000  blablabla...

What I want to do is to extract rows from b.txt. The rows which contain a.txt's IDs are to be extracted. This will compare thousands of strings and take long time.

Body:
String comparisons per se are not terribly slow:

> v <- rep("1234567890",100)
> microbenchmark(v=="1234567890")
Unit: nanoseconds
              expr min  lq    mean median  uq   max neval
 v == "1234567890"   0 355 1006.05    355 709 39639   100

The expression v == "1234567890" requires 100 string comparisons to evaluate. The mean time to do so is 1000 nanoseconds which implies that (on my machine) it takes an average of 10 nanoseconds for such a comparison. That is reasonably quick for strings of length 10. On the other hand for loops in R are notoriously slow. You need to find a way to vectorize the code (which will run the implicit loops in optimized C rather than interpreted R).

For example, the following vectorized code (which computes the same value of tt as your code) runs in less than 1 second:

print(date())
strArray1<-rep("1234567890",10000)
strArray2<-rep("1234567890",10000)
tt<-sum(sapply(strArray1,function(s){sum(strArray2 == s)}))
print(tt)
print(date())

Doubtless it could be improved even better since solutions which use sapply are frequently suboptimal.


问:
How to use matrixvariable in FeignClient api class?
I have one FeignClient class and I want to use MatrixVariable to pass parameters
like below

```<code>@FeignClient(value = "apiService", url = "${api.url}", configuration =ApiServiceConfiguration.class)
public interface ApiServiceFeign {
    @RequestMapping(value = "/students{matrixParam}", method = RequestMethod.GET)
    StudentList getStudents(@MatrixVariable("matrixParam") Map<String,List<String>>);
}
</code>```

but when I use above code it doesn't work. Feign Client can not understand the MatrixVariable.
Is there any way to make this call?

Currently, I have found the temporary solution using PathVariable like below

```<code>@FeignClient(value = "apiService", url = "${api.url}", configuration =ApiServiceConfiguration.class)
public interface ApiServiceFeign {
    @RequestMapping(value = "/students;name={name};accountId={accountId}", method = RequestMethod.GET)
    StudentList getStudents(@PathVariable("name") String name,@PathVariable("accountId") Long accountId);
}
</code>```

I really appreciate if any one give better solution using MatrixVariable in Feignclient

答:
You must enable the matrix variables usage in spring. That can be done by following.

Note that to enable the use of matrix variables, you must set the removeSemicolonContent property of RequestMappingHandlerMapping to false. By default it is set to true.

The MVC Java config and the MVC namespace both provide options for enabling the use of matrix variables.
If you are using Java config, The Advanced Customizations with MVC Java Config section describes how the RequestMappingHandlerMapping can be customized.

In the MVC namespace, the  element has an enable-matrix-variables attribute that should be set to true. By default it is set to false.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven enable-matrix-variables="true"/>

</beans>
</code>```

Body:
I have one FeignClient class and I want to use MatrixVariable to pass parameters
like below

@FeignClient(value = "apiService", url = "${api.url}", configuration =ApiServiceConfiguration.class)
public interface ApiServiceFeign {
    @RequestMapping(value = "/students{matrixParam}", method = RequestMethod.GET)
    StudentList getStudents(@MatrixVariable("matrixParam") Map<String,List<String>>);
}

but when I use above code it doesn't work. Feign Client can not understand the MatrixVariable.
Is there any way to make this call?

Currently, I have found the temporary solution using PathVariable like below

@FeignClient(value = "apiService", url = "${api.url}", configuration =ApiServiceConfiguration.class)
public interface ApiServiceFeign {
    @RequestMapping(value = "/students;name={name};accountId={accountId}", method = RequestMethod.GET)
    StudentList getStudents(@PathVariable("name") String name,@PathVariable("accountId") Long accountId);
}

I really appreciate if any one give better solution using MatrixVariable in Feignclient

Body:
You must enable the matrix variables usage in spring. That can be done by following.

Note that to enable the use of matrix variables, you must set the removeSemicolonContent property of RequestMappingHandlerMapping to false. By default it is set to true.

The MVC Java config and the MVC namespace both provide options for enabling the use of matrix variables.
If you are using Java config, The Advanced Customizations with MVC Java Config section describes how the RequestMappingHandlerMapping can be customized.

In the MVC namespace, the  element has an enable-matrix-variables attribute that should be set to true. By default it is set to false.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven enable-matrix-variables="true"/>

</beans>


问:
Sorting dropdown list using Javascript
i want to sort the drop down items using javascript,can anyone tell me how to do this.</p>

答:
DEPENDS ON JQUERY

```<code>function SortOptions(id) {
    var prePrepend = "#";
    if (id.match("^#") == "#") prePrepend = "";
    $(prePrepend + id).html($(prePrepend + id + " option").sort(
        function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 })
    );
}
</code>```

Examples:

<select id="my-list-id"> is sorted with:

```<code>SortOptions("#my-list-id");
</code>```

OR

```<code>SortOptions("my-list-id");
</code>```

OwnerDisplayName: Chetan

Title: Sorting dropdown list using Javascript

Body:
DEPENDS ON JQUERY

function SortOptions(id) {
    var prePrepend = "#";
    if (id.match("^#") == "#") prePrepend = "";
    $(prePrepend + id).html($(prePrepend + id + " option").sort(
        function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 })
    );
}

Examples:

<select id="my-list-id"> is sorted with:

SortOptions("#my-list-id");

OR

SortOptions("my-list-id");


问:
Handling "refresh" or "back" in AJAX to keep "parent" html
So I'm fairly new to AJAX, I have a simple 3 page project which I am using AJAX to transition between pages.

I have an index.html page which loads all the html / body / scripts etc:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax practice</title>

    <link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>

    <div class="" id="wrapper">
    <div class="overlay"></div>
        <header>
            <nav>
                <ul>
                    <li><a class="aboutBtn" href="main.html">Home</a></li>
                    <li><a class="aboutBtn" href="about.html">About</a></li>
                    <li><a class="aboutBtn" href="#">Menu</a></li>
                    <li><a class="aboutBtn" href="#">Contact</a></li>
                </ul>
            </nav>
        </header>

        <div class="page wrapper" id="page">
            <div class="circle" id="black"></div>
            <div class="circle" id="red"></div>
            <div class="circle" id="blue"></div>

            <section class="mainSplash main">

                <div class="mainSplash__content" id="content">

                </div>

            </section>
        </div> <!-- page -->
    </div> <!-- wrapper -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="scripts/index.js"></script>

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

and my 2 pages are:

main.html:

```<code><h1 class="mainSplash__header--h1">Main</h1>
</code>```

about.html:

```<code><h1 class="mainSplash__header--h1">About</h1>
</code>```

Here is the AJAX which transitions the pages:

```<code>    $(document).ready(function() {

  var pathname = window.location.pathname; // Returns path only

  console.log(pathname);

    // $('.mainSplash').css('height',$(window).height() - 60);

    $(".aboutBtn").click(function(e) {
        e.preventDefault();
        var pageTitle =  $(this).text();
        var pageUrl = $(this).attr('href');

        changePage(pageUrl, true, pageTitle);
    }); // click

    function changePage(url, bool, pageTitle){
        $('#page').addClass('fadeOut');

        loadContent(url, bool, pageTitle);
    }

    function loadContent(url, bool, pageTitle){
      $.ajax({
        url: './' + url,
        type: 'get',
        contentType: 'html',
        success: function(data){
          $('#page').one('animationend',
            function(e) {
            // load content
            $('#page').removeClass('fadeOut');
            $('#page').addClass('fadeIn');
            $('#content').html(data);
            //$("html").html(data);
            // Change url
            if(url != window.location){
              window.history.pushState({path: url}, pageTitle, url);
            }
          });
                }
        });
    }

  function removeAnimation(){
    $('#page').removeClass('animate');
  }

});
</code>```

So my transitions work fine when I have come from index.html, though when I refresh main.html or about.html, they do not keep the code from index.html (obviously).

My question is:

How do I handle a refresh or back button from my pages without losing the index.html content? Any help or advice is appreciated - thank you in advance.

PS: If anyone knows of any AJAX html page transition examples I would love to know so I can improve my code, as I'm looking for best practice for AJAX transitions!

答: multi way available to do this but best way is use hash routing. see this plugin  'Routei '.set param in hash route then and get it when click on back button and handel ajax whit this param.</p>

Body:
So I'm fairly new to AJAX, I have a simple 3 page project which I am using AJAX to transition between pages.

I have an index.html page which loads all the html / body / scripts etc:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Ajax practice</title>

    <link rel="stylesheet" href="styles/index.processed.css">

Home

About

Menu

Contact

and my 2 pages are:

main.html:

Main

about.html:

About

Here is the AJAX which transitions the pages:

    $(document).ready(function() {

  var pathname = window.location.pathname; // Returns path only

  console.log(pathname);

    // $('.mainSplash').css('height',$(window).height() - 60);

    $(".aboutBtn").click(function(e) {
        e.preventDefault();
        var pageTitle =  $(this).text();
        var pageUrl = $(this).attr('href');

        changePage(pageUrl, true, pageTitle);
    }); // click

    function changePage(url, bool, pageTitle){
        $('#page').addClass('fadeOut');

        loadContent(url, bool, pageTitle);
    }

    function loadContent(url, bool, pageTitle){
      $.ajax({
        url: './' + url,
        type: 'get',
        contentType: 'html',
        success: function(data){
          $('#page').one('animationend',
            function(e) {
            // load content
            $('#page').removeClass('fadeOut');
            $('#page').addClass('fadeIn');
            $('#content').html(data);
            //$("html").html(data);
            // Change url
            if(url != window.location){
              window.history.pushState({path: url}, pageTitle, url);
            }
          });
                }
        });
    }

  function removeAnimation(){
    $('#page').removeClass('animate');
  }

});

So my transitions work fine when I have come from index.html, though when I refresh main.html or about.html, they do not keep the code from index.html (obviously).

My question is:

How do I handle a refresh or back button from my pages without losing the index.html content? Any help or advice is appreciated - thank you in advance.

PS: If anyone knows of any AJAX html page transition examples I would love to know so I can improve my code, as I'm looking for best practice for AJAX transitions!