问:
VSCode WSL - Installing VS Code Server for x64 - FAIL
Can anyone decode the following for me?

WSL was working perfectly on C++ a few weeks back.
Switched to try to run older Python under windows (not WSL) and it seems all twisted up now.
Can't get Win10 nor WSL to run. Keeps trying and failing to update. I re-ran the WSL and updated VSCode on the windows side. I AM behind a proxy but as far as I know, I've update all the files that google searches pointed me at. Pretty frustrated and would appreciate any help there is.

"
Request downloadRequest failed with message: getaddrinfo ENOTFOUND update.code.visualstudio.com. Will try to download on WSL side."

"
[2022-02-10 13:51:09.374] Setting up server environment: Looking for /home/ubuntu/.vscode-server/server-env-setup. Not found.
[2022-02-10 13:51:09.374] WSL version: 4.4.0-19041-Microsoft Ubuntu-20.04
[2022-02-10 13:51:09.374] Updating VS Code Server to version d6ee99e4c045a6716e5c653d7da8e9ae6f5a8b03
[2022-02-10 13:51:09.374] Removing previous installation...
[2022-02-10 13:51:09.674] Installing VS Code Server for x64 (d6ee99e4c045a6716e5c653d7da8e9ae6f5a8b03)
[2022-02-10 13:51:09.674] Downloading:

[2022-02-10 13:52:43.314] VS Code Server for WSL failed to start. No messages received for 90s
[2022-02-10 13:52:43.314] For help with startup problems, go to
[2022-02-10 13:52:43.314] https://code.visualstudio.com/docs/remote/troubleshooting#_wsl-tips
[2022-02-10 13:52:43.328] WSL Daemon exited with code 0

"

答:
I'm not 100% which step fixed it however I was able to proceed after.
Launching C++ project in wsl also tried to update and failed. The difference being that the install button did actually install the wsl server update w/o fail. So that error was gone.

I then launched another VSCode session with the Python project and the cmd terminal. I then had to use this help (https://github.com/pypa/pip/issues/9216#issuecomment-741836058) to adjust the proxy.

I could then proceed to reinstall ipykernel which is what had stopped working and was blocking me.

I'm pretty sure my environments are conflicting with each other. I'm afraid I don't understand VSCode environments well enough and very likely caused this problem for myself.


来源: stackexchange

问:
Python script repeat
I have an LED strip on a raspberry and would like to indicate the status of the internet on the LED strip by means of a color.

Now I came up with this:

```<code>import os
hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:
    exec(open("random_blink.py").read())

else:
    exec(open("random_blink_colours.py").read())
</code>```

How can I get the script to rerun every 10 seconds?

答:
Just use an infinite loop that sleeps for 10 seconds.</p>
```<code>import subprocess
import time

...

while True:
    result = subprocess.run(["ping", "-c", "1", hostname])
    to_run = "random_blink.py" if result.returncode == 0 else "random_blink_colors.py"
    subprocess.run([to_run])
    time.sleep(10)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python script repeat

Body:
I have an LED strip on a raspberry and would like to indicate the status of the internet on the LED strip by means of a color.

Now I came up with this:

import os
hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:
    exec(open("random_blink.py").read())

else:
    exec(open("random_blink_colours.py").read())

How can I get the script to rerun every 10 seconds?

Body:
Just use an infinite loop that sleeps for 10 seconds.

import subprocess
import time

...

while True:
    result = subprocess.run(["ping", "-c", "1", hostname])
    to_run = "random_blink.py" if result.returncode == 0 else "random_blink_colors.py"
    subprocess.run([to_run])
    time.sleep(10)


问:
Pandas Drop Rows when a String is Matched to a Longer String in a Column in an Exact Match
I'm trying to drop rows in a pandas DataFrame if a substring in a column exactly matches a string in a list. At the moment I can only get it working for partial matches.

```<code># list of strings to drop in an exact match
drop_list = ["sock", "shirt"]

# initialize data of lists.
data = {'keyword': ['adidas socks', 'adidas sock', 'adidas shoes', "sock"]}

# Create DataFrame
df = pd.DataFrame(data)

df = df[~df['keyword'].str.contains("|".join(drop_list))]
</code>```

Current Output:

```<code>        keyword
2  adidas shoes
</code>```

Desired Output:

```<code>        keyword
0  adidas socks
1  adidas shoes
</code>```

答:
You can create a set from drop_list and use set.isdisjoint on the split words in each row to evaluate if the exact match appears.

```<code>drop_set = set(drop_list)
msk = df['keyword'].apply(lambda x: drop_set.isdisjoint(x.split()))
df = df[msk]
</code>```

Output:

```<code>        keyword
0  adidas socks
2  adidas shoes
</code>```

Body:
I'm trying to drop rows in a pandas DataFrame if a substring in a column exactly matches a string in a list. At the moment I can only get it working for partial matches.

# list of strings to drop in an exact match
drop_list = ["sock", "shirt"]

# initialize data of lists.
data = {'keyword': ['adidas socks', 'adidas sock', 'adidas shoes', "sock"]}

# Create DataFrame
df = pd.DataFrame(data)

df = df[~df['keyword'].str.contains("|".join(drop_list))]

Current Output:

        keyword
2  adidas shoes

Desired Output:

        keyword
0  adidas socks
1  adidas shoes

Body:
You can create a set from drop_list and use set.isdisjoint on the split words in each row to evaluate if the exact match appears.

drop_set = set(drop_list)
msk = df['keyword'].apply(lambda x: drop_set.isdisjoint(x.split()))
df = df[msk]

Output:

        keyword
0  adidas socks
2  adidas shoes


问:
Own DSL with XText. Problem with unlimited brackets ("(", ")")
I am developing my own DSL in XText.

I want do something like this:

```<code>1 AND (2 OR (3 OR 4))
</code>```

Here my current .xtext file:

```<code>grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

Model:
    (greetings+=CONDITION_LEVEL)
;

terminal NUMBER :
    ('1'..'9') ('0'..'9')*
;

AND:
    ' AND '
;

OR:
    ' OR '
;

OPERATOR :
    AND | OR
;

CONDITION_LEVEL:
    ('('* NUMBER (=>')')* OPERATOR)+ NUMBER ')'*
;
</code>```

The problem I am having is that the dsl should have the possibility to make unlimited bracket, but show an error when the programmer don't closes all opened bracket.

example:

```<code>1 AND (2 OR (3 OR 4)
</code>```

one bracket is missing --> should make error.

I don't know how I can realize this in XText. Can anybody help?

thx for helping.

答:
You need to make your syntax recursive. The basic idea is that a CONDITION_LEVEL can be, for example, two CONDITION_LEVEL separated by an OPERATOR.

I don't know the specifics of the xtext syntax, but using a BCNF-like syntax you could have:

```<code>CONDITION_LEVEL:
    NUMBER
    '(' CONDITION_LEVEL OPERATOR CONDITION_LEVEL ')'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing my own DSL in XText.

I want do something like this:

1 AND (2 OR (3 OR 4))

Here my current .xtext file:

grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

Model:
    (greetings+=CONDITION_LEVEL)
;

terminal NUMBER :
    ('1'..'9') ('0'..'9')*
;

AND:
    ' AND '
;

OR:
    ' OR '
;

OPERATOR :
    AND | OR
;

CONDITION_LEVEL:
    ('('* NUMBER (=>')')* OPERATOR)+ NUMBER ')'*
;

The problem I am having is that the dsl should have the possibility to make unlimited bracket, but show an error when the programmer don't closes all opened bracket.

example:

1 AND (2 OR (3 OR 4)

one bracket is missing --> should make error.

I don't know how I can realize this in XText. Can anybody help?

thx for helping.

Body:
You need to make your syntax recursive. The basic idea is that a CONDITION_LEVEL can be, for example, two CONDITION_LEVEL separated by an OPERATOR.

I don't know the specifics of the xtext syntax, but using a BCNF-like syntax you could have:

CONDITION_LEVEL:
    NUMBER
    '(' CONDITION_LEVEL OPERATOR CONDITION_LEVEL ')'


问:
Chunk transfer vs grpc streaming
I am working on a project, where I want to expose an API which will read a large file send that in response.

Since file can be large in size, it is better to send the file in chunks, so not much memory pressure on system.

I evaluated 2 options : chunked transfer (https://en.m.wikipedia.org/wiki/Chunked_transfer_encoding)  which is supported by HTTP-1.1, and a server side streaming by grpc.

In grpc approach, client request through a rpc, while server will stream bytes over grpc channel and close the same once done.

My ecosystem can support both, and client also supports grpc.

Can you please suggest which option is better, what are pros and cons of both approaches.

答:
Both approaches will yield similar results. Just choose the stack you are most comfortable with.

HTTP chunking uses length-prefixed batches. gRPC streaming uses length-prefixed messages. The main difference is the batch size is chosen for you with chunking.

gRPC uses chunking to provide its streaming, although chunking is implemented differently between HTTP/1.1 and HTTP/2. When using gRPC the main thing is to use a "reasonable" message size; there's an overhead of ~5-10 bytes per message. Overheads exist in chunking as well, just you didn't have to choose the "reasonable" message size.

Both chunking and gRPC streaming use pipelining, where you send a chunk before the previous chunk has been fully received and processed. This reduces the influence of the chunk size on network performance. As long as you choose a chunk size of at least 1 KB, the chunk size shouldn't matter too much and fine-tuning will rapidly see diminishing returns.

Title: Chunk transfer vs grpc streaming


问:
Focus on textarea in popup
When I click on a button , a popup will appear which consists of textarea. I want the textarea to be focused when the popup is opened.

I tried using autofocus, textarea.focus .. but it is not working.

Can anyone please help...

by default popup= false

```<code><div *ngIf = "popup" class="post">
    <p>enter your answer</p>
    <textarea  #textarea1 id = "ta"></textarea>
</div>

<button (click)="popup= true;
textarea1.focus()">Answer Popup</button>
</code>```

答:
The following works for me, however most likely there is a better way to do it in Angular using states and event binding instead of this more like "plain JavaScript" solution:

app.component.ts

import { Component, ElementRef } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  constructor(private _elementRef: ElementRef) {
  }

  openPopUp() {
    const div = this._elementRef.nativeElement.querySelector('#the_div')
    div.style.display = 'block'
    const textarea = this._elementRef.nativeElement.querySelector('#the_textarea')
    textarea.focus()
  }
}
```
<p><em>app.component.html</em></p>
<pre class="lang-html prettyprint-override"><code><div hidden id="the_div">
  <textarea id="the_textarea"></textarea>
</div>

<button (click)="openPopUp()">
  Answer Popup
</button>
</code>```

Title: Focus on textarea in popup

Body:
When I click on a button , a popup will appear which consists of textarea. I want the textarea to be focused when the popup is opened.

I tried using autofocus, textarea.focus .. but it is not working.

Can anyone please help...

by default popup= false

enter your answer

    <textarea  #textarea1 id = "ta"></textarea>

<button (click)="popup= true;
textarea1.focus()">Answer Popup</button>

Body:
The following works for me, however most likely there is a better way to do it in Angular using states and event binding instead of this more like "plain JavaScript" solution:

app.component.ts

import { Component, ElementRef } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  constructor(private _elementRef: ElementRef) {
  }

  openPopUp() {
    const div = this._elementRef.nativeElement.querySelector('#the_div')
    div.style.display = 'block'
    const textarea = this._elementRef.nativeElement.querySelector('#the_textarea')
    textarea.focus()
  }
}

app.component.html

<div hidden id="the_div">
  <textarea id="the_textarea"></textarea>
</div>

<button (click)="openPopUp()">
  Answer Popup
</button>


问:
IIS7 does not start my Exe file by Process Start
I've read a lot of articles. But as far as I know I've done all.
On local computer VS2010 all works fine. The problem occurs only when working on IIS7 Server.

I want to start a exe file which works great on server if I start it manually from Windows Explorer.

```<code> Dim fiExe As New IO.FileInfo(IO.Path.Combine(diBase.FullName, "ClientBin\ConvertAudio.exe"))
    Dim SI As New ProcessStartInfo(fiExe.FullName, args)
    SI.Verb = "runas"
    SI.UseShellExecute = True
    SI.WorkingDirectory = fiExe.Directory.FullName
    Dim P As Process = Process.Start(SI)
    P.PriorityClass = ProcessPriorityClass.Idle
</code>```

I've converted the directory ClientBin in an Application in IIS.

But when using the service I receive this error (callback in Silverlight application):

```<code>{System.Security.SecurityException ---> System.Security.SecurityException: Sicherheitsfehler
   bei System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   bei System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
   bei System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
   --- Ende der internen Ausnahmestapelüberwachung ---
   bei System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   bei System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   bei System.Net.WebClient.WebClientWriteStream.<Dispose>b__3(IAsyncResult ar)}
</code>```

I've tried to store the file "clientaccesspolicy.xml"
in same directory like ClientBin

```<code><?xml version="1.0" encoding="utf-8"?>
<access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="*">
                <domain uri="*"/>
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</access-policy>
</code>```

Still the same message.
Any idea?

*** new info - verb ***
When using this function

```<code>Dim startInfo As New ProcessStartInfo(fiExe.FullName)
            Dim V As String = ""
            For Each verb As String In startInfo.Verbs
                V &= V & ", "
            Next
            Throw New Exception("Verbs=" & V)
</code>```

I receive this result:

Verbs=, , , , , , ,

*** Solution found ***
I've found the solution while using http://www.fiddler2.com and http://technet.microsoft.com/en-us/sysinternals/bb896653
Problem was while using x86 application on a x64 IIS in combination with verb=runas flag. Now application is set to anycpu (Perhaps that does not matter) and verb on ProcessStartInfo is not set to anything.

答: Giving Full Control permission to any web users is always a very bad idea. For a better solution, please see Process.Start doesn't work in IIS</p>

Body:
I've read a lot of articles. But as far as I know I've done all.
On local computer VS2010 all works fine. The problem occurs only when working on IIS7 Server.

I want to start a exe file which works great on server if I start it manually from Windows Explorer.

 Dim fiExe As New IO.FileInfo(IO.Path.Combine(diBase.FullName, "ClientBin\ConvertAudio.exe"))
    Dim SI As New ProcessStartInfo(fiExe.FullName, args)
    SI.Verb = "runas"
    SI.UseShellExecute = True
    SI.WorkingDirectory = fiExe.Directory.FullName
    Dim P As Process = Process.Start(SI)
    P.PriorityClass = ProcessPriorityClass.Idle

I've converted the directory ClientBin in an Application in IIS.

But when using the service I receive this error (callback in Silverlight application):

{System.Security.SecurityException ---> System.Security.SecurityException: Sicherheitsfehler
   bei System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   bei System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
   bei System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
   --- Ende der internen Ausnahmestapelüberwachung ---
   bei System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   bei System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   bei System.Net.WebClient.WebClientWriteStream.<Dispose>b__3(IAsyncResult ar)}

I've tried to store the file "clientaccesspolicy.xml"
in same directory like ClientBin

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="*">
                <domain uri="*"/>
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</access-policy>

Still the same message.
Any idea?

*** new info - verb ***
When using this function

Dim startInfo As New ProcessStartInfo(fiExe.FullName)
            Dim V As String = ""
            For Each verb As String In startInfo.Verbs
                V &= V & ", "
            Next
            Throw New Exception("Verbs=" & V)

I receive this result:

Verbs=, , , , , , ,

*** Solution found ***
I've found the solution while using http://www.fiddler2.com and http://technet.microsoft.com/en-us/sysinternals/bb896653
Problem was while using x86 application on a x64 IIS in combination with verb=runas flag. Now application is set to anycpu (Perhaps that does not matter) and verb on ProcessStartInfo is not set to anything.


问:
how can I translate an array with react-native-i18n?
I have my translation that goes like this:

en.json

```<code>{
   "Welcome": "Welcome to react native",
   "days": ["Sun","Mon","Tue","Wed","Thur","Fri","Sat"]
}
</code>```

and my page that it's like this:

```<code>import React, { PropTypes } from 'react';
import { View, Image } from 'react-native';
import i18n from 'react-native-i18n';
import ReactNativeCalendar from 'react-native-calendar';
import translations from '../../translations';
import styles from './styles';

const dayHeadings = i18n.t('days');
</code>```

[...]

```<code>const Calendar = (props) => {
  console.log(dayHeadings);
  return (
    <View>
      <ReactNativeCalendar
        customStyle={styles}
        nextButtonText={nextButton}
        prevButtonText={prevButton}
        dayHeadings={dayHeadings}
        monthNames={monthNames}
        onDateSelect={props.onDateSelect}
        eventDates={props.eventDates}
        showEventIndicators
        showControls
        events={props.events}
        calendarFormat={props.calendarFormat}
      />
      <Legend items={legendItems} />
    </View>
  );
};
</code>```

dayHeadings is supposed to be an array of translated strings but instead I get

missing "en.days" translation

from the console. The weird thing is that if I save the translation and trigger the hot reload the translation work just fine like here. Also the translation is present in the file screenshot

答:
In your i18n config, be sure to set returnObjects: true

example:

```<code>i18n
  ...
  .init({
    lng: "en",
    fallbackLng: "en",
    backend: {
      loadPath: `...`,
    },
    returnObjects: true,
    interpolation: {
      escapeValue: false,
    },
  });
</code>```

and then your en json file would look like this...

```<code>{
  ...
  "days": ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]
}
</code>```

Body:
I have my translation that goes like this:

en.json

{
   "Welcome": "Welcome to react native",
   "days": ["Sun","Mon","Tue","Wed","Thur","Fri","Sat"]
}

and my page that it's like this:

import React, { PropTypes } from 'react';
import { View, Image } from 'react-native';
import i18n from 'react-native-i18n';
import ReactNativeCalendar from 'react-native-calendar';
import translations from '../../translations';
import styles from './styles';

const dayHeadings = i18n.t('days');

[...]

const Calendar = (props) => {
  console.log(dayHeadings);
  return (
    <View>
      <ReactNativeCalendar
        customStyle={styles}
        nextButtonText={nextButton}
        prevButtonText={prevButton}
        dayHeadings={dayHeadings}
        monthNames={monthNames}
        onDateSelect={props.onDateSelect}
        eventDates={props.eventDates}
        showEventIndicators
        showControls
        events={props.events}
        calendarFormat={props.calendarFormat}
      />
      <Legend items={legendItems} />
    </View>
  );
};

dayHeadings is supposed to be an array of translated strings but instead I get

missing "en.days" translation

from the console. The weird thing is that if I save the translation and trigger the hot reload the translation work just fine like here. Also the translation is present in the file screenshot

Body:
In your i18n config, be sure to set returnObjects: true

example:

i18n
  ...
  .init({
    lng: "en",
    fallbackLng: "en",
    backend: {
      loadPath: `...`,
    },
    returnObjects: true,
    interpolation: {
      escapeValue: false,
    },
  });

and then your en json file would look like this...

{
  ...
  "days": ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]
}


问:
javascript sum values from two different functions
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

```<code>      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }
</code>```

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

```<code>function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

</code>```

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

```<code>      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }
</code>```

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

```<code>function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }
</code>```

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?

答:
```<code>      function showHourlyRate(showHourlyRate) {
            // ... do some more logic if needed
            return showHourlyRate
      };

      function showMileageRate(showMileageRate) {
            // ... do some more logic if needed
            return showMileageRate
      };

      function combinedTotal(hourlyRate,mileageRate){
            // ... do some more logic if needed
            return showHourlyRate(hourlyRate) + showMileageRate(mileageRate);
      }

      console.log(combinedTotal(5,20))
</code>```

Body:
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?


问:
Copying UDP traffic from a bound port
I have two applications that both bind to the same port to receive UDP traffic. I am able to change the listen port of one of the programs but not the other. I need both to be able to see the traffic.

I have tried using socat for this but have been unable to figure out how to get it to send a copy of the traffic to a different port without interfering with the program bound to the original port.

答: A few tricks come to mind, but when you are not able to change both receiving ports or the target port of the sender, you will need to use iptables to modify the port of the incoming packets. On that port Socat with sniffing (option -r) to a pipe and another Socat instance could solve your problem.</p>

Title: Copying UDP traffic from a bound port


问:
Split data frame string column into multiple columns (comma separated characters)
I am trying to split a column of comma separated characters into several columns (as many as different characters overall).
I read similar questions such as this:

Split data frame string column into multiple columns

But the solutions were based on a small number of possible characters, so that the new columns could be named in advanced before the columns was split.

This is my example:

```<code>subject <- c(1,2,3)
 letters <- c("a, b, f, g", "b, g, m, l", "g, m, z")

df1 <- data.frame(subject, letters)

df1

 subject    letters
1       1 a, b, f, g
2       2 b, g, m, l
3       3    g, m, z
</code>```

The desired result would be:

```<code>  subject a b f g m z
1       1 1 1 1 1 0 0
2       2 0 1 0 1 1 0
3       3 0 0 0 1 1 1
</code>```

Thanks in advance for any help.

答:
Another solution:</p>
```<code>library(dplyr)
library(tidyr)
df1 %>%
  mutate(row = row_number()) %>%
  separate_rows(letters, sep = ', ') %>%
  pivot_wider(names_from = letters, values_from = letters,
              values_fn = function(x) 1, values_fill = 0) %>%
  select(-row)
# A tibble: 3 × 8
  subject     a     b     f     g     m     l     z
    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1       1     1     1     1     1     0     0     0
2       2     0     1     0     1     1     1     0
3       3     0     0     0     1     1     0     1
</code>```

Body:
I am trying to split a column of comma separated characters into several columns (as many as different characters overall).
I read similar questions such as this:

Split data frame string column into multiple columns

But the solutions were based on a small number of possible characters, so that the new columns could be named in advanced before the columns was split.

This is my example:

subject <- c(1,2,3)
 letters <- c("a, b, f, g", "b, g, m, l", "g, m, z")

df1 <- data.frame(subject, letters)

df1

 subject    letters
1       1 a, b, f, g
2       2 b, g, m, l
3       3    g, m, z

The desired result would be:

  subject a b f g m z
1       1 1 1 1 1 0 0
2       2 0 1 0 1 1 0
3       3 0 0 0 1 1 1

Thanks in advance for any help.

Body:
Another solution:

library(dplyr)
library(tidyr)
df1 %>%
  mutate(row = row_number()) %>%
  separate_rows(letters, sep = ', ') %>%
  pivot_wider(names_from = letters, values_from = letters,
              values_fn = function(x) 1, values_fill = 0) %>%
  select(-row)
# A tibble: 3 × 8
  subject     a     b     f     g     m     l     z
    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1       1     1     1     1     1     0     0     0
2       2     0     1     0     1     1     1     0
3       3     0     0     0     1     1     0     1


问:
How can I have a users role change when they enter a pass code?
I have a table of users where each has a role (provided by the cancan gem). All new users are given the role of author.

I would like to be able to issue a sort of voucher code to certain users which when entered will change their role from author to admin.

Is there a way of doing this?

All the roles are already set up and can be changed by an existing admin by editing the users profile.

Thanks very much for any help its much appreciated!

答:
Here is an idea:

Generate a token for each user in the system and store it in the database. Make a form where user can submit his code. Then, in a controller, you may add role you want, if the code supplied by user corresponds to the one written in the database.


问:
Azure Load Balancer uses zone 1 since subscription xxx-xxx-xxx-xxx does not support zone 1 in location westus
I am trying to create a load balancer in Azure using terraform but I am getting this error:

Error: creating/updating Load Balancer "lbclassic" (Resource Group "apim-appGw-RG"): network.LoadBalancersClient#CreateOrUpdate: Failure sending request: StatusCode=0 -- Original Error: Code="SubscriptionDoesNotSupportZone" Message="Cannot create/move resource /subscriptions/xxx-xxx-xxx-xxx/resourceGroups/apim-appGw-RG/providers/Microsoft.Network/loadBalancers/lbclassic/frontendIPConfigurations/lbclassic which uses zone 1 since subscription xxx-xxx-xxx-xxx does not support zone 1 in location westus." Details=[]
│
│   with azurerm_lb.example,
│   on 12-lb.tf line 1, in resource "azurerm_lb" "example":
│    1: resource "azurerm_lb" "example" {

And here's my code sample:

```<code>resource "azurerm_lb" "example" {
  name                = "lbclassic"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  sku                 = "Standard"

  frontend_ip_configuration {
    name                          = "lbclassic"
    subnet_id                     = azurerm_subnet.lb.id
    private_ip_address_allocation = "Dynamic"
  }
}
</code>```

Can someone please help me on this?

答:
I was having the same issue. It only fails on West US

I fixed it by adding availability_zone ="No-Zone" under frontend_ip_configuration

```<code>frontend_ip_configuration {
name                          = "SQLFrontEnd"
#subnet_id                     = var.lb_azure_subnet_id
subnet_id=var.subnetid
private_ip_address_allocation = "Static"
private_ip_address            = var.sql_front_end_ip
availability_zone ="No-Zone"
</code>```

Body:
I am trying to create a load balancer in Azure using terraform but I am getting this error:

Error: creating/updating Load Balancer "lbclassic" (Resource Group "apim-appGw-RG"): network.LoadBalancersClient#CreateOrUpdate: Failure sending request: StatusCode=0 -- Original Error: Code="SubscriptionDoesNotSupportZone" Message="Cannot create/move resource /subscriptions/xxx-xxx-xxx-xxx/resourceGroups/apim-appGw-RG/providers/Microsoft.Network/loadBalancers/lbclassic/frontendIPConfigurations/lbclassic which uses zone 1 since subscription xxx-xxx-xxx-xxx does not support zone 1 in location westus." Details=[]
│
│   with azurerm_lb.example,
│   on 12-lb.tf line 1, in resource "azurerm_lb" "example":
│    1: resource "azurerm_lb" "example" {

And here's my code sample:

resource "azurerm_lb" "example" {
  name                = "lbclassic"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  sku                 = "Standard"

  frontend_ip_configuration {
    name                          = "lbclassic"
    subnet_id                     = azurerm_subnet.lb.id
    private_ip_address_allocation = "Dynamic"
  }
}

Can someone please help me on this?

Body:
I was having the same issue. It only fails on West US

I fixed it by adding availability_zone ="No-Zone" under frontend_ip_configuration

frontend_ip_configuration {
name                          = "SQLFrontEnd"
#subnet_id                     = var.lb_azure_subnet_id
subnet_id=var.subnetid
private_ip_address_allocation = "Static"
private_ip_address            = var.sql_front_end_ip
availability_zone ="No-Zone"


问:
Get a value of key from JSON response in Python
I am accessing an API through a get request from which I get a response.

This is my code:

```<code>import requests
import json
symbol = "AAPL"
end_point="https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/"+symbol+"?apiKey=my_key"

r=requests.get(end_point).json()

print(r)
print(r['min'])
</code>```

print(r) returned:

```<code>{'request_id': '2735c0be51de7719fd99460fe8696080', 'status': 'OK', 'ticker': {'day': {'c': 172.93, 'h': 175.48, 'l': 172.37, 'o': 174.14, 'v': 65575561, 'vw': 174.0984}, 'lastQuote': {'P': 172.83, 'S': 3, 'p': 172.82, 's': 1, 't': 1644524332922450142}, 'lastTrade': {'c': None, 'i': '139592', 'p': 172.8199, 's': 2014, 't': 1644524331573573011, 'x': 4}, 'min': {'av': 65559987, 'c': 172.9, 'h': 173.14, 'l': 172.89, 'o': 173.09, 'v': 107429, 'vw': 173.0138}, 'prevDay': {'c': 176.28, 'h': 176.65, 'l': 174.9, 'o': 176.05, 'v': 71204538, 'vw': 175.8287}, 'ticker': 'AAPL', 'todaysChange': -3.46, 'todaysChangePerc': -1.963, 'updated': 1644524331573573011}}
</code>```

but when I try to access the key "min", I get key error:

```<code>KeyError: 'min'
</code>```

This is super-simple. What am I doing wrong?

答:
Please try:</p>
```<code>r['ticker']['min']
</code>```

Body:
I am accessing an API through a get request from which I get a response.

This is my code:

import requests
import json
symbol = "AAPL"
end_point="https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/"+symbol+"?apiKey=my_key"

r=requests.get(end_point).json()

print(r)
print(r['min'])

print(r) returned:

{'request_id': '2735c0be51de7719fd99460fe8696080', 'status': 'OK', 'ticker': {'day': {'c': 172.93, 'h': 175.48, 'l': 172.37, 'o': 174.14, 'v': 65575561, 'vw': 174.0984}, 'lastQuote': {'P': 172.83, 'S': 3, 'p': 172.82, 's': 1, 't': 1644524332922450142}, 'lastTrade': {'c': None, 'i': '139592', 'p': 172.8199, 's': 2014, 't': 1644524331573573011, 'x': 4}, 'min': {'av': 65559987, 'c': 172.9, 'h': 173.14, 'l': 172.89, 'o': 173.09, 'v': 107429, 'vw': 173.0138}, 'prevDay': {'c': 176.28, 'h': 176.65, 'l': 174.9, 'o': 176.05, 'v': 71204538, 'vw': 175.8287}, 'ticker': 'AAPL', 'todaysChange': -3.46, 'todaysChangePerc': -1.963, 'updated': 1644524331573573011}}

but when I try to access the key "min", I get key error:

KeyError: 'min'

This is super-simple. What am I doing wrong?

Body:
Please try:

r['ticker']['min']


问:
find the paragraph and url in text using beautfulsoup and put in the dataframe
I want to extract the paragraph in this XML file (between

 tags)

```<code>'<p>jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}</p>\n<p>center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.</p>\n<p><img src="https://cdn.mathpix.com/cropped/2022_01_11_c20225c6c8f29d2e0e54g-1.jpg?height=608&width=332&top_left_y=642&top_left_x=440" alt="" />

</code>```

and put them in one column of dataframe, in the second column I want to collect the URL that existed in the text

here is my file  which I read it so

```<code>with open('../AN_markdown/kapitel_{0}.mmd'.format(ch), 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)
</code>```

I used beautifulsoup but still can not add link, here is my code

```<code>from bs4 import BeautifulSoup
text = BeautifulSoup(rendered,'html.parser')
para=[]
for p in text.find_all("p"):
     para.append(p)

df = pd.DataFrame({"Paragraphs":para})

</code>```

it only find the paragraph, I do not know how to extract the link and add them as column behind the paragraph

thank you in advance

```<code></code>```

答:
It turns out I can do it using "BeautifulSoup" and "mistletoe", here is my code:

```<code>from pathlib import Path
import pandas as pd
from bs4 import BeautifulSoup
import mistletoe
with open(my_file, 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)
XML = BeautifulSoup(rendered,'html.parser')
para=XML.find_all("p")
df = pd.DataFrame({"Paragraphs":para})
df = df.rename(columns={"0":'Paragraph'})

</code>```
```<code>def urlFinder(text):
    links=[]
    for link in text.find_all('img'):
        #print(link.get('src'))
        links.append(link.get('src'))
    return(links)
</code>```
```<code>df['Links'] = df['Paragraphs'].apply(lambda x: urlFinder(x))
</code>```

however, the solution of @Martin Evans is also perfect!

here is my result:

Body:
I want to extract the paragraph in this XML file (between

 tags)

'
jo\\section{$430 \\quad$ Part $4 \\quad$ The First Inequality, from Physical Causes}
\n
center $A$, with radius $A M$, let the arc $M N$ be described, intersecting $P V$ at $O$, and $P B$ at $N$. So, by analogy with the above, just as we are taking I in place of F, let us now take $N$ for $O$, and let us consider that just as $A N$ is the correct distance in length, it is also correct in position. Now the points $I, N$, and the like do indeed make the planet\'s path puff-cheeked. For the arcs $G D$ and $Q P$ are equal. And $B D, B P$, projected from a common center, intersect the lunule cut off. But DI and PN, the breadths of the lunule extended towards the center are unequal. And DI is smaller breadihs of the lunule extended towaras the center, are unequal. And DI is smaller, and $P N$ greater. For since $E D$ and $M P$ are equal, and $E D I, M P N$ are right, while EI is a greater circle, since its radius $A E$ is greater, and $M N$ is a smaller circle, since its radius AM is smaller, therefore, PN will definitely be greater, and DI smaller. Therefore the lunule cut off is narrower above at $D$ and broader belowe at $P$. In Therefore, the lunule cut off is narrower above, at $D$, and broader below, at $P$. In the ellipse, in contrast, this iunule is of equal breadth at points equally removed from the apsides $G$ and $Q .$ So it is clear that the path is puff-cheeked, so it is not an ellipse. And since the ellipse gives the correct equations, this puff-cheeked path should by rights give incorrect ones.
\n

and put them in one column of dataframe, in the second column I want to collect the URL that existed in the text

here is my file  which I read it so

with open('../AN_markdown/kapitel_{0}.mmd'.format(ch), 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)

I used beautifulsoup but still can not add link, here is my code

from bs4 import BeautifulSoup
text = BeautifulSoup(rendered,'html.parser')
para=[]
for p in text.find_all("p"):
     para.append(p)

df = pd.DataFrame({"Paragraphs":para})

it only find the paragraph, I do not know how to extract the link and add them as column behind the paragraph

thank you in advance

Body:
It turns out I can do it using "BeautifulSoup" and "mistletoe", here is my code:

from pathlib import Path
import pandas as pd
from bs4 import BeautifulSoup
import mistletoe
with open(my_file, 'r',encoding='utf-8') as fin:
    rendered = mistletoe.markdown(fin)
XML = BeautifulSoup(rendered,'html.parser')
para=XML.find_all("p")
df = pd.DataFrame({"Paragraphs":para})
df = df.rename(columns={"0":'Paragraph'})

def urlFinder(text):
    links=[]
    for link in text.find_all('img'):
        #print(link.get('src'))
        links.append(link.get('src'))
    return(links)

df['Links'] = df['Paragraphs'].apply(lambda x: urlFinder(x))

however, the solution of @Martin Evans is also perfect!

here is my result:


问:
Postgres array intersection queries performance
I have a int[] column, category_ids, which has a cardinality of 5.

I have users which look for products that match certain category_ids, and I'm currently returning results based on intersection between the ids they request and ids that match in category_ids. Currently we have only 14 categories, but soon will be adding a lot more (~40). So, if a user wants to find 38/40 categories, that seems like it will be hairy.

I'm trying to learn more about arrays, but completely lost on indexing for this type of querying. How can I improve performance for this kind of query?

Basic high level example would be find me products that match category_ids [1..35], and finding it via array overlaps user_requested_category_ids && my_table.category_ids

答:
There is no simple an efficient way to do this. You'll have to unnest both arrays and intersect the result.

My recommendation is to avoid data models where you store references to other data in arrays. Instead, use a “junction table” to model m:n relationships. That is the natural way to do it, and your queries will become simple and probably more efficient. Also, you can define foreign key constraints that way, so that you cannot end up with inconsistent data.


问:
NOT GROUP By issue
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

```<code>SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0
</code>```

答:
I'd simply use a derived table, to save some typing and but also to reduce the risk of errors when repeating the same columns over and over again:

```<code>SELECT the_sum
FROM
(
    SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) / 3600 * 10) as the_sum
    FROM FACT_WLT_AGENT
    JOIN dim_reorganization reorg
      ON FACT_WLT_AGENT.reorg_id = reorg.reorg_id
    WHERE is_last_master_reorg    = 'Y
) dt
WHERE the_sum > 0;
</code>```

Note the explicit JOIN syntax! Easier to write (without errors), easier to read and maintain, and easier to convert to outer join if needed!

Title: NOT GROUP By issue

Body:
I try to make a sum in this formula but I have one issue, not group by expression ?

WHo is the problem ?

SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) /
         3600 * 10
       )
FROM FACT_WLT_AGENT,
     dim_reorganization reorg
WHERE FACT_WLT_AGENT.reorg_id = reorg.reorg_id
  AND is_last_master_reorg    = 'Y'
HAVING FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
       FACT_WLT_AGENT.WLT_LHV_PO_ENA +
       FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
       FACT_WLT_AGENT.WLT_LHV_PO_PAQ /
       3600 > 0

Body:
I'd simply use a derived table, to save some typing and but also to reduce the risk of errors when repeating the same columns over and over again:

SELECT the_sum
FROM
(
    SELECT ROUND( SUM( FACT_WLT_AGENT.WLT_LHV_PO_FNGF +
                   FACT_WLT_AGENT.WLT_LHV_PO_ENA +
                   FACT_WLT_AGENT.WLT_LHV_PO_EEIND +
                   FACT_WLT_AGENT.WLT_LHV_PO_PAQ
              ) / 3600 * 10) as the_sum
    FROM FACT_WLT_AGENT
    JOIN dim_reorganization reorg
      ON FACT_WLT_AGENT.reorg_id = reorg.reorg_id
    WHERE is_last_master_reorg    = 'Y
) dt
WHERE the_sum > 0;

Note the explicit JOIN syntax! Easier to write (without errors), easier to read and maintain, and easier to convert to outer join if needed!


问:
This is the response getting from a server. I am trying get value of an atribute Folio ID. How can we get using PHP
I am getting below response from server and want extract attribute value from it. When I am using simplexml_load_string and DOMDocument it gives only  PersonName & HKStatus outout.

XML

```<code><OTA_ResRetrieveRS EchoToken="a" TimeStamp="2022-02-10T18:49:29+05:30" Version="0.0" Target="Test" xmlns="http://www.example.com/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/OTA/2003/05 OTA_ResRetrieveRS.xsd">
  <Success/>
  <ReservationsList>
   <HotelReservation ResStatus="In-house" RoomStayReservation="true" WalkInIndicator="true" CreatorID="roommaster:17.10">
    <RoomStays>
     <RoomStay MarketCode="UNK" SourceOfBusiness="WALK">
      <RoomTypes>
       <RoomType IsRoom="true" RoomTypeCode="KNG" RoomID="100"/>
      </RoomTypes>
      <RatePlans>
       <RatePlan RatePlanCode="RACK"/>
      </RatePlans>
      <GuestCounts>
       <GuestCount AgeQualifyingCode="10" Count="1"/>
      </GuestCounts>
      <TimeSpan Start="2022-02-10" End="2022-02-14"/>
     </RoomStay>
    </RoomStays>
    <ResGuests>
     <ResGuest PrimaryIndicator="true">
      <Profiles>
       <ProfileInfo>
        <UniqueID Type="10" ID="100000" ID_Context="roommaster"/>
        <Profile>
         <Customer>
          <PersonName>
          <NamePrefix>Mr</NamePrefix>
          <GivenName>Sanya</GivenName>
          <Surname>Raj</Surname>
          </PersonName>
         </Customer>
        </Profile>
       </ProfileInfo>
      </Profiles>
     </ResGuest>
    </ResGuests>
    <ResGlobalInfo>
     <Guarantee GuaranteeCode="CASH">
      <GuaranteesAccepted>
       <GuaranteeAccepted GuaranteeIndicator="true" PaymentTransactionTypeCode="CASH" GuaranteeTypeCode="1"/>
      </GuaranteesAccepted>
     </Guarantee>
     <HotelReservationIDs>
      <HotelReservationID ResID_Type="10" ResID_Value="100000-A" ResID_Source="roommaster" ResID_SourceContext="Master Folio"/>
     </HotelReservationIDs>
    </ResGlobalInfo>
    <TPA_Extensions>
     <HTNG>
      <ProfileMessageSummary Text="0"/>
     <HKStatus>Occupied</HKStatus>
     </HTNG>
     <Folios>
      <Folio ID="100000-A" Description="Master Folio" Balance="0"/>
     </Folios>
    </TPA_Extensions>
   </HotelReservation>
  </ReservationsList>
 </OTA_ResRetrieveRS>
</code>```

PHP

```<code>$bcdoc = new DOMDocument();
$bcdoc->loadXML($xml);
$warning = $bcdoc->getElementsByTagName('Warnings')->item(0);

if(empty($warning)){
    $FolioID = $bcdoc->getElementsByTagName('Folio')->item(0)->nodeValue;
    echo $FoliaID."\n";

}else{
    $warning = $bcdoc->getElementsByTagName('Warnings')->item(0)->nodeValue;
    echo $warning."\n";
}
</code>```

Only PersonName and HKstatus get output. I have used simplexml also to extract atribute but same result. What is the function can be used to extract attributes? Any idea how can I get value of Folio ID? In above example it is 100000-A.

答:
The function you are looking for is getAttribute, but because getElementsByTagName returns an array, you will either need to get the first item or loop through the list if you have multiple folios.

```<code>$bcdoc = new DOMDocument();
$bcdoc->loadXML($xml);
$warning = $bcdoc->getElementsByTagName('Warnings')->item(0);

if (empty($warning)) {
  $FolioID  = $bcdoc->getElementsByTagName('Folio')[0]->getAttribute('ID');
  echo $FolioID . "\n";
} else {
  $warning = $bcdoc->getElementsByTagName('Warnings')->item(0)->nodeValue;
  echo $warning . "\n";
}

</code>```

Body:
I am getting below response from server and want extract attribute value from it. When I am using simplexml_load_string and DOMDocument it gives only  PersonName & HKStatus outout.

XML

<OTA_ResRetrieveRS EchoToken="a" TimeStamp="2022-02-10T18:49:29+05:30" Version="0.0" Target="Test" xmlns="http://www.example.com/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/OTA/2003/05 OTA_ResRetrieveRS.xsd">
  <Success/>
  <ReservationsList>
   <HotelReservation ResStatus="In-house" RoomStayReservation="true" WalkInIndicator="true" CreatorID="roommaster:17.10">
    <RoomStays>
     <RoomStay MarketCode="UNK" SourceOfBusiness="WALK">
      <RoomTypes>
       <RoomType IsRoom="true" RoomTypeCode="KNG" RoomID="100"/>
      </RoomTypes>
      <RatePlans>
       <RatePlan RatePlanCode="RACK"/>
      </RatePlans>
      <GuestCounts>
       <GuestCount AgeQualifyingCode="10" Count="1"/>
      </GuestCounts>
      <TimeSpan Start="2022-02-10" End="2022-02-14"/>
     </RoomStay>
    </RoomStays>
    <ResGuests>
     <ResGuest PrimaryIndicator="true">
      <Profiles>
       <ProfileInfo>
        <UniqueID Type="10" ID="100000" ID_Context="roommaster"/>
        <Profile>
         <Customer>
          <PersonName>
          <NamePrefix>Mr</NamePrefix>
          <GivenName>Sanya</GivenName>
          <Surname>Raj</Surname>
          </PersonName>
         </Customer>
        </Profile>
       </ProfileInfo>
      </Profiles>
     </ResGuest>
    </ResGuests>
    <ResGlobalInfo>
     <Guarantee GuaranteeCode="CASH">
      <GuaranteesAccepted>
       <GuaranteeAccepted GuaranteeIndicator="true" PaymentTransactionTypeCode="CASH" GuaranteeTypeCode="1"/>
      </GuaranteesAccepted>
     </Guarantee>
     <HotelReservationIDs>
      <HotelReservationID ResID_Type="10" ResID_Value="100000-A" ResID_Source="roommaster" ResID_SourceContext="Master Folio"/>
     </HotelReservationIDs>
    </ResGlobalInfo>
    <TPA_Extensions>
     <HTNG>
      <ProfileMessageSummary Text="0"/>
     <HKStatus>Occupied</HKStatus>
     </HTNG>
     <Folios>
      <Folio ID="100000-A" Description="Master Folio" Balance="0"/>
     </Folios>
    </TPA_Extensions>
   </HotelReservation>
  </ReservationsList>
 </OTA_ResRetrieveRS>

PHP

$bcdoc = new DOMDocument();
$bcdoc->loadXML($xml);
$warning = $bcdoc->getElementsByTagName('Warnings')->item(0);

if(empty($warning)){
    $FolioID = $bcdoc->getElementsByTagName('Folio')->item(0)->nodeValue;
    echo $FoliaID."\n";

}else{
    $warning = $bcdoc->getElementsByTagName('Warnings')->item(0)->nodeValue;
    echo $warning."\n";
}

Only PersonName and HKstatus get output. I have used simplexml also to extract atribute but same result. What is the function can be used to extract attributes? Any idea how can I get value of Folio ID? In above example it is 100000-A.

Body:
The function you are looking for is getAttribute, but because getElementsByTagName returns an array, you will either need to get the first item or loop through the list if you have multiple folios.

$bcdoc = new DOMDocument();
$bcdoc->loadXML($xml);
$warning = $bcdoc->getElementsByTagName('Warnings')->item(0);

if (empty($warning)) {
  $FolioID  = $bcdoc->getElementsByTagName('Folio')[0]->getAttribute('ID');
  echo $FolioID . "\n";
} else {
  $warning = $bcdoc->getElementsByTagName('Warnings')->item(0)->nodeValue;
  echo $warning . "\n";
}


问:
The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1
I'm getting this below warning message in my Xcode 10.1.

The iOS Simulator deployment targets are set to 7.0, but the range of supported deployment target versions for this platform is 8.0 to 12.1.

My simulator os in 12.1
Xcode 10.1

And I updated my pod file.

My deployment target is 9.0

In my target

答:
Xcode > Runner > Info deployment Target > IOS Deployment Target: 11
.

open terminal :

```<code>pod cache clean --all
</code>```

.

```<code>pod update
</code>```

Body:
Xcode > Runner > Info deployment Target > IOS Deployment Target: 11
.

open terminal :

pod cache clean --all

.

pod update


问:
Python script repeat
I have an LED strip on a raspberry and would like to indicate the status of the internet on the LED strip by means of a color.

Now I came up with this:

```<code>import os
hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:
    exec(open("random_blink.py").read())

else:
    exec(open("random_blink_colours.py").read())
</code>```

How can I get the script to rerun every 10 seconds?

答:
I'm sure there's a better way to do it but I would try</p>
```<code>import os, time
hostname = "google.com" #example

while True:
    response = os.system("ping -c 1 " + hostname)

    #and then check the response...

    if response == 0:
        exec(open("random_blink.py").read())
        time.sleep(10)

    else:
        exec(open("random_blink_colours.py").read())
</code>```

Title: Python script repeat

Body:
I have an LED strip on a raspberry and would like to indicate the status of the internet on the LED strip by means of a color.

Now I came up with this:

import os
hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:
    exec(open("random_blink.py").read())

else:
    exec(open("random_blink_colours.py").read())

How can I get the script to rerun every 10 seconds?

Body:
I'm sure there's a better way to do it but I would try

import os, time
hostname = "google.com" #example

while True:
    response = os.system("ping -c 1 " + hostname)

    #and then check the response...

    if response == 0:
        exec(open("random_blink.py").read())
        time.sleep(10)

    else:
        exec(open("random_blink_colours.py").read())


问:
I need to return the string instead of True in Haskell
I have a list of sentences and need to print the quotes with the 'theWord' include inside.
it returns True but I need to see the sentences.

```<code>myList = ["hello world","good boy","good night"]

theWord = "good"

theQuote = filter (==True) (map (isInfixOf theWord) myList)
</code>```

output:

```<code>*Main> theQuote

[True,True]
</code>```

答:
The filter takes a predicate to check what items to retain, you thus can use isInfixOf theWord as predicate:

```<code>theQuote :: [String]
theQuote = filter <strong>(isInfixOf theWord)</strong> myList</code>```

Body:
I have a list of sentences and need to print the quotes with the 'theWord' include inside.
it returns True but I need to see the sentences.

myList = ["hello world","good boy","good night"]

theWord = "good"

theQuote = filter (==True) (map (isInfixOf theWord) myList)

output:

*Main> theQuote

[True,True]

Body:
The filter takes a predicate to check what items to retain, you thus can use isInfixOf theWord as predicate:

theQuote :: [String]
theQuote = filter (isInfixOf theWord) myList


答:
```<code>import os, time

hostname = "google.com"

while True:
    response = os.system("ping -c 1 " + hostname)

    if response == 0:
        exec(open("random_blink.py","r").read())

    else:
        exec(open("random_blink_colours.py","r").read())

    time.sleep(10)

</code>```

Should do the work

Title: Python script repeat

Body:
import os, time

hostname = "google.com"

while True:
    response = os.system("ping -c 1 " + hostname)

    if response == 0:
        exec(open("random_blink.py","r").read())

    else:
        exec(open("random_blink_colours.py","r").read())

    time.sleep(10)

Should do the work


答:
isInfix theWord is the predicate to pass to filter, which should iterate over the list itself.

```<code>theQuote = filter (isInfixOf theWord) myList
</code>```

Title: I need to return the string instead of True in Haskell

Body:
isInfix theWord is the predicate to pass to filter, which should iterate over the list itself.

theQuote = filter (isInfixOf theWord) myList


答:
the key min is inside ticker. Do this:

```<code>r['ticker']['min']
</code>```

Title: Get a value of key from JSON response in Python

Body:
the key min is inside ticker. Do this:

r['ticker']['min']


问:
Scrollable table with Vue.js
So I have table which gets filled using vue.js v-for method:

```<code><table>
  <tr><th>Name</th><th>Surname</th></tr>
  <tr v-for="user in users"><td>@{{user.name}}</td><td>@{{user.surname}}</td></tr>
</table>
</code>```

And I need this table to be maximum 300px in height, and if it gets longer, it becomes scrollable.

So basically I need to set max-height and overflow:auto parameters in my css, but the problem is that the code does not "see" this table appropriately because it is rendered with vue.

So far I've tried just adding parameters in css and adding them dynamically after loading the table; none of these worked.

But, if I call $('table').height(), it returns the actual height of the rendered table. Maybe I can use it somehow?

Would highly appreciate any possible help!

答:
package.json

"cssnano-preset-default": {
      "version": "4.0.7",
      ...
        "postcss-calc": "^7.0.1",
```
<p>Wrap <code><b-table</code> or <code><table></code> with <code><template></code> then <code><div></code> and add <code>css</code></p>
<p>table.vue</p>
```
<template>

    <b-table

</template>

```

Title: Scrollable table with Vue.js

Body:
So I have table which gets filled using vue.js v-for method:

Name	Surname

@{{user.name}}	@{{user.surname}}

And I need this table to be maximum 300px in height, and if it gets longer, it becomes scrollable.

So basically I need to set max-height and overflow:auto parameters in my css, but the problem is that the code does not "see" this table appropriately because it is rendered with vue.

So far I've tried just adding parameters in css and adding them dynamically after loading the table; none of these worked.

But, if I call $('table').height(), it returns the actual height of the rendered table. Maybe I can use it somehow?

Would highly appreciate any possible help!

Body:
package.json

"cssnano-preset-default": {
      "version": "4.0.7",
      ...
        "postcss-calc": "^7.0.1",

Wrap <b-table or <table> with <template> then <div> and add css

table.vue

<!--wrapper--->
<template>
  <div>
    <b-table
      <!--...--->
    </b-table>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";

export default {
  name: "data-table",
  props: ["pageSource"],
  middleware: ["auth", "enable"],
  computed: {
    ...mapGetters(["loggedInUser", "userSettings"]),
  }
  <!--...--->
}
</script

<!-- css at bottom of page -->
<style lang="scss" scoped>

.b-table {
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}
</style>


问:
Xamarin Android RequestPermissions( ) doesn't work 2nd time. No permissions popup Dialog 2nd time
I am writing a Xamarin (android flavor) app, OS 12, and am trying to call ActivityCompat.RequestPermissions. Maybe I'm expecting the wrong behavior, since I'm not familiar with this stuff. I expect no matter how many times I run the app, that calling ActivityCompat.RequestPermissions( xxx, yyy, 1 ) will popup a system OS dialog box and ask the user to permit or deny the permissions I specify...

In my MainActivity for my Xamarin Forms (android) app, I correctly init Xamarin Essentials...

I override OnRequestPermissionsResult( )....

Now, in my one LoginViewModel, I call back into MainActivity (via a callback) and inside THAT callback, in MainActivity, it calls

```<code>public void Foo()
{
    foreach (string s in m_szNeededAppPermissions)
    {
        bool b = ActivityCompat.ShouldShowRequestPermissionRationale(this, s);
        System.Diagnostics.Debug.WriteLine("should show request for " + s + ", = " + b);
    }
    ActivityCompat.RequestPermissions(this, m_szNeededAppPermissions.ToArray(), 1);
}
</code>```

Not that big of a deal, right? First time I run the app, the OS dialog for allowing permissions work GREAT. Now if I press "Deny" in those permissions dialogs, I get called back with OnRequestPermissionsResult( ) and the grantResults are -1. Super, that's what I'd expect.

Now, if I stop the app debugging and run it AGAIN, the 2nd time it calls Foo( ) which calls ActivityCompat.RequestPermissions( ), I get a callback immediately with OnRequestPermissionsResult( ) with denied grantResults. No OS dialogs. If I go in and delete the app and re-start debugging, I DO get the OS permission dialogs again.

I think it's because when I say "No" to the 1st-run OS permissions dialogs, it's taking that answer as "never ask again". I think somehow the OS itself is remembering not to show the OS dialogs a 2nd time, even though i'm ASKING it to! How weird!

I think my expectations must be off, or I'm missing 1 key step. Can anybody explain why?

```<code>public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    // OS dialog ran and told us which permissions user accepted vs which ones they denied.
    // We look at them and then call back with whether they all succeeded or not.

    bool bGotAllPermissions = true;
    foreach( Permission p in grantResults )
    {
        if( p != Permission.Granted )
        {
            bGotAllPermissions = false;
            break;
        }
    }

    // ps.OnRequestPermissionsResult(bGotAllPermissions);
}
</code>```

here is the main activity:

```<code>public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ICallbackApp
{
    PermissionsService ps;
    string[] m_szNeededAppPermissions = { Manifest.Permission.AccessFineLocation, Manifest.Permission.BluetoothAdmin };

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        DependencyService.RegisterSingleton<ICallbackApp>(this);

        ps = new PermissionsService(this, m_szNeededAppPermissions);

        LoadApplication(new App());
    }
</code>```

and in the view model:

```<code>public LoginViewModel()
{
    LoginCommand = new Command(OnLoginClicked);

    // m_pCrossPlatUtils = DependencyService.Get<ICrossPlatUtils>();
    // RefreshPermissions();

    Foo();
}

public void Foo()
{
    ICallbackApp p = DependencyService.Get<ICallbackApp>();
    p.Foo();
}
</code>```

答:
The answer these days is different than it used to be. Both iOS and Android are getting tighter about "bugging users for permissions". If you open the system OS permissions dialog to ask the user for permission, if they Deny them, then on successive runs of the app, or future usages of RequestPermissions( ), it WILL NOT SHOW the OS permissions dialog for those permissions that were denied previously! Yeah. That.

The only ways around this, if your app needs those permissions to run are:

Ask the user to reinstall the app

Bring up the app's settings pages and ask them to "fix it themselves", and then verify it is fixed when the user returns to the temporarily backgrounded app (backgrounded in order to show the App's settings page)

I think this is all true, I got it from a pretty reliable Xamarin source @ MSFT....

Body:
I am writing a Xamarin (android flavor) app, OS 12, and am trying to call ActivityCompat.RequestPermissions. Maybe I'm expecting the wrong behavior, since I'm not familiar with this stuff. I expect no matter how many times I run the app, that calling ActivityCompat.RequestPermissions( xxx, yyy, 1 ) will popup a system OS dialog box and ask the user to permit or deny the permissions I specify...

In my MainActivity for my Xamarin Forms (android) app, I correctly init Xamarin Essentials...

I override OnRequestPermissionsResult( )....

Now, in my one LoginViewModel, I call back into MainActivity (via a callback) and inside THAT callback, in MainActivity, it calls

public void Foo()
{
    foreach (string s in m_szNeededAppPermissions)
    {
        bool b = ActivityCompat.ShouldShowRequestPermissionRationale(this, s);
        System.Diagnostics.Debug.WriteLine("should show request for " + s + ", = " + b);
    }
    ActivityCompat.RequestPermissions(this, m_szNeededAppPermissions.ToArray(), 1);
}

Not that big of a deal, right? First time I run the app, the OS dialog for allowing permissions work GREAT. Now if I press "Deny" in those permissions dialogs, I get called back with OnRequestPermissionsResult( ) and the grantResults are -1. Super, that's what I'd expect.

Now, if I stop the app debugging and run it AGAIN, the 2nd time it calls Foo( ) which calls ActivityCompat.RequestPermissions( ), I get a callback immediately with OnRequestPermissionsResult( ) with denied grantResults. No OS dialogs. If I go in and delete the app and re-start debugging, I DO get the OS permission dialogs again.

I think it's because when I say "No" to the 1st-run OS permissions dialogs, it's taking that answer as "never ask again". I think somehow the OS itself is remembering not to show the OS dialogs a 2nd time, even though i'm ASKING it to! How weird!

I think my expectations must be off, or I'm missing 1 key step. Can anybody explain why?

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

    // OS dialog ran and told us which permissions user accepted vs which ones they denied.
    // We look at them and then call back with whether they all succeeded or not.

    bool bGotAllPermissions = true;
    foreach( Permission p in grantResults )
    {
        if( p != Permission.Granted )
        {
            bGotAllPermissions = false;
            break;
        }
    }

    // ps.OnRequestPermissionsResult(bGotAllPermissions);
}

here is the main activity:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ICallbackApp
{
    PermissionsService ps;
    string[] m_szNeededAppPermissions = { Manifest.Permission.AccessFineLocation, Manifest.Permission.BluetoothAdmin };

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        DependencyService.RegisterSingleton<ICallbackApp>(this);

        ps = new PermissionsService(this, m_szNeededAppPermissions);

        LoadApplication(new App());
    }

and in the view model:

public LoginViewModel()
{
    LoginCommand = new Command(OnLoginClicked);

    // m_pCrossPlatUtils = DependencyService.Get<ICrossPlatUtils>();
    // RefreshPermissions();

    Foo();
}

public void Foo()
{
    ICallbackApp p = DependencyService.Get<ICallbackApp>();
    p.Foo();
}


问:
Connect Azure CosmosDB using Managed Identities from Azure Function App both locally and on Azure
I create a Managed Identity for a Function app and assigned it to DocumentDB Account Contributor by following the two sections below

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#assign-a-system-assigned-managed-identity-to-a-function-app

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#grant-access-to-your-azure-cosmos-account

Microsoft.Azure.Services.AppAuthentication

I got an exception when I tried to run the code from the section below:

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#programmatically-access-the-azure-cosmos-db-keys

Could not load file or assembly 'System.Text.Encodings.Web,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
The system cannot find the file specified.
at
System.Text.Json.Serialization.Metadata.JsonPropertyInfo.DeterminePropertyName()
at
System.Text.Json.Serialization.Metadata.JsonPropertyInfo.GetPolicies(Nullable1 ignoreCondition, Nullable1 declaringTypeNumberHandling)    at
...
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at
Cosmos.Samples.AzureFunctions.AzureFunctionsCosmosClientMI.d__7.MoveNext()
in
C:.ME\MyLab.Code\AzureCode\CosmosDB\azure-cosmos-dotnet-v3-usage\AzureFunctions\AzureFunctionsCosmosClientMI.cs:line
85

Azure.Identity

Since AppAuthentication is not recommended by MS, then I switched to using Azure.Identity by following the links below:
https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet

https://joonasaijala.com/2021/07/01/how-to-using-managed-identities-to-access-cosmos-db-data-via-rbac-and-disabling-authentication-via-keys/

and the code below

```<code> static string cosmosUrl = "https://xxx.documents.azure.com:443/";
    private static CosmosClient client = new CosmosClient(cosmosUrl, new DefaultAzureCredential());
   var container = client.GetContainer("FamilyDatabase", "FamilyContainer");
        try
        {
            var result = await container.CreateItemAsync<Item>(data, new PartitionKey(data.LastName));
            return new OkObjectResult(result.Resource.Id);
        }
        catch (CosmosException cosmosException)
        {
            log.LogError("Creating item failed with error {0}", cosmosException.ToString());
            return new BadRequestObjectResult($"Failed to create item. Cosmos Status Code {cosmosException.StatusCode}, Sub Status Code {cosmosException.SubStatusCode}: {cosmosException.Message}.");
        }
</code>```

However, I got the exception below both locally and running it in Azure.

Failed to create item. Cosmos Status Code Forbidden, Sub Status Code
5301: Response status code does not indicate success: Forbidden (403);
Substatus: 5301; ActivityId: xxxx-bf03-4355-8642-5d316f9d3373;
Reason: (Request blocked by Auth xxxx : Request is blocked because
principal [xxx-2bff-44e9-97be-9ffeb3aae3ee] does not have
required RBAC permissions to perform action
[Microsoft.DocumentDB/databaseAccounts/readMetadata] on resource [/].
Learn more: https://aka.ms/cosmos-native-rbac. ActivityId:
xxx-bf03-4355-8642-5d316f9d3373,
Microsoft.Azure.Documents.Common/2.14.0, Windows/10.0.14393
cosmos-netstandard-sdk/3.24.1);.

Locally, I logged into VS following the link
https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#authenticating-via-visual-studio

Any idea for resolving issues with Azure.Identity?

Ref:

Connect Function App to CosmosDB with Managed Identity

https://github.com/Azure/azure-sdk-for-net/tree/Azure.Identity_1.5.0/sdk/identity/Azure.Identity/samples

答:
I ran into this same error this morning while setting up CosmosDB to use the Managed Identity of my Azure VM. The error message states that your principal does not have the RBAC permission Microsoft.DocumentDB/databaseAccounts/readMetadata. Once you give the principal you are using that permission authentication using Azure.Identity should work.

The DocumentDB Account Contributor doesn't have the role Microsoft.DocumentDB/databaseAccounts/readMetadata, and I couldn't find a built in Azure role that contained that permission so I created my own custom CosmosDBReadWrite role by following the example in this article.

To create the custom role definitions and assignments, you will need to have the Azure CLI installed.

Configuring Custom Role Definitions

Prepare JSON Role Definition File

First you will need to create a json file with the role definition. Here are 2 different custom role configuration json files, one for read-only access to the CosmosDB and the other has read-write role access.

Json file for read-only custom role

```<code>{
    "RoleName": "CosmosDBReadOnlyRole",
    "Type": "CustomRole",
    "AssignableScopes": ["/"],
    "Permissions": [{
        "DataActions": [
            "Microsoft.DocumentDB/databaseAccounts/readMetadata",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/read",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/executeQuery",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/readChangeFeed"
        ]
    }]
}
</code>```

Json file for read-write custom role

```<code>{
    "RoleName": "CosmosDBReadWriteRole",
    "Type": "CustomRole",
    "AssignableScopes": ["/"],
    "Permissions": [{
        "DataActions": [
            "Microsoft.DocumentDB/databaseAccounts/readMetadata",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*"
        ]
    }]
}
</code>```

Create and Assign Role Definition

After you have your json file saved with your custom role definition, we can create the custom role with the Azure CLI and then assign it to the correct principal.

Create your custom role using the JSON file you created above

```<code>resourceGroupName='<myResourceGroup>'
accountName='<myCosmosAccount>'
az cosmosdb sql role definition create -a $accountName -g $resourceGroupName -b @role-definition.json
</code>```

After you create the role, the definition of the created role should be returned. If not, use the following command to find the roleDefinitionId which can be found in the name property.

```<code>az cosmosdb sql role definition list --account-name $accountName -g $resourceGroupName
</code>```

Finally, apply the custom role to your principal that needs permission to access CosmosDB.

```<code>resourceGroupName='<myResourceGroup>'
accountName='<myCosmosAccount>'
roleDefinitionId = '<roleDefinitionId>'
principalId = '<ID for the Object that needs access to the CosmosDB>'
az cosmosdb sql role assignment create -a $accountName -g $resourceGroupName -s "/" -p $principalId -d $roleDefinitionId
</code>```

Hope this solves the error you are running into as well!

Body:
I create a Managed Identity for a Function app and assigned it to DocumentDB Account Contributor by following the two sections below

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#assign-a-system-assigned-managed-identity-to-a-function-app

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#grant-access-to-your-azure-cosmos-account

Microsoft.Azure.Services.AppAuthentication

I got an exception when I tried to run the code from the section below:

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#programmatically-access-the-azure-cosmos-db-keys

Could not load file or assembly 'System.Text.Encodings.Web,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
The system cannot find the file specified.
at
System.Text.Json.Serialization.Metadata.JsonPropertyInfo.DeterminePropertyName()
at
System.Text.Json.Serialization.Metadata.JsonPropertyInfo.GetPolicies(Nullable1 ignoreCondition, Nullable1 declaringTypeNumberHandling)    at
...
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at
Cosmos.Samples.AzureFunctions.AzureFunctionsCosmosClientMI.d__7.MoveNext()
in
C:.ME\MyLab.Code\AzureCode\CosmosDB\azure-cosmos-dotnet-v3-usage\AzureFunctions\AzureFunctionsCosmosClientMI.cs:line
85

Azure.Identity

Since AppAuthentication is not recommended by MS, then I switched to using Azure.Identity by following the links below:
https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet

https://joonasaijala.com/2021/07/01/how-to-using-managed-identities-to-access-cosmos-db-data-via-rbac-and-disabling-authentication-via-keys/

and the code below

 static string cosmosUrl = "https://xxx.documents.azure.com:443/";
    private static CosmosClient client = new CosmosClient(cosmosUrl, new DefaultAzureCredential());
   var container = client.GetContainer("FamilyDatabase", "FamilyContainer");
        try
        {
            var result = await container.CreateItemAsync<Item>(data, new PartitionKey(data.LastName));
            return new OkObjectResult(result.Resource.Id);
        }
        catch (CosmosException cosmosException)
        {
            log.LogError("Creating item failed with error {0}", cosmosException.ToString());
            return new BadRequestObjectResult($"Failed to create item. Cosmos Status Code {cosmosException.StatusCode}, Sub Status Code {cosmosException.SubStatusCode}: {cosmosException.Message}.");
        }

However, I got the exception below both locally and running it in Azure.

Failed to create item. Cosmos Status Code Forbidden, Sub Status Code
5301: Response status code does not indicate success: Forbidden (403);
Substatus: 5301; ActivityId: xxxx-bf03-4355-8642-5d316f9d3373;
Reason: (Request blocked by Auth xxxx : Request is blocked because
principal [xxx-2bff-44e9-97be-9ffeb3aae3ee] does not have
required RBAC permissions to perform action
[Microsoft.DocumentDB/databaseAccounts/readMetadata] on resource [/].
Learn more: https://aka.ms/cosmos-native-rbac. ActivityId:
xxx-bf03-4355-8642-5d316f9d3373,
Microsoft.Azure.Documents.Common/2.14.0, Windows/10.0.14393
cosmos-netstandard-sdk/3.24.1);.

Locally, I logged into VS following the link
https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#authenticating-via-visual-studio

Any idea for resolving issues with Azure.Identity?

Ref:

Connect Function App to CosmosDB with Managed Identity

https://github.com/Azure/azure-sdk-for-net/tree/Azure.Identity_1.5.0/sdk/identity/Azure.Identity/samples

Body:
I ran into this same error this morning while setting up CosmosDB to use the Managed Identity of my Azure VM. The error message states that your principal does not have the RBAC permission Microsoft.DocumentDB/databaseAccounts/readMetadata. Once you give the principal you are using that permission authentication using Azure.Identity should work.

The DocumentDB Account Contributor doesn't have the role Microsoft.DocumentDB/databaseAccounts/readMetadata, and I couldn't find a built in Azure role that contained that permission so I created my own custom CosmosDBReadWrite role by following the example in this article.

To create the custom role definitions and assignments, you will need to have the Azure CLI installed.

Configuring Custom Role Definitions

Prepare JSON Role Definition File

First you will need to create a json file with the role definition. Here are 2 different custom role configuration json files, one for read-only access to the CosmosDB and the other has read-write role access.

Json file for read-only custom role

{
    "RoleName": "CosmosDBReadOnlyRole",
    "Type": "CustomRole",
    "AssignableScopes": ["/"],
    "Permissions": [{
        "DataActions": [
            "Microsoft.DocumentDB/databaseAccounts/readMetadata",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/read",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/executeQuery",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/readChangeFeed"
        ]
    }]
}

Json file for read-write custom role

{
    "RoleName": "CosmosDBReadWriteRole",
    "Type": "CustomRole",
    "AssignableScopes": ["/"],
    "Permissions": [{
        "DataActions": [
            "Microsoft.DocumentDB/databaseAccounts/readMetadata",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*"
        ]
    }]
}

Create and Assign Role Definition

After you have your json file saved with your custom role definition, we can create the custom role with the Azure CLI and then assign it to the correct principal.

Create your custom role using the JSON file you created above

resourceGroupName='<myResourceGroup>'
accountName='<myCosmosAccount>'
az cosmosdb sql role definition create -a $accountName -g $resourceGroupName -b @role-definition.json

After you create the role, the definition of the created role should be returned. If not, use the following command to find the roleDefinitionId which can be found in the name property.

az cosmosdb sql role definition list --account-name $accountName -g $resourceGroupName

Finally, apply the custom role to your principal that needs permission to access CosmosDB.

resourceGroupName='<myResourceGroup>'
accountName='<myCosmosAccount>'
roleDefinitionId = '<roleDefinitionId>'
principalId = '<ID for the Object that needs access to the CosmosDB>'
az cosmosdb sql role assignment create -a $accountName -g $resourceGroupName -s "/" -p $principalId -d $roleDefinitionId

Hope this solves the error you are running into as well!


问:
Global Class for SQL enumerated objects
I'm working on a tool crib VB.NET project, my first real one, so I'm struggling with a few things.  In my SQL database I have a few tables that translate into enumerated fields.  For example I have code and code type tables.  I have a code type with CodeTypeID = 2 and description = Tool Status.  These are used to track the location of a tool; Shop, In Transit, On Site, Out of Service, etc.  I've set up enumerations for some of these.

```<code>Enum CodeType
    User = 1
    ToolStatus = 2
    Repair = 3
    OutOfService = 4
End Enum
ToolStatus
    Shop = 5
    Reserved = 6
    InTransit = 7
    OnSite = 9
    ReturnTransit = 10
    OutOfService = 11
    Repair = 12
End Enum
</code>```

The problem is if I change a code in SQL I then have to edit my enumerations as well.  In the SQL tables I am only storing the CodeID and join to the code table to get the description.  Other than an enumeration, I haven't found a good way to load these tables when the project opens that will allow me to code as easily, for example ToolStatus.OnSite to return the number 9 to my SQL table.  It just seems inefficient to me.  I always try to code my SQL procedures so if something changes I don't have to go and edit a bunch of procedures and would like to do the same here, especially as a simple addition of a new code could force a version update.  Is there a better way to do this?  I have searched the Internet and haven't found anything that really works as well as enumeration.

Example Code:
In the following code both OnSite and ReturnTransit are enumerations.
I'm moving items between two datagridviews, a Source and a Target DGV.  Also  updating the underlying shared datatable.

```<code>        Dim cbo As ComboBox = sender
        With cbo
            Select Case .Name
                Case "cboPeeps"
                    dvgFilter = "N"
                Case "cboToolbox"
                    For i As Integer = 0 To dtTools.Rows.Count - 1
                        dtTools.Rows(i)("dgvFilter") = dtTools.Rows(i)("dbFilter")
                    Next
                    If cbo.Items.Count > 0 Then
                        filter = "ToolboxID=" & .SelectedValue.ToString & " And ToolStatus=" & OnSite
                        filter += " And UserID=" & .SelectedItem("UserID").ToString
                    End If
                    dvgFilter = "T"
            End Select
        End With
    End If
    Dim result() As DataRow = dtTools.Select(filter)
    For i As Integer = 0 To result.Count - 1
        result(i)("dgvFilter") = dvgFilter
        If result(i)("dgvToolStatus") <> OutOfService Then result(i)("dgvToolStatus") = ReturnTransit
    Next
</code>```

答:
I was, of course, trying to make this way too difficult.  Simple solution along these lines.

```<code>Public Class Crepair
Public repairID As Integer
Public techID As Integer
Public repairCodeID As Integer
Public acceptedDate As Date
Public remarks As String
Public isComplete As Boolean
</code>```

End Class

```<code>        With nRepair
            .repairID = row.Cells("RepairID").Value
            .techID = row.Cells("TechID").Value
            .repairCodeID = row.Cells("RepairCodeID").Value
            .acceptedDate = row.Cells("AcceptedDate").Value
            .remarks = row.Cells("Remarks").Value
            .isComplete = row.Cells("IsComplete").Value
        End With
</code>```

Title: Global Class for SQL enumerated objects

Body:
I'm working on a tool crib VB.NET project, my first real one, so I'm struggling with a few things.  In my SQL database I have a few tables that translate into enumerated fields.  For example I have code and code type tables.  I have a code type with CodeTypeID = 2 and description = Tool Status.  These are used to track the location of a tool; Shop, In Transit, On Site, Out of Service, etc.  I've set up enumerations for some of these.

Enum CodeType
    User = 1
    ToolStatus = 2
    Repair = 3
    OutOfService = 4
End Enum
ToolStatus
    Shop = 5
    Reserved = 6
    InTransit = 7
    OnSite = 9
    ReturnTransit = 10
    OutOfService = 11
    Repair = 12
End Enum

The problem is if I change a code in SQL I then have to edit my enumerations as well.  In the SQL tables I am only storing the CodeID and join to the code table to get the description.  Other than an enumeration, I haven't found a good way to load these tables when the project opens that will allow me to code as easily, for example ToolStatus.OnSite to return the number 9 to my SQL table.  It just seems inefficient to me.  I always try to code my SQL procedures so if something changes I don't have to go and edit a bunch of procedures and would like to do the same here, especially as a simple addition of a new code could force a version update.  Is there a better way to do this?  I have searched the Internet and haven't found anything that really works as well as enumeration.

Example Code:
In the following code both OnSite and ReturnTransit are enumerations.
I'm moving items between two datagridviews, a Source and a Target DGV.  Also  updating the underlying shared datatable.

        Dim cbo As ComboBox = sender
        With cbo
            Select Case .Name
                Case "cboPeeps"
                    dvgFilter = "N"
                Case "cboToolbox"
                    For i As Integer = 0 To dtTools.Rows.Count - 1
                        dtTools.Rows(i)("dgvFilter") = dtTools.Rows(i)("dbFilter")
                    Next
                    If cbo.Items.Count > 0 Then
                        filter = "ToolboxID=" & .SelectedValue.ToString & " And ToolStatus=" & OnSite
                        filter += " And UserID=" & .SelectedItem("UserID").ToString
                    End If
                    dvgFilter = "T"
            End Select
        End With
    End If
    Dim result() As DataRow = dtTools.Select(filter)
    For i As Integer = 0 To result.Count - 1
        result(i)("dgvFilter") = dvgFilter
        If result(i)("dgvToolStatus") <> OutOfService Then result(i)("dgvToolStatus") = ReturnTransit
    Next

Body:
I was, of course, trying to make this way too difficult.  Simple solution along these lines.

Public Class Crepair
Public repairID As Integer
Public techID As Integer
Public repairCodeID As Integer
Public acceptedDate As Date
Public remarks As String
Public isComplete As Boolean

End Class

        With nRepair
            .repairID = row.Cells("RepairID").Value
            .techID = row.Cells("TechID").Value
            .repairCodeID = row.Cells("RepairCodeID").Value
            .acceptedDate = row.Cells("AcceptedDate").Value
            .remarks = row.Cells("Remarks").Value
            .isComplete = row.Cells("IsComplete").Value
        End With


问:
Mysql: Select all values alphabetically between two strings in a table
Okay let's say I have this in my table:

id
name

1
tom

2
anna

3
beatrice

4
robert

5
xavier

6
zoe

7
eustace

How can I select all ids of the names that are alphabetically sorted?

Say, select * from myTable where name "between" 'beatrice' and 'tom' order by name;

Should give me :

id
name

3
beatrice

7
eustace

4
robert

1
tom

Because in alphabetical order, those are in between 'beatrice' and 'tom'.

答:
If you only want the ID's you need:</p>
```<code>select id from myTable where name between 'beatrice' and 'tom' order by name;
</code>```

Body:
If you only want the ID's you need:

select id from myTable where name between 'beatrice' and 'tom' order by name;


问:
actionresult to refresh current page
From some of the action methods I want to return a result that will force current page to refresh.

I wrote this to acquire such result:

```<code> public class RefreshResult : ActionResult {

        public override void ExecuteResult(ControllerContext context) {
            Uri referrer = context.HttpContext.Request.UrlReferrer;
            if(referrer == null || string.IsNullOrEmpty(referrer.AbsoluteUri)) {
                return;
            }
            context.HttpContext.Response.Redirect(referrer.AbsoluteUri);
        }
    }
</code>```

In my action methods I simply return new RefreshResult. It works, but I am curious of the possible limitations of such approach. I am not intrested in giving customers an option to access action methods returning such results directly, so I think that I always will be able to refresh current page in such a way. Am I right?

I found this (and couple of other questions) on stackoverflow:
ActionResult return to page that called it

But I am more intrested in possible limitations of such approach, not in a "how to".

Thanx in advance

答:
I am not sure what do you mean by "result that will force current page to refresh". If you are executing action on server, you are already "refreshing" the page.

If what you want is some kind of post-redirect-get pattern in order to "land" on original page by GET action again, it is very easy - just implement your custom ActionResult as derived from RedirectToRouteResult (used by RedirectToAction() method on Controller), and supply it with current route values.

Your approach based on referrer is not entirely bad, but keep in mind that referrer is header sent by browser and can by optional in some clients (disabled in browser etc.), while current route values are always available to you.

Title: actionresult to refresh current page

Body:
From some of the action methods I want to return a result that will force current page to refresh.

I wrote this to acquire such result:

 public class RefreshResult : ActionResult {

        public override void ExecuteResult(ControllerContext context) {
            Uri referrer = context.HttpContext.Request.UrlReferrer;
            if(referrer == null || string.IsNullOrEmpty(referrer.AbsoluteUri)) {
                return;
            }
            context.HttpContext.Response.Redirect(referrer.AbsoluteUri);
        }
    }

In my action methods I simply return new RefreshResult. It works, but I am curious of the possible limitations of such approach. I am not intrested in giving customers an option to access action methods returning such results directly, so I think that I always will be able to refresh current page in such a way. Am I right?

I found this (and couple of other questions) on stackoverflow:
ActionResult return to page that called it

But I am more intrested in possible limitations of such approach, not in a "how to".

Thanx in advance


问:
Could not automatically select an Xcode project
When i type "pod install" in a correct directory I always get this

Analyzing dependencies

```<code>[!] Could not automatically select an Xcode project. Specify one in your Podfile like so:

    project 'path/to/Project.xcodeproj'
</code>```

podfile

```<code>platform :ios, '8.0'
use_frameworks!

target 'Posting' do
pod 'ALCameraViewController'

end
</code>```

I'm in the project directory where Podfile can be found.

答:
In my case project folder I was trying to run my project from was located in my usb, I moved the project from usb to Desktop also my project folder name was huge which I changed to concise like this

/Users/Untitled/abcxyz-123123/abcxyz-123123/

after that I changed it to

/Users/username/XYZ/

after that I ran 'pod install' and it worked!

Body:
When i type "pod install" in a correct directory I always get this

Analyzing dependencies

[!] Could not automatically select an Xcode project. Specify one in your Podfile like so:

    project 'path/to/Project.xcodeproj'

podfile

platform :ios, '8.0'
use_frameworks!

target 'Posting' do
pod 'ALCameraViewController'

end

I'm in the project directory where Podfile can be found.