问:
Menu doesn't appear in custom toolbar layout
I've seen a tutorial video that the guy create custom layout for toolbar and set manu to that toolbar ant that worked fine
I did the same thing but menu didn't appear in my custom toolbar !!
This is my code. Do you know where is the problem ?

This is toolbar layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="@color/colorPrimary"
android:minWidth="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_height="wrap_content">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txtCounter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0 Item Selected"
        android:textSize="18sp"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.appcompat.widget.Toolbar>
</code>```

This is main activity layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<include
    android:id="@+id/include"
    layout="@layout/toolbar_layout"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

 </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And this is my main activity that handles the toolbar and menu

```<code>public class MainActivity extends AppCompatActivity {

Toolbar toolbar ;

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

    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return super.onCreateOptionsMenu(menu);
}
}
</code>```

答:
you are using the wrong ID for calling it in the findViewByID(). please make sure you need only one. Make changes like this.

in your main activity layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<include
layout="@layout/toolbar_layout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

in your main activity class

```<code>    toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
</code>```

Body:
I've seen a tutorial video that the guy create custom layout for toolbar and set manu to that toolbar ant that worked fine
I did the same thing but menu didn't appear in my custom toolbar !!
This is my code. Do you know where is the problem ?

This is toolbar layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="@color/colorPrimary"
android:minWidth="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_height="wrap_content">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txtCounter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0 Item Selected"
        android:textSize="18sp"
        android:textColor="@android:color/white"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.appcompat.widget.Toolbar>

This is main activity layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<include
    android:id="@+id/include"
    layout="@layout/toolbar_layout"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

 </androidx.constraintlayout.widget.ConstraintLayout>

And this is my main activity that handles the toolbar and menu

public class MainActivity extends AppCompatActivity {

Toolbar toolbar ;

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

    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return super.onCreateOptionsMenu(menu);
}
}

Body:
you are using the wrong ID for calling it in the findViewByID(). please make sure you need only one. Make changes like this.

in your main activity layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<include
layout="@layout/toolbar_layout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

in your main activity class

    toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);


来源: stackexchange

问:
Is there a way to compile SASS to CSS without NodeJS?
NodeJS is being restricted to be installed and we received a web work with a SASS file that I would like to continue working in that way. So I was hoping there could be other way to compile into CSS with all the same functionalities that Gulp has preferably.</p>

答:
Yes, we can compile SCSS/SASS to CSS without using any Node Command.

With just one click you can compile SCSS/CSS to CSS.

Follow these steps in Visual Studio Code Editor

Click on the Extensions button on left side.

Then search "Live Sass Compiler" and install it.

Create a .scss file.

Then Press Watch Sass button at the bottom of the Editor,

This Learnopidia article will explain it in more details:

ContentLicense: CC BY-SA 4.0


问:
UIDocumentInteractionController for remote pdf files
Does anybody know how to use UIDocumentInteractionController to "Open in iBooks" remote pdf files, i can't seem to be able to get around this one. I have managed to open my pdf in QLPreviewController and get the OptionsMenu to give me the option to open in iBooks but i won't open the file if it is remote...when i use local file it works fine.

If this is not possible what is the alternative?

Thanks in advance

答: Although UIDocumentInteractionController has a convenience method interactionControllerForURL:, it requires the argument to be a file URL. So you either download the PDF within your app and open it with the UIDocumentInteractionController object or you can use a UIWebView object to open remote PDFs. Pass the URL to the web view and they open just fine.

ContentLicense: CC BY-SA 3.0


问:
C# Linq OrderBy based on condition
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

```<code>var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)
</code>```

But I am sure there is a more elegant solution.

答:
As @AlanK have mentioned, the closest we can get for simplifying OrderBy would be something like:

Func<OrderLines, string> selector = (orderLine) => condition ? orderLine.ColB : orderLine.ColA;

List<OrderLines> orderLines = lines.OrderBy(selector);
```

provided both ColA and ColB are of same data type. Otherwise it wouldn't be efficient due to the overhead of data type conversion.

Title: C# Linq OrderBy based on condition

Body:
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)

But I am sure there is a more elegant solution.

Body:
As @AlanK have mentioned, the closest we can get for simplifying OrderBy would be something like:

Func<OrderLines, string> selector = (orderLine) => condition ? orderLine.ColB : orderLine.ColA;

List<OrderLines> orderLines = lines.OrderBy(selector);

provided both ColA and ColB are of same data type. Otherwise it wouldn't be efficient due to the overhead of data type conversion.


问:
JS Regex returning -1 & 0
I was tasked with the following:

take a string

print each of the vowels on a new line (in order) then...

print each of the consonants on a new line (in order)

The problem I found was with the regex. I originally used...

/[aeiouAEIOU\s]/g```
</div>
</div>
</p>

<p>But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
    for(i=0;i<s.length;i++){
        //if char is vowel then push to array
        if(s[i].search(vowels)){
           array.push(s[i]);
        }

    }
    for(i=0;i<s.length;i++){
        //if char is cons then push to array
        if(!s[i].search(vowels)){
           array.push(s[i]);
        }
    }
    for(i=0;i<s.length;i++){
        console.log(array[i]);
    }
}

vowelsAndConsonants("javascript");</code>```

答:
There are a couple of inbuilt functions available:

let some_string = 'Mary had a little lamb';

let vowels = [...some_string.match(/[aeiouAEIOU\s]/g)];
let consonents = [...some_string.match(/[^aeiouAEIOU\s]/g)];

console.log(vowels);
console.log(consonents);```

Title: JS Regex returning -1 & 0

Body:
I was tasked with the following:

take a string

print each of the vowels on a new line (in order) then...

print each of the consonants on a new line (in order)

The problem I found was with the regex. I originally used...

/[aeiouAEIOU\s]/g

But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?

let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
    for(i=0;i<s.length;i++){
        //if char is vowel then push to array
        if(s[i].search(vowels)){
           array.push(s[i]);
        }

    }
    for(i=0;i<s.length;i++){
        //if char is cons then push to array
        if(!s[i].search(vowels)){
           array.push(s[i]);
        }
    }
    for(i=0;i<s.length;i++){
        console.log(array[i]);
    }
}

vowelsAndConsonants("javascript");


问:
Is there any guide for iOS runloop mechanism?
I'm learning socket communication on iPhone, and its guide said something about CFRunloop(it is a guide for CFNetwork, can this be used on iOS?)
Where can I learn about runloop on iOS?API reference is not enough.

答:
Look at the "Run Loops" chapter of Apple's Threading Programming Guide. In brief:

There is one run loop associated with each thread.

The run loop has to be run to do anything. Apple's application main function takes care of this for you on the main thread.

A run loop is run in a specific mode. The "common mode" is actually a set of modes, and there is an API for adding modes to that set.

A run loop's main purpose is to monitor timers and run loop sources. Each source is registered with a specific run loop for a specific mode, and will only be checked at the appropriate time when the runloop is running in that mode.

The run loop goes through several stages in each go around its loop, such as checking timers and checking other event sources. If it finds that any source is ready to fire, it triggers the appropriate callback.

Aside from using ready-made run loop tools, you can create your own run loop sources as well as registering a run loop observer to track the progress of the run loop.

One major pitfall is forgetting to run the run loop while waiting for a callback from a runloop source. This is sometimes a problem when you decide to busy-wait for something to happen on the main thread, but you're most likely to run into it when you create your own thread and register a runloop source with that runloop. You are responsible for establishing an autorelease pool and running the runloop if needed on non-main threads, since the application main function will not be there to do it for you.

You would do better to read Apple's Concurrency Programming Guide instead, which suggests alternatives to the runloop mechanism such as operation queues and dispatch sources. The "Replacing Run-Loop Code" section of the "Migrating Away from Threads" chapter suggests using dispatch sources instead of runloop sources to handle events.


问:
python regular expression returns empty string
Given:

```<code>lst = ['(abc): my name is ?123']
</code>```

I'm trying to return everything from ': ' till the end of lst[0], for that I tried a regex expression:

```<code>    result = re.search(r': (.*?)', lst[0]).group(1)
</code>```

It returns an empty string.
How can this be done using regex correctly?
Expected output :

'my name is ?123'

Resources used : Regex wiki

答:
The issue is that you made your .* lazy by placing ? at the end.  Lazy means match as little as possible, for a valid match.  In this case, since your pattern does not have anything to match beyond the (.*?), the regex engine is matching empty string.  Just use (.*), the non lazy version, and it will work.

```<code>lst = ['(abc): my name is ?123']
result = re.search(r': (.*)', lst[0]).group(1)
print(result)
</code>```

This prints:

```<code>my name is ?123
</code>```

Body:
Given:

lst = ['(abc): my name is ?123']

I'm trying to return everything from ': ' till the end of lst[0], for that I tried a regex expression:

    result = re.search(r': (.*?)', lst[0]).group(1)

It returns an empty string.
How can this be done using regex correctly?
Expected output :

'my name is ?123'

Resources used : Regex wiki

Body:
The issue is that you made your .* lazy by placing ? at the end.  Lazy means match as little as possible, for a valid match.  In this case, since your pattern does not have anything to match beyond the (.*?), the regex engine is matching empty string.  Just use (.*), the non lazy version, and it will work.

lst = ['(abc): my name is ?123']
result = re.search(r': (.*)', lst[0]).group(1)
print(result)

This prints:

my name is ?123


问:
Spring Data JPA - How to implement LIKE search with multiple values on the same column
Lets say I've the following table,

MOVIE_TITLE

Batman Begins

Batman Returns

Return of the Jedi

The Lord of the Rings: The Return of the King

Shakespeare in Love

Dead Poets Society

Deadpool

The Lord of the Rings: The Fellowship of the Ring

I'd like to implement a search on the movie title and pass comma separated values (search with multiple keywords)

For example,

search text: Batman
result: Records #1,2

search text: Batman, Return
result: Records #1,2,3,4

search text: Lord, Love
result: Records #4,5,8

Without looping for each of the keyword, can this be implemented in one call using the LIKE search (or something else) in Spring Data JPA?

Thanks

答:
I suspect you have an entity like this

```<code>@Entity
public class Movie {
   @Id
   Long id;
   String title;

   //getters, setters ...
}
</code>```

Then you need repository extends JpaSpecificationExecutor

```<code>public interface MovieRepository
        extends JpaRepository<Movie, Long>, JpaSpecificationExecutor<Movie> {
}
</code>```

and Specification utility class

```<code>public class MovieSpecification {
    public static Specification<Movie> titleContains(String searchWord) {
        return (root, query, builder) -> {
           Expression<String> titleLowerCase = builder.lower(root.get("title"));
           return builder.like(titleLowerCase, "%" + searchWord.toLowerCase() + "%")
        }
    }
}
</code>```

Usage on service layer:

```<code>MovieRepository repository;

public List<Movie> getMoviesWhereTitleContainsAnyWord(List<String> words) {
    if(words.isEmpty()) {
        return Collections.emptyList();
    }

    Specification<Movie> specification = null;
    for(String word : words) {
       Specification<Movie> wordSpecification = MovieSpecification.titleContains(word);
       if(specification == null) {
           specification = wordSpecification;
       } else {
           specification = specification.or(wordSpecification);
       }
    }

    return repository.findAll(specification);
}
</code>```

The more words you pass to the method the slower your query become due to multiple or clauses.

Body:
I suspect you have an entity like this

@Entity
public class Movie {
   @Id
   Long id;
   String title;

   //getters, setters ...
}

Then you need repository extends JpaSpecificationExecutor

public interface MovieRepository
        extends JpaRepository<Movie, Long>, JpaSpecificationExecutor<Movie> {
}

and Specification utility class

public class MovieSpecification {
    public static Specification<Movie> titleContains(String searchWord) {
        return (root, query, builder) -> {
           Expression<String> titleLowerCase = builder.lower(root.get("title"));
           return builder.like(titleLowerCase, "%" + searchWord.toLowerCase() + "%")
        }
    }
}

Usage on service layer:

MovieRepository repository;

public List<Movie> getMoviesWhereTitleContainsAnyWord(List<String> words) {
    if(words.isEmpty()) {
        return Collections.emptyList();
    }

    Specification<Movie> specification = null;
    for(String word : words) {
       Specification<Movie> wordSpecification = MovieSpecification.titleContains(word);
       if(specification == null) {
           specification = wordSpecification;
       } else {
           specification = specification.or(wordSpecification);
       }
    }

    return repository.findAll(specification);
}

The more words you pass to the method the slower your query become due to multiple or clauses.


问:
How to fix misalignment column using DataTables after reload first time or refresh
I have a table using DataTables and table data comes from a web service.
If page width reduced, table column fixed but if refresh the page column data disappear or be secret.

How to fix the problem.

Pictures of the page can explain better.

Problematic column, after refresh and first load.

After F12 open and closed column fixed

UPDATE: First and Last column are fixed column and there is no scroll options.

答:
I put .DataTable().columns.adjust(); code piece after jquery my table id selector. And it worked for me. Critical point is after created table with datatable, i should insert the code

Also check below links to misalignment of columns

https://datatables.net/forums/discussion/46821/column-misalignment-only-at-first-time-or-reload


答:
I think that you don't understand correctly how your regular expression works. In the brackets you have only defined a set of characters you want to match /[^aeiouAEIOU\s]/g and further by using the caret [^]as first in your group, you say that you want it to match everything but the characters in the carets. Sadly you don't provide an example of input and expected output, so I am only guessing, but I thing you could do the following:

```<code>let s = "avndexleops";
let keep_vowels = s.replace(/[^aeiouAEIOU\s]/g, '');
console.log(keep_vowels);
let keep_consonants = s.replace(/[aeiouAEIOU\s]/g, '');
console.log(keep_consonants);
</code>```

Please provide example of expected input and output.

Title: JS Regex returning -1 & 0

Body:
I think that you don't understand correctly how your regular expression works. In the brackets you have only defined a set of characters you want to match /[^aeiouAEIOU\s]/g and further by using the caret [^]as first in your group, you say that you want it to match everything but the characters in the carets. Sadly you don't provide an example of input and expected output, so I am only guessing, but I thing you could do the following:

let s = "avndexleops";
let keep_vowels = s.replace(/[^aeiouAEIOU\s]/g, '');
console.log(keep_vowels);
let keep_consonants = s.replace(/[aeiouAEIOU\s]/g, '');
console.log(keep_consonants);

Please provide example of expected input and output.


问:
python search the user name
```<code>Mon Apr 27 18:12:54 '<rdpDirect> ITC\109975@win_itsskdcbkp2_10.18.2.104
Mon Apr 27 18:14:31 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:14:32 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
</code>```

From the above text, need to search user name which is mentioned between the "\" and "@" sign. This can be numeric, characters, or alphanumeric.

eg: in the above example, 109975, VINOTHKUMAR, UITSMUSR etc.

答:
```<code>buffer = '''
Mon Apr 27 18:12:54 ' ITC\\19975@win_itsskdcbkp2_10.18.2.104 Mon Apr 27 18:14:31 ' JDAWMSAPPDEV\\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172 Mon Apr 27 18:14:32 ' JDAWMSAPPDEV\\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172 Mon Apr 27 18:24:21 ' SAAMARTHA\\UITSMUSR@win_saamarthaad_10.10.45.147 Mon Apr 27 18:24:21 ' SAAMARTHA\\UITSMUSR@win_saamarthaad_10.10.45.147'''
import re
print(re.findall('\\\([\d\w\W]+?)@', buffer))

['19975', 'VINOTHKUMAR', 'VINOTHKUMAR', 'UITSMUSR', 'UITSMUSR']
</code>```

Title: python search the user name

Body:
Mon Apr 27 18:12:54 '<rdpDirect> ITC\109975@win_itsskdcbkp2_10.18.2.104
Mon Apr 27 18:14:31 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:14:32 '<rdpDirect> JDAWMSAPPDEV\VINOTHKUMAR@win_jdawmsappdev_10.10.45.172
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147
Mon Apr 27 18:24:21 '<rdpDirect> SAAMARTHA\UITSMUSR@win_saamarthaad_10.10.45.147

From the above text, need to search user name which is mentioned between the "\" and "@" sign. This can be numeric, characters, or alphanumeric.

eg: in the above example, 109975, VINOTHKUMAR, UITSMUSR etc.


问:
Node.js Cheerio returning empty with no errors
i am trying to get data from table with structure like this:

```<code><table id="ros_table" class="info" style="display: none;">
    <tr>
        <th>First</th>
        <th>Second</th>
        <th>Third</th>
        <th>Forth</th>
        <th>Fifth</th>
        <th>Six</th>
    </tr>
    <tr>
        <td style="white-space: nowrap;"><a href="#">120241</a></td>
        <td style="white-space: nowrap;"><a href="#">69801:001:0255</a></td>
        <td>Name</td>
        <td>Name 2</td>
        <td><span style="white-space: nowrap;">90400 m<sup>2</sup></span> <span style="white-space: nowrap;">(9.04 ha)</span></td>
        <td style="white-space: nowrap;">jah</td>
    </tr>
</code>```

And the code im useing is this:

```<code>fetchData(url).then( (res) => {
    const html = res.data;
    const $ = cheerio.load(html);
    const statsTable = $('.table#ros_table > tr');
    statsTable.each(function() {
        let title = $(this).find('td').text();
        console.log(title);
    });
})

async function fetchData(url){
    console.log("Looking for stuff you need...")
    // Make the call
    let response = await axios(url).catch((err) => console.log(err));

    if(response.status !== 200){
        console.log("Blah, this did not work out");
        return;
    }
    return response;
}
</code>```

It works fine with just a simple que, but for some reason i can get it to work for this table.

答:
You need to return something out of each .then() block, i assume you want something like this?:

```<code>fetchData(url).then( (res) => {
    const html = res.data;
    const $ = cheerio.load(html);
    const statsTable = $('.table#ros_table > tr');
    return statsTable.map(function() {
        return $(this).find('td').text();
    });
})
</code>```

Body:
i am trying to get data from table with structure like this:

        First
        Second
        Third
        Forth
        Fifth
        Six

        120241
        69801:001:0255
        Name
        Name 2
        90400 m2 (9.04 ha)
        jah

And the code im useing is this:

fetchData(url).then( (res) => {
    const html = res.data;
    const $ = cheerio.load(html);
    const statsTable = $('.table#ros_table > tr');
    statsTable.each(function() {
        let title = $(this).find('td').text();
        console.log(title);
    });
})

async function fetchData(url){
    console.log("Looking for stuff you need...")
    // Make the call
    let response = await axios(url).catch((err) => console.log(err));

    if(response.status !== 200){
        console.log("Blah, this did not work out");
        return;
    }
    return response;
}

It works fine with just a simple que, but for some reason i can get it to work for this table.

Body:
You need to return something out of each .then() block, i assume you want something like this?:

fetchData(url).then( (res) => {
    const html = res.data;
    const $ = cheerio.load(html);
    const statsTable = $('.table#ros_table > tr');
    return statsTable.map(function() {
        return $(this).find('td').text();
    });
})


问:
Parallelize the function in Python
I have a below function that Im trying to parallelize using multiprocessing but I couldn't get it working successful.  </p>

```<code>for d in result_list:
    v=d['content'][0]['template']['module']
    if isinstance(v, list):
        for i, v2 in enumerate(v):
            df_module,  = normalizeJSON(d,i,v2['id'])
            dim_content_module=dim_content_module.append(df_module, ignore_index=True,sort=False)

    else:
        print('module is not a list')

</code>```

答:
Try Pool from multiprocessing module as following:-</p>

```<code>from multiprocessing import Pool

# function which contain main functional logic
def foo(arg):
    # some processing
    return "return for {}".format(arg)

# function which will invoke multiple processes
def function_which_invokes_multiprocesses(some_arg):
    # pass the number of processes you want to invoke
    with Pool(5) as p:
        invoke the function for each process
        print(foo("some arg"))
</code>```

Title: Parallelize the function in Python

Body:
I have a below function that Im trying to parallelize using multiprocessing but I couldn't get it working successful.

for d in result_list:
    v=d['content'][0]['template']['module']
    if isinstance(v, list):
        for i, v2 in enumerate(v):
            df_module,  = normalizeJSON(d,i,v2['id'])
            dim_content_module=dim_content_module.append(df_module, ignore_index=True,sort=False)

    else:
        print('module is not a list')

Body:
Try Pool from multiprocessing module as following:-

from multiprocessing import Pool

# function which contain main functional logic
def foo(arg):
    # some processing
    return "return for {}".format(arg)

# function which will invoke multiple processes
def function_which_invokes_multiprocesses(some_arg):
    # pass the number of processes you want to invoke
    with Pool(5) as p:
        invoke the function for each process
        print(foo("some arg"))


问:
How to use templated emails with Bootstrap on Symfony Mailer?
I have been following some Symfony Casts tutorial to send emails using Symfony Mailer bundle. I am also using Bootstrap 4 installed with NPM and Webpack Encore. I can't figure out how to provide styles to these templated emails:

Some controller

use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;

class SomeController extends AbstractController
{
    public function send(MailerInterface $mailer)
    {
        $email = (new TemplatedEmail())
            ->from(new Address('email@email.com', 'My app'))
            ->to(new Address($contact_form->getEmail(), $contact_form->getName()))
            ->subject('Hemos recibido tu mensaje')
            ->htmlTemplate('email/contact_form.html.twig');

        $mailer->send($email);
    }
}
```

<h3>The template <code>email/contact_form.html.twig</code> is extending <code>email/layout.html.twig</code>:</h3>

```<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{{ absolute_url(asset('build/app.css')) }}">

{% block body %}{% endblock %}

```

Style and scripts have the right link reference when I see the email HTML source but they don't have any styles or scripts applied anyway.

Usually, in "normal" layout template I use {{ encore_entry_link_tags('app') }} and {{ encore_entry_script_tags('app') }} but that would generate a relative path to the URLs, I have tried wrapping them in absolute_url() function, but it does not work.

I have tried this Github issue by creating a file macros.html.twig, then importing them in the template and adding {{ encore_absolute_link_tags('app') }} and {{ encore_absolute_script_tags('app') }} in the layout. But I still don't have any applied styles to the email.

What is the right way to import Webpack/Encore styles / scripts to templated emails?

Body:
I have been following some Symfony Casts tutorial to send emails using Symfony Mailer bundle. I am also using Bootstrap 4 installed with NPM and Webpack Encore. I can't figure out how to provide styles to these templated emails:

Some controller

use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;

class SomeController extends AbstractController
{
    public function send(MailerInterface $mailer)
    {
        $email = (new TemplatedEmail())
            ->from(new Address('email@email.com', 'My app'))
            ->to(new Address($contact_form->getEmail(), $contact_form->getName()))
            ->subject('Hemos recibido tu mensaje')
            ->htmlTemplate('email/contact_form.html.twig');

        $mailer->send($email);
    }
}

The template email/contact_form.html.twig is extending email/layout.html.twig:

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{{ absolute_url(asset('build/app.css')) }}">

{% block body %}{% endblock %}

Style and scripts have the right link reference when I see the email HTML source but they don't have any styles or scripts applied anyway.

Usually, in "normal" layout template I use {{ encore_entry_link_tags('app') }} and {{ encore_entry_script_tags('app') }} but that would generate a relative path to the URLs, I have tried wrapping them in absolute_url() function, but it does not work.

I have tried this Github issue by creating a file macros.html.twig, then importing them in the template and adding {{ encore_absolute_link_tags('app') }} and {{ encore_absolute_script_tags('app') }} in the layout. But I still don't have any applied styles to the email.

What is the right way to import Webpack/Encore styles / scripts to templated emails?

Body:
Most email clients will not download external CSS files and apply styles and apply them to the email HTML. You really shouldn't count on that (and linking to an external javascript file is even less likely to succeed, as it appears you are doing in your example).

Not only that, but email clients will most of the time ignore any <style> tags, even if the resources are not external.

What you should do is use the advise in the documentation and inline your CSS styles.

{% apply inline_css(source('@css/email.css')) %}
    <h1>Welcome {{ username }}!</h1>
    {# ... #}
{% endapply %}

But inlining styles generated by webpack encore is is not as straigh-forward and requires you jump a few more hoops.

This guide explains how to do it for Foundation styles, but it's easily adjusted for Bootstrap.


问:
Azure AD B2C with React Native Expo
I am new to mobile app development with react-native and expo. I'm trying to add authentication/authorization in my mobile app with Azure AD B2C but I find it more difficult to understand from Microsoft docs and even I couldn't find any clear directions on Google. Could anyone with this experience please guide me in right direction. Any help would be appreciated.</p>

答:
I tried to implement Implicit auth flow with Expo Auth Session. But from the Microsoft Docs I learnt that Auth Code flow is most secured to use in mobile apps compared to Implicit flow. Does anyone tried Auth Code flow with expo React native apps?

This is how I achieved Implicit flow with expo Auth Session:

```<code>  let redirectUrl = AuthSession.getRedirectUrl();
  console.log({redirectUrl});
  let result = await AuthSession.startAsync({
        authUrl:
            `https://{{YourB2CTenant}}.com/{{YourB2CAD}}.onmicrosoft.com/oauth2/v2.0/authorize?p={{YourB2CPolicy}}` +
            `&client_id=${clientId}` +
            `&nonce=default` +
            `&redirect_uri=${encodeURIComponent(redirectUrl)}` +
            `&scope=${encodeURIComponent("openid offline_access")}` +
            `&response_mode=fragment` +
            `&response_type=id_token+token` +
            `&prompt=login` +
            `&state=login`
    });
    if(result.type !== 'success') {
        alert('Uh oh, something went wrong');
        return;
    }
</code>```

Title: Azure AD B2C with React Native Expo

Body:
I tried to implement Implicit auth flow with Expo Auth Session. But from the Microsoft Docs I learnt that Auth Code flow is most secured to use in mobile apps compared to Implicit flow. Does anyone tried Auth Code flow with expo React native apps?

This is how I achieved Implicit flow with expo Auth Session:

  let redirectUrl = AuthSession.getRedirectUrl();
  console.log({redirectUrl});
  let result = await AuthSession.startAsync({
        authUrl:
            `https://{{YourB2CTenant}}.com/{{YourB2CAD}}.onmicrosoft.com/oauth2/v2.0/authorize?p={{YourB2CPolicy}}` +
            `&client_id=${clientId}` +
            `&nonce=default` +
            `&redirect_uri=${encodeURIComponent(redirectUrl)}` +
            `&scope=${encodeURIComponent("openid offline_access")}` +
            `&response_mode=fragment` +
            `&response_type=id_token+token` +
            `&prompt=login` +
            `&state=login`
    });
    if(result.type !== 'success') {
        alert('Uh oh, something went wrong');
        return;
    }


问:
two std::cout, only one outputting
I have a program which accepts input for 10 people, and is then supposed to cout the person who consumed the highest number of pancakes and the person who ate the fewest. I've tried:

std::endl; at the end of every cout.

std::flush; at the end.

after this didn't work on my machine, I put the code into repl.it, and it still didn't work. This (from my understanding of how repl.it works) rules out an issue with compiler/ide (which is g++ and visual studio 2019).

My code:

main.cpp:

```<code>    #include <iostream>
    #include <string>
    #include <vector>
    #include "header.h"

    std::vector<int> person = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::vector<int> num_eaten_pancakes(10);

    int most_pancakes = 0;
    int least_pancakes = 0;
    int person_who_ate_most = 0;
    int person_who_ate_least = 0;

     int main() {
       get_nums_of_pancakes();
       person_who_ate_most = who_ate_most();
       std::cout << "Person " << who_ate_most() << " ate the most pancakes with " << num_eaten_pancakes[person_who_ate_most - 1] << " eaten." << std::flush;

       person_who_ate_least = who_ate_least();
       std::cout << "Person " << who_ate_least() << " ate the least pancakes with " << num_eaten_pancakes[person_who_ate_least - 1] << " eaten." << std::flush;
       return 0;
    }
</code>```

funcs.cpp

```<code>#include <iostream>
#include <string>
#include <vector>
#include "header.h"

void get_nums_of_pancakes() {
//Get the no. of pancakes eaten by person 1, 2, etc. up to person 10.
for (int i = 0; i < 10; i++) {
    person[i] = i + 1;
    std::cout << "Input the number of pancakes entered by person " << person[i] << ": ";
    std::cin >> num_eaten_pancakes[i];
  }
}

//Who ate the most pancakes
int who_ate_most() {
for (int i = 0; i < 10; i++) {
    if (num_eaten_pancakes[i] > most_pancakes) {
        most_pancakes = num_eaten_pancakes[i];
        person_who_ate_most = person[i];
    }
  }
  return person_who_ate_most;
}

//Who ate the least pancakes
int who_ate_least() {
  for (int i = 0; i < 10; i++) {
     do
        least_pancakes = num_eaten_pancakes[i];
     while (i == 0);

     if (num_eaten_pancakes[i] < least_pancakes) {
         least_pancakes = num_eaten_pancakes[i];
         person_who_ate_least = person[i];
     }
   }
   return person_who_ate_least;
 }
</code>```

header.h

```<code>#include <vector>
#include <string>

//VARIABLES
//Vectors for 10 people, pancakes
extern std::vector<int> person;
extern std::vector<int> num_eaten_pancakes;

extern int most_pancakes;
extern int least_pancakes;
extern int person_who_ate_most;
extern int person_who_ate_least;

//FUNCTIONS
void get_nums_of_pancakes();
int who_ate_most();
int who_ate_least();
</code>```

The output, when I enter the number of pancakes consumed, is correct for the person who ate the most, but when it comes to the person who consumed the fewest, there's nothing.

答:
I think you should change "who_ate_least()" function as follows:</p>

```<code>int who_ate_least() {
  for (int i = 0; i < 10; i++) {
     if(i==0)
        least_pancakes = num_eaten_pancakes[i];

     if (num_eaten_pancakes[i] <= least_pancakes) {
         least_pancakes = num_eaten_pancakes[i];
         person_who_ate_least = person[i];
     }
   }
   return person_who_ate_least;
 }
</code>```

Title: two std::cout, only one outputting

Body:
I have a program which accepts input for 10 people, and is then supposed to cout the person who consumed the highest number of pancakes and the person who ate the fewest. I've tried:

std::endl; at the end of every cout.

std::flush; at the end.

after this didn't work on my machine, I put the code into repl.it, and it still didn't work. This (from my understanding of how repl.it works) rules out an issue with compiler/ide (which is g++ and visual studio 2019).

My code:

main.cpp:

    #include <iostream>
    #include <string>
    #include <vector>
    #include "header.h"

    std::vector<int> person = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::vector<int> num_eaten_pancakes(10);

    int most_pancakes = 0;
    int least_pancakes = 0;
    int person_who_ate_most = 0;
    int person_who_ate_least = 0;

     int main() {
       get_nums_of_pancakes();
       person_who_ate_most = who_ate_most();
       std::cout << "Person " << who_ate_most() << " ate the most pancakes with " << num_eaten_pancakes[person_who_ate_most - 1] << " eaten." << std::flush;

       person_who_ate_least = who_ate_least();
       std::cout << "Person " << who_ate_least() << " ate the least pancakes with " << num_eaten_pancakes[person_who_ate_least - 1] << " eaten." << std::flush;
       return 0;
    }

funcs.cpp

#include <iostream>
#include <string>
#include <vector>
#include "header.h"

void get_nums_of_pancakes() {
//Get the no. of pancakes eaten by person 1, 2, etc. up to person 10.
for (int i = 0; i < 10; i++) {
    person[i] = i + 1;
    std::cout << "Input the number of pancakes entered by person " << person[i] << ": ";
    std::cin >> num_eaten_pancakes[i];
  }
}

//Who ate the most pancakes
int who_ate_most() {
for (int i = 0; i < 10; i++) {
    if (num_eaten_pancakes[i] > most_pancakes) {
        most_pancakes = num_eaten_pancakes[i];
        person_who_ate_most = person[i];
    }
  }
  return person_who_ate_most;
}

//Who ate the least pancakes
int who_ate_least() {
  for (int i = 0; i < 10; i++) {
     do
        least_pancakes = num_eaten_pancakes[i];
     while (i == 0);

     if (num_eaten_pancakes[i] < least_pancakes) {
         least_pancakes = num_eaten_pancakes[i];
         person_who_ate_least = person[i];
     }
   }
   return person_who_ate_least;
 }

header.h

#include <vector>
#include <string>

//VARIABLES
//Vectors for 10 people, pancakes
extern std::vector<int> person;
extern std::vector<int> num_eaten_pancakes;

extern int most_pancakes;
extern int least_pancakes;
extern int person_who_ate_most;
extern int person_who_ate_least;

//FUNCTIONS
void get_nums_of_pancakes();
int who_ate_most();
int who_ate_least();

The output, when I enter the number of pancakes consumed, is correct for the person who ate the most, but when it comes to the person who consumed the fewest, there's nothing.

Body:
I think you should change "who_ate_least()" function as follows:

int who_ate_least() {
  for (int i = 0; i < 10; i++) {
     if(i==0)
        least_pancakes = num_eaten_pancakes[i];

     if (num_eaten_pancakes[i] <= least_pancakes) {
         least_pancakes = num_eaten_pancakes[i];
         person_who_ate_least = person[i];
     }
   }
   return person_who_ate_least;
 }


问:
Custom Shopify Button embed on other website
I would like to embed a shopify buy button and checkout onto a separate website. I would like to customize it so it looks native. However, I can't figure out how I can do this such that I can have a completely custom CSS button and a separate button to open cart.

```<code>    var client = ShopifyBuy.buildClient({
        domain: 'XXXX.myshopify.com',
        storefrontAccessToken: 'XXXX',
    });

    var ui = ShopifyBuy.UI.init(client);
    ui.createComponent('product', {
      id: XXXX,
      options: {
        product: {
          buttonDestination: 'cart',
        },
        cart: {
          startOpen: false,
        }
      }
    });

    ui.openCart();
</code>```

Can't i just have a div that calls some function "AddToCart()"? Is there a simple way to do this?

答:
I believe that you can use Shopify's 'Buy Button' sales channel.

After activating that channel, you can then use it to select a product or category. In this section, you can also alter the styling of the button etc. After everything is updated to your liking, click next and it will generate the code for the product or catalogue that you selected. Simply copy and paste the code that it generates on the website that you desire.

Hope this helps!

Body:
I would like to embed a shopify buy button and checkout onto a separate website. I would like to customize it so it looks native. However, I can't figure out how I can do this such that I can have a completely custom CSS button and a separate button to open cart.

    var client = ShopifyBuy.buildClient({
        domain: 'XXXX.myshopify.com',
        storefrontAccessToken: 'XXXX',
    });

    var ui = ShopifyBuy.UI.init(client);
    ui.createComponent('product', {
      id: XXXX,
      options: {
        product: {
          buttonDestination: 'cart',
        },
        cart: {
          startOpen: false,
        }
      }
    });

    ui.openCart();

Can't i just have a div that calls some function "AddToCart()"? Is there a simple way to do this?


问:
Closing a pdf by reading the file size
I am auto creating pdf's from a list of items in excel.  Everything is working fine but sometimes the created pdf is corrupted since the program closes the original too fast.  I realize I could add time to the Application.Wait but sometimes that will add a lot of time if the list is very long.  I am trying to read the file size using FileLen and looping until that value is greater than 0 and then close the file.  My code below is throwing an error saying Next without For.

Any help is appreciated.

```<code>For WaitTime = 0 To 0.5
If FileLen(SavePDFFldr & "\" & Description & ".pdf") > 10 Then
    Application.SendKeys "^(q)", True
    Application.SendKeys "{numlock}%s", True                    ' Closes the template when the file is done saving
    Application.SendKeys "{Tab}", True
    Application.SendKeys "{Enter}", True
Else: Next WaitTime
</code>```

Where the SavePDFFldr and Description are set prior to this.

答:
The question raised in the comment could be answered like that. You add a second exit condition to the loop which leaves the loop after a couple of seconds.</p>

```<code>Sub LoopTest()

Dim a As Long
Dim startTime As Date
Dim endTime As Date
    startTime = Now
    endTime = startTime + TimeValue("00:00:03")
    Do While a < 10
        ' Without a second condition this is an endless loop

        ' this example will leave the loop after ~3 seconds
        If Now > endTime Then
            MsgBox "Done"
            Exit Do
        End If

        'DoEvents
    Loop
End Sub
</code>```

Title: Closing a pdf by reading the file size

Body:
I am auto creating pdf's from a list of items in excel.  Everything is working fine but sometimes the created pdf is corrupted since the program closes the original too fast.  I realize I could add time to the Application.Wait but sometimes that will add a lot of time if the list is very long.  I am trying to read the file size using FileLen and looping until that value is greater than 0 and then close the file.  My code below is throwing an error saying Next without For.

Any help is appreciated.

For WaitTime = 0 To 0.5
If FileLen(SavePDFFldr & "\" & Description & ".pdf") > 10 Then
    Application.SendKeys "^(q)", True
    Application.SendKeys "{numlock}%s", True                    ' Closes the template when the file is done saving
    Application.SendKeys "{Tab}", True
    Application.SendKeys "{Enter}", True
Else: Next WaitTime

Where the SavePDFFldr and Description are set prior to this.

Body:
The question raised in the comment could be answered like that. You add a second exit condition to the loop which leaves the loop after a couple of seconds.

Sub LoopTest()

Dim a As Long
Dim startTime As Date
Dim endTime As Date
    startTime = Now
    endTime = startTime + TimeValue("00:00:03")
    Do While a < 10
        ' Without a second condition this is an endless loop

        ' this example will leave the loop after ~3 seconds
        If Now > endTime Then
            MsgBox "Done"
            Exit Do
        End If

        'DoEvents
    Loop
End Sub


问:
Anyone help me to divide this column1 and column2 values. The values are in millions
Need to divide the two columns which as the values in Millions using python pandas dataframe.

movies[new_columns]=movies[column1] / movies[column2] /* Not Working */

Example:
After concentrate I see the columns look like below:

```<code>movies[new_columns]=movies[column1] + movies[column2]

0       $151.1MM$30.0MM
1     $341.27MM$150.0MM
2       $51.74MM$12.0MM
3      $100.55MM$47.0MM
4         $47.7MM$9.0MM
</code>```

Anyone help me to divide this column1 and column2 values. The values are in millions.

Logic implemented:

```<code># Divide the 'gross' and 'budget' columns by 1000000 to convert '$' to 'million $'
movies['Budget_in_($)_millions'] = '$' + (movies['budget'].astype(float)/1000000).round(2).astype(str) + 'MM'
movies
</code>```

Kindly assist.

Thanks, SB

答:
Problem is you need processing floats columns:

```<code>movies['budget'] = movies['budget'].astype(float)/1000000)

movies['new_columns'] = movies['column1'] / movies['column2']
</code>```

Last step convert to strings and addded prefixes, suffixes:

```<code>movies['Budget_in_($)_millions'] = '$' + movies['budget'].round(2).astype(str) + 'MM'
</code>```

Body:
Need to divide the two columns which as the values in Millions using python pandas dataframe.

movies[new_columns]=movies[column1] / movies[column2] /* Not Working */

Example:
After concentrate I see the columns look like below:

movies[new_columns]=movies[column1] + movies[column2]

0       $151.1MM$30.0MM
1     $341.27MM$150.0MM
2       $51.74MM$12.0MM
3      $100.55MM$47.0MM
4         $47.7MM$9.0MM

Anyone help me to divide this column1 and column2 values. The values are in millions.

Logic implemented:

# Divide the 'gross' and 'budget' columns by 1000000 to convert '$' to 'million $'
movies['Budget_in_($)_millions'] = '$' + (movies['budget'].astype(float)/1000000).round(2).astype(str) + 'MM'
movies

Kindly assist.

Thanks, SB

Body:
Problem is you need processing floats columns:

movies['budget'] = movies['budget'].astype(float)/1000000)

movies['new_columns'] = movies['column1'] / movies['column2']

Last step convert to strings and addded prefixes, suffixes:

movies['Budget_in_($)_millions'] = '$' + movies['budget'].round(2).astype(str) + 'MM'


问:
Help with running the Yesod Development server?
I'm currently trying out web development frameworks for haskell and I recently came across yesod. It seemed pretty interesting so I installed it using cabal, however I'm not able to run the development server. Following their getting started instructions here's the result:

```<code>$ yesod init
$ cd mysite
$ yesod devel

Configuring mysite-0.0.0...
Testing files...
Rebuilding app
yesod: bind: resource busy (Address already in use)
Preprocessing library mysite-0.0.0...
Preprocessing executables for mysite-0.0.0...
Building mysite-0.0.0...

Controller.hs:16:7:
    Could not find module `Data.Dynamic':
      It is a member of the hidden package `base'.
      Perhaps you need to add `base' to the build-depends in your .cabal file.
      It is a member of the hidden package `base-3.0.3.2'.
      Perhaps you need to add `base' to the build-depends in your .cabal file.
      Use -v to see a list of the files searched for.
Testing files...
Testing files...
^^ above line just keeps repeating...
</code>```

I'm assuming it has something to do with the Data.Dynamic module but I don't know how to go about fixing it.

Additional Info

Running Ubuntu 10.10 Maverick

ghc version:

```<code>$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 6.12.1
</code>```

答:
I haven't run into this specific issue, but the error message looks like it's a simple question of GHC being unable to find version 3.0.3.2 the package "base." This version has been buildable since GHC 6.9, so you should have it. Try running the following command:

```<code>ghc-pkg check
</code>```

This will tell you if there is something wrong with your packages. Cabal can be a bit of a nightmare for dependencies -- partly, it seems, because a lot of Haskell developers underestimate the extent to which their underlying libraries will shift in the future. So they will define a dependency as ">= [version of package x]" without limiting the max version to the one presently available. Or they just leave out version-limiting altogether.

Yesod, I'm happy to say, doesn't fall into this trap. But several of the libraries it depends on do. When you start developing in Haskell, learn this lesson: never assume that future versions of a library won't break your code. They will. A lot.

If ghc-pkg comes up with broken packages, you may need to clean up/uninstall/reinstall these packages until they are either cleaned up or hidden. (Just do ghc-pkg hide [package name] to tell ghc to ignore that package.

Your next problem is that hidden base package. Try the following:

```<code>ghc-pkg list | grep base
</code>```

If you see brackets around the library, that means it's hidden. The package base-3.0.3.2 might show up as hidden (although that's a bit unlikely, as that's where the backward-compatible Prelude lives). If it is hidden, try to unhide it with the following command:

```<code>ghc-pkg expose base-3.0.3.2
</code>```

Now try re-running yesod devel and see how it goes. Best case scenario is that it works. If not, let us know.

Body:
I'm currently trying out web development frameworks for haskell and I recently came across yesod. It seemed pretty interesting so I installed it using cabal, however I'm not able to run the development server. Following their getting started instructions here's the result:

$ yesod init
$ cd mysite
$ yesod devel

Configuring mysite-0.0.0...
Testing files...
Rebuilding app
yesod: bind: resource busy (Address already in use)
Preprocessing library mysite-0.0.0...
Preprocessing executables for mysite-0.0.0...
Building mysite-0.0.0...

Controller.hs:16:7:
    Could not find module `Data.Dynamic':
      It is a member of the hidden package `base'.
      Perhaps you need to add `base' to the build-depends in your .cabal file.
      It is a member of the hidden package `base-3.0.3.2'.
      Perhaps you need to add `base' to the build-depends in your .cabal file.
      Use -v to see a list of the files searched for.
Testing files...
Testing files...
^^ above line just keeps repeating...

I'm assuming it has something to do with the Data.Dynamic module but I don't know how to go about fixing it.

Additional Info

Running Ubuntu 10.10 Maverick

ghc version:

$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 6.12.1

Body:
I haven't run into this specific issue, but the error message looks like it's a simple question of GHC being unable to find version 3.0.3.2 the package "base." This version has been buildable since GHC 6.9, so you should have it. Try running the following command:

ghc-pkg check

This will tell you if there is something wrong with your packages. Cabal can be a bit of a nightmare for dependencies -- partly, it seems, because a lot of Haskell developers underestimate the extent to which their underlying libraries will shift in the future. So they will define a dependency as ">= [version of package x]" without limiting the max version to the one presently available. Or they just leave out version-limiting altogether.

Yesod, I'm happy to say, doesn't fall into this trap. But several of the libraries it depends on do. When you start developing in Haskell, learn this lesson: never assume that future versions of a library won't break your code. They will. A lot.

If ghc-pkg comes up with broken packages, you may need to clean up/uninstall/reinstall these packages until they are either cleaned up or hidden. (Just do ghc-pkg hide [package name] to tell ghc to ignore that package.

Your next problem is that hidden base package. Try the following:

ghc-pkg list | grep base

If you see brackets around the library, that means it's hidden. The package base-3.0.3.2 might show up as hidden (although that's a bit unlikely, as that's where the backward-compatible Prelude lives). If it is hidden, try to unhide it with the following command:

ghc-pkg expose base-3.0.3.2

Now try re-running yesod devel and see how it goes. Best case scenario is that it works. If not, let us know.


问:
error: 'python_ipc_popen2' undefined near line 62 column 15 When running Octave
Trying to run Octave on Mac. When I run the diagnose command sympref diagnose. I get that everything is configured fine:

```<code>Symbolic package diagnostics
============================

Python and SymPy are needed for most features of the Symbolic package.

The Python interpreter is currently: "/Library/Frameworks/Python.framework/Versions/3.7/bin/python3".

Computers may have more than one Python interpreter installed.  If you
need to, you can select a different one using the PYTHON environment
variable (see "help sympref").  For example, to use Python 2, try
    setenv PYTHON python2
    sympref reset

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "print(\"Python says hello\")"

status = 0
output = Python says hello

Good, Python ran correctly.

Python version
--------------

Let's check what version of Python we are calling...

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "import sys; print(sys.version)"

status = 0
output = 3.7.6 (v3.7.6:43364a7ae0, Dec 18 2019, 14:18:50)
[Clang 6.0 (clang-600.0.57)]

SymPy Python Library
--------------------

SymPy is a Python library used by Symbolic for almost all features.

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "import sympy; print(sympy.__version__)"

status = 0
output = 1.6

SymPy must be at least version 1.2; you have version 1.6.

Good, a working version of SymPy is installed.

Python XML Parsing and DOM Support
----------------------------------

The XML DOM library is used by Symbolic for passing values to and from Python.
Some older versions of Python formatted XML output differently.  As long as you
have any reasonably recent version of Python, this should pass.

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "import xml.dom.minidom as minidom; doc = minidom.parseString(\"<item>value</item>\"); print(doc.toprettyxml(indent=\"\"))"

status = 0
output = <?xml version="1.0" ?>
<item>value</item>

Your kit looks good for running the Symbolic package.  Happy hacking!
</code>```

but as soon as I try to declare a variable syms x I get the following error:

```<code>error: 'python_ipc_popen2' undefined near line 62 column 15
error: called from
    python_ipc_driver at line 62 column 13
    pycall_sympy__ at line 163 column 9
    valid_sym_assumptions at line 38 column 10
    assumptions at line 82 column 7
    syms at line 97 column 13
</code>```

答:
Ok, I've found out how to solve it. Super strange.
Apparently Octave (or SymPy, not sure exactly) is looking for a system variable called Python like this with a capital P in the docs it's said the variable should be PYTHON. Anyway setting setenv Python <path to python> solved the issue.

Body:
Trying to run Octave on Mac. When I run the diagnose command sympref diagnose. I get that everything is configured fine:

Symbolic package diagnostics
============================

Python and SymPy are needed for most features of the Symbolic package.

The Python interpreter is currently: "/Library/Frameworks/Python.framework/Versions/3.7/bin/python3".

Computers may have more than one Python interpreter installed.  If you
need to, you can select a different one using the PYTHON environment
variable (see "help sympref").  For example, to use Python 2, try
    setenv PYTHON python2
    sympref reset

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "print(\"Python says hello\")"

status = 0
output = Python says hello

Good, Python ran correctly.

Python version
--------------

Let's check what version of Python we are calling...

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "import sys; print(sys.version)"

status = 0
output = 3.7.6 (v3.7.6:43364a7ae0, Dec 18 2019, 14:18:50)
[Clang 6.0 (clang-600.0.57)]

SymPy Python Library
--------------------

SymPy is a Python library used by Symbolic for almost all features.

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "import sympy; print(sympy.__version__)"

status = 0
output = 1.6

SymPy must be at least version 1.2; you have version 1.6.

Good, a working version of SymPy is installed.

Python XML Parsing and DOM Support
----------------------------------

The XML DOM library is used by Symbolic for passing values to and from Python.
Some older versions of Python formatted XML output differently.  As long as you
have any reasonably recent version of Python, this should pass.

Attempting to run /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -c "import xml.dom.minidom as minidom; doc = minidom.parseString(\"<item>value</item>\"); print(doc.toprettyxml(indent=\"\"))"

status = 0
output = <?xml version="1.0" ?>
<item>value</item>

Your kit looks good for running the Symbolic package.  Happy hacking!

but as soon as I try to declare a variable syms x I get the following error:

error: 'python_ipc_popen2' undefined near line 62 column 15
error: called from
    python_ipc_driver at line 62 column 13
    pycall_sympy__ at line 163 column 9
    valid_sym_assumptions at line 38 column 10
    assumptions at line 82 column 7
    syms at line 97 column 13


问:
Using reduce to remap an array with child arrays
I'm struggling to work out how to remap the below array.

I have tried to use the reduce function built into JS but to no avail.

The furthest I have got it creating the function:

```<code>var comb = []
var setEle = []
var setEle = []
input.forEach(a => {
  a.productVariations.forEach(element => {
    if (comb.indexOf(element.variationName) === -1) {
      comb.push(element.variationName)

      let group = element.variationOptions.reduce((r, a) => {
        r['variationName'] = element.variationName
        r['variationOptions'] = [...(r[a.name] || []), a]

        return r
      }, {})

      group['linked'] = []
      setEle.push(group)
    }
  })

})
</code>```

How do I remap the array as below and get my reduce function working?

```<code>var input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          }
        ]
      },
      {
        variationName: 'Pattern',
        variationOptions: [
          {
            name: 'Bold'
          },
          {
            name: 'Spotted'
          }
        ]
      }
    ]
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          },
          {
            name: 'Purple '
          }
        ]
      }
    ]
  }
]
</code>```

I would like the output to look like this:

```<code>var output = [
  {
    variationName: 'Colour',
    variationOptions: [
      {
        name: 'Blue'
      },
      {
        name: 'Purple'
      },
      {
        name: 'Red'
      },
    ],
    linked: [
      {
        companyName: 'BBC'
      },
      {
        companyName: 'ABC'
      }
    ]
  },
  {
    variationName: 'Pattern',
    variationOptions: [
      {
        name: 'Bold'
      },
      {
        name: 'Spotted'
      },
    ],
    linked: [
      {
        companyName: 'ABC',
      }
    ]
  }
]
</code>```

The output array, groups the variationOptions by variationName and adds the relevant companyName to the linked child array.

答:
if not particular about reduce, use forEach and build the object with values companyNames and variationOptions as Set so that we will have unique items.
From above object, again build the array using map over above sets.

const converge = (arr) => {
  const res = {};
  arr.forEach(({ companyName, productVariations }) => {
    productVariations.forEach(({ variationName, variationOptions }) => {
      if (!res[variationName]) {
        res[variationName] = { options: new Set(), links: new Set() };
      }
      res[variationName].links.add(companyName);
      variationOptions.forEach(({ name }) =>
        res[variationName].options.add(name)
      );
    });
  });
  return Object.entries(res).map(([variationName, {options, links}]) => ({
    variationName,
    variationOptions: [...options].map((name) => ({ name })),
    linked: [...links].map((companyName) => ({ companyName })),
  }));
};

var input = [
  {
    companyName: "ABC",
    productVariations: [
      {
        variationName: "Colour",
        variationOptions: [
          {
            name: "Blue",
          },
          {
            name: "Red",
          },
        ],
      },
      {
        variationName: "Pattern",
        variationOptions: [
          {
            name: "Bold",
          },
          {
            name: "Spotted",
          },
        ],
      },
    ],
  },
  {
    companyName: "BBC",
    productVariations: [
      {
        variationName: "Colour",
        variationOptions: [
          {
            name: "Blue",
          },
          {
            name: "Red",
          },
          {
            name: "Purple ",
          },
        ],
      },
    ],
  },
];

console.log(converge(input));```

Body:
I'm struggling to work out how to remap the below array.

I have tried to use the reduce function built into JS but to no avail.

The furthest I have got it creating the function:

var comb = []
var setEle = []
var setEle = []
input.forEach(a => {
  a.productVariations.forEach(element => {
    if (comb.indexOf(element.variationName) === -1) {
      comb.push(element.variationName)

      let group = element.variationOptions.reduce((r, a) => {
        r['variationName'] = element.variationName
        r['variationOptions'] = [...(r[a.name] || []), a]

        return r
      }, {})

      group['linked'] = []
      setEle.push(group)
    }
  })

})

How do I remap the array as below and get my reduce function working?

var input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          }
        ]
      },
      {
        variationName: 'Pattern',
        variationOptions: [
          {
            name: 'Bold'
          },
          {
            name: 'Spotted'
          }
        ]
      }
    ]
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          },
          {
            name: 'Purple '
          }
        ]
      }
    ]
  }
]

I would like the output to look like this:

var output = [
  {
    variationName: 'Colour',
    variationOptions: [
      {
        name: 'Blue'
      },
      {
        name: 'Purple'
      },
      {
        name: 'Red'
      },
    ],
    linked: [
      {
        companyName: 'BBC'
      },
      {
        companyName: 'ABC'
      }
    ]
  },
  {
    variationName: 'Pattern',
    variationOptions: [
      {
        name: 'Bold'
      },
      {
        name: 'Spotted'
      },
    ],
    linked: [
      {
        companyName: 'ABC',
      }
    ]
  }
]

The output array, groups the variationOptions by variationName and adds the relevant companyName to the linked child array.


问:
SpringBoot, controller return data through ResponseBodyAdvice occur an error (class can't cast to string)
I want format controller's result by using ResponseBodyAdvice.
For example, controller method return a string ("hello"), the ResponseBodyAdvice format it as a Json data {code:1, data:"hello"}.

Here is my controller method code:

```<code>@PostMapping("login")
public String login(String username, String pwd) throws Exception {
    System.out.println(username + pwd);
    return "hhh";
}
</code>```

Here is my ResponseBodyAdvice:

```<code>@ControllerAdvice
public class GlobalControllerAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return TResult.success(o); // result is my class, it occur error
        // return JSON.toJSONString(TResult.success(o)); // result is string, it's ok
    }
}
</code>```

the error message is :

```<code>java.lang.ClassCastException: cn.tianyu.blog_api.util.TResult cannot be cast to java.lang.String
at org.springframework.http.converter.StringHttpMessageConverter.getContentLength(StringHttpMessageConverter.java:43) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.http.converter.AbstractHttpMessageConverter.addDefaultHeaders(AbstractHttpMessageConverter.java:259) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:210) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:275) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:180) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
</code>```

the result is

TResult.class

```<code>public class TResult {

private Integer code;
private String message;
private Object data;

public TResult() {
}

public TResult(Integer code, String message) {
    this.code = code;
    this.message = message;
}

public static TResult success() {
    TResult result = new TResult();
    result.setResultCode(TResultCode.SUCCESS);
    return result;
}

public static TResult success(Object data) {
    TResult result = new TResult();
    result.setResultCode(TResultCode.SUCCESS);
    result.setData(data);
    return result;
}
</code>```

Note the return type in the direction of the red arrow.
The final result type is application/json, I set a breakpoints, the method "ResponseBodyAdvice.beforeBodyWrite()" was called two times. The error happened for the first time. Assembled error message for the second time.

please help! thank you very much!

答:
Understood what you are trying to implement as I did the same recently. If you wish to customize the response along with its class type (as against the one specified in your controller return type), then you can use class generics while implementing ResponseBodyAdvice.
Note: you have used ResponseBodyAdvice as against the expected *ResponseBodyAdvice <Object> *

```<code>    @ControllerAdvice
    public class GlobalControllerAdvice implements ResponseBodyAdvice<Object> {

     @Override
        public boolean supports(MethodParameter methodParameter, Class aClass) {
            return true;
        }

        @Override
        public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
            JSONObject responseObj = new JSONObject();
            responseObj.put("code1", TResult.success(o);
            return responseObj;
        }
}
</code>```

Body:
I want format controller's result by using ResponseBodyAdvice.
For example, controller method return a string ("hello"), the ResponseBodyAdvice format it as a Json data {code:1, data:"hello"}.

Here is my controller method code:

@PostMapping("login")
public String login(String username, String pwd) throws Exception {
    System.out.println(username + pwd);
    return "hhh";
}

Here is my ResponseBodyAdvice:

@ControllerAdvice
public class GlobalControllerAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return TResult.success(o); // result is my class, it occur error
        // return JSON.toJSONString(TResult.success(o)); // result is string, it's ok
    }
}

the error message is :

java.lang.ClassCastException: cn.tianyu.blog_api.util.TResult cannot be cast to java.lang.String
at org.springframework.http.converter.StringHttpMessageConverter.getContentLength(StringHttpMessageConverter.java:43) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.http.converter.AbstractHttpMessageConverter.addDefaultHeaders(AbstractHttpMessageConverter.java:259) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:210) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:275) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:180) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]

the result is

TResult.class

public class TResult {

private Integer code;
private String message;
private Object data;

public TResult() {
}

public TResult(Integer code, String message) {
    this.code = code;
    this.message = message;
}

public static TResult success() {
    TResult result = new TResult();
    result.setResultCode(TResultCode.SUCCESS);
    return result;
}

public static TResult success(Object data) {
    TResult result = new TResult();
    result.setResultCode(TResultCode.SUCCESS);
    result.setData(data);
    return result;
}

Note the return type in the direction of the red arrow.
The final result type is application/json, I set a breakpoints, the method "ResponseBodyAdvice.beforeBodyWrite()" was called two times. The error happened for the first time. Assembled error message for the second time.

please help! thank you very much!

Body:
Understood what you are trying to implement as I did the same recently. If you wish to customize the response along with its class type (as against the one specified in your controller return type), then you can use class generics while implementing ResponseBodyAdvice.
Note: you have used ResponseBodyAdvice as against the expected *ResponseBodyAdvice <Object> *

    @ControllerAdvice
    public class GlobalControllerAdvice implements ResponseBodyAdvice<Object> {

     @Override
        public boolean supports(MethodParameter methodParameter, Class aClass) {
            return true;
        }

        @Override
        public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
            JSONObject responseObj = new JSONObject();
            responseObj.put("code1", TResult.success(o);
            return responseObj;
        }
}


问:
How to groupby specifically datetime index in a multiindex column by month

The data frame shows the date with the amount of import and export
and it is further bifurcated into coastal and regional data per day
of one month.

What I wish to achieve is to club i.e sum all the data presented, which is of one month in this
case, in the end, it will show only one entry that will be of month
ending date and adding all the corresponding fields.

This is the following code:

```<code>df=pd.read_csv('output.csv',
             encoding="utf-8",skipinitialspace=True,engine='python')
datadf = df

datadf = datadf.dropna(axis = 0, how ='any')

datadf = datadf.astype({'ForeignType' : 'category','ImportType' : 'category','ArrDate' : 'datetime64',
                        'DepDate' : 'datetime64'})

# datadf = datadf.groupby(datadf['ArrDate'].dt.strftime('%B'))['ComoQty'].sum()
datadf1 = datadf.groupby(['ArrDate','ImportType','ForeignType'])['ComoQty'].sum()
datadf2 = datadf1.to_frame()
datadf2.fillna(value=0,inplace=True)
# datadf2 = datadf2.reset_index('ImportType')
# datadf2 = datadf2.reset_index('ForeignType')
# datadf2 = datadf2.reset_index('ArrDate')
datadf2
</code>```

答:
```<code>datadf1 = datadf.drop(columns='Unnamed: 0')
prac = datadf1
prac =prac.set_index('ArrDate')
prac_dates = prac.copy()

prac = prac.resample('D').apply({'ShipName':'count','ComoQty':'sum'}).reset_index()

prac_dates = ((prac_dates.resample('M').apply({'ComoQty':'sum'}))/1000).reset_index()
prac_dates['Month'] = pd.DatetimeIndex(prac_dates['ArrDate']).strftime('%B')
del prac_dates['ArrDate']
# prac_dates

prac['Month'] = pd.DatetimeIndex(prac['ArrDate']).strftime('%B')
# prac['Month'] = pd.to_datetime(prac['Month'], format='%B')
prac['ArrDate'] = pd.DatetimeIndex(prac['ArrDate']).strftime('%d')
</code>```

Body:
The data frame shows the date with the amount of import and export
and it is further bifurcated into coastal and regional data per day
of one month.

What I wish to achieve is to club i.e sum all the data presented, which is of one month in this
case, in the end, it will show only one entry that will be of month
ending date and adding all the corresponding fields.

This is the following code:

df=pd.read_csv('output.csv',
             encoding="utf-8",skipinitialspace=True,engine='python')
datadf = df

datadf = datadf.dropna(axis = 0, how ='any')

datadf = datadf.astype({'ForeignType' : 'category','ImportType' : 'category','ArrDate' : 'datetime64',
                        'DepDate' : 'datetime64'})

# datadf = datadf.groupby(datadf['ArrDate'].dt.strftime('%B'))['ComoQty'].sum()
datadf1 = datadf.groupby(['ArrDate','ImportType','ForeignType'])['ComoQty'].sum()
datadf2 = datadf1.to_frame()
datadf2.fillna(value=0,inplace=True)
# datadf2 = datadf2.reset_index('ImportType')
# datadf2 = datadf2.reset_index('ForeignType')
# datadf2 = datadf2.reset_index('ArrDate')
datadf2


问:
how to pass or reference model between asp.net core razor pages MVVM
My MVVM core 3.1 Index page displays database data nicely from it's model using this directive:

```<code> @model IndexModel
</code>```

I launch a second page 'TOCPrintable" (for printing the exact same data but styled differently) with this:

```<code><form method="post">
    <input type="submit" value="Print TOC" asp-page="TOCPrintable" target="_blank"/>
</form>
</code>```

The problem: I am unable to pass or reference the IndexModel of the Index page and consume it in the TOCPrintable page.

My reason for referencing/passing the model to the second page is  I want to avoid coding the same database connections, calls, objects, etc.

IS my approach wrong?

答:
Passing data between pages, or State Management as it is known can be done in a number of ways: https://www.learnrazorpages.com/razor-pages/state-management

In your example, since you are already posting a form, you may as well use hidden form fields.

Body:
My MVVM core 3.1 Index page displays database data nicely from it's model using this directive:

 @model IndexModel

I launch a second page 'TOCPrintable" (for printing the exact same data but styled differently) with this:

<form method="post">
    <input type="submit" value="Print TOC" asp-page="TOCPrintable" target="_blank"/>
</form>

The problem: I am unable to pass or reference the IndexModel of the Index page and consume it in the TOCPrintable page.

My reason for referencing/passing the model to the second page is  I want to avoid coding the same database connections, calls, objects, etc.

IS my approach wrong?


答:
The problem are your paths. After every line you are using a move to command (m) where you are moving to the last point. I've rewritten the first 2 paths bu removing the move to (m0,0) Now the paths can be filled. The third path is just a line.

Now you can fill the paths using css or bu resetting the value of the attribute fill

path{fill:red}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 130 600" width="100">
<path id="svg_1" stroke-width="0.5" stroke="black" fill="none" d="M50.610001,63.470001l12.869999,0
   l0,464.709991
   l-12.869999,0
   l0,-464.709991"/>
  <path id="svg_2" stroke-width="0.5" stroke="black" fill="none" d="M66.529999,260.670013l12.870003,0
   l-0.029999,267.519989
   l-12.870003,0
   l0.029999,-267.519989"/>
  <path id="svg_3" stroke-width="0.5" stroke="black" fill="none" d="m66.519997,275.440002l-3.039997,0"/>
</svg></code>```

Title: How to change fill color SVG object for specific path id via AngularJS

Body:
svg:

  <path id="svg_1" stroke-width="0.5" stroke="black" fill="none" d="m50.610001,63.470001l12.869999,0m0,0l0,464.709991m0,0l-12.869999,0m0,0l0,-464.709991"/>
  <path id="svg_2" stroke-width="0.5" stroke="black" fill="none" d="m66.529999,260.670013l12.870003,0m0,0l-0.029999,267.519989m0,0l-12.870003,0m0,0l0.029999,-267.519989"/>
  <path id="svg_3" stroke-width="0.5" stroke="black" fill="none" d="m66.519997,275.440002l-3.039997,0"/>

html:

I would like to change fill color for id="svg_2" for example on button click, How to do it?

Body:
The problem are your paths. After every line you are using a move to command (m) where you are moving to the last point. I've rewritten the first 2 paths bu removing the move to (m0,0) Now the paths can be filled. The third path is just a line.

Now you can fill the paths using css or bu resetting the value of the attribute fill

path{fill:red}

<svg viewBox="0 0 130 600" width="100">
<path id="svg_1" stroke-width="0.5" stroke="black" fill="none" d="M50.610001,63.470001l12.869999,0
   l0,464.709991
   l-12.869999,0
   l0,-464.709991"/>
  <path id="svg_2" stroke-width="0.5" stroke="black" fill="none" d="M66.529999,260.670013l12.870003,0
   l-0.029999,267.519989
   l-12.870003,0
   l0.029999,-267.519989"/>
  <path id="svg_3" stroke-width="0.5" stroke="black" fill="none" d="m66.519997,275.440002l-3.039997,0"/>
</svg>