问:
How to convert NaN value to 0 inside app.post in .js file
In below code question1 value is coming as NaN. I want to convert it to 0 but I am not able to do it using parseInt. How can I do this?

```<code>app.post('/auth/total',function(req,res){
    console.log(req.body);
    const {  question1, question2, question3, question4} = req.body;
    let total1 = parseInt(question1) + parseInt(question2)
    let total2 = parseInt(question3) + parseInt(question4)

    //some code to insert data in db and render the view

});
</code>```

答:
you can do this:

```<code>let total1 = (parseInt(question1) || 0) + (parseInt(question2) || 0)
</code>```

this will convert any falsy value to 0

Body:
In below code question1 value is coming as NaN. I want to convert it to 0 but I am not able to do it using parseInt. How can I do this?

app.post('/auth/total',function(req,res){
    console.log(req.body);
    const {  question1, question2, question3, question4} = req.body;
    let total1 = parseInt(question1) + parseInt(question2)
    let total2 = parseInt(question3) + parseInt(question4)

    //some code to insert data in db and render the view

});

Body:
you can do this:

let total1 = (parseInt(question1) || 0) + (parseInt(question2) || 0)

this will convert any falsy value to 0


来源: stackexchange

问:
What are the arguments against the use of the "<?="?

Possible Duplicate:

  Are PHP short tags acceptable to use?

The <?= is one of the very few elegant things about PHP, IMO. Yet, there are people that deliberately avoid it (in favor of the much longer <?php echo). Why would they do that?

答:
<?= is easier to use but some servers don't support short tags. Therefore, if you ever run into a server that doesn't support them, you need to replace all tags.

A more elaborate answer is already given: Are PHP short tags acceptable to use?

ContentLicense: CC BY-SA 3.0


问:
Shortening code with a for loop is possible?
I have a strategy including 20 poses pyramiding, and i follow the all pose seperately like this.

```<code>strategy.entry("BUY1", strategy.long, when= PoseCount==1 and PoseCount[1] !=1 and barstate.isconfirmed, alert_message = message_long_entry)
.....
strategy.entry("BUY20", strategy.long, when= PoseCount==20 and PoseCount[1] !=20  and barstate.isconfirmed, alert_message = message_long_entry)

strategy.entry("SELL1", strategy.short, when= PoseCount==-1 and PoseCount[1] !=-1  and barstate.isconfirmed, alert_message = message_short_entry)
....
strategy.entry("SELL20", strategy.short, when= PoseCount==-20 and PoseCount[1] !=-20  and barstate.isconfirmed, alert_message = message_short_entry)

strategy.close("BUY1", when= PoseCount==-1 and PoseCount[1] !=-1   and barstate.isconfirmed, alert_message = message_long_exit)
.....
strategy.close("BUY20", when= PoseCount==-20 and PoseCount[1] !=-20   and barstate.isconfirmed, alert_message = message_long_exit)

strategy.close("SELL1", when= PoseCount==1 and PoseCount[1] !=1  and barstate.isconfirmed, alert_message = message_short_exit)
....
strategy.close("SELL20", when= PoseCount==20 and PoseCount[1] !=20  and barstate.isconfirmed, alert_message = message_short_exit)

strategy.exit("BUY1 TP/SL",  "BUY1",    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)
....
strategy.exit("BUY20 TP/SL",  "BUY20",    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)

strategy.exit("SELL1 TP/SL",  "SELL1",   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)
....
strategy.exit("SELL20 TP/SL",  "SELL20",   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)
</code>```

I want to shorten this structure using for loop. I tried the following but failed. Thanks in advance for your help.

```<code>for x = 1 to 20
   strategy.entry("BUY" + tostring(x), strategy.long, when= PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)
   strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)
   strategy.close("BUY"+ tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)
   strategy.close("SELL"+ tostring(x), when= PoseCount==x and PoseCount[1] !=x  and barstate.isconfirmed, alert_message = message_short_exit)
   strategy.exit("BUY TP/SL"+ tostring(x),  "BUY"+ tostring(x),    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)
   strategy.exit("SELL TP/SL"+ tostring(x),  "SELL"+ tostring(x),   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)
</code>```

edit

still same error (Mismatched input 'to' expecting 'end of line without line continuation') with the following

```<code>for x = 1 to 20
     strategy.entry("BUY" + tostring(x), strategy.long, when= PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)

for x = 1 to 20
     strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)

for x = 1 to 20
     strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)

for x = 1 to 20
     strategy.close("BUY"+ tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)

for x = 1 to 20
     strategy.exit("BUY TP/SL"+ tostring(x),  "BUY"+ tostring(x),    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)

for x = 1 to 20
     strategy.exit("SELL TP/SL"+ tostring(x),  "SELL"+ tostring(x),   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)
</code>```

答:
this is the way. I solved :)</p>
```<code>for x = 1 to 20
    strategy.entry("BUY"+str.tostring(x), strategy.long, when=   PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)
    strategy.entry("SELL"+str.tostring(x) , strategy.short, when=   PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)
    strategy.close("BUY"+str.tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)
    strategy.close("SELL"+str.tostring(x), when= PoseCount==x and PoseCount[1] !=x  and barstate.isconfirmed, alert_message = message_short_exit)
    strategy.exit("BUY TP/SL"+str.tostring(x),  "BUY"+str.tostring(x),     profit = per(tp), loss = per(stoploss) , trail_points=per(trpo) , trail_offset=per(trof), alert_message = message_long_exit)
    strategy.exit("SELL TP/SL"+str.tostring(x),  "SELL"+str.tostring(x),    profit = per(tp), loss = per(stoploss) ,trail_points=per(trpo),trail_offset=per(trof), alert_message = message_short_exit)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a strategy including 20 poses pyramiding, and i follow the all pose seperately like this.

strategy.entry("BUY1", strategy.long, when= PoseCount==1 and PoseCount[1] !=1 and barstate.isconfirmed, alert_message = message_long_entry)
.....
strategy.entry("BUY20", strategy.long, when= PoseCount==20 and PoseCount[1] !=20  and barstate.isconfirmed, alert_message = message_long_entry)

strategy.entry("SELL1", strategy.short, when= PoseCount==-1 and PoseCount[1] !=-1  and barstate.isconfirmed, alert_message = message_short_entry)
....
strategy.entry("SELL20", strategy.short, when= PoseCount==-20 and PoseCount[1] !=-20  and barstate.isconfirmed, alert_message = message_short_entry)

strategy.close("BUY1", when= PoseCount==-1 and PoseCount[1] !=-1   and barstate.isconfirmed, alert_message = message_long_exit)
.....
strategy.close("BUY20", when= PoseCount==-20 and PoseCount[1] !=-20   and barstate.isconfirmed, alert_message = message_long_exit)

strategy.close("SELL1", when= PoseCount==1 and PoseCount[1] !=1  and barstate.isconfirmed, alert_message = message_short_exit)
....
strategy.close("SELL20", when= PoseCount==20 and PoseCount[1] !=20  and barstate.isconfirmed, alert_message = message_short_exit)

strategy.exit("BUY1 TP/SL",  "BUY1",    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)
....
strategy.exit("BUY20 TP/SL",  "BUY20",    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)

strategy.exit("SELL1 TP/SL",  "SELL1",   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)
....
strategy.exit("SELL20 TP/SL",  "SELL20",   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)

I want to shorten this structure using for loop. I tried the following but failed. Thanks in advance for your help.

for x = 1 to 20
   strategy.entry("BUY" + tostring(x), strategy.long, when= PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)
   strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)
   strategy.close("BUY"+ tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)
   strategy.close("SELL"+ tostring(x), when= PoseCount==x and PoseCount[1] !=x  and barstate.isconfirmed, alert_message = message_short_exit)
   strategy.exit("BUY TP/SL"+ tostring(x),  "BUY"+ tostring(x),    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)
   strategy.exit("SELL TP/SL"+ tostring(x),  "SELL"+ tostring(x),   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)

edit

still same error (Mismatched input 'to' expecting 'end of line without line continuation') with the following

for x = 1 to 20
     strategy.entry("BUY" + tostring(x), strategy.long, when= PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)

for x = 1 to 20
     strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)

for x = 1 to 20
     strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)

for x = 1 to 20
     strategy.close("BUY"+ tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)

for x = 1 to 20
     strategy.exit("BUY TP/SL"+ tostring(x),  "BUY"+ tostring(x),    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)

for x = 1 to 20
     strategy.exit("SELL TP/SL"+ tostring(x),  "SELL"+ tostring(x),   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)

Body:
this is the way. I solved :)

for x = 1 to 20
    strategy.entry("BUY"+str.tostring(x), strategy.long, when=   PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)
    strategy.entry("SELL"+str.tostring(x) , strategy.short, when=   PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)
    strategy.close("BUY"+str.tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)
    strategy.close("SELL"+str.tostring(x), when= PoseCount==x and PoseCount[1] !=x  and barstate.isconfirmed, alert_message = message_short_exit)
    strategy.exit("BUY TP/SL"+str.tostring(x),  "BUY"+str.tostring(x),     profit = per(tp), loss = per(stoploss) , trail_points=per(trpo) , trail_offset=per(trof), alert_message = message_long_exit)
    strategy.exit("SELL TP/SL"+str.tostring(x),  "SELL"+str.tostring(x),    profit = per(tp), loss = per(stoploss) ,trail_points=per(trpo),trail_offset=per(trof), alert_message = message_short_exit)


问:
check if object exist before saving django rest framework
When i post new data i want to check create new man object and  dok object related to  man objects but if man object alredy exist i want to append related dok to it
any idea how to start i'm totally new to rest_framework

```<code>class Man(ListCreateAPIView):
    queryset =  Man.objects.all()
    serializer_class = ManSerial
</code>```

model.py

```<code>
class Man(models.Model):
    name = models.CharField(max_length=50,unique=True)
    age = models.IntegerField()
    def __str__(self):
        return self.name

class Dok(models.Model):
    man = models.ForeignKey(Man,on_delete=models.CASCADE,related_name="dok_man")
    cool =  models.CharField(max_length=400)
    def __str__(self) :
        return str(self.man)

</code>```

serializer.py

```<code>class Dokserial(serializers.ModelSerializer):
    class Meta:
        model = Dok
        fields ='__all__'

class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'
</code>```

答:
I do not know why or how, but this solved my problem: I edited my serializer class to</p>
```<code>class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'
        extra_kwargs = {
            'name': {'validators': []},
        }
</code>```

Body:
When i post new data i want to check create new man object and  dok object related to  man objects but if man object alredy exist i want to append related dok to it
any idea how to start i'm totally new to rest_framework

class Man(ListCreateAPIView):
    queryset =  Man.objects.all()
    serializer_class = ManSerial

model.py

class Man(models.Model):
    name = models.CharField(max_length=50,unique=True)
    age = models.IntegerField()
    def __str__(self):
        return self.name

class Dok(models.Model):
    man = models.ForeignKey(Man,on_delete=models.CASCADE,related_name="dok_man")
    cool =  models.CharField(max_length=400)
    def __str__(self) :
        return str(self.man)

serializer.py

class Dokserial(serializers.ModelSerializer):
    class Meta:
        model = Dok
        fields ='__all__'

class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'

Body:
I do not know why or how, but this solved my problem: I edited my serializer class to

class ManSerial(serializers.ModelSerializer):
    data = Dokserial(source="dok_man",many=True)
    class Meta:
        model = Man
        fields = '__all__'
        extra_kwargs = {
            'name': {'validators': []},
        }


问:
Event handling with WinRT for python

The Task

I'm trying to make a tool that auto recognizes playback from a non Spotify source and pauses Spotify for the duration of the other audio. I've been using Microsoft's WinRT projection for Python (https://github.com/Microsoft/xlang/tree/master/src/package/pywinrt/projection). I can get the program to recognize audio sources and playback status but only from the moment the function was called. After that it stops updating.

The Problem

My main problem is understanding how WinRT implemented event handling in Python. The windows docs talk about a "changed playback event" (https://learn.microsoft.com/en-us/uwp/api/windows.media.control.globalsystemmediatransportcontrolssession.playbackinfochanged?view=winrt-22000) but I can't find any clue to how this is accomplished in the Python projection of the API.

Current State

Here is my code so far, any help is appreciated.

```<code>import asyncio
import time
from winrt.windows.media.control import \
    GlobalSystemMediaTransportControlsSessionManager as MediaManager
from winrt.windows.media.control import \
    GlobalSystemMediaTransportControlsSession as SessionMananger
from winrt.windows.media.control import \
    PlaybackInfoChangedEventArgs as PlaybackEventArgs

async def toggle_spotify():
    sessions = await MediaManager.request_async() #grab session manager instance

    all_sessions = sessions.get_sessions() #grab sequence of current instances
    for current_session in all_sessions: #iterate and grab desired instances
        if "chrome" in current_session.source_app_user_model_id.lower():
            chrome_info = current_session.get_playback_info()
        if "spotify" in current_session.source_app_user_model_id.lower():
            spotify_manager = current_session
            spotify_info = current_session.get_playback_info()
    if chrome_info.playback_status == 4 and spotify_info.playback_status == 4: #status of 4 is playing, 5 is paused
        await spotify_manager.try_toggle_play_pause_async()
    elif chrome_info.playback_status == 5 and spotify_info.playback_status == 5:
        await spotify_manager.try_toggle_play_pause_async()
        # print(f"chrome playback status: {chrome_info.playback_status}")
        # print(f"chrome playback status: {spotify_info.playback_status}")
        # print("+++++++++++++++++")
        # time.sleep(2)

if __name__ == '__main__':
    #asyncio.run(get_media_info())
    while True: #mimicking event handling by looping
        asyncio.run(toggle_spotify())
        time.sleep(0.1)
</code>```

答:
First, FYI, I've started a community fork of PyWinRT and the winrt package at https://github.com/pywinrt and published a winsdk package on PyPI. This contains many, many fixes over the seemingly unmaintained winrt package, including fixing some serious problems like leaking a COM object on every await of an _async() method. The new winsdk package also includes type hints which make solving issues like this much easier.

The way event handlers are used is currently documented here.

So for this specific case, your code might look something like this:

import asyncio

from winsdk.windows.media.control import (
    GlobalSystemMediaTransportControlsSessionManager as SessionManager,
    GlobalSystemMediaTransportControlsSessionPlaybackStatus as PlaybackStatus,
    SessionsChangedEventArgs,
)

async def update_sessions(manager: SessionManager) -> None:
    for session in manager.get_sessions():
        if "chrome" in session.source_app_user_model_id.lower():
            chrome_info = session.get_playback_info()
            if chrome_info.playback_status == PlaybackStatus.PLAYING:
                ...

def handle_sessions_changed(manager: SessionManager, args: SessionsChangedEventArgs) -> None:
    asyncio.create_task(update_sessions(manager))

async def main():
    manager = await SessionManager.request_async()

    # add callback to handle any future changes
    sessions_changed_token = manager.add_sessions_changed(handle_sessions_changed)

    try:
        # handle current state
        asyncio.create_task(update_sessions(manager))

        event = asyncio.Event()
        # wait forever - a real app would call event.set() to end the app
        await event.wait()
    finally:
        # remove the callback
        manager.remove_sessions_changed(sessions_changed_token)

if __name__ == '__main__':
    asyncio.run(main())

```

For some reason, the event doesn't actually seem to be firing, but a quick web search reveals that this is a common problem for the GlobalSystemMediaTransportControlsSessionManager.SesssionsChanged and seems unrelated to the Python bindings.

Also note that asyncio.create_task() is only needed if update_sessions() actually awaits something, otherwise it could just be called directly.

Title: Event handling with WinRT for python

Body:
The Task

I'm trying to make a tool that auto recognizes playback from a non Spotify source and pauses Spotify for the duration of the other audio. I've been using Microsoft's WinRT projection for Python (https://github.com/Microsoft/xlang/tree/master/src/package/pywinrt/projection). I can get the program to recognize audio sources and playback status but only from the moment the function was called. After that it stops updating.

The Problem

My main problem is understanding how WinRT implemented event handling in Python. The windows docs talk about a "changed playback event" (https://learn.microsoft.com/en-us/uwp/api/windows.media.control.globalsystemmediatransportcontrolssession.playbackinfochanged?view=winrt-22000) but I can't find any clue to how this is accomplished in the Python projection of the API.

Current State

Here is my code so far, any help is appreciated.

import asyncio
import time
from winrt.windows.media.control import \
    GlobalSystemMediaTransportControlsSessionManager as MediaManager
from winrt.windows.media.control import \
    GlobalSystemMediaTransportControlsSession as SessionMananger
from winrt.windows.media.control import \
    PlaybackInfoChangedEventArgs as PlaybackEventArgs

async def toggle_spotify():
    sessions = await MediaManager.request_async() #grab session manager instance

    all_sessions = sessions.get_sessions() #grab sequence of current instances
    for current_session in all_sessions: #iterate and grab desired instances
        if "chrome" in current_session.source_app_user_model_id.lower():
            chrome_info = current_session.get_playback_info()
        if "spotify" in current_session.source_app_user_model_id.lower():
            spotify_manager = current_session
            spotify_info = current_session.get_playback_info()
    if chrome_info.playback_status == 4 and spotify_info.playback_status == 4: #status of 4 is playing, 5 is paused
        await spotify_manager.try_toggle_play_pause_async()
    elif chrome_info.playback_status == 5 and spotify_info.playback_status == 5:
        await spotify_manager.try_toggle_play_pause_async()
        # print(f"chrome playback status: {chrome_info.playback_status}")
        # print(f"chrome playback status: {spotify_info.playback_status}")
        # print("+++++++++++++++++")
        # time.sleep(2)

if __name__ == '__main__':
    #asyncio.run(get_media_info())
    while True: #mimicking event handling by looping
        asyncio.run(toggle_spotify())
        time.sleep(0.1)

Body:
First, FYI, I've started a community fork of PyWinRT and the winrt package at https://github.com/pywinrt and published a winsdk package on PyPI. This contains many, many fixes over the seemingly unmaintained winrt package, including fixing some serious problems like leaking a COM object on every await of an _async() method. The new winsdk package also includes type hints which make solving issues like this much easier.

The way event handlers are used is currently documented here.

So for this specific case, your code might look something like this:

import asyncio

from winsdk.windows.media.control import (
    GlobalSystemMediaTransportControlsSessionManager as SessionManager,
    GlobalSystemMediaTransportControlsSessionPlaybackStatus as PlaybackStatus,
    SessionsChangedEventArgs,
)

async def update_sessions(manager: SessionManager) -> None:
    for session in manager.get_sessions():
        if "chrome" in session.source_app_user_model_id.lower():
            chrome_info = session.get_playback_info()
            if chrome_info.playback_status == PlaybackStatus.PLAYING:
                ...

def handle_sessions_changed(manager: SessionManager, args: SessionsChangedEventArgs) -> None:
    asyncio.create_task(update_sessions(manager))

async def main():
    manager = await SessionManager.request_async()

    # add callback to handle any future changes
    sessions_changed_token = manager.add_sessions_changed(handle_sessions_changed)

    try:
        # handle current state
        asyncio.create_task(update_sessions(manager))

        event = asyncio.Event()
        # wait forever - a real app would call event.set() to end the app
        await event.wait()
    finally:
        # remove the callback
        manager.remove_sessions_changed(sessions_changed_token)

if __name__ == '__main__':
    asyncio.run(main())

For some reason, the event doesn't actually seem to be firing, but a quick web search reveals that this is a common problem for the GlobalSystemMediaTransportControlsSessionManager.SesssionsChanged and seems unrelated to the Python bindings.

Also note that asyncio.create_task() is only needed if update_sessions() actually awaits something, otherwise it could just be called directly.


问:
Doing multiple sorts across more than one line of code?
I have an array that stores the order that I want to sort a list by.

```<code>SortOrderArray: "Color", "Volume", "Weight"
</code>```

So I want to order my list by Color, Volume, then Weight

```<code>MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();
</code>```

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

```<code>public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}
</code>```

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

```<code>switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}
</code>```

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.

答:
Using Dynamic LINQ, you can do something like:

```<code>public List<row> GetSortedList(List<row> list, string[] sortOrder)
{
    // argument-validation, including testing that
    // sort-order has at least 1 item.

    return sortOrder.Skip(1)
                    .Aggregate(list.AsQueryable().OrderBy(sortOrder.First()),
                               (query, nextSortTerm) => query.ThenBy(nextSortTerm))
                    .ToList();
}
</code>```

Essentially: OrderBy the first sort-term, ThenBy the remaining.

EDIT: Added an AsQueryable call to make Dynamic LINQ work on IEnumerable<T>

Body:
I have an array that stores the order that I want to sort a list by.

SortOrderArray: "Color", "Volume", "Weight"

So I want to order my list by Color, Volume, then Weight

MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.

Body:
Using Dynamic LINQ, you can do something like:

public List<row> GetSortedList(List<row> list, string[] sortOrder)
{
    // argument-validation, including testing that
    // sort-order has at least 1 item.

    return sortOrder.Skip(1)
                    .Aggregate(list.AsQueryable().OrderBy(sortOrder.First()),
                               (query, nextSortTerm) => query.ThenBy(nextSortTerm))
                    .ToList();
}

Essentially: OrderBy the first sort-term, ThenBy the remaining.

EDIT: Added an AsQueryable call to make Dynamic LINQ work on IEnumerable<T>


问:
error running pod install error launching application on iphone11 Pro Max
I finished my flutter app, and i want to test it in ios device, so i used a mac laptop and i did all the installations but when i did the command "flutter run" i got this error
Launching lib/main.dart on iPhone 11 Pro Max in debug mode...</p>

```<code> Running pod install...                                              4,0s
 CocoaPods' output:
 ↳
  Preparing

Analyzing dependencies

Inspecting targets to integrate
  Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)

Finding Podfile changes
  A flutter_barcode_scanner
  A geolocator
  A google_api_availability
  A google_maps_flutter
  A location
  A location_permissions
  A shared_preferences
  A shared_preferences_macos
  A shared_preferences_web
  - Flutter

Fetching external sources
-> Fetching podspec for `Flutter` from `Flutter`
-> Fetching podspec for `flutter_barcode_scanner` from `.symlinks/plugins/flutter_barcode_scanner/ios`
-> Fetching podspec for `geolocator` from `.symlinks/plugins/geolocator/ios`
-> Fetching podspec for `google_api_availability` from `.symlinks/plugins/google_api_availability/ios`
-> Fetching podspec for `google_maps_flutter` from `.symlinks/plugins/google_maps_flutter/ios`
-> Fetching podspec for `location` from `.symlinks/plugins/location/ios`
-> Fetching podspec for `location_permissions` from `.symlinks/plugins/location_permissions/ios`
-> Fetching podspec for `shared_preferences` from `.symlinks/plugins/shared_preferences/ios`
-> Fetching podspec for `shared_preferences_macos` from `.symlinks/plugins/shared_preferences_macos/ios`
-> Fetching podspec for `shared_preferences_web` from `.symlinks/plugins/shared_preferences_web/ios`

Resolving dependencies of `Podfile`
  CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only perfomed in repo update
[!] CocoaPods could not find compatible versions for pod "flutter_barcode_scanner":
  In Podfile:
    flutter_barcode_scanner (from `.symlinks/plugins/flutter_barcode_scanner/ios`)

Specs satisfying the `flutter_barcode_scanner (from `.symlinks/plugins/flutter_barcode_scanner/ios`)` dependency were found, but they required a higher minimum deployment target.

/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:328:in `raise_error_unless_state'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:310:in `block in unwind_for_conflict'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `tap'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `unwind_for_conflict'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:684:in `attempt_to_activate'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:254:in `process_topmost_state'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:182:in `resolve'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolver.rb:43:in `resolve'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/resolver.rb:94:in `resolve'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer/analyzer.rb:986:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer/analyzer.rb:984:in `resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer/analyzer.rb:124:in `analyze'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:410:in `analyze'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:234:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:233:in `resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:156:in `install!'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/command/install.rb:52:in `run'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:22:in `load'
/usr/local/bin/pod:22:in `<main>'

Error running pod install
Error launching application on iPhone 11 Pro Max.
</code>```

答:
For the m1 Mac I had a similar error for google mobile ads. The solution was that you have to download cocoa-pods from homebrew.
Follow The 2022 update: https://stackoverflow.com/a/65334677/16122154</p>

Body:
I finished my flutter app, and i want to test it in ios device, so i used a mac laptop and i did all the installations but when i did the command "flutter run" i got this error
Launching lib/main.dart on iPhone 11 Pro Max in debug mode...

 Running pod install...                                              4,0s
 CocoaPods' output:
 ↳
  Preparing

Analyzing dependencies

Inspecting targets to integrate
  Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)

Finding Podfile changes
  A flutter_barcode_scanner
  A geolocator
  A google_api_availability
  A google_maps_flutter
  A location
  A location_permissions
  A shared_preferences
  A shared_preferences_macos
  A shared_preferences_web
  - Flutter

Fetching external sources
-> Fetching podspec for `Flutter` from `Flutter`
-> Fetching podspec for `flutter_barcode_scanner` from `.symlinks/plugins/flutter_barcode_scanner/ios`
-> Fetching podspec for `geolocator` from `.symlinks/plugins/geolocator/ios`
-> Fetching podspec for `google_api_availability` from `.symlinks/plugins/google_api_availability/ios`
-> Fetching podspec for `google_maps_flutter` from `.symlinks/plugins/google_maps_flutter/ios`
-> Fetching podspec for `location` from `.symlinks/plugins/location/ios`
-> Fetching podspec for `location_permissions` from `.symlinks/plugins/location_permissions/ios`
-> Fetching podspec for `shared_preferences` from `.symlinks/plugins/shared_preferences/ios`
-> Fetching podspec for `shared_preferences_macos` from `.symlinks/plugins/shared_preferences_macos/ios`
-> Fetching podspec for `shared_preferences_web` from `.symlinks/plugins/shared_preferences_web/ios`

Resolving dependencies of `Podfile`
  CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only perfomed in repo update
[!] CocoaPods could not find compatible versions for pod "flutter_barcode_scanner":
  In Podfile:
    flutter_barcode_scanner (from `.symlinks/plugins/flutter_barcode_scanner/ios`)

Specs satisfying the `flutter_barcode_scanner (from `.symlinks/plugins/flutter_barcode_scanner/ios`)` dependency were found, but they required a higher minimum deployment target.

/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:328:in `raise_error_unless_state'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:310:in `block in unwind_for_conflict'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `tap'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:308:in `unwind_for_conflict'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:684:in `attempt_to_activate'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:254:in `process_topmost_state'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolution.rb:182:in `resolve'
/Library/Ruby/Gems/2.3.0/gems/molinillo-0.6.6/lib/molinillo/resolver.rb:43:in `resolve'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/resolver.rb:94:in `resolve'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer/analyzer.rb:986:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer/analyzer.rb:984:in `resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer/analyzer.rb:124:in `analyze'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:410:in `analyze'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:234:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:233:in `resolve_dependencies'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/installer.rb:156:in `install!'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/command/install.rb:52:in `run'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.8.4/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:22:in `load'
/usr/local/bin/pod:22:in `'

Error running pod install
Error launching application on iPhone 11 Pro Max.


问:
How to write x^2 in my python code? Can someone give me suggestion about my code
The Quadratic Equation Calculator and the code that I used didn't work well.
There are some errors on the code.

I already tried with basic numbers, like 1/2/3. No equation. Still the code doesn't works.
The things that actually work is putting the variable only and that's all.
After I press enter to see what is the answer, it said that my code has some errors on it.

```<code>print ("Quadratic Equation Calculator")

import math

print ("Enter the first variable : ")
first = float(input(''))
print ("Enter the second variable : ")
second = float(input(''))
print ("Enter the third variable : ")
third = float(input(''))

Answer1 = ((-1 * second) - math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)
Answer2 = ((-1 * second) + math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)

print (Answer1)
print (Answer2)
</code>```

I expect to answer the questions properly and this equation calculator can be used for real equations and using variables. x square and 3x and something like that.

答:
X^2 is a bit-wise XOR operator in python. you can rewrite your equation as
x**2(exponential),x*x or pow(x,2) in python</p>

Body:
The Quadratic Equation Calculator and the code that I used didn't work well.
There are some errors on the code.

I already tried with basic numbers, like 1/2/3. No equation. Still the code doesn't works.
The things that actually work is putting the variable only and that's all.
After I press enter to see what is the answer, it said that my code has some errors on it.

print ("Quadratic Equation Calculator")

import math

print ("Enter the first variable : ")
first = float(input(''))
print ("Enter the second variable : ")
second = float(input(''))
print ("Enter the third variable : ")
third = float(input(''))

Answer1 = ((-1 * second) - math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)
Answer2 = ((-1 * second) + math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)

print (Answer1)
print (Answer2)

I expect to answer the questions properly and this equation calculator can be used for real equations and using variables. x square and 3x and something like that.


问:
how can pass different parameters using [routerLink] or router.navigate to a component?
I configured app-routing.module.ts as following:

const routes: Routes = [
  {
    path: "branches/:branch",
    component: BranchesComponent
  },

  // ...
];```
</div>
</div>
</p>
<p>and also in app.component.html have:</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-html lang-html prettyprint-override"><code><li>
       engineering
    </li>
    <li>
       baseSciense
    </li>
    <li>
       humanities
    </li>
  </ul>

  <router-outlet></router-outlet></code>```

and in the barnches.component.ts I coded as bellow:

branch: string ='';

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {

    this.route.params.subscribe(({branch: branch1}) => this.branch = branch1);

    // I also tried this code:
    // this.route.params.subscribe(branch => this.branch = branch['branch']);

    // unfortunately, bellow codes have error on p.branch and params.branch! why?
    // this.route.params.subscribe(p => this.branch = p.branch)
    // this.branch = this.route.snapshot.params.branch;

    console.log(`branch is : ${this.branch}`);
  }```
</div>
</div>
</p>
<p>till here everything comes correct, and URL is changed once the respective link is clicked, such as :</p>
```http://localhost:4200/branches/engineering

http://localhost:4200/branches/baseSciense

http://localhost:4200/branches/humanities
```

but the property branch in Branches component is not changed and has same value (engineering) for different parameters in log of the console. it is illogical for me!

how can solve this problem as pass different parameters to and capture them into branches component? Best regards

答:
In your component you can subscribe to router events and listen for them like this.</p>
```<code>this.router.events.pipe(filter(r => r instanceof NavigationEnd)).subscribe(r => {
  console.log((r as NavigationEnd).url);
});
</code>```

Body:
I configured app-routing.module.ts as following:

const routes: Routes = [
  {
    path: "branches/:branch",
    component: BranchesComponent
  },

  // ...
];

and also in app.component.html have:

       engineering

       baseSciense

       humanities

  <router-outlet></router-outlet>

and in the barnches.component.ts I coded as bellow:

branch: string ='';

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {

    this.route.params.subscribe(({branch: branch1}) => this.branch = branch1);

    // I also tried this code:
    // this.route.params.subscribe(branch => this.branch = branch['branch']);

    // unfortunately, bellow codes have error on p.branch and params.branch! why?
    // this.route.params.subscribe(p => this.branch = p.branch)
    // this.branch = this.route.snapshot.params.branch;

    console.log(`branch is : ${this.branch}`);
  }

till here everything comes correct, and URL is changed once the respective link is clicked, such as :

http://localhost:4200/branches/engineering

http://localhost:4200/branches/baseSciense

http://localhost:4200/branches/humanities

but the property branch in Branches component is not changed and has same value (engineering) for different parameters in log of the console. it is illogical for me!

how can solve this problem as pass different parameters to and capture them into branches component? Best regards

Body:
In your component you can subscribe to router events and listen for them like this.

this.router.events.pipe(filter(r => r instanceof NavigationEnd)).subscribe(r => {
  console.log((r as NavigationEnd).url);
});


问:
How to upload a bytes image on Google Cloud Storage from a Python script
I want to upload an image on Google Cloud Storage from a python script. This is my code:

```<code>from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery

scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)

body = {'name':'my_image.jpg'}

req = service.objects().insert(
   bucket='my_bucket', body=body,
   media_body=googleapiclient.http.MediaIoBaseUpload(
      gcs_image, 'application/octet-stream'))

resp = req.execute()
</code>```

if gcs_image = open('img.jpg', 'r') the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: gcs_image = cv2.imread('img.jpg'))

答:
Here is how to directly upload a PIL Image from memory:

from google.cloud import storage
import io
from PIL import Image

# Define variables
bucket_name = XXXXX
destination_blob_filename = XXXXX

# Configure bucket and blob
client = storage.Client()
bucket = client.bucket(bucket_name)

im = Image.open("test.jpg")
bs = io.BytesIO()
im.save(bs, "jpeg")
blob.upload_from_string(bs.getvalue(), content_type="image/jpeg")
```
<p>In addition to that, here is how to download blobfiles directly to memory as PIL Images:</p>
<pre class="lang-py prettyprint-override"><code>blob = bucket.blob(destination_blob_filename)
downloaded_im_data = blob.download_as_bytes()
downloaded_im = Image.open(io.BytesIO(downloaded_im_data))
</code>```

Body:
I want to upload an image on Google Cloud Storage from a python script. This is my code:

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery

scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)

body = {'name':'my_image.jpg'}

req = service.objects().insert(
   bucket='my_bucket', body=body,
   media_body=googleapiclient.http.MediaIoBaseUpload(
      gcs_image, 'application/octet-stream'))

resp = req.execute()

if gcs_image = open('img.jpg', 'r') the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: gcs_image = cv2.imread('img.jpg'))

Body:
Here is how to directly upload a PIL Image from memory:

from google.cloud import storage
import io
from PIL import Image

# Define variables
bucket_name = XXXXX
destination_blob_filename = XXXXX

# Configure bucket and blob
client = storage.Client()
bucket = client.bucket(bucket_name)

im = Image.open("test.jpg")
bs = io.BytesIO()
im.save(bs, "jpeg")
blob.upload_from_string(bs.getvalue(), content_type="image/jpeg")

In addition to that, here is how to download blobfiles directly to memory as PIL Images:

blob = bucket.blob(destination_blob_filename)
downloaded_im_data = blob.download_as_bytes()
downloaded_im = Image.open(io.BytesIO(downloaded_im_data))


问:
jQuery - remove user input text from textarea
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

```<code>$("#commentField").text(" ");
$("#commentField").value = ' ';
</code>```

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor

答:
Since textarea is a input field it has a value property so you have to use val() method. Try this

```<code>$("#commentField").val('');
</code>```

Body:
Okay I have a list of devices where i can select which to edit.
I have 3 states for the edit. When no devices are selected, when 1 device is selected or when x devices are selected.

The problem i have is when a user type some text in the textarea (commentField) and cancels the edit to edit another device, the text there was typed in the textarea won't disapere. It stays so when i get the new dialog for the new edit, the commentfield has the text from the old commentField (as if it wasn't cleared)

I have tried the following codes to remove the text (both when then cancel button is pressed and when i start a new dialog), but nothing works:

$("#commentField").text(" ");
$("#commentField").value = ' ';

Is there anyone who knows how to remove user-typed text from a textarea using jQuery??

Thanks in advance.

-Thor

Body:
Since textarea is a input field it has a value property so you have to use val() method. Try this

$("#commentField").val('');


问:
Angular routing not working after running ng build at deployment
not sure what im doing wrong here, im fairly new to Angular and im fumbling along somewhat with regards to routing.

I'm running Angular 12.2.0 and have setup routes on localhost. I'm just navigating between two pages at the moment to see how it works, its working fine locally.

For example on localhost I can browse from the root http://localhost:4200/ to http://localhost:4200/locations which works fine.

```<code> const routes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'locations', component: LocationsComponent}
];
</code>```

When I run ng build to build the project, it runs fine and I can open the index.html fine

what I cannot do is navigate between the routes no more

Launching the build at dist/angular-app/index.html when I click on the locations link its wanting to link to dist/angular-app/index.html/locations which is blank even if I change the URL to dist/angular-app/locations that's also blank

Anyone point me in the right direction as to why its doing this?

Many thanks

Attaching my angular.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-app": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        },
        "@schematics/angular:application": {
          "strict": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "angular-app:build:production"
            },
            "development": {
              "browserTarget": "angular-app:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular-app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        }
      }
    }
  },
  "defaultProject": "angular-app"
}
</code>```

答:
Most likely it is because your webserver is actually trying to find a page corresponding to the URL. However, since an Angular app is a SPA the elements are injected into a page dynamically based on the url in your browser, therefore, when requesting a route the server returns 404 HTTP error.
This can be solved by using HashLocationStrategy from angular, which appends a # to your URL making it possible to navigate when the app is deployed.

Add this to your app.module.ts in the providers section.

```<code>providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
</code>```

Import:

```<code>import { HashLocationStrategy, LocationStrategy } from '@angular/common';
</code>```

Edit:
Alternatively, If you are serving the application through Nginx or an Apache Server, you can add configuration entry in the config file to redirect all requests that have no matching file to /index.html.
More on that you can see https://angular.io/guide/deployment#server-configuration

Body:
not sure what im doing wrong here, im fairly new to Angular and im fumbling along somewhat with regards to routing.

I'm running Angular 12.2.0 and have setup routes on localhost. I'm just navigating between two pages at the moment to see how it works, its working fine locally.

For example on localhost I can browse from the root http://localhost:4200/ to http://localhost:4200/locations which works fine.

 const routes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'locations', component: LocationsComponent}
];

When I run ng build to build the project, it runs fine and I can open the index.html fine

what I cannot do is navigate between the routes no more

Launching the build at dist/angular-app/index.html when I click on the locations link its wanting to link to dist/angular-app/index.html/locations which is blank even if I change the URL to dist/angular-app/locations that's also blank

Anyone point me in the right direction as to why its doing this?

Many thanks

Attaching my angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-app": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        },
        "@schematics/angular:application": {
          "strict": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "angular-app:build:production"
            },
            "development": {
              "browserTarget": "angular-app:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular-app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        }
      }
    }
  },
  "defaultProject": "angular-app"
}

Body:
Most likely it is because your webserver is actually trying to find a page corresponding to the URL. However, since an Angular app is a SPA the elements are injected into a page dynamically based on the url in your browser, therefore, when requesting a route the server returns 404 HTTP error.
This can be solved by using HashLocationStrategy from angular, which appends a # to your URL making it possible to navigate when the app is deployed.

Add this to your app.module.ts in the providers section.

providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]

Import:

import { HashLocationStrategy, LocationStrategy } from '@angular/common';

Edit:
Alternatively, If you are serving the application through Nginx or an Apache Server, you can add configuration entry in the config file to redirect all requests that have no matching file to /index.html.
More on that you can see https://angular.io/guide/deployment#server-configuration


问:
Docker-compose : php:7.0-apache , enable mod_rewrite
I want to develop my php app with docker-compose.
Here is my docker-compose.yml

```<code>version: '3'
services:
  db:
    image: mysql:5.7
    container_name: app_db
    environment:
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - "9906:3306"
  web:
    image: php:7.0-apache
    container_name: app_web
    depends_on:
      - db
    volumes:
    - ./yii2/web/:/var/www/html/
    ports:
      - "8000:80"
    stdin_open: true
    tty: true
</code>```

The app is running with .htaccess. So, I need to enable mod_rewrite.
How to enable this apache configuration ?

```<code> Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration
</code>```

答:
Try adding

```<code>command: >
  bash -c "a2enmod rewrite
  && apache2-foreground"
</code>```

Like so:

```<code>version: '3'
services:
  db:
    image: mysql:5.7
    container_name: app_db
    environment:
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - "9906:3306"
  web:
    image: php:7.0-apache
    command: >
      bash -c "a2enmod rewrite
      && apache2-foreground"
    container_name: app_web
    depends_on:
      - db
    volumes:
      - ./yii2/web/:/var/www/html/
    ports:
      - "8000:80"
    stdin_open: true
    tty: true
</code>```

Body:
I want to develop my php app with docker-compose.
Here is my docker-compose.yml

version: '3'
services:
  db:
    image: mysql:5.7
    container_name: app_db
    environment:
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - "9906:3306"
  web:
    image: php:7.0-apache
    container_name: app_web
    depends_on:
      - db
    volumes:
    - ./yii2/web/:/var/www/html/
    ports:
      - "8000:80"
    stdin_open: true
    tty: true

The app is running with .htaccess. So, I need to enable mod_rewrite.
How to enable this apache configuration ?

 Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Body:
Try adding

command: >
  bash -c "a2enmod rewrite
  && apache2-foreground"

Like so:

version: '3'
services:
  db:
    image: mysql:5.7
    container_name: app_db
    environment:
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - "9906:3306"
  web:
    image: php:7.0-apache
    command: >
      bash -c "a2enmod rewrite
      && apache2-foreground"
    container_name: app_web
    depends_on:
      - db
    volumes:
      - ./yii2/web/:/var/www/html/
    ports:
      - "8000:80"
    stdin_open: true
    tty: true


问:
Modify css Property in react
Hi I'm creating a dynamic table component using css grid. But I want to modify the grid-template-columns css property. I know how to do it in css. I'm using repeat to do this. But I want to modify the repeat value every time I use the component in react. For example if I need a table with 5 columns y use repeat(5, 1fr) and if I want to create a 3 column table I use repeat(3, 1fr).

```<code><div className="xx-table">
    <div className="xx-table-header">
        <div className="xx-table-row">
            <div className="xx-table-data">Title1</div>
            <div className="xx-table-data">Title2</div>
            <div className="xx-table-data">Title3</div>
            <div className="xx-table-data">Title4</div>
            <div className="xx-table-data">Title5</div>
        </div>
    </div>
    <div className="xx-table-body">
        <div className="xx-table-row">
            <div className="xx-table-data">Data1</div>
            <div className="xx-table-data">Data2</div>
            <div className="xx-table-data">Data3</div>
            <div className="xx-table-data">Data4</div>
            <div className="xx-table-data">Data5</div>
        </div>
        <div className="xx-table-row">
            <div className="xx-table-data">Data6</div>
            <div className="xx-table-data">Data7</div>
            <div className="xx-table-data">Data8</div>
            <div className="xx-table-data">Data9</div>
            <div className="xx-table-data">Data10</div>
        </div>
    </div>
</div>
</code>```

And the css

```<code>xx-table-row {
    display: grid;
    grid-template-columns: repeat(5, minmax(100px, 1fr));
}
</code>```

I can´t figure it out how to do this. I don´t know if inline style is the way or any other method that I don´t know

答:
You should look into styled-components.

Through styled-components, you could set the number of columns as a prop to dynamically choose its value every time you use the component (and from what I know it also helps in terms of performance).

The code would look like this:

```<code>import styled from 'styled-components'

const StyledRow = styled.div`
  display: grid;
  grid-template-columns: ${props => `repeat(${props.columns}, minmax(100px, 1fr))`};
`

// in the component
<StyledRow columns={5}>
    // ideally, style these with styled-components as well
    <div className="xx-table-data">Data1</div>
    <div className="xx-table-data">Data2</div>
    <div className="xx-table-data">Data3</div>
    <div className="xx-table-data">Data4</div>
    <div className="xx-table-data">Data5</div>
</StyledRow>
</code>```

Title: Modify css Property in react

Body:
Hi I'm creating a dynamic table component using css grid. But I want to modify the grid-template-columns css property. I know how to do it in css. I'm using repeat to do this. But I want to modify the repeat value every time I use the component in react. For example if I need a table with 5 columns y use repeat(5, 1fr) and if I want to create a 3 column table I use repeat(3, 1fr).

Title1

Title2

Title3

Title4

Title5

Data1

Data2

Data3

Data4

Data5

Data6

Data7

Data8

Data9

Data10

And the css

xx-table-row {
    display: grid;
    grid-template-columns: repeat(5, minmax(100px, 1fr));
}

I can´t figure it out how to do this. I don´t know if inline style is the way or any other method that I don´t know

Body:
You should look into styled-components.

Through styled-components, you could set the number of columns as a prop to dynamically choose its value every time you use the component (and from what I know it also helps in terms of performance).

The code would look like this:

import styled from 'styled-components'

const StyledRow = styled.div`
  display: grid;
  grid-template-columns: ${props => `repeat(${props.columns}, minmax(100px, 1fr))`};
`

// in the component
<StyledRow columns={5}>
    // ideally, style these with styled-components as well
    <div className="xx-table-data">Data1</div>
    <div className="xx-table-data">Data2</div>
    <div className="xx-table-data">Data3</div>
    <div className="xx-table-data">Data4</div>
    <div className="xx-table-data">Data5</div>
</StyledRow>


问:
How to Draw Polyline on mapmyindia using React?
I am just exploring Mapmyindia.
I have gone through the basic location display on the map.
I am not getting how to display polyline on map.

code for location
app.js

```<code>import "./App.css";
import SideBar from "./componants/SideBar";
import Map from "mapmyindia-react";
// import MapmyIndia, { MapMarker } from "react-mapmyindia";

function App() {
  return (
    <div className="App">
      Hello
      <Map
        markers={[
          {
            position: [21.1588329, 72.7688111],
            draggable: true,
            zoom: 15,
            title: "Marker title",
            onClick: (e) => {
              console.log("clicked ");
            },
            onDragend: (e) => {
              console.log("dragged");
            },
            onMouseover: (e) => {
              console.log("Mouse over");
            },
          },
        ]}
      />
      {/* <Map /> */}
      <SideBar></SideBar>
    </div>
  );
}

export default App;

</code>```

Which result this

Now, Please help with drawing polyline.

答:
I guess you're using the npm package for maps. If you go through the library's code in gitHub, you can see the owner has only added marker functionality. You can simply copy the code from there and add it manually to your project and then add the polyline functionality and then pass the data as props from your app.js file like you're doing for markers.

```<code>    renderPolylines = () => {
    const { polylines = [] } = this.props;
    if (!this.map) {
      return;
    }
    polylines.map(m => {
      if (m?.position && Array.isArray(m.position)) {
        const { position, color, weight, opacity } = m;
        let points = [];
        position.map(p => {
          const { lat, lng } = p;
          const center = new L.LatLng(lat, lng);
          points.push(
            new L.LatLng(center.lat, center.lng))/*array of wgs points*/
        })
        const polyline = new L.Polyline(points, { color, weight, opacity });
        this.map.addLayer(polyline);
        this.polylines.push(polyline);
      }
    });
  };
</code>```

Props for rendering polyline from app.js

```<code>    polylines = {[
    {
      position: [
        {
          lat: 18.5014,
          lng: 73.805,
        },
        {
          lat: 18.5414,
          lng: 73.855,
        },
        {
          lat: 18.5514,
          lng: 73.855,
        },
        {
          lat: 18.5614,
          lng: 73.855,
        },
      ],
      color: "red",
      weight: 4,
      opacity: 0.5,
    },
  ]}
</code>```

Body:
I am just exploring Mapmyindia.
I have gone through the basic location display on the map.
I am not getting how to display polyline on map.

code for location
app.js

import "./App.css";
import SideBar from "./componants/SideBar";
import Map from "mapmyindia-react";
// import MapmyIndia, { MapMarker } from "react-mapmyindia";

function App() {
  return (

      Hello
      <Map
        markers={[
          {
            position: [21.1588329, 72.7688111],
            draggable: true,
            zoom: 15,
            title: "Marker title",
            onClick: (e) => {
              console.log("clicked ");
            },
            onDragend: (e) => {
              console.log("dragged");
            },
            onMouseover: (e) => {
              console.log("Mouse over");
            },
          },
        ]}
      />
      {/* <Map /> */}
      <SideBar></SideBar>

  );
}

export default App;

Which result this

Now, Please help with drawing polyline.

Body:
I guess you're using the npm package for maps. If you go through the library's code in gitHub, you can see the owner has only added marker functionality. You can simply copy the code from there and add it manually to your project and then add the polyline functionality and then pass the data as props from your app.js file like you're doing for markers.

    renderPolylines = () => {
    const { polylines = [] } = this.props;
    if (!this.map) {
      return;
    }
    polylines.map(m => {
      if (m?.position && Array.isArray(m.position)) {
        const { position, color, weight, opacity } = m;
        let points = [];
        position.map(p => {
          const { lat, lng } = p;
          const center = new L.LatLng(lat, lng);
          points.push(
            new L.LatLng(center.lat, center.lng))/*array of wgs points*/
        })
        const polyline = new L.Polyline(points, { color, weight, opacity });
        this.map.addLayer(polyline);
        this.polylines.push(polyline);
      }
    });
  };

Props for rendering polyline from app.js

    polylines = {[
    {
      position: [
        {
          lat: 18.5014,
          lng: 73.805,
        },
        {
          lat: 18.5414,
          lng: 73.855,
        },
        {
          lat: 18.5514,
          lng: 73.855,
        },
        {
          lat: 18.5614,
          lng: 73.855,
        },
      ],
      color: "red",
      weight: 4,
      opacity: 0.5,
    },
  ]}


问:
Unable to import module when using alias in package json
I was using this question as a reference to import my modules with aliases.

I have the following package.json :

```<code>{
  ...
  "imports": {
    "#components/*": "src/components/*", // tried both #components/* and #components
    "#config/*": "src/config/*",
    "#hooks/*": "src/hooks/*",
    "#pages/*": "src/pages/*",
    "#utils/*": "src/utils/*"
  }
}
</code>```

In my file, I do:

```<code>import { Layout, About } from '#components';
</code>```

But I get the following error:

```<code>Module not found: Error: Can't resolve '#components' in 'pwd/src/pages'
assets by chunk 1.56 MiB (name: main)
  asset static/js/bundle.js 1.56 MiB [emitted] (name: main) 1 related asset
  asset main.a40280fd506751c0b92a.hot-update.js 362 bytes [emitted] [immutable] [hmr] (name: main) 1 related asset
assets by path *.json 343 bytes
  asset asset-manifest.json 315 bytes [emitted]
  asset main.a40280fd506751c0b92a.hot-update.json 28 bytes [emitted] [immutable] [hmr]
asset index.html 1.67 KiB [emitted]
Entrypoint main 1.56 MiB (1.64 MiB) = static/js/bundle.js 1.56 MiB main.a40280fd506751c0b92a.hot-update.js 362 bytes 2 auxiliary assets
cached modules 1.44 MiB [cached] 117 modules
runtime modules 28.2 KiB 13 modules

ERROR in ./src/pages/HomePage.js 7:0-53
Module not found: Error: Can't resolve '#components' in 'pwd/src/pages'
resolve '#components' in 'pwd/src/pages'
  using description file: pwd/package.json (relative path: ./src/pages)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as internal import
      using imports field: src/components/*
        Parsed request is a module
        using description file: pwd/package.json (relative path: ./src/pages)
          Field 'browser' doesn't contain a valid alias configuration
          resolve as module
            pwd/src/pages/node_modules doesn't exist or is not a directory
            pwd/src/node_modules doesn't exist or is not a directory
            looking for modules in pwd/node_modules
              pwd/node_modules/src doesn't exist
            /Users/ankit/...paths to pwd.../node_modules doesn't exist or is not a directory
            ...
            /Users/node_modules doesn't exist or is not a directory
            /node_modules doesn't exist or is not a directory
            looking for modules in pwd/node_modules
              pwd/node_modules/src doesn't exist
 @ ./src/App.js 15:0-26 16:0-40 20:30-38
 @ ./src/index.js 7:0-24 10:33-36

webpack 5.68.0 compiled with 1 error in 117 ms
</code>```

Any help would be great, thanks!

答:
That question applies to nodejs, not React. You can add configurations to your React app with craco.

Install craco with yarn or npm

```<code>yarn add @craco/craco
</code>```

Create a craco.config.js file in your project's root and insert your aliases

```<code>const path = require(`path`);

module.exports = {
    webpack: {
        alias: {
            '#components': path.resolve(__dirname, 'src/components'),
            '#x': path.resolve(__dirname, 'src/x'),
        }
    },
};
</code>```

Replace react-scripts under the scripts section in package.json to craco like this

```<code> "scripts": {
   "start": "craco start",
   "build": "craco build",
   ...
 },
</code>```

Restart the dev server and you should be able to use your aliases.

Body:
I was using this question as a reference to import my modules with aliases.

I have the following package.json :

{
  ...
  "imports": {
    "#components/*": "src/components/*", // tried both #components/* and #components
    "#config/*": "src/config/*",
    "#hooks/*": "src/hooks/*",
    "#pages/*": "src/pages/*",
    "#utils/*": "src/utils/*"
  }
}

In my file, I do:

import { Layout, About } from '#components';

But I get the following error:

Module not found: Error: Can't resolve '#components' in 'pwd/src/pages'
assets by chunk 1.56 MiB (name: main)
  asset static/js/bundle.js 1.56 MiB [emitted] (name: main) 1 related asset
  asset main.a40280fd506751c0b92a.hot-update.js 362 bytes [emitted] [immutable] [hmr] (name: main) 1 related asset
assets by path *.json 343 bytes
  asset asset-manifest.json 315 bytes [emitted]
  asset main.a40280fd506751c0b92a.hot-update.json 28 bytes [emitted] [immutable] [hmr]
asset index.html 1.67 KiB [emitted]
Entrypoint main 1.56 MiB (1.64 MiB) = static/js/bundle.js 1.56 MiB main.a40280fd506751c0b92a.hot-update.js 362 bytes 2 auxiliary assets
cached modules 1.44 MiB [cached] 117 modules
runtime modules 28.2 KiB 13 modules

ERROR in ./src/pages/HomePage.js 7:0-53
Module not found: Error: Can't resolve '#components' in 'pwd/src/pages'
resolve '#components' in 'pwd/src/pages'
  using description file: pwd/package.json (relative path: ./src/pages)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as internal import
      using imports field: src/components/*
        Parsed request is a module
        using description file: pwd/package.json (relative path: ./src/pages)
          Field 'browser' doesn't contain a valid alias configuration
          resolve as module
            pwd/src/pages/node_modules doesn't exist or is not a directory
            pwd/src/node_modules doesn't exist or is not a directory
            looking for modules in pwd/node_modules
              pwd/node_modules/src doesn't exist
            /Users/ankit/...paths to pwd.../node_modules doesn't exist or is not a directory
            ...
            /Users/node_modules doesn't exist or is not a directory
            /node_modules doesn't exist or is not a directory
            looking for modules in pwd/node_modules
              pwd/node_modules/src doesn't exist
 @ ./src/App.js 15:0-26 16:0-40 20:30-38
 @ ./src/index.js 7:0-24 10:33-36

webpack 5.68.0 compiled with 1 error in 117 ms

Any help would be great, thanks!

Body:
That question applies to nodejs, not React. You can add configurations to your React app with craco.

Install craco with yarn or npm

yarn add @craco/craco

Create a craco.config.js file in your project's root and insert your aliases

const path = require(`path`);

module.exports = {
    webpack: {
        alias: {
            '#components': path.resolve(__dirname, 'src/components'),
            '#x': path.resolve(__dirname, 'src/x'),
        }
    },
};

Replace react-scripts under the scripts section in package.json to craco like this

 "scripts": {
   "start": "craco start",
   "build": "craco build",
   ...
 },

Restart the dev server and you should be able to use your aliases.


问:
Stack multiple columns on top of eachother on Google Sheet?
I am using Google SpreadSheet, and I'm trying to import data from different sources together using a combination of query, importrange and curly brackets:

```<code>={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}
</code>```

But the result formula only returns SheetA data.

Since I only need 4 particular columns from SheetA and SheetB, I'd want the columns from both sheets to stack on top of eachother like this:

Col1
Col2
Col3
Col4

Data SheetA
Data SheetA
Data SheetA
Data SheetA

Data SheetB
Data SheetB
Data SheetB
Data SheetB

I tried running each =query(importrange) individually and combine them afterwards using {A:D;E:H} but it gives Result was not automatically expanded, please insert more rows error.

I tried looking for other similar threads but they were mostly about stacking different columns into one singular column. Can you help me with my case?

答:
first, you need to run every importrange separately as standalone formula to connect your sheets by allowing access

when done, only then, you can run this array:

```<code>=QUERY({IMPORTRANGE("url_or_id", "SheetA!A:D");
        IMPORTRANGE("url_or_id", "SheetB!A:D")},
 "where Col1 is not null", 0)
</code>```

Body:
I am using Google SpreadSheet, and I'm trying to import data from different sources together using a combination of query, importrange and curly brackets:

={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}

But the result formula only returns SheetA data.

Since I only need 4 particular columns from SheetA and SheetB, I'd want the columns from both sheets to stack on top of eachother like this:

Col1
Col2
Col3
Col4

Data SheetA
Data SheetA
Data SheetA
Data SheetA

Data SheetB
Data SheetB
Data SheetB
Data SheetB

I tried running each =query(importrange) individually and combine them afterwards using {A:D;E:H} but it gives Result was not automatically expanded, please insert more rows error.

I tried looking for other similar threads but they were mostly about stacking different columns into one singular column. Can you help me with my case?

Body:
first, you need to run every importrange separately as standalone formula to connect your sheets by allowing access

when done, only then, you can run this array:

=QUERY({IMPORTRANGE("url_or_id", "SheetA!A:D");
        IMPORTRANGE("url_or_id", "SheetB!A:D")},
 "where Col1 is not null", 0)


问:
Generating RouteUrl in MVC3 returns null in one case
I have a route defined like this:

```<code> routes.MapRoute("Date", "Date/{year}/{month}/{day}",
    new { controller = "Date", action = "Index", year = UrlParameter.Optional,
         month = UrlParameter.Optional, day = UrlParameter.Optional });
</code>```

So it has 3 optional parameters, year, month and day.  It works fine in routing a GET request, all the following work fine:

```<code>http://myhost/myapp/Date
http://myhost/myapp/Date/2011
http://myhost/myapp/Date/2011/8
http://myhost/myapp/Date/2011/8/17
</code>```

Generating links using RouteUrl works in all cases except one.

For example, the case where I want a link including the year and a month works fine.  I use the following (simplified) code in my view:

```<code> string linkUrl = Url.RouteUrl("Date",
     new { controller = "Date", year = 2011, month = 8 },
     Request.Url.Scheme);
</code>```

But the case where only the year is defined does not work and returns null, the code is:

```<code>string linkUrl = Url.RouteUrl("Date",
    new { controller = "Date", year = 2011 },
    Request.Url.Scheme);
</code>```

So it all looks correct to me.  Any clue what I'm doing wrong, or how to debug this further.

答:
Ok, it looks like this is a known 'issue' introduced in MVC3, but due to an underlying issue in routing in .NET4, so cannot be quickly fixed by the MVC team.  Although silently returning null is clearly a bug, its unclear whether the route I originally created should be allowed to work the way I wanted it too (see below).

I found this SO Question which asks for people to replicate a similar issue with two optional parameters, and an answer refers to this article too, which has a workaround.

I resolved this as per the workaround by making multiple routes, with only one optional parameter in each.

```<code>  routes.MapRoute(
    "Date-ByDay", // Route name
    "Date/{year}/{month}/{day}", // URL with parameters
    new { controller = "Date", action = "Index" } // Parameter defaults
  );

  routes.MapRoute(
    "Date-ByMonth", // Route name
    "Date/{year}/{month}", // URL with parameters
    new { controller = "Date", action = "Index", month = UrlParameter.Optional } // Parameter defaults
  );

  routes.MapRoute(
    "Date-ByYear", // Route name
    "Date/{year}", // URL with parameters
    new { controller = "Date", action = "Index", year = UrlParameter.Optional } // Parameter defaults
  );
</code>```

It is arguable whether my original approach should work anyway, for example what if you miss out the optional 'month' parameter, and should the original route generate a URL of /2011/18?  The 'workaround' whilst ugly, certainly is much more explicit about the behavior you want.   I would argue that the expected behavior of my original route is clear (to me) and that I would have expected an exception if I had asked for a route with a year and a day, missing out the month - but I can see that this may not be everyones point of view.  However this did work in MVC2.

Body:
I have a route defined like this:

 routes.MapRoute("Date", "Date/{year}/{month}/{day}",
    new { controller = "Date", action = "Index", year = UrlParameter.Optional,
         month = UrlParameter.Optional, day = UrlParameter.Optional });

So it has 3 optional parameters, year, month and day.  It works fine in routing a GET request, all the following work fine:

http://myhost/myapp/Date
http://myhost/myapp/Date/2011
http://myhost/myapp/Date/2011/8
http://myhost/myapp/Date/2011/8/17

Generating links using RouteUrl works in all cases except one.

For example, the case where I want a link including the year and a month works fine.  I use the following (simplified) code in my view:

 string linkUrl = Url.RouteUrl("Date",
     new { controller = "Date", year = 2011, month = 8 },
     Request.Url.Scheme);

But the case where only the year is defined does not work and returns null, the code is:

string linkUrl = Url.RouteUrl("Date",
    new { controller = "Date", year = 2011 },
    Request.Url.Scheme);

So it all looks correct to me.  Any clue what I'm doing wrong, or how to debug this further.

Body:
Ok, it looks like this is a known 'issue' introduced in MVC3, but due to an underlying issue in routing in .NET4, so cannot be quickly fixed by the MVC team.  Although silently returning null is clearly a bug, its unclear whether the route I originally created should be allowed to work the way I wanted it too (see below).

I found this SO Question which asks for people to replicate a similar issue with two optional parameters, and an answer refers to this article too, which has a workaround.

I resolved this as per the workaround by making multiple routes, with only one optional parameter in each.

  routes.MapRoute(
    "Date-ByDay", // Route name
    "Date/{year}/{month}/{day}", // URL with parameters
    new { controller = "Date", action = "Index" } // Parameter defaults
  );

  routes.MapRoute(
    "Date-ByMonth", // Route name
    "Date/{year}/{month}", // URL with parameters
    new { controller = "Date", action = "Index", month = UrlParameter.Optional } // Parameter defaults
  );

  routes.MapRoute(
    "Date-ByYear", // Route name
    "Date/{year}", // URL with parameters
    new { controller = "Date", action = "Index", year = UrlParameter.Optional } // Parameter defaults
  );

It is arguable whether my original approach should work anyway, for example what if you miss out the optional 'month' parameter, and should the original route generate a URL of /2011/18?  The 'workaround' whilst ugly, certainly is much more explicit about the behavior you want.   I would argue that the expected behavior of my original route is clear (to me) and that I would have expected an exception if I had asked for a route with a year and a day, missing out the month - but I can see that this may not be everyones point of view.  However this did work in MVC2.