问:
Multiple Inner HTML in a few lines
I have a piano with 88 keys.
"keys" are the event key "k" .
I use handlebars and backbone so it is impossible to write thousands of lines here..

What I would like is, if there is any way to write the following code in fewer lines .. (I use Javascript and jQuery so both are ok)
Thank you very much

if (document.getElementById('do').innerHTML) {
document.getElementById(keys).innerHTML = "C";
}

if (document.getElementById('re').innerHTML) {
document.getElementById(keys).innerHTML = "D";
}

if (document.getElementById('mi').innerHTML) {
document.getElementById(keys).innerHTML = "E";
}
if (document.getElementById('fa').innerHTML) {
document.getElementById(keys).innerHTML = "F";
}

if (document.getElementById('sol').innerHTML) {
document.getElementById(keys).innerHTML = "G";
}
if (document.getElementById('la').innerHTML) {
document.getElementById(keys).innerHTML = "A";
}

if (document.getElementById('si').innerHTML) {
document.getElementById(keys).innerHTML = "B";
}
if (document.getElementById('do2').innerHTML) {
document.getElementById(keys).innerHTML = "C";
}

if (document.getElementById('re2').innerHTML) {
document.getElementById(keys).innerHTML = "D";
}

if (document.getElementById('mi').innerHTML) {
document.getElementById(keys).innerHTML = "E";
}```

答:
You can create a lookup of your mapping and using iterate through each pair of key and value check for condition and assign it to html.</p>
```<code>const lookup = {do: 'C', re: 'D', mi: 'E', fa: 'F', sol: 'G', la: 'A', si: 'B', do2: 'C', re2: 'D'}
Object.entries(lookup).forEach(([key, val]) => {
  if (document.getElementById(key).innerHTML) {
    document.getElementById(keys).innerHTML = value;
  }
});
</code>```

Title: Multiple Inner HTML in a few lines

Body:
You can create a lookup of your mapping and using iterate through each pair of key and value check for condition and assign it to html.

const lookup = {do: 'C', re: 'D', mi: 'E', fa: 'F', sol: 'G', la: 'A', si: 'B', do2: 'C', re2: 'D'}
Object.entries(lookup).forEach(([key, val]) => {
  if (document.getElementById(key).innerHTML) {
    document.getElementById(keys).innerHTML = value;
  }
});


来源: stackexchange

问:
Creating Signature for Text
I'm creating a program where I need to read all the lines and words in a txt file, count the number of times the words show up and do this for multiple txt files. Then I need to create a "signature" which is the 25 most common words and compare each txt file's signature to the other files. I worked all day today to get the program that counts the words in each text but I was stuck on the part on how to get the signature. Essentially when the program runs, this is what is shown:

The program creates a column called word, which shows all the words that are in the text and the number of times they show up for each text file. I have 2 for now, but I'll have more later on. I need to sort this list of words out, so the top 25 words that show up the most will be part of the "signature" and stored in a list, one list for each text. I am not sure how to sort out this many words. I have been thinking about how I could do this, and I thought of creating a list of lists, but I don't think that will work. Could anyone suggest something and show some code with it? I could also show you the program in private and show the change in code that way. Any help would really be great considering how long this has taken me today. Thanks in advance!

答:
you have all the words with the repeating frequency just apply

from collections import Counter

count = Counter(your whole code text file to string)

this will give you the frequency of each word and then sort this out in descending order with this code

list(reversed(sorted(count.keys())))

and then you have the list of the most repeating numbers.

ContentLicense: CC BY-SA 4.0

Title: Creating Signature for Text


问:
How to test a bad request in cypress
I am testing logging in POST method in cypress with incorrect credentials. this returns 400 bad requests which I need to test.

This is what I have:

describe('Login API Test - Correct user login', () => {
  it('Validate the header', () => {
    cy.request({
      method: 'POST',
      url: 'https://myrAPI',
      auth: {
        username: 'user@user',
        password: 'user123',
      },
      headers: {
        'Authorization': 'Basic dXNlckB1c2VyOnVzZXI=',
        'Content-Type': 'text/plain'
      }
    }).then((response) => {
      // expect(response.body).to.exist // true
      // expect(response.body).('User.Access: Exception occured:User.Access : CheckUser: Exception occurred:Error with Authentication Header. result =') // true
      // expect(response.headers).should.contain('text/plain; charset=utf-8')
      // expect(response.body).statusCode.should.equal(400)
      response.status.should.equal(400)
      //expect(response).to.have.property('headers')
    })
  }})
```
<p>The request that was sent:</p>
<pre class="lang-none prettyprint-override"><code>Method: POST
URL: https://myapi
Headers: {
  "Connection": "keep-alive",
  "Authorization": "Basic dXNlckB1c2VyOnVzZXIxMjM=",
   "Content-Type": "text/plain",
   "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
  "accept": "*/*",
  "accept-encoding": "gzip, deflate",
  "content-length": 0
  }
</code>```

This is the response I get:

Status: 400 - Bad Request
 Headers: {
  "content-length": "239",
   "content-type": "text/plain; charset=utf-8",
 "request-context": "appId=cid-v1:d994e38c-9493-4dd6-ac8c-5395bb9ce790",
   "date": "Tue, 02 Jul 2019 13:35:18 GMT"
}
 Body: User.Access: Exception occured:User.Access : CheckUser: Exception occurred:Exception when checkin...
```

I'd like to know what is in the response or body

答:
please add in order to valide the response is equal to 400
expect(response.body).has.property("statusCode", 400);</p>

Title: How to test a bad request in cypress

Body:
I am testing logging in POST method in cypress with incorrect credentials. this returns 400 bad requests which I need to test.

This is what I have:

describe('Login API Test - Correct user login', () => {
  it('Validate the header', () => {
    cy.request({
      method: 'POST',
      url: 'https://myrAPI',
      auth: {
        username: 'user@user',
        password: 'user123',
      },
      headers: {
        'Authorization': 'Basic dXNlckB1c2VyOnVzZXI=',
        'Content-Type': 'text/plain'
      }
    }).then((response) => {
      // expect(response.body).to.exist // true
      // expect(response.body).('User.Access: Exception occured:User.Access : CheckUser: Exception occurred:Error with Authentication Header. result =') // true
      // expect(response.headers).should.contain('text/plain; charset=utf-8')
      // expect(response.body).statusCode.should.equal(400)
      response.status.should.equal(400)
      //expect(response).to.have.property('headers')
    })
  }})

The request that was sent:

Method: POST
URL: https://myapi
Headers: {
  "Connection": "keep-alive",
  "Authorization": "Basic dXNlckB1c2VyOnVzZXIxMjM=",
   "Content-Type": "text/plain",
   "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
  "accept": "*/*",
  "accept-encoding": "gzip, deflate",
  "content-length": 0
  }

This is the response I get:

Status: 400 - Bad Request
 Headers: {
  "content-length": "239",
   "content-type": "text/plain; charset=utf-8",
 "request-context": "appId=cid-v1:d994e38c-9493-4dd6-ac8c-5395bb9ce790",
   "date": "Tue, 02 Jul 2019 13:35:18 GMT"
}
 Body: User.Access: Exception occured:User.Access : CheckUser: Exception occurred:Exception when checkin...

I'd like to know what is in the response or body


问:
Why does eclipse SOMETIMES prompt me which device to launch my app on?
Why does eclipse SOMETIMES prompt me which device to launch my app on when there is only 1 phone connected to my machine? Sometimes, it stays like this for months.... how to fix?

It says my target phone is 2.3.4    and there is a small yellow exclamation warning next to it.

答: I don't know why it happens (it drives me mad too) but I find you can cure it by disconnecting and then reconnecting the phone.</p>

ContentLicense: CC BY-SA 3.0


问:
Using Axios to send a token to the backend
I am new to this

I am writing a Vue app that connects to a Wordpress backend and I need to log in. I am using a plugin called Simple JWT-Login and I am able to send the email and password to the back end and i get the JWT back. But trying to log in and sending the jWT back to the back end gets me an error Bad Request.
Here is the function that is supposed to handle the login

```<code>    async login(){
      try{
        const response = await axios.post('/?rest_route=/simple-jwt-login/v1/auth&email=email&password=password',
          {
            email: this.email,
            password: this.password,
          }
        );
        const token = response.data.data.jwt
        localStorage.setItem('token', token)
        console.log(token)
        const login = await axios.get('/?rest_route=/simple-jwt-login/v1/autologin&JWT=token')
        console.log(login)
        // this.$router.push("/");
      } catch(err){
        console.log(err)
        // if(err.response.status === 400){
        //   this.error = "Wrong credentials! Please make sure"
        // }
      } finally{

      }
    }
</code>```

答:
The issue was a setting in the plugin that the docs does not explain to you and unless you are an expert the only way to find out is by trial and error.

The setting under general for SESSION must be On

Body:
I am new to this

I am writing a Vue app that connects to a Wordpress backend and I need to log in. I am using a plugin called Simple JWT-Login and I am able to send the email and password to the back end and i get the JWT back. But trying to log in and sending the jWT back to the back end gets me an error Bad Request.
Here is the function that is supposed to handle the login

    async login(){
      try{
        const response = await axios.post('/?rest_route=/simple-jwt-login/v1/auth&email=email&password=password',
          {
            email: this.email,
            password: this.password,
          }
        );
        const token = response.data.data.jwt
        localStorage.setItem('token', token)
        console.log(token)
        const login = await axios.get('/?rest_route=/simple-jwt-login/v1/autologin&JWT=token')
        console.log(login)
        // this.$router.push("/");
      } catch(err){
        console.log(err)
        // if(err.response.status === 400){
        //   this.error = "Wrong credentials! Please make sure"
        // }
      } finally{

      }
    }


问:
Does CLS penalize websites using animated HTML elements?
A lot of online games use animations of HTML elements as a core gameplay mechanics. For example, a solitaire game may have a DIV element or an IMG element for every card on the gameboard. Players drag and drop these cards across the board, and the game often shows animations that last a few seconds. An example of such animation is dealing cards, i.e. distributing them from the deck to their proper places on the gameboard at the beginning of the game. This is usually done 1) without user interaction, upon entering the website, and then 2) after user interaction, upon finishing one game and starting another.

These animations are longer than 500 ms, and so (as I understand) the elements, which finish their movement after that time, count towards CLS regardless of whether the user initiated the animation or not. Moreover, the card-dealing animation that greets the user on the website is entirely counted towards CLS. This might be solved by forcing the user to interact with the website before the initial animation, but it is a bad UX, as this is an extra unnecessary and potentially annoying click for the user. There is a lot to write about it, but for now, I’ll just state that showing a (not user-initiated) greeting animation is the best UX practice in this context and it is employed by the most popular games (also those using canvas).

The websites with games based on HTML elements are quite popular, and include Solitaire, Mahjong, Minesweeper etc. Some are at the top spots in the Google search results and have hundreds of thousands of users every month. I suspect that other, non-game-related sites may also employ useful movement animations of HTML elements which are appreciated by the users. Hence, I’ll ask in general:

Do I understand correctly that such animations of HTML elements, despite being expected by the user, are misclassified by contemporary CLS measures as unexpected?

Is the intention of the designers of the CLS measures to penalize this type of website behavior? I am especially asking in terms of SEO as I suspect CLS may be used as a factor by some ranking algorithms.

答:
It's hard to say exactly what's causing your issue without knowing how you've implemented your animations, but if you are animating or transitioning using the CSS transform property, then it shouldn't contribute to CLS because it doesn't trigger a re-layout of the page.

In general, this is a best practice for smooth animations, so I'd recommend it even if your CLS was fine.

See more details here: https://web.dev/optimize-cls/#animations


问:
How to ignore certain files in Git
I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated.

I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked.

How can I make Git ignore Hello.class?

答: The one case you might be experiencing is that .gitignore won't ignore the files you committed before. You should first remove or move those files from the repository, commit the changes you just did, and then add "*.class" to .gitignore.

Title: How to ignore certain files in Git


问:
Unique month-year combinations in excel/google spreadsheets
I have one column (A) with dates and I want to create a column with unique month-year.

I could use the UNIQUE function but that requires creating an extra column (B) with:
= DATE(YEAR(A1),MONTH(A1)) and the final column = UNIQUE(B1:B)

The question is, can I do it without creating the extra column?

答:
When I used the answer from Feb 2018, I kept getting an odd date at the end of the list. It was because the blank cells were being taken into account.

I used FILTER to remove them. This gave me the unique month/year values

```<code>=UNIQUE(ARRAYFORMULA(DATE(YEAR(FILTER(A1:A10, A1:A10<>"")), MONTH(FILTER(A1:A10, A1:A10<>"")), 1)))
</code>```

Body:
When I used the answer from Feb 2018, I kept getting an odd date at the end of the list. It was because the blank cells were being taken into account.

I used FILTER to remove them. This gave me the unique month/year values

=UNIQUE(ARRAYFORMULA(DATE(YEAR(FILTER(A1:A10, A1:A10<>"")), MONTH(FILTER(A1:A10, A1:A10<>"")), 1)))


答:
yes you can with variable</p>
```<code>const constVar = document.getElementById(keys);
if (document.getElementById('do').innerHTML)
{ constVar.innerHTML = "C"; }
</code>```

Title: Multiple Inner HTML in a few lines

Body:
I have a piano with 88 keys.
"keys" are the event key "k" .
I use handlebars and backbone so it is impossible to write thousands of lines here..

What I would like is, if there is any way to write the following code in fewer lines .. (I use Javascript and jQuery so both are ok)
Thank you very much

if (document.getElementById('do').innerHTML) {
document.getElementById(keys).innerHTML = "C";
}

if (document.getElementById('re').innerHTML) {
document.getElementById(keys).innerHTML = "D";
}

if (document.getElementById('mi').innerHTML) {
document.getElementById(keys).innerHTML = "E";
}
if (document.getElementById('fa').innerHTML) {
document.getElementById(keys).innerHTML = "F";
}

if (document.getElementById('sol').innerHTML) {
document.getElementById(keys).innerHTML = "G";
}
if (document.getElementById('la').innerHTML) {
document.getElementById(keys).innerHTML = "A";
}

if (document.getElementById('si').innerHTML) {
document.getElementById(keys).innerHTML = "B";
}
if (document.getElementById('do2').innerHTML) {
document.getElementById(keys).innerHTML = "C";
}

if (document.getElementById('re2').innerHTML) {
document.getElementById(keys).innerHTML = "D";
}

if (document.getElementById('mi').innerHTML) {
document.getElementById(keys).innerHTML = "E";
}

Body:
yes you can with variable

const constVar = document.getElementById(keys);
if (document.getElementById('do').innerHTML)
{ constVar.innerHTML = "C"; }


问:
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
I'm compiling a project in Eclipse using m2eclipse. I set the JDK path in Eclipse like this:

```<code>Windows-->preferences-->installed jres--> jdk1.7.xx  path
</code>```

But this is showing an error

```<code>[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE    rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.424s
[INFO] Finished at: Tue Oct 29 15:21:01 IST 2013
[INFO] Final Memory: 5M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-   plugin:3.1:compile (default-compile) on project TEST-WEB: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
</code>```

答: While building the project, make sure to point the jre to jdk path. This can be done in Run configuration section for the particular project.</p>

Body:
I'm compiling a project in Eclipse using m2eclipse. I set the JDK path in Eclipse like this:

Windows-->preferences-->installed jres--> jdk1.7.xx  path

But this is showing an error

[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE    rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.424s
[INFO] Finished at: Tue Oct 29 15:21:01 IST 2013
[INFO] Final Memory: 5M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-   plugin:3.1:compile (default-compile) on project TEST-WEB: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?


问:
Can the Activity of TabHost be a ListAcitivty?
EventsActivity is one of my tabs (3 tabs have 3 activities).

The question is:

Can this Activity be displayed as a list? If yes, which list should I use (SimpleList, ArrayList, etc.)?

I use an ArrayList HashMap but the stop unexpectedly occurs. How should I fix this?

I have some example in my code:

Class EventsActivity extends ListActivity. This is one of my tabs.

Class EventDataSet. Getter and setter methods.

Class EventXMLHandler. XML Handler.

Class Convertor. Converts date and time.

Layout Folder:

eventitem.xml

listplaceholder.xml

EventsActivity.class

```<code>public class EventsActivity extends ListActivity {

    EventDataSet eventDataSet = null;
    ArrayList<HashMap<String, String>> mylist =
        new ArrayList<HashMap<String, String>>();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
        try {
            /** Handling XML */
            /** Send URL to parse XML Tags */
            /*URL sourceUrl */

            /** Create handler to handle XML Tags ( extends DefaultHandler ) */

        } catch (Exception e) {

        }

        /** Get result from EventXMLHandler EventDataSet Object */
        eventDataSet = EventXMLHandler.eventDataSet;

        for (int i = 0; i < eventDataSet.getName().size(); i++) {

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name", "Name: " + eventDataSet.getName().get(i));
            map.put("createat", "Create-At: " +
                Convertor.getDateTimeDDMMYY(
                    eventDataSet.getCreateat().get(i)));

            mylist.add(map);

        }

        ListAdapter adapter = new SimpleAdapter(this, mylist ,
                R.layout.eventitem,  new String[] { "name", "createat" },
                new int[] { R.id.item_title, R.id.item_subtitle });

            setListAdapter(adapter);

        }

</code>```

listplaceholder.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ListView android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawSelectorOnTop="false" />

    <TextView android:id="@id/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No data"/>

</LinearLayout>
</code>```

eventitem.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">

    <TextView android:id="@+id/item_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:textSize="15dp"
        android:layout_weight="1" />

    <TextView android:id="@+id/item_subtitle"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:textSize="13dp"
        android:layout_weight="1" />
</LinearLayout>
</code>```

LogCat

```<code>08-18 14:11:00.112: ERROR/AndroidRuntime(294): Uncaught handler: thread main exiting due to uncaught exception
08-18 14:11:00.142: ERROR/AndroidRuntime(294): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ctg/com.ctg.EventsActivity}: java.lang.NullPointerException
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:2335)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:648)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabHost.setCurrentTab(TabHost.java:320)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:129)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:379)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.View.performClick(View.java:2364)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.View.onTouchEvent(View.java:4179)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.View.dispatchTouchEvent(View.java:3709)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:852)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.os.Looper.loop(Looper.java:123)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.main(ActivityThread.java:4363)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at java.lang.reflect.Method.invokeNative(Native Method)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at java.lang.reflect.Method.invoke(Method.java:521)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at dalvik.system.NativeStart.main(Native Method)
08-18 14:11:00.142: ERROR/AndroidRuntime(294): Caused by: java.lang.NullPointerException
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.ctg.EventsActivity.onCreate(EventsActivity.java:64)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     ... 30 more
</code>```

答:
Yes it can.

1.1. It all depends on your code and how you get the information. The easiest Adapter to use if you get the information from a database would in my oppinion be CursorAdapter and if you get it from parsing like you do I would use an ArrayAdapter.
 I would create my own custom adapter which extends ArrayAdapter. Here is an example. There are loads of other examples out there.

2: Your crash. Take a look at line 64 in your EventsActivity and post it here. Otherwise, please include your complete source code with all the imports and packages so that we can take a look.

Body:
EventsActivity is one of my tabs (3 tabs have 3 activities).

The question is:

Can this Activity be displayed as a list? If yes, which list should I use (SimpleList, ArrayList, etc.)?

I use an ArrayList HashMap but the stop unexpectedly occurs. How should I fix this?

I have some example in my code:

Class EventsActivity extends ListActivity. This is one of my tabs.

Class EventDataSet. Getter and setter methods.

Class EventXMLHandler. XML Handler.

Class Convertor. Converts date and time.

Layout Folder:

eventitem.xml

listplaceholder.xml

EventsActivity.class

public class EventsActivity extends ListActivity {

    EventDataSet eventDataSet = null;
    ArrayList<HashMap<String, String>> mylist =
        new ArrayList<HashMap<String, String>>();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
        try {
            /** Handling XML */
            /** Send URL to parse XML Tags */
            /*URL sourceUrl */

            /** Create handler to handle XML Tags ( extends DefaultHandler ) */

        } catch (Exception e) {

        }

        /** Get result from EventXMLHandler EventDataSet Object */
        eventDataSet = EventXMLHandler.eventDataSet;

        for (int i = 0; i < eventDataSet.getName().size(); i++) {

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name", "Name: " + eventDataSet.getName().get(i));
            map.put("createat", "Create-At: " +
                Convertor.getDateTimeDDMMYY(
                    eventDataSet.getCreateat().get(i)));

            mylist.add(map);

        }

        ListAdapter adapter = new SimpleAdapter(this, mylist ,
                R.layout.eventitem,  new String[] { "name", "createat" },
                new int[] { R.id.item_title, R.id.item_subtitle });

            setListAdapter(adapter);

        }

listplaceholder.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ListView android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawSelectorOnTop="false" />

    <TextView android:id="@id/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No data"/>

</LinearLayout>

eventitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">

    <TextView android:id="@+id/item_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:textSize="15dp"
        android:layout_weight="1" />

    <TextView android:id="@+id/item_subtitle"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:textSize="13dp"
        android:layout_weight="1" />
</LinearLayout>

LogCat

08-18 14:11:00.112: ERROR/AndroidRuntime(294): Uncaught handler: thread main exiting due to uncaught exception
08-18 14:11:00.142: ERROR/AndroidRuntime(294): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ctg/com.ctg.EventsActivity}: java.lang.NullPointerException
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:2335)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:648)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabHost.setCurrentTab(TabHost.java:320)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:129)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:379)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.View.performClick(View.java:2364)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.View.onTouchEvent(View.java:4179)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.View.dispatchTouchEvent(View.java:3709)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:852)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.os.Looper.loop(Looper.java:123)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.main(ActivityThread.java:4363)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at java.lang.reflect.Method.invokeNative(Native Method)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at java.lang.reflect.Method.invoke(Method.java:521)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at dalvik.system.NativeStart.main(Native Method)
08-18 14:11:00.142: ERROR/AndroidRuntime(294): Caused by: java.lang.NullPointerException
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at com.ctg.EventsActivity.onCreate(EventsActivity.java:64)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
08-18 14:11:00.142: ERROR/AndroidRuntime(294):     ... 30 more


答:
I am not sure of the exact use case, but this code can be optimized by a map and for-loop. The sample code is below.

Sample approach below:

```<code>const KEY_MAP = {
  "do": "C",
  "re": "D",
  "mi": "E",
  "fa": "F",
  "sol": "G",
  "la": "A",
  "si": "B",
  "do2": "C",
  "re2": "D",
}

function updateDomLabelUsingKeyMap(keys) {
  Object.keys(KEY_MAP).forEach(el => {
    if (document.getElementById(el).innerHTML) {
      document.getElementById(keys).innerHTML = KEY_MAP[el];
    }
  });
}
</code>```

Call this updateDomLabelUsingKeyMap function with the keys prop.

Title: Multiple Inner HTML in a few lines

Body:
I am not sure of the exact use case, but this code can be optimized by a map and for-loop. The sample code is below.

Sample approach below:

const KEY_MAP = {
  "do": "C",
  "re": "D",
  "mi": "E",
  "fa": "F",
  "sol": "G",
  "la": "A",
  "si": "B",
  "do2": "C",
  "re2": "D",
}

function updateDomLabelUsingKeyMap(keys) {
  Object.keys(KEY_MAP).forEach(el => {
    if (document.getElementById(el).innerHTML) {
      document.getElementById(keys).innerHTML = KEY_MAP[el];
    }
  });
}

Call this updateDomLabelUsingKeyMap function with the keys prop.


问:
Spring-Content: Moving files from content store to another content store
What I want: I'd like to move content from one ContentStore (regular) to another ContentStore (e.g. an archive) with Spring-Content version 1.2.7.

What I did is this (and it does work at least with DefaultFilesystemStoreImpls):

Creating two ContentStores like this:

```<code>@Bean(name = "mytmpfsstore1")
public ContentStore<File, String> getFileContentStore1() {
    FileSystemResourceLoader loader = new FileSystemResourceLoader(".\\tmpstore1");
    PlacementService placementService = new PlacementServiceImpl();
    return new DefaultFilesystemStoreImpl<File, String>(loader, placementService, new FileServiceImpl());
}
</code>```

Moving content from one ContentStore to another like this:

```<code>Optional<File> fileEntity = filesRepo.findById(id);
if (fileEntity.isPresent()) {
    Resource resource = regularContentStore.getResource(fileEntity.get());
    archiveContentStore.setContent(fileEntity.get(), resource);
    filesRepo.save(fileEntity.get());
    if (resource instanceof DeletableResource) {
        ((DeletableResource) resource).delete();
    }
}
</code>```

Question: Is this the intended way of moving (/archiving) content with Spring-Content or is there a more elegant / more convenient / more intended way of moving/archiving files (especially from filesystem to S3 and back again)?

答:
Spring Content doesn't provide any magic here.  I try to keep the API fairly low-level and this use case, whilst valid, is a little too granular.
So, ultimately you have to build the "archiving" yourself and at the end of the day copy the content from one store to another as you are doing.

A couple of comments/pointers:

Not sure why you instantiated mytmpfsstore1 yourself.  If you have file storage and s3 storage you can just make your storage interfaces extend FileSystemContentStore and S3ContentStore respectively and let the framework instantiate them for you; i.e.

public interface MyTmpFsStore extends FileSystemContentStore {}

public interface MyS3store extends S3ContentStore()

You can then wire these two beans into your 'archive' code.  Assuming that is a controller, something like:

@RequestMapping(...) public void archive(MyTmpFsStore fsStore, S3ContentStore s3Store { ... }

where you do your copy operation.

ContentStore extends AssociativeStore and there are a few different APIs for setting/unsetting content.  Resource-based or InputStream.  They all achieve the same objective at the end of the day.  You could just have easily used getContent instead of getResource and unsetContent instead of delete.

The 'archive' code probably needs to be in a @Transactional so the archive operation is atomic.

Body:
What I want: I'd like to move content from one ContentStore (regular) to another ContentStore (e.g. an archive) with Spring-Content version 1.2.7.

What I did is this (and it does work at least with DefaultFilesystemStoreImpls):

Creating two ContentStores like this:

@Bean(name = "mytmpfsstore1")
public ContentStore<File, String> getFileContentStore1() {
    FileSystemResourceLoader loader = new FileSystemResourceLoader(".\\tmpstore1");
    PlacementService placementService = new PlacementServiceImpl();
    return new DefaultFilesystemStoreImpl<File, String>(loader, placementService, new FileServiceImpl());
}

Moving content from one ContentStore to another like this:

Optional<File> fileEntity = filesRepo.findById(id);
if (fileEntity.isPresent()) {
    Resource resource = regularContentStore.getResource(fileEntity.get());
    archiveContentStore.setContent(fileEntity.get(), resource);
    filesRepo.save(fileEntity.get());
    if (resource instanceof DeletableResource) {
        ((DeletableResource) resource).delete();
    }
}

Question: Is this the intended way of moving (/archiving) content with Spring-Content or is there a more elegant / more convenient / more intended way of moving/archiving files (especially from filesystem to S3 and back again)?


问:
Getting 401 from custom Api when using Microsoft.Identity.platform to protect api
I am following the tutorial from Microsfot.document for how to protect api using Azure AD (Microsoft Identity).

The steps I took are following: Sorry I tried to put information that might be helpful but too much to get to the issue most of the time contributors ask for screenshot or the code.

I followed several documents and video tutorials but here is the link for one of them:  https://learn.microsoft.com/en-us/learn/modules/identity-secure-custom-api/2-secure-api-microsoft-identity

WebApi.

Created a webapi using core 5. Register it in Azure AD.

Created single scope 'check' and allowed permission to user and admin.

Webapp
Created webapp using .net(classic) Note that webapi is core 5.

Created a webapp and register it in Azure AD.

Setup the authentication and created a OnAuthorizationCodeReceived to get the access token to call the api.

Configuration:
1.From Azure AD->Registration for Webapi-> selected application(web app created above) and give permission to the scope.

2. For Azure AD->Registration for webapp-> Access permission->delegate->selected the scope.

Test:
1.Run the test. At this point; I do not have [Authorization] on the api method which I am calling.
2. Webapp successfully able to get the string which is returned by the api. Somewhat I get the idea that plumbing was right.

Added [Authorize] filter on the app method.

Result 401 unauthorized.

I have checked multiple times and looked at multiple tutorial and rewrote my code, watched several videos and updated my code but I am always getting 401 error.

Below is the code;
Api controller:

```<code>namespace Utility.Controllers
 {
   [Authorize]
    [Route("api/[controller]")]
   [ApiController]
   public class AzAdUtility : ControllerBase
     {
    // GET: api/<AzAdUtility>
    [HttpGet]
    public string Get()
    {
        //HttpContext.VerifyUserHasAnyAcceptedScope(new string[] {"check"});
        var name = "Vaqas";
        return name;
    }
 }
}
</code>```

Api startup :
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

```<code>    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));
        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "GlobalNetApiUtility", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Utility v1"));
        }

        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
</code>```

Api Appsettings:

```<code>"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "myorg.onmicrosoft.com",
"ClientId": "abcd.............................",
"TenantId": "dabcd.............................."
</code>```

},

Webapp startup:
Only adding startup page because at first all I am doing getting some data for testing purpose in the OnAuthorizationCodeReceived.

```<code>public class Startup
    {
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
       static string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

        // RedirectUri is the URL where the user will be redirected to after they sign in.
        string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

        // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
       static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

    // Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
     string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
    //string authority = "https://login.microsoftonline.com/" + tenant + "/adminconsent?client_id=" + clientId;
    string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ClientSecret"];
    /// <summary>
    /// Configure OWIN to use OpenIdConnect
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                //ResponseType = OpenIdConnectResponseType.CodeIdToken,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,

                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                   AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed = OnAuthenticationFailed

                }
            }
        );
        }

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
    {
        notification.HandleCodeRedemption();

        var idClient = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithRedirectUri(redirectUri)
            .WithClientSecret(clientSecret)
            .WithAuthority(authority)
            .Build();

        try
        {

            var apiScope = "api://28......................../check2 api://28................/check api://28...........................1d/AzAdUtility.Get";
            string[] scopes = apiScope.Split(' ');

            //gettig the token no issues.
            var result = await idClient.AcquireTokenByAuthorizationCode(
                scopes, notification.Code).ExecuteAsync();

            var myurl = "https://localhost:99356/api/AzAdUtility";

            var client = new HttpClient();
            // var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(Constants.ProductCatalogAPI.SCOPES);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); //accessToken

            var json = await client.GetStringAsync(myurl);

            var serializerOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            //getting 401 response
            var checkResponse = JsonSerializer.Deserialize(json, typeof(string), serializerOptions) as string;

        }

        catch (Exception ex)
        {
            string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
            notification.HandleResponse();
            notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
        }

    }

    /// <summary>
    /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("Error/AccessDenied/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }
    }
</code>```

答:
In Api startup class I was missing app.UseAuthentication().

I never really thought that would be an issue. Once I added this code. I got the expected response rather than 401 Unauthorized error

Body:
I am following the tutorial from Microsfot.document for how to protect api using Azure AD (Microsoft Identity).

The steps I took are following: Sorry I tried to put information that might be helpful but too much to get to the issue most of the time contributors ask for screenshot or the code.

I followed several documents and video tutorials but here is the link for one of them:  https://learn.microsoft.com/en-us/learn/modules/identity-secure-custom-api/2-secure-api-microsoft-identity

WebApi.

Created a webapi using core 5. Register it in Azure AD.

Created single scope 'check' and allowed permission to user and admin.

Webapp
Created webapp using .net(classic) Note that webapi is core 5.

Created a webapp and register it in Azure AD.

Setup the authentication and created a OnAuthorizationCodeReceived to get the access token to call the api.

Configuration:
1.From Azure AD->Registration for Webapi-> selected application(web app created above) and give permission to the scope.

2. For Azure AD->Registration for webapp-> Access permission->delegate->selected the scope.

Test:
1.Run the test. At this point; I do not have [Authorization] on the api method which I am calling.
2. Webapp successfully able to get the string which is returned by the api. Somewhat I get the idea that plumbing was right.

Added [Authorize] filter on the app method.

Result 401 unauthorized.

I have checked multiple times and looked at multiple tutorial and rewrote my code, watched several videos and updated my code but I am always getting 401 error.

Below is the code;
Api controller:

namespace Utility.Controllers
 {
   [Authorize]
    [Route("api/[controller]")]
   [ApiController]
   public class AzAdUtility : ControllerBase
     {
    // GET: api/<AzAdUtility>
    [HttpGet]
    public string Get()
    {
        //HttpContext.VerifyUserHasAnyAcceptedScope(new string[] {"check"});
        var name = "Vaqas";
        return name;
    }
 }
}

Api startup :
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));
        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "GlobalNetApiUtility", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Utility v1"));
        }

        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Api Appsettings:

"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "myorg.onmicrosoft.com",
"ClientId": "abcd.............................",
"TenantId": "dabcd.............................."

},

Webapp startup:
Only adding startup page because at first all I am doing getting some data for testing purpose in the OnAuthorizationCodeReceived.

public class Startup
    {
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
       static string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

        // RedirectUri is the URL where the user will be redirected to after they sign in.
        string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

        // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
       static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

    // Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
     string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
    //string authority = "https://login.microsoftonline.com/" + tenant + "/adminconsent?client_id=" + clientId;
    string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ClientSecret"];
    ///
    /// Configure OWIN to use OpenIdConnect
    ///
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                //ResponseType = OpenIdConnectResponseType.CodeIdToken,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,

                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                   AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed = OnAuthenticationFailed

                }
            }
        );
        }

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
    {
        notification.HandleCodeRedemption();

        var idClient = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithRedirectUri(redirectUri)
            .WithClientSecret(clientSecret)
            .WithAuthority(authority)
            .Build();

        try
        {

            var apiScope = "api://28......................../check2 api://28................/check api://28...........................1d/AzAdUtility.Get";
            string[] scopes = apiScope.Split(' ');

            //gettig the token no issues.
            var result = await idClient.AcquireTokenByAuthorizationCode(
                scopes, notification.Code).ExecuteAsync();

            var myurl = "https://localhost:99356/api/AzAdUtility";

            var client = new HttpClient();
            // var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(Constants.ProductCatalogAPI.SCOPES);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); //accessToken

            var json = await client.GetStringAsync(myurl);

            var serializerOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            //getting 401 response
            var checkResponse = JsonSerializer.Deserialize(json, typeof(string), serializerOptions) as string;

        }

        catch (Exception ex)
        {
            string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
            notification.HandleResponse();
            notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
        }

    }

    ///
    /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
    ///
    /// <param name="context"></param>
    /// <returns></returns>
    private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("Error/AccessDenied/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }
    }


答:
df %>%
  mutate(date = as.Date(date)) %>%
  group_by(userid, year = (1900+as.POSIXlt(date)$year) < 2018) %>%
  mutate(rownumber = if (year[1]) 0 else order(date)) %>%
  ungroup() %>%
  select(-year)
# # A tibble: 7 x 3
#   userid date       rownumber
#   <chr>  <date>         <dbl>
# 1 1      2016-10-23         0
# 2 1      2018-01-01         1
# 3 1      2020-03-03         2
# 4 2      2008-09-04         0
# 5 2      2021-08-08         1
# 6 3      2019-10-02         1
# 7 3      2022-01-02         2
```

I could have used row_number() in place of order(date), but I didn't know for certain if your data was known to be pre-sorted. You can use row_number() for the same results here.

(FYI, your date is a string, so I also converted it to a proper Date class, for better or worse. If you don't want to do that, you can replace the first mutate and the (1900+...)<2018 with as.integer(substring(date,1,4)) < 2018 for the same effect.)

Title: get row number of group but with condition in R

Body:
I have a dataframe that has been sorted by userid and date as below:

df <- data.frame(
  userid = c("1", "1", "1", "2", "2", "3", "3"),
  date = c("2016-10-23", "2018-01-01", "2020-03-03", "2008-09-04", "2021-08-08", "2019-10-02", "2022-01-02")
)

 userid       date
      1 2016-10-23
      1 2018-01-01
      1 2020-03-03
      2 2008-09-04
      2 2021-08-08
      3 2019-10-02
      3 2022-01-02

I want to group by userid and assign row numbers, BUT anything before 2017 should be row number 0:

df2 <- data.frame(
  userid = c("1", "1", "1", "2", "2", "3", "3"),
  date = c("2016-10-23", "2018-01-01", "2020-03-03", "2008-09-04", "2021-08-08", "2019-10-02", "2022-01-02"),
  rownumber = c("0", "1", "2", "0", "1", "1", "2")
)

 userid       date rownumber
      1 2016-10-23         0
      1 2018-01-01         1
      1 2020-03-03         2
      2 2008-09-04         0
      2 2021-08-08         1
      3 2019-10-02         1
      3 2022-01-02         2

As you can see, the dates with years 2016 and 2008 have been assigned as 0 and the rownumber increments from 1 excluding those.

I have tried the below, but it does not assign 0 to dates before 2017.

df %>%
  group_by(userid) %>%
  mutate(rownumber = row_number()) %>%
  ungroup()

Thanks!

Body:
df %>%
  mutate(date = as.Date(date)) %>%
  group_by(userid, year = (1900+as.POSIXlt(date)$year) < 2018) %>%
  mutate(rownumber = if (year[1]) 0 else order(date)) %>%
  ungroup() %>%
  select(-year)
# # A tibble: 7 x 3
#   userid date       rownumber
#   <chr>  <date>         <dbl>
# 1 1      2016-10-23         0
# 2 1      2018-01-01         1
# 3 1      2020-03-03         2
# 4 2      2008-09-04         0
# 5 2      2021-08-08         1
# 6 3      2019-10-02         1
# 7 3      2022-01-02         2

I could have used row_number() in place of order(date), but I didn't know for certain if your data was known to be pre-sorted. You can use row_number() for the same results here.

(FYI, your date is a string, so I also converted it to a proper Date class, for better or worse. If you don't want to do that, you can replace the first mutate and the (1900+...)<2018 with as.integer(substring(date,1,4)) < 2018 for the same effect.)


问:
How do I share user controls between web applications in ASP.NET?
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

```
Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3
```

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

答:
Check this post for how to solve this issue.

The basic idea is to change your project to have a prebuild step to copy over the .ascx files to a subdirectory of the web application.  Then just refer to those copies when using them.  Of course you also need to reference the UserControls assembly as well.

OwnerDisplayName: Jan Aagaard

ContentLicense: CC BY-SA 2.5

Body:
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

LastEditorDisplayName: Jan Aagaard

OwnerDisplayName: Daniel


问:
is it possible to use the github url to install typescript npm dependencies
When we want a npm lib write using typescript, we should write the source code using typescript, then push the source code to github, then transfer from typescript to javascript and push javascript to npm repo. when we add dependencies, we use the transfered javascript. Is it possible to using the typescript directly in github or keep the transfered javascript in github and use it through github url? I do not want to publish everytime change the typescript source code. The npm did not supprt override or snapshot version. I have to compile the typescript to javascript and publish to npm?Any suggestion?</p>

答:
How I generally do it is by having a src/ folder that contains the TypeScript files, and have a separate folder for the built/compiled JS files say lib/

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./lib"
    },
    "exclude": [
        "lib"
    ]
}

```
<p>Now, in the <code>package.json</code> file, you can declare your <code>main</code> field as <code>./lib/index.js</code> (or whatever your main entry file is)</p>
<p>You can tell NPM to ignore files by using an <code>.npmignore</code> file, which operates similar to a <code>.gitignore</code> file.</p>
<h4>.npmignore</h4>
```# Ignore all src files
src
```

You can use npm pack to test what NPM will pack (it will print the tarball contents).

You can even .gitignore the lib folder since it's a generated folder.

If you provide source maps, you may still want to include the original source typescript files however.

Body:
How I generally do it is by having a src/ folder that contains the TypeScript files, and have a separate folder for the built/compiled JS files say lib/

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./lib"
    },
    "exclude": [
        "lib"
    ]
}

Now, in the package.json file, you can declare your main field as ./lib/index.js (or whatever your main entry file is)

You can tell NPM to ignore files by using an .npmignore file, which operates similar to a .gitignore file.

.npmignore

# Ignore all src files
src

You can use npm pack to test what NPM will pack (it will print the tarball contents).

You can even .gitignore the lib folder since it's a generated folder.

If you provide source maps, you may still want to include the original source typescript files however.


问:
Suppose You have an array that contains some strings as name of something. Now,you have to find one string that contains odd letter by java script
const array=['abul','babu','rony','babul','suny'];
function{enter code here}

答:
I think you would want to use the remainder operator to determine if the string length is odd and Array.prototype.find() to find the value in the list

The remainder operator (%) returns the remainder left over when one operand is divided by a second operand.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

```<code>const names = ['abul','babu','rony','babul','suny']

// function that takes a string and returns true if the string has odd length
// determines whether a string's length is odd using modulo operator and checking remainder
const hasOddLength = str => str.length % 2 !== 0

// uses hasOddLength as callback for find()
const findStringWithOddLength = (list) => (
  list.find(str => hasOddLength(str))
)

console.log(findStringWithOddLength(names)) // "babul"
</code>```

Note: if there are multiple names with an odd length, find() will only return the first one.

Body:
I think you would want to use the remainder operator to determine if the string length is odd and Array.prototype.find() to find the value in the list

The remainder operator (%) returns the remainder left over when one operand is divided by a second operand.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

const names = ['abul','babu','rony','babul','suny']

// function that takes a string and returns true if the string has odd length
// determines whether a string's length is odd using modulo operator and checking remainder
const hasOddLength = str => str.length % 2 !== 0

// uses hasOddLength as callback for find()
const findStringWithOddLength = (list) => (
  list.find(str => hasOddLength(str))
)

console.log(findStringWithOddLength(names)) // "babul"

Note: if there are multiple names with an odd length, find() will only return the first one.


问:
OverflowError: Python int too large to convert to C long tensorflow datsets
```<code>import tensorflow_datasets as tfds
</code>```

and then:

```<code>OverflowError                             Traceback (most recent call last)
<ipython-input-1-7342ce159b6a> in <module>
      1 import tensorflow as tf
----> 2 import tensorflow_datasets as tfds

~\anaconda3\lib\site-packages\tensorflow_datasets\__init__.py in <module>
     63 from tensorflow_datasets import translate
     64 from tensorflow_datasets import video
---> 65 from tensorflow_datasets import vision_language
     66
     67

~\anaconda3\lib\site-packages\tensorflow_datasets\vision_language\__init__.py in <module>
     19 from tensorflow_datasets.vision_language.grounded_scan import GroundedScan
     20 from tensorflow_datasets.vision_language.refcoco import RefCoco
---> 21 from tensorflow_datasets.vision_language.wit import Wit
     22 from tensorflow_datasets.vision_language.wit_kaggle import WitKaggle

~\anaconda3\lib\site-packages\tensorflow_datasets\vision_language\wit\__init__.py in <module>
     16 """wit dataset."""
     17
---> 18 from tensorflow_datasets.vision_language.wit.wit import Wit

~\anaconda3\lib\site-packages\tensorflow_datasets\vision_language\wit\wit.py in <module>
     23 import tensorflow_datasets.public_api as tfds
     24
---> 25 csv.field_size_limit(sys.maxsize)
     26
     27 _DESCRIPTION = """

OverflowError: Python int too large to convert to C long
</code>```

答:
Issue is fixed in tensorflow-datasets 4.5.2

You can import tensorflow_datasets without any error.

```<code>import tensorflow_datasets as tfds
</code>```

Body:
import tensorflow_datasets as tfds

and then:

OverflowError                             Traceback (most recent call last)
<ipython-input-1-7342ce159b6a> in <module>
      1 import tensorflow as tf
----> 2 import tensorflow_datasets as tfds

~\anaconda3\lib\site-packages\tensorflow_datasets\__init__.py in <module>
     63 from tensorflow_datasets import translate
     64 from tensorflow_datasets import video
---> 65 from tensorflow_datasets import vision_language
     66
     67

~\anaconda3\lib\site-packages\tensorflow_datasets\vision_language\__init__.py in <module>
     19 from tensorflow_datasets.vision_language.grounded_scan import GroundedScan
     20 from tensorflow_datasets.vision_language.refcoco import RefCoco
---> 21 from tensorflow_datasets.vision_language.wit import Wit
     22 from tensorflow_datasets.vision_language.wit_kaggle import WitKaggle

~\anaconda3\lib\site-packages\tensorflow_datasets\vision_language\wit\__init__.py in <module>
     16 """wit dataset."""
     17
---> 18 from tensorflow_datasets.vision_language.wit.wit import Wit

~\anaconda3\lib\site-packages\tensorflow_datasets\vision_language\wit\wit.py in <module>
     23 import tensorflow_datasets.public_api as tfds
     24
---> 25 csv.field_size_limit(sys.maxsize)
     26
     27 _DESCRIPTION = """

OverflowError: Python int too large to convert to C long

Body:
Issue is fixed in tensorflow-datasets 4.5.2

You can import tensorflow_datasets without any error.

import tensorflow_datasets as tfds


问:
How should I extend the TTL of a document in Azure CosmosDB using the Python SDK?
I'm working with a Cosmos DB database with the SQL API. I have a container with TTL policy of 6 months. When a certain action is taken, my code receives an id and need to extend the deletion time for the item with that id in that container to now + 6 months. What is the recommended way to do this? An empty upsert?

I can assume the document exists.

The documents only need to be deleted in approximately six months. I'm not worried about exact timing.

I'm using the Python SDK. I looked through the documentation, but I could not find anything like an "extend" operation.

Should I not be leveraging the TTL? Should I be doing something else?

答:
Any update on the document resets the timestamp of that document (the _ts property).

The TTL basically acts based on that value.

So in your case, a simple Replace operation over that document would reset the timestamp so it would effectively be deleted 6 months after this last update.


问:
Android Studio Bumblebee | 2021.1.1 Auto suggestion and error detection is not working
Yesterday I have Updated my android studio, since then auto completion and error detection is not working.</p>

答:
First close Android Studio.

On mac just go to ~/Library/Application Support/Google/

And delete all the AndroidStudio< version > folders, after this you will see the errors.


问:
Flutter HTML response instead of json
I am having error, kindly help me with this code, new to Flutter here.
When I'm using https://jsonplaceholder.typicode.com/posts it is working fine, but I am receiving error using my company URL, but when I am using postman to POST the company URL it is working fine, kindly refer to my code and the image below.

Code:

```<code>   Dio dio = Dio();

  Future postData() async{
    const String pathUrl = 'https://202.57.135.121:8443/icbs/ATMInterfaceListener/mobileAppRegistration';
    //const String pathUrl = 'https://jsonplaceholder.typicode.com/posts';

dynamic data = {
  'email': 'darwikf@gkdkkk.com',
  'password': 'test123456',
  'firstName': 'Darwin',
  'middleName': 'D',
  'lastName': 'L',
  'birthDate': 095545,
  'mobile': 1256789,
  'telephone': 12367891,
  'presentAddress': 'mla',
  'permanentAddress': 'mla',
  'country': 'phl',

  // 'title': 'Darwin',
  // 'body': 'Success',
  // 'userId': '1',
};

try{
  var response = await dio.post(pathUrl, data: data, options: Options(
    followRedirects: false,
    validateStatus: (status) => true,
    headers: {
      'Content-type' : 'application/json; charset=UTF-8',
    }
  ));
  return response.data;
}catch(e){
  print(e);
}
</code>```

}`

Image Postman

Image Error

答:
This is the exact answer, this works for me.</p>
```<code>Dio dio = Dio();

Future postData() async{
    const String pathUrl = 'https://202.57.135.121:8443/icbs/ATMInterfaceListener/mobileAppRegistration';
    dynamic data = {
      'email': 'darwikf@gkdkkk.com',
      'password': 'test123456',
      'firstName': 'Darwin',
      'middleName': 'D',
      'lastName': 'L',
      'birthDate': 095545,
      'mobile': 1256789,
      'telephone': 12367891,
      'presentAddress': 'mla',
      'permanentAddress': 'mla',
      'country': 'phl',
    };
    try{
      var response = await dio.post(pathUrl, data: data, options: Options(
          followRedirects: false,
          validateStatus: (status) => true,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          }
      ));
      return response.data;
    }catch(e){
      print(e);
    }
}
</code>```

Title: Flutter HTML response instead of json

Body:
I am having error, kindly help me with this code, new to Flutter here.
When I'm using https://jsonplaceholder.typicode.com/posts it is working fine, but I am receiving error using my company URL, but when I am using postman to POST the company URL it is working fine, kindly refer to my code and the image below.

Code:

   Dio dio = Dio();

  Future postData() async{
    const String pathUrl = 'https://202.57.135.121:8443/icbs/ATMInterfaceListener/mobileAppRegistration';
    //const String pathUrl = 'https://jsonplaceholder.typicode.com/posts';

dynamic data = {
  'email': 'darwikf@gkdkkk.com',
  'password': 'test123456',
  'firstName': 'Darwin',
  'middleName': 'D',
  'lastName': 'L',
  'birthDate': 095545,
  'mobile': 1256789,
  'telephone': 12367891,
  'presentAddress': 'mla',
  'permanentAddress': 'mla',
  'country': 'phl',

  // 'title': 'Darwin',
  // 'body': 'Success',
  // 'userId': '1',
};

try{
  var response = await dio.post(pathUrl, data: data, options: Options(
    followRedirects: false,
    validateStatus: (status) => true,
    headers: {
      'Content-type' : 'application/json; charset=UTF-8',
    }
  ));
  return response.data;
}catch(e){
  print(e);
}

}`

Image Postman

Image Error

Body:
This is the exact answer, this works for me.

Dio dio = Dio();

Future postData() async{
    const String pathUrl = 'https://202.57.135.121:8443/icbs/ATMInterfaceListener/mobileAppRegistration';
    dynamic data = {
      'email': 'darwikf@gkdkkk.com',
      'password': 'test123456',
      'firstName': 'Darwin',
      'middleName': 'D',
      'lastName': 'L',
      'birthDate': 095545,
      'mobile': 1256789,
      'telephone': 12367891,
      'presentAddress': 'mla',
      'permanentAddress': 'mla',
      'country': 'phl',
    };
    try{
      var response = await dio.post(pathUrl, data: data, options: Options(
          followRedirects: false,
          validateStatus: (status) => true,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          }
      ));
      return response.data;
    }catch(e){
      print(e);
    }
}


问:
Store authentication token in iPhone application
I want to store authentication token, that i received from log-in response.

It is right to use for this NSUserDefaults? Or I must use KeyChainWrapper?

What is the best way store authentication token?

答: NSUserDefaults is the way to go. It is the simplest.


问:
How to find or check the MSB of a register using LC-3 instructions?
I need to figure out if the MSB of a set of bits in a register is one or zero. How would you go about doing this using LC-3 instructions?

LC-3 Instruction Set:

https://www.cs.utexas.edu/users/fussell/courses/cs310h/lectures/Lecture_10-310h.pdf

答:
If you are allowed to use the conditional branch instruction, then you'll need to set the conditions based on the register value.

One way to accomplish setting the conditions is to add 0 to the register — it might seem like adding 0 wouldn't do anything but has the side effect of setting the conditions, N, Z, and P.  There are other ways to get the conditions set, but this is simple and direct.

Once the conditions are set you can conditionally branch on negative, or else on zero-or-positive.  Either way, you can put then/else code after such a conditional branch.


问:
Emberjs - How to map api json response to a model?
While trying to build an Ember.js sample application, to call a REST Api and display results. I was able to call, fetch and display the results. In the component I am reading through the json response results.

How can I map the response data to a pre-defined model and use that in the component instead? I could not find relevant docs at https://guides.emberjs.com/release/models/defining-models/ or https://guides.emberjs.com/release/in-depth-topics/making-api-requests/#toc_where-to-make-api-requests

Code details:

Using this sample API https://reqres.in/api/users

Model: (--update--)

```<code>export default class UserModel extends Model {
  @attr('string') id;
  @attr('string') firstname;
  @attr('string') lastname;
  @attr('string') email;
  @attr('string') avatar;
}
</code>```

Route:

```<code>export default class UsersRoute extends Route {
  async model() {
    let response = await fetch('https://reqres.in/api/users');
    let data = await response.json();
    return data.data;
  }
}
</code>```

Template:

```<code><UserList
  @title="List of Users"
  @users={{@model}}
/>
</code>```

Component:

```<code>{{#each @users as |user|}}
    <tr>
      <td>{{user.id}}</td>
       <td>{{user.first_name}}</td>
       <td>{{user.last_name}}</td>
       <td>{{user.email}}</td>
    </tr>
  {{/each}}
</code>```

答:
Generate a user model:

ember g model user

import Model, { attr } from '@ember-data/model';

export default class UserModel extends Model {
  @attr('string') email;
  @attr('string') firstName;
  @attr('string') lastName;
  @attr('string') avatar;
}
```
<p>Generate an application adapter and serializer:</p>
```ember g adapter application
ember g serializer application
```
<p>Add your API URL to the adapter:</p>
<pre class="lang-js prettyprint-override"><code>import JSONAPIAdapter from '@ember-data/adapter/json-api';

export default class ApplicationAdapter extends JSONAPIAdapter {
  host = 'https://reqres.in/api'; // the `users` part of the path is autogenerated based on the model name
}
</code>```

Update the serializer:

import JSONSerializer from '@ember-data/serializer/json'; // note that this is not the default serializer, JSONAPISerializer
import { underscore } from '@ember/string';

export default class ApplicationSerializer extends JSONSerializer {
  // specify underscore-formatted keys
  keyForAttribute(attr) {
    return underscore(attr);
  }

  // use the `data` property in the payload as the serializable response
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    payload = payload.data;
    return super.normalizeResponse(store, primaryModelClass, payload, id, requestType);
  }
}

```
<p>Update your route to use Ember Data methods instead of raw <code>fetch</code>:</p>
<pre class="lang-js prettyprint-override"><code>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class UsersRoute extends Route {
  @service store;

  model() {
    return this.store.findAll('user');
  }
}
</code>```

And finally you can then use the data (using camelcase-formatted attributes):

```<code>{{#each @users as |user|}}
  <tr>
    <td>{{user.id}}</td>
    <td>{{user.firstName}}</td>
    <td>{{user.lastName}}</td>
    <td>{{user.email}}</td>
  </tr>
{{/each}}
</code>```

Body:
While trying to build an Ember.js sample application, to call a REST Api and display results. I was able to call, fetch and display the results. In the component I am reading through the json response results.

How can I map the response data to a pre-defined model and use that in the component instead? I could not find relevant docs at https://guides.emberjs.com/release/models/defining-models/ or https://guides.emberjs.com/release/in-depth-topics/making-api-requests/#toc_where-to-make-api-requests

Code details:

Using this sample API https://reqres.in/api/users

Model: (--update--)

export default class UserModel extends Model {
  @attr('string') id;
  @attr('string') firstname;
  @attr('string') lastname;
  @attr('string') email;
  @attr('string') avatar;
}

Route:

export default class UsersRoute extends Route {
  async model() {
    let response = await fetch('https://reqres.in/api/users');
    let data = await response.json();
    return data.data;
  }
}

Template:

<UserList
  @title="List of Users"
  @users={{@model}}
/>

Component:

{{#each @users as |user|}}

      {{user.id}}
       {{user.first_name}}
       {{user.last_name}}
       {{user.email}}

  {{/each}}

Body:
Generate a user model:

ember g model user

import Model, { attr } from '@ember-data/model';

export default class UserModel extends Model {
  @attr('string') email;
  @attr('string') firstName;
  @attr('string') lastName;
  @attr('string') avatar;
}

Generate an application adapter and serializer:

ember g adapter application
ember g serializer application

Add your API URL to the adapter:

import JSONAPIAdapter from '@ember-data/adapter/json-api';

export default class ApplicationAdapter extends JSONAPIAdapter {
  host = 'https://reqres.in/api'; // the `users` part of the path is autogenerated based on the model name
}

Update the serializer:

import JSONSerializer from '@ember-data/serializer/json'; // note that this is not the default serializer, JSONAPISerializer
import { underscore } from '@ember/string';

export default class ApplicationSerializer extends JSONSerializer {
  // specify underscore-formatted keys
  keyForAttribute(attr) {
    return underscore(attr);
  }

  // use the `data` property in the payload as the serializable response
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    payload = payload.data;
    return super.normalizeResponse(store, primaryModelClass, payload, id, requestType);
  }
}

Update your route to use Ember Data methods instead of raw fetch:

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class UsersRoute extends Route {
  @service store;

  model() {
    return this.store.findAll('user');
  }
}

And finally you can then use the data (using camelcase-formatted attributes):

{{#each @users as |user|}}
  <tr>
    <td>{{user.id}}</td>
    <td>{{user.firstName}}</td>
    <td>{{user.lastName}}</td>
    <td>{{user.email}}</td>
  </tr>
{{/each}}


问:
how to call azure to get resource for classic (ASM) storage account
We have some ARM as well as some legacy Azure ASM resources and I have a need to query azure endpoints for info on both the ARM and the classic storage resources.  I can query the  ARM just fine, but when I try to query the classic via the same url, I get no data.

ARM attempt url:

```<code>https://management.azure.com/subscriptions/abcdef-123456/resourceGroups/MyEastResourceGroup/providers/Microsoft.ClassicStorage/storageAccounts
/myazureresourcename?api-version=2015-08-19
</code>```

Attempted classic (ASM) url:

```<code>https://management.azure.com/subscriptions/abcdef-123456/resourceGroups/MyEastResourceGroup/providers/Microsoft.ClassicStorage/storageAccounts/myazureresourcename?api-version=2015-08-19
</code>```

答:
api-version=2015-08-19

Looks like the API Version, you are using is not valid when we have tried to get the properties of the storage account using postman & request got failed with the below error.

We have tested this in our local environment it is working fine, Below statements are based on the analysis.

In our local environment, Using postman & Azure Management Rest API's. We are able to get the properties of the classic storage account.

Below are the list of api versions supported by the classic storage account's:

2016-11-01

2016-04-01

2015-12-01

2015-06-01

2014-06-01

2014-04-01-beta

2014-04-01

2014-01-01

Here is the sample output for reference :

Body:
We have some ARM as well as some legacy Azure ASM resources and I have a need to query azure endpoints for info on both the ARM and the classic storage resources.  I can query the  ARM just fine, but when I try to query the classic via the same url, I get no data.

ARM attempt url:

https://management.azure.com/subscriptions/abcdef-123456/resourceGroups/MyEastResourceGroup/providers/Microsoft.ClassicStorage/storageAccounts
/myazureresourcename?api-version=2015-08-19

Attempted classic (ASM) url:

https://management.azure.com/subscriptions/abcdef-123456/resourceGroups/MyEastResourceGroup/providers/Microsoft.ClassicStorage/storageAccounts/myazureresourcename?api-version=2015-08-19


问:
Trigger for conditional insert into table
I have subscription data that is being appended to a table in real-time (via kafka). i have set up a trigger such that once the data is added it is checked for consistency. If checks pass some of the data should be added to other tables (that have master information on the customer profile etc.). The checks function i wrote works fine but i keep getting errors on the function used in the trigger. The function for the trigger is:

```<code>CREATE OR REPLACE FUNCTION update_tables()
   RETURNS TRIGGER
   LANGUAGE plpgsql
   AS
$$
BEGIN
        CASE (SELECT check_incoming_data()) WHEN 0
        THEN INSERT INTO
            sub_master(sub_id, sub_date, customer_id, product_id)
            VALUES(
                (SELECT sub_id::int FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime)),
                (SELECT sub_date::date FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime)),
                (SELECT customer_id::int FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime)),
                (SELECT product_id::int FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime))
            );
        RETURN sub_master;
    END CASE;

   RETURN sub_master;
END;
$$
</code>```

The trigger is then:

```<code>CREATE TRIGGER incoming_data
   AFTER INSERT
   ON claims_realtime_3
   FOR EACH ROW
       EXECUTE PROCEDURE update_tables();
</code>```

What I am saying is 'if checks pass then select data from the last added row and add them to the master table'. What is the best way to structure this query?

Thanks a lot!

答:
The trigger functions are executed for each row and you must use a record type variable called "NEW" which is automatically created by the database in the trigger functions. "NEW" gets only inserted records. For example, I want to insert data to users_log table when inserting records to users table.

```<code>CREATE OR REPLACE FUNCTION users_insert()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
begin

    insert into users_log
    (
        username,
        first_name,
        last_name
    )
    select
        new.username,
        new.first_name,
        new.last_name;

    return new;
END;
$function$;

create trigger store_data_to_history_insert
before insert
on users for each row execute function users_insert();
</code>```

Body:
I have subscription data that is being appended to a table in real-time (via kafka). i have set up a trigger such that once the data is added it is checked for consistency. If checks pass some of the data should be added to other tables (that have master information on the customer profile etc.). The checks function i wrote works fine but i keep getting errors on the function used in the trigger. The function for the trigger is:

CREATE OR REPLACE FUNCTION update_tables()
   RETURNS TRIGGER
   LANGUAGE plpgsql
   AS
$$
BEGIN
        CASE (SELECT check_incoming_data()) WHEN 0
        THEN INSERT INTO
            sub_master(sub_id, sub_date, customer_id, product_id)
            VALUES(
                (SELECT sub_id::int FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime)),
                (SELECT sub_date::date FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime)),
                (SELECT customer_id::int FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime)),
                (SELECT product_id::int FROM sub_realtime WHERE CTID = (SELECT MAX(CTID) FROM sub_realtime))
            );
        RETURN sub_master;
    END CASE;

   RETURN sub_master;
END;
$$

The trigger is then:

CREATE TRIGGER incoming_data
   AFTER INSERT
   ON claims_realtime_3
   FOR EACH ROW
       EXECUTE PROCEDURE update_tables();

What I am saying is 'if checks pass then select data from the last added row and add them to the master table'. What is the best way to structure this query?

Thanks a lot!

Body:
The trigger functions are executed for each row and you must use a record type variable called "NEW" which is automatically created by the database in the trigger functions. "NEW" gets only inserted records. For example, I want to insert data to users_log table when inserting records to users table.

CREATE OR REPLACE FUNCTION users_insert()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
begin

    insert into users_log
    (
        username,
        first_name,
        last_name
    )
    select
        new.username,
        new.first_name,
        new.last_name;

    return new;
END;
$function$;

create trigger store_data_to_history_insert
before insert
on users for each row execute function users_insert();


问:
Non nullable instance field must be initalised
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

```<code>import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}
</code>```

in that video it runs, but for me it shows error as

```<code>Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.
</code>```

i have no idea what the problem is..
can you guys help me to troubleshoot the error

答:
Since you're compiling with null safety, you may change to this:

int? id;
String? url;
```

For further info about null safety, please refer to this link https://dart.dev/null-safety

Body:
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}

in that video it runs, but for me it shows error as

Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.

i have no idea what the problem is..
can you guys help me to troubleshoot the error

Body:
Since you're compiling with null safety, you may change to this:

int? id;
String? url;

For further info about null safety, please refer to this link https://dart.dev/null-safety