问:
How can we find multiple used range addresses in one sheet?
How can we loop through all cells in a sheet and find multiple used range addresses on this one sheet? In this screen shot we have used ranges of B2:F17, I2:M17, Q2:U17, C19:M34, and Q19:U34. How can I identify these beginning and ending cell addresses of these five used ranges, and print them in an array of cells? I have some sample code that shows the total used range on a sheet.

```<code>Sub Vba_Used_Range()

Dim iCell As Range
Dim iRange As Range
Dim c As Long
Dim i As Long

Set iRange = ActiveSheet.UsedRange

For Each iCell In ActiveSheet.UsedRange
    c = c + 1
    If IsEmpty(iCell) = True Then
        i = i + 1
    End If
Next iCell

MsgBox "There are total " & c & _
" cell(s) in the range, and out of those " & _
i & " cell(s) are empty."

End Sub
</code>```

Again, how can I print cell addresses for multiple used ranges on one sheet?

答:
Empty Cells in Worksheet Regions

Inspired by userMT.

It is assumed that the regions contain values, not formulas.

Option Explicit

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the number of cells and the number of empty cells
'               of the worksheet regions containing values in a message box.
' Calls:        RefWorksheetValueRegions,CountEmptyCells.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub Vba_Used_Range()

    Dim ws As Worksheet: Set ws = ActiveSheet

    Dim uarg As Range: Set uarg = RefWorksheetValueRegions(ws)
    If uarg Is Nothing Then Exit Sub

    Dim ecCount As Long: ecCount = CountEmptyCells(uarg)

    MsgBox "There is a total of " & uarg.Cells.Count & _
        " cell(s) in the range, and out of those " & _
        ecCount & " cell(s) are empty."

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Creates a reference to the worksheet regions containing values.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefWorksheetValueRegions( _
    ByVal ws As Worksheet) _
As Range
    Const ProcName As String = "RefWorksheetValueRegions"
    On Error GoTo ClearError

    Dim turg As Range
    Dim curg As Range
    Dim arg As Range

    For Each arg In ws.UsedRange.SpecialCells(xlCellTypeConstants).Areas
'        Debug.Print "Area:       " & arg.Address
        If turg Is Nothing Then
            Set curg = arg.CurrentRegion
            Set turg = curg
        Else
            If Intersect(arg, curg) Is Nothing Then
                Set curg = arg.CurrentRegion
                Set turg = Union(turg, curg)
            End If
        End If
    Next arg

    If turg Is Nothing Then Exit Function

'    For Each arg In turg.Areas
'        Debug.Print "Total Area: " & arg.Address
'    Next arg

    Set RefWorksheetValueRegions = turg

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the number of empty cells of a range.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function CountEmptyCells( _
    ByVal mrg As Range) _
As Long
    Const ProcName As String = "CountEmptyCells"
    On Error GoTo ClearError

    Dim arg As Range
    Dim ecCount As Long

    For Each arg In mrg.Areas
        On Error Resume Next
            ecCount = ecCount + arg.SpecialCells(xlCellTypeBlanks).Count
        On Error GoTo ClearError
    Next arg

    CountEmptyCells = ecCount

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function
```

Body:
How can we loop through all cells in a sheet and find multiple used range addresses on this one sheet? In this screen shot we have used ranges of B2:F17, I2:M17, Q2:U17, C19:M34, and Q19:U34. How can I identify these beginning and ending cell addresses of these five used ranges, and print them in an array of cells? I have some sample code that shows the total used range on a sheet.

Sub Vba_Used_Range()

Dim iCell As Range
Dim iRange As Range
Dim c As Long
Dim i As Long

Set iRange = ActiveSheet.UsedRange

For Each iCell In ActiveSheet.UsedRange
    c = c + 1
    If IsEmpty(iCell) = True Then
        i = i + 1
    End If
Next iCell

MsgBox "There are total " & c & _
" cell(s) in the range, and out of those " & _
i & " cell(s) are empty."

End Sub

Again, how can I print cell addresses for multiple used ranges on one sheet?


来源: stackexchange

问:
Blank Page on Github Pages React App Start
I have a react app that runs perfectly on the local port, but when I upload it to github pages through npm I get nothing but a blank screen.

```<code>Failed to load resource: the server responded with a status of 404 ()
</code>```

I receive many 404 errors like these with no clear source. the page built fine, but it doesnt render anything.

heartlocket.github.io/IF

答:
The problem is that you reference resources(js, css) using absolute urls, with site route as base url, like /static/js/main.b9eb92d4.chunk.js, but your gh-pages actually published to subdirectory /IF/, so real location of your resources is like /IF/static/js/main.b9eb92d4.chunk.js

You can fix it several ways:

change all links to relative - i.e. remove leading slash character, like static/js/main.b9eb92d4.chunk.js

add directory to your absolute urls - like /IF/static/js/main.b9eb92d4.chunk.js

ContentLicense: CC BY-SA 4.0

Body:
I have a react app that runs perfectly on the local port, but when I upload it to github pages through npm I get nothing but a blank screen.

Failed to load resource: the server responded with a status of 404 ()

I receive many 404 errors like these with no clear source. the page built fine, but it doesnt render anything.

heartlocket.github.io/IF


问:
calculate cumulative sum until the selected date (represented by filter drop down list)
I'm traying to calculate cumulative sum for a Project until date selected in the filter.
My filter date is a drop down list and it shows like this for example:
July 2020
Aug 2020
.....

I have 2 tables: factworkinghours table and dimdates table.
enter image description here

and I want to calculate cumulative sum of total hours per Project.
for example if I have project #714 and I know this project took place from Jan 2020 until Fab 2020:

enter image description here

I want to get those result:

If my filter is on jan 2020 - I want to get 15.5 hours

If my filter is on fab 2020- I want to get 20.5 hours ( 15.5+5)

If  my filter is on Mar 2020- I want to get 20.5 hours since the Project ended and no total hours was added.

If my filter is on Dec 2019 I want to get 0 since the project hasn't started yet.

I tried to do write this dax but it's not working:

test hadar =
VAR _maxdate =
CALCULATE ( MAX ( dimDates[date]) ) // max date of the selected dates
return
CALCULATE (
[sum of total hours],
FILTER ( all( dimDates),  dimDates[date] <= _maxdate ))

hope this is understood ...
Thanks!

答:
You'll need to create a further table of dates to use in the slicer. This could be a new Calculated Table, SlicerDates, say, which is identical to dimDates and generated by

```<code>SlicerDates = dimDates
</code>```

Your slicer can then reference this table, choosing e.g. Month and Year from the hierarchy.

The required measure is then:

```<code>MyMeasure =
VAR SelectedMonthEnd =
    EOMONTH ( MIN ( SlicerDates[Date] ), 0 )
RETURN
    CALCULATE ( SUM ( 'Table'[TotalHours] ), dimDates[Date] <= SelectedMonthEnd )
</code>```

Body:
You'll need to create a further table of dates to use in the slicer. This could be a new Calculated Table, SlicerDates, say, which is identical to dimDates and generated by

SlicerDates = dimDates

Your slicer can then reference this table, choosing e.g. Month and Year from the hierarchy.

The required measure is then:

MyMeasure =
VAR SelectedMonthEnd =
    EOMONTH ( MIN ( SlicerDates[Date] ), 0 )
RETURN
    CALCULATE ( SUM ( 'Table'[TotalHours] ), dimDates[Date] <= SelectedMonthEnd )


问:
How can retrieve information about RAM,CPU, Disk usage from asp.net core on linux OS?
I need to retrieve total usage of system resource. On similar/other question told about calculation for specific process but I need info about total resource usage in system like in "Task Manager".  Environment is asp.net core API on Ubuntu 20.01.  How I can get it? I didn't find any info in documentation for .net core/asp.net core  >3.0.</p>

答:
There is no simple API for this, however you can read /proc/stat and calculate the CPU usage your self.

https://www.baeldung.com/linux/get-cpu-usage#2-getting-cpu-usage-using-procstat


问:
backtick " ` " in request body in bash shell script while calling CURL
I'm writing CURL COMMAND

HTTP_Method : POST

API : api/databricks/query

```<code>Request body  {"query":" GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }
</code>```

The query,I have execute using POSTMAN it's working

```<code>curl --location --request POST 'https://<databick_workspace-url>/api/sql/databricks/query' \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID` " }
# Working, And user can access DB
</code>```

I believe the problem is with backticks,

```<code>// Function
function grantReadAccess() {
  local path="/api/sql/databricks/query"
  local url="https://<databricks-workspace-url>/${path}"
  printf 'curl %q' "${url}"
  local DATABASENAME="DB-NAME"
  local userID="userID"

  local content="GRANT SELECT,READ_METADATA,USAGE on DATABASE \`${DATABASENAME}\` to \`${userID}\` "
  echo "------------$content"
  // OUTPUT Here : GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID`
  // Same I have to pass in request body
  local permissionToGroup=$(
    curl -X POST "${url}" -H "Authorization: Bearer ${authtoken}" -H "Content-Type: application/json" -d '{ "query": \"'"${content}"'\" } ')
    //Required in this {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

  echo "${permissionToGroup}"
}

// Tried In Postman insted of using backtick
 1. Single Quote "'" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE 'DB' to 'userID' "
 2. Blacket "(" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE (DB) to (userID) "

Error

{
  "query": "grant SELECT, READ_METADATA, USAGE on DATABASE 'DB' to 'useID' ",
    "data": null,
    "error": " org.apache.spark.sql.catalyst.parser.ParseException: \nOperation not allowed: grant(line 1, pos 0)\n\n== SQL ==\ngrant SELECT, READ_METADATA, USAGE on DATABASE 'DB"
}

</code>```

The above function is not working,

答:
Your question is not very clear, but I'll guess you're having problems in this part:

```<code>-d '{ "query": \"'"${content}"'\" } '
</code>```

That will get you literal backslashes before the double quotes around your content, since backslashes inside single quotes are inserted literally. You could swap that for -d '{ "query": "'"${content}"'" }' or -d "{ \"query\": \"${content}\" }"

Body:
I'm writing CURL COMMAND

HTTP_Method : POST

API : api/databricks/query

Request body  {"query":" GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

The query,I have execute using POSTMAN it's working

curl --location --request POST 'https://<databick_workspace-url>/api/sql/databricks/query' \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID` " }
# Working, And user can access DB

I believe the problem is with backticks,

// Function
function grantReadAccess() {
  local path="/api/sql/databricks/query"
  local url="https://<databricks-workspace-url>/${path}"
  printf 'curl %q' "${url}"
  local DATABASENAME="DB-NAME"
  local userID="userID"

  local content="GRANT SELECT,READ_METADATA,USAGE on DATABASE \`${DATABASENAME}\` to \`${userID}\` "
  echo "------------$content"
  // OUTPUT Here : GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID`
  // Same I have to pass in request body
  local permissionToGroup=$(
    curl -X POST "${url}" -H "Authorization: Bearer ${authtoken}" -H "Content-Type: application/json" -d '{ "query": \"'"${content}"'\" } ')
    //Required in this {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

  echo "${permissionToGroup}"
}

// Tried In Postman insted of using backtick
 1. Single Quote "'" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE 'DB' to 'userID' "
 2. Blacket "(" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE (DB) to (userID) "

Error

{
  "query": "grant SELECT, READ_METADATA, USAGE on DATABASE 'DB' to 'useID' ",
    "data": null,
    "error": " org.apache.spark.sql.catalyst.parser.ParseException: \nOperation not allowed: grant(line 1, pos 0)\n\n== SQL ==\ngrant SELECT, READ_METADATA, USAGE on DATABASE 'DB"
}

The above function is not working,

Body:
Your question is not very clear, but I'll guess you're having problems in this part:

-d '{ "query": \"'"${content}"'\" } '

That will get you literal backslashes before the double quotes around your content, since backslashes inside single quotes are inserted literally. You could swap that for -d '{ "query": "'"${content}"'" }' or -d "{ \"query\": \"${content}\" }"


问:
Pandas dataframe incomplete output

I have a dataframe where one column has multiline text like shown in the screenshot.
However, when i extract the contents of that cell, i see only first line. Is there anything wrong that i am doing ? Please help. Thank you

答:
to_list() and then print? –
Marco Cerliani
May 16 2020 at 18:52</p>

Title: Pandas dataframe incomplete output


问:
Download a file from server using HTPPS Protocol
I want to download a file from server using https protocol I am using NSUrlConnection but that would not work.any sample code is appreciated </p>

答:
Checkout ASIHTTPRequest
,Use it for network related stuff. Really useful.</p>

ContentLicense: CC BY-SA 3.0


问:
Cannot resolve parameter 'Volo.Abp.Domain.Repositories.IRepository`
In ABP Framework v5.1.3, I'm trying to seed database with data using a generic IRepository<> (I know this isn't best practice).
However I can't get the dependency injection to work.

I've created a sample project reproducing my issue at GitHub.

private DbSet<Sample> Samples { get; set; }
```
<p>I didn't have this issue a couple weeks ago when following the Web Application Development Tutorial.</p>
<p>This is part of the error I'm seeing:</p>
<blockquote>
```Unhandled exception. Autofac.Core.DependencyResolutionException: An exception was thrown while activating SampleProject.SampleProjectDataSeederContributor.
 ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'SampleProject.SampleProjectDataSeederContributor' can be invoked with the av
ailable services and parameters:
Cannot resolve parameter 'Volo.Abp.Domain.Repositories.IRepository`2[SampleProject.Samples.Sample,System.Guid] sampleRepository' of constructor 'Void .ctor(Volo.Abp.Domain.Repositories.IRepository`2[SampleProject.Samples.Sample,Syste
m.Guid], Volo.Abp.Guids.IGuidGenerator)'.
   at Autofac.Core.Activators.Reflection.ReflectionActivator.GetAllBindings(ConstructorBinder[] availableConstructors, IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Activators.Reflection.ReflectionActivator.<ConfigurePipeline>b__11_0(ResolveRequestContext ctxt, Action`1 next)
   at Autofac.Core.Resolving.Middleware.DelegateMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt)
   at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt)
   at Autofac.Builder.RegistrationBuilder`3.<>c__DisplayClass41_0.<PropertiesAutowired>b__0(ResolveRequestContext ctxt, Action`1 next)
   at Autofac.Core.Resolving.Middleware.DelegateMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt)
   at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   --- End of inner exception stack trace ---
```

Why is it that it cannot resolve the parameters in my case, but when following the tutorial above it's working?

答:
Make the DbSet public:

// private DbSet<Sample> Samples { get; set; }
public DbSet<Sample> Samples { get; set; }
```

Body:
In ABP Framework v5.1.3, I'm trying to seed database with data using a generic IRepository<> (I know this isn't best practice).
However I can't get the dependency injection to work.

I've created a sample project reproducing my issue at GitHub.

private DbSet<Sample> Samples { get; set; }

I didn't have this issue a couple weeks ago when following the Web Application Development Tutorial.

This is part of the error I'm seeing:

Unhandled exception. Autofac.Core.DependencyResolutionException: An exception was thrown while activating SampleProject.SampleProjectDataSeederContributor.
 ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'SampleProject.SampleProjectDataSeederContributor' can be invoked with the av
ailable services and parameters:
Cannot resolve parameter 'Volo.Abp.Domain.Repositories.IRepository`2[SampleProject.Samples.Sample,System.Guid] sampleRepository' of constructor 'Void .ctor(Volo.Abp.Domain.Repositories.IRepository`2[SampleProject.Samples.Sample,Syste
m.Guid], Volo.Abp.Guids.IGuidGenerator)'.
   at Autofac.Core.Activators.Reflection.ReflectionActivator.GetAllBindings(ConstructorBinder[] availableConstructors, IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Activators.Reflection.ReflectionActivator.<ConfigurePipeline>b__11_0(ResolveRequestContext ctxt, Action`1 next)
   at Autofac.Core.Resolving.Middleware.DelegateMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt)
   at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt)
   at Autofac.Builder.RegistrationBuilder`3.<>c__DisplayClass41_0.<PropertiesAutowired>b__0(ResolveRequestContext ctxt, Action`1 next)
   at Autofac.Core.Resolving.Middleware.DelegateMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt)
   at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
   --- End of inner exception stack trace ---

Why is it that it cannot resolve the parameters in my case, but when following the tutorial above it's working?


问:
How to outer-join two CSV files, using shell script?
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"
```
<p><strong>file2.csv</strong></p>
<pre class="lang-none prettyprint-override"><code>label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"
</code>```

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"
```
<p>Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:</p>
```awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv
```

答:
We suggest gawk script which is standard Linux awk:

script.awk

```<code>NR == FNR {
  valsStr = sprintf("%s,%s", $2, "na");
  rowsArr[$1] = valsStr;
}
NR != FNR && $1 in rowsArr {
  split(rowsArr[$1],valsArr);
  valsStr = sprintf("%s,%s", valsArr[1], $2);
  rowsArr[$1] = valsStr;
  next;
}
NR != FNR {
  valsStr = sprintf("%s,%s", "na", $2);
  rowsArr[$1] = valsStr;
}
END {
  printf("%s,%s\n", "label", rowsArr["label"]);
  for (rowName in rowsArr) {
     if (rowName == "label") continue;
     printf("%s,%s\n", rowName, rowsArr[rowName]);
  }
}
</code>```

output:

```<code>awk -F, -f script.awk input.{1,2}.txt

label,Part-A,Part-B
LMN,na,8
ABC,2,na
PQR,6,6
EFG,na,1
XYZ,3,4
</code>```

Body:
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"

file2.csv

label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"

Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:

awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv

Body:
We suggest gawk script which is standard Linux awk:

script.awk

NR == FNR {
  valsStr = sprintf("%s,%s", $2, "na");
  rowsArr[$1] = valsStr;
}
NR != FNR && $1 in rowsArr {
  split(rowsArr[$1],valsArr);
  valsStr = sprintf("%s,%s", valsArr[1], $2);
  rowsArr[$1] = valsStr;
  next;
}
NR != FNR {
  valsStr = sprintf("%s,%s", "na", $2);
  rowsArr[$1] = valsStr;
}
END {
  printf("%s,%s\n", "label", rowsArr["label"]);
  for (rowName in rowsArr) {
     if (rowName == "label") continue;
     printf("%s,%s\n", rowName, rowsArr[rowName]);
  }
}

output:

awk -F, -f script.awk input.{1,2}.txt

label,Part-A,Part-B
LMN,na,8
ABC,2,na
PQR,6,6
EFG,na,1
XYZ,3,4


问:
Jupyter Notebook dead Kernel after Anaconda update
I got the following problem. After update Anaconda because I got an error to import skimage.io to a project in Jupyter Notebook an even a greater error appear - Dead Kernel. Right now I could not ever start a project because the Jupyter gives the following error is: </p>

```<code>Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
    http://localhost:8888/?
token=aaf85a5e18489792c87cce65d7a53a0263cd5c08cc7248b 6
[I 00:55:13.451 NotebookApp] Accepting one-time-token-authenticated
connection from ::1
[I 00:55:31.607 NotebookApp] Kernel started: 608d2190-59e6-4888-b09a-
e616f67bd5b4
Traceback (most recent call last):
ERROR:tornado.general:Uncaught exception in ZMQStream callback
Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 432, in _run_callback
callback(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-
packages\tornado\stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 233, in dispatch_shell
self.pre_handler_hook()
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 248, in pre_handler_hook
self.saved_sigint_handler = signal(SIGINT, default_int_handler)
File "C:\Program Files\Anaconda3\lib\signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread  File "C:\Program
Files\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)

File "C:\Program Files\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel_launcher.py",
line 16, in <module>
app.launch_new_instance()
File "C:\Program Files\Anaconda3\lib\site-
packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelapp.py",
line 477, in start
ioloop.IOLoop.instance().start()
File "C:\Program Files\Anaconda3\lib\site-
packages\tornado\platform\asyncio.py", line 112, in start
self.asyncio_loop.run_forever()
ERROR:tornado.general:Uncaught exception in zmqstream callback
Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 450, in _handle_events
self._handle_recv()
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 480, in _handle_recv
self._run_callback(callback, msg)
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 432, in _run_callback
callback(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-
packages\tornado\stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 233, in dispatch_shell
self.pre_handler_hook()
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 248, in pre_handler_hook
self.saved_sigint_handler = signal(SIGINT, default_int_handler)
File "C:\Program Files\Anaconda3\lib\signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread  File "C:\Program
Files\Anaconda3\lib\asyncio\base_events.py", line 409, in run_forever
</code>```

答:
If you are using Jupyter Notebook inside Vscode,

Uninstall all of conda packages

Install Anaconda Clean to remove conda packages

```<code>conda install anaconda-clean
</code>```

This will remove all of your conda packages

```<code>anaconda-clean --yes
</code>```

Then uninstall Jupyter extension in Vscode, close your current jupyter notebook tab, reopen your jupyter notebook file, run it and reinstall jupyter in the pop-up inside Vscode.

This worked for me.

Body:
I got the following problem. After update Anaconda because I got an error to import skimage.io to a project in Jupyter Notebook an even a greater error appear - Dead Kernel. Right now I could not ever start a project because the Jupyter gives the following error is:

Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
    http://localhost:8888/?
token=aaf85a5e18489792c87cce65d7a53a0263cd5c08cc7248b 6
[I 00:55:13.451 NotebookApp] Accepting one-time-token-authenticated
connection from ::1
[I 00:55:31.607 NotebookApp] Kernel started: 608d2190-59e6-4888-b09a-
e616f67bd5b4
Traceback (most recent call last):
ERROR:tornado.general:Uncaught exception in ZMQStream callback
Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 432, in _run_callback
callback(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-
packages\tornado\stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 233, in dispatch_shell
self.pre_handler_hook()
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 248, in pre_handler_hook
self.saved_sigint_handler = signal(SIGINT, default_int_handler)
File "C:\Program Files\Anaconda3\lib\signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread  File "C:\Program
Files\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)

File "C:\Program Files\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel_launcher.py",
line 16, in <module>
app.launch_new_instance()
File "C:\Program Files\Anaconda3\lib\site-
packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelapp.py",
line 477, in start
ioloop.IOLoop.instance().start()
File "C:\Program Files\Anaconda3\lib\site-
packages\tornado\platform\asyncio.py", line 112, in start
self.asyncio_loop.run_forever()
ERROR:tornado.general:Uncaught exception in zmqstream callback
Traceback (most recent call last):
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 450, in _handle_events
self._handle_recv()
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 480, in _handle_recv
self._run_callback(callback, msg)
File "C:\Program Files\Anaconda3\lib\site-
packages\zmq\eventloop\zmqstream.py", line 432, in _run_callback
callback(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-
packages\tornado\stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 233, in dispatch_shell
self.pre_handler_hook()
File "C:\Program Files\Anaconda3\lib\site-packages\ipykernel\kernelbase.py",
line 248, in pre_handler_hook
self.saved_sigint_handler = signal(SIGINT, default_int_handler)
File "C:\Program Files\Anaconda3\lib\signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread  File "C:\Program
Files\Anaconda3\lib\asyncio\base_events.py", line 409, in run_forever

Body:
If you are using Jupyter Notebook inside Vscode,

Uninstall all of conda packages

Install Anaconda Clean to remove conda packages

conda install anaconda-clean

This will remove all of your conda packages

anaconda-clean --yes

Then uninstall Jupyter extension in Vscode, close your current jupyter notebook tab, reopen your jupyter notebook file, run it and reinstall jupyter in the pop-up inside Vscode.

This worked for me.


问:
Mysql join calculation
So I'm trying to calculate this mysql query that orders the results based on a subquery of sorts.

Table design

Reports
--------
report_id
title

Voting
--------
report_id
user_id
vote_id    //This can be 1-6
```

So I am searching the reports table but want to include a percentage of vote_id's on a join.

Because the vote_id's can be different types, I need to calculate the percentage of that occurrence compared to other votes and then order by that percentage.

Example 1 - Report 1 has four votes (vote_id's 1, 1, 2, 3) so if I am searching for vote_id 1 it would come up 50%.

Example 2 - If I am searching for vote_id 3 it would come up 25%.

答:
```<code>SELECT vote_id,
  ( COUNT(*) / (SELECT COUNT(*) FROM Voting WHERE report_id = 1) ) * 100 AS percentage
  FROM Voting WHERE report_id = 1
  GROUP BY vote_id
</code>```

This gives you a list of all vote_id's in report 1 with their corresponding percentage.

Title: Mysql join calculation

Body:
So I'm trying to calculate this mysql query that orders the results based on a subquery of sorts.

Table design

Reports
--------
report_id
title

Voting
--------
report_id
user_id
vote_id    //This can be 1-6

So I am searching the reports table but want to include a percentage of vote_id's on a join.

Because the vote_id's can be different types, I need to calculate the percentage of that occurrence compared to other votes and then order by that percentage.

Example 1 - Report 1 has four votes (vote_id's 1, 1, 2, 3) so if I am searching for vote_id 1 it would come up 50%.

Example 2 - If I am searching for vote_id 3 it would come up 25%.

Body:
SELECT vote_id,
  ( COUNT(*) / (SELECT COUNT(*) FROM Voting WHERE report_id = 1) ) * 100 AS percentage
  FROM Voting WHERE report_id = 1
  GROUP BY vote_id

This gives you a list of all vote_id's in report 1 with their corresponding percentage.


问:
what is this format and how to read it in pandas
I have a file like this:

```<code>{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}
</code>```

they are on the same line.  What kind of format this file belongs to?
How to read it into pandas dataframe so that

```<code>name    age
John    15
Anna    12
</code>```

Thanks!

答:
Approach 1 (use regex)

In your case, you may read the content of your file using:

```<code>with open('file_path', 'r') as f:
    content = f.read()
</code>```

but in my test I will just assign content with your example line

```<code>content = '''{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}'''
</code>```

Then re.findall to extract the data into a list of tuples.

```<code>import re
data = re.findall(r'{"Name": "([^"]*)", "age": (\d+)}', content)

print(data)
[('John', '15'), ('Anna', '12')]
</code>```

Then build the dataframe with

```<code>pd.DataFrame(data, columns=['Name', 'age'])
</code>```

Note: re.findall attempts to find this pattern {"Name": "([^"]*)", "age": (\d+)} from content, and anything within the brackets () is extracted. ([^"]*) is used for Name and means any length of string that does not include a " (so my assumption is that a name field never contains a ".  For age, (\d+) means any length (>=1) of digits.

Approach 2 (use json)

Another way is to make your content a json.

```<code>import json

pd.DataFrame(json.loads('[' + content.replace('}{"Name": ', '},{"Name": ') + ']'))
</code>```

Body:
I have a file like this:

{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}

they are on the same line.  What kind of format this file belongs to?
How to read it into pandas dataframe so that

name    age
John    15
Anna    12

Thanks!

Body:
Approach 1 (use regex)

In your case, you may read the content of your file using:

with open('file_path', 'r') as f:
    content = f.read()

but in my test I will just assign content with your example line

content = '''{"Name": "John", "age": 15}{"Name": "Anna", "age": 12}'''

Then re.findall to extract the data into a list of tuples.

import re
data = re.findall(r'{"Name": "([^"]*)", "age": (\d+)}', content)

print(data)
[('John', '15'), ('Anna', '12')]

Then build the dataframe with

pd.DataFrame(data, columns=['Name', 'age'])

Note: re.findall attempts to find this pattern {"Name": "([^"]*)", "age": (\d+)} from content, and anything within the brackets () is extracted. ([^"]*) is used for Name and means any length of string that does not include a " (so my assumption is that a name field never contains a ".  For age, (\d+) means any length (>=1) of digits.

Approach 2 (use json)

Another way is to make your content a json.

import json

pd.DataFrame(json.loads('[' + content.replace('}{"Name": ', '},{"Name": ') + ']'))


问:
LARAVEL Payload is invalid error but decrypted data is correct
Recently i made new project with composer and added very basic authentication with make:auth - nothing fancy.

Next i wanted to encrypt name and email columns on my database so i changed their types from VARCHAR(191) to LONGTEXT and added some very basic mutators to Users model

```<code>public function setNameAttribute($value) {
    $this->attributes['name'] = Crypt::encryptString($value);
}

public function getNameAttribute($value) {
    return Crypt::decryptString($value);
}

public function setEmailAttribute($value) {
    $this->attributes['email'] = Crypt::encryptString($value);
}

public function getEmailAttribute($value) {
    return Crypt::decryptString($value);
}
</code>```

But when im testing with my very simple route i get Payload is invalid error even though i see in error contents that fields has been decrypted properly.

```<code>Route::get('user',function(){
$user= \App\User::find(3);
//dd($user->name);
dd(Crypt::decryptString($user->name));
dd(Crypt::decryptString($user->email));
</code>```

});

Screenshot link
https://ibb.co/deBPpR

答: Payload is invalid is also the response I get when I try to decrypt a null value. Make sure to catch null values before decrypting.

Body:
Recently i made new project with composer and added very basic authentication with make:auth - nothing fancy.

Next i wanted to encrypt name and email columns on my database so i changed their types from VARCHAR(191) to LONGTEXT and added some very basic mutators to Users model

public function setNameAttribute($value) {
    $this->attributes['name'] = Crypt::encryptString($value);
}

public function getNameAttribute($value) {
    return Crypt::decryptString($value);
}

public function setEmailAttribute($value) {
    $this->attributes['email'] = Crypt::encryptString($value);
}

public function getEmailAttribute($value) {
    return Crypt::decryptString($value);
}

But when im testing with my very simple route i get Payload is invalid error even though i see in error contents that fields has been decrypted properly.

Route::get('user',function(){
$user= \App\User::find(3);
//dd($user->name);
dd(Crypt::decryptString($user->name));
dd(Crypt::decryptString($user->email));

});

Screenshot link
https://ibb.co/deBPpR


问:
Glide 4.13.0 : thumbnail(float) is deprecated
Just updated Glide to Version 4.13.0 and getting this deprecation warning.

On checking the release page, I found this:

So, what should be the appropriate equivalent to this part of code?

```<code>GlideApp.with(holder.itemView.getContext())
            .load(sr)
            .thumbnail(0.2f)
            .placeholder(R.drawable.background_splash)
            .into(holder.album);
</code>```

What I tried:

I think the syntax should be something like this but confused on what to pass to the constructor.

答:
With RequestBuilder you can configure the request for thumbnail with a multiplier. below is an example

```<code> RequestBuilder<Drawable> requestBuilder= GlideApp.with(holder.itemView.getContext())
            .asDrawable().sizeMultiplier(0.1f);
 GlideApp.with(holder.itemView.getContext())
            .load(sr)
            .thumbnail(requestBuilder)
            .placeholder(R.drawable.background_splash)
            .into(holder.album);
</code>```

its should work . just play around with it to explore more options .

Body:
Just updated Glide to Version 4.13.0 and getting this deprecation warning.

On checking the release page, I found this:

So, what should be the appropriate equivalent to this part of code?

GlideApp.with(holder.itemView.getContext())
            .load(sr)
            .thumbnail(0.2f)
            .placeholder(R.drawable.background_splash)
            .into(holder.album);

What I tried:

I think the syntax should be something like this but confused on what to pass to the constructor.

Body:
With RequestBuilder you can configure the request for thumbnail with a multiplier. below is an example

 RequestBuilder<Drawable> requestBuilder= GlideApp.with(holder.itemView.getContext())
            .asDrawable().sizeMultiplier(0.1f);
 GlideApp.with(holder.itemView.getContext())
            .load(sr)
            .thumbnail(requestBuilder)
            .placeholder(R.drawable.background_splash)
            .into(holder.album);

its should work . just play around with it to explore more options .


问:
How to remove LOST.DIR folder from USB Mass Storage in Android programmatically
I copy files from Android internal storage to USB drive, folder LOST.DIR always is created by system.
How can I remove this folder programmatically

I use library libaums to handle communicate with USB
I tried to delete this folder after copy but USB get error

    private fun exportOnlyFilesToUsb(fileSystem: FileSystem, file: File) {
        val root = fileSystem.rootDirectory
        if (!file.isDirectory) {
            root.search(file.name)?.delete()
            val targetFile = root.createFile(file.name)
            copyFile(file, targetFile)
            return
        }
        file.listFiles()?.forEach {
            exportOnlyFilesToUsb(fileSystem, it)
        }
    }

    private fun copyFile(file: File, usbFile: UsbFile) {
        if (file.isDirectory || usbFile.isDirectory) return
        FileInputStream(file).use { input ->
            UsbFileOutputStream(usbFile).use { output ->
                input.copyTo(output)
            }
        }
    }

// Then I delete
root.search(LOST_DIR)?.delete()
```

答:
LOST.DIR is a folder created by an Android phone on the SD card to get back accidentally deleted files like photos, videos, etc. If you are a smartphone user, you would have already seen LOST.DIR folders are located on your external SD card.

Lost.DIR folder basically helps you to recover files lost due to various reasons like application crash, improper ejection of the USB drive or SD card/ ejection of SD card during the reading/ writing process, Android abruptly frozen or shut down unexpectedly, interruptions while downloading files on SD card, etc.

Some users might delete Lost.DIR folder thinking that it is a virus folder, which is completely false. You might have observed that once you delete Lost.DIR folder, again it will be automatically recreated after you boot your phone, this is because LOST.DIR is the Android system folder.

So don't delete this. Actually, you can't do that.


问:
React Native/Redux State not updating after making API Call
I can return values from the Redux State, and when I make an API call, I see those being logged out but the state is not updating. I setup a basic App with a Redux Store to prove this out. And I've also include the Thunk library, which I read is needed for asynchronous State actions (like API). My guess is I am not returning the state properly at the end of the reducer, because again, if I log the values, there is detail being returned.

To consolidate the code as best as possible, I am only including the necessary pieces:

```<code>export default function App() {

  const OtherVal =  useSelector((state) => state.reducer2.WorkoutDetails);

  const dispatch = useDispatch();

  React.useEffect (() =>{
      dispatch({   type: 'Test_API' })
  })

  return (

<View style={styles.container}>
  <Text>Open up App.js to start rking on your app!</Text>

 <Text>Value is: {OtherVal}</Text>
  <StatusBar style="auto" />
</View>

  );
}
</code>```

My Store:

```<code>import {createStore, applyMiddleware } from 'redux';
import rootReducer from './index';
import thunk from 'redux-thunk'

const store = createStore(rootReducer, applyMiddleware(thunk) );

export default store;
</code>```

My Root Reducer (could be in the Store):

```<code>import { combineReducers } from 'redux'
import reducer2 from './FirstReducer'

export default combineReducers({
  reducer2,
})
</code>```

My Reducer:

```<code>import axios from 'axios';

const initialState = {
    WorkoutDetails:null,
}

const reducer2 =  (state = initialState, action) => {

    if(action.type == 'Test_API'){
            axios.post('https://xxxx',{},
        {
            headers:{
            'X-Requested-With':'XMLHttpRequest'
            , 'Content-Type': 'application/json',
            }
        }
        ).then(function (response) {
            // handle success
            console.log('API Call 2')
            const val = JSON.parse(response.data.recordset[0].EndPoint)
            console.log('JSON Val', val)
            return {...state,WorkoutDetails: val}
        })
    }

    console.log('default Red',state)
    return state
}
export default reducer2;
</code>```

答:
Instead of calling your API in reducer , you can call it in Action creator and then dispatch your action with payload as response. Based on the dispatch action type you can return your updated state to store through reducer.

Component dispatch an action -> apply your thunk (api call)->dispatch an action with API response data ->reducer update the store with correct state based on the action type.

Please refer the below URL:
https://www.freecodecamp.org/news/redux-thunk-explained-with-examples/

Body:
I can return values from the Redux State, and when I make an API call, I see those being logged out but the state is not updating. I setup a basic App with a Redux Store to prove this out. And I've also include the Thunk library, which I read is needed for asynchronous State actions (like API). My guess is I am not returning the state properly at the end of the reducer, because again, if I log the values, there is detail being returned.

To consolidate the code as best as possible, I am only including the necessary pieces:

export default function App() {

  const OtherVal =  useSelector((state) => state.reducer2.WorkoutDetails);

  const dispatch = useDispatch();

  React.useEffect (() =>{
      dispatch({   type: 'Test_API' })
  })

  return (

<View style={styles.container}>
  <Text>Open up App.js to start rking on your app!</Text>

 <Text>Value is: {OtherVal}</Text>
  <StatusBar style="auto" />
</View>

  );
}

My Store:

import {createStore, applyMiddleware } from 'redux';
import rootReducer from './index';
import thunk from 'redux-thunk'

const store = createStore(rootReducer, applyMiddleware(thunk) );

export default store;

My Root Reducer (could be in the Store):

import { combineReducers } from 'redux'
import reducer2 from './FirstReducer'

export default combineReducers({
  reducer2,
})

My Reducer:

import axios from 'axios';

const initialState = {
    WorkoutDetails:null,
}

const reducer2 =  (state = initialState, action) => {

    if(action.type == 'Test_API'){
            axios.post('https://xxxx',{},
        {
            headers:{
            'X-Requested-With':'XMLHttpRequest'
            , 'Content-Type': 'application/json',
            }
        }
        ).then(function (response) {
            // handle success
            console.log('API Call 2')
            const val = JSON.parse(response.data.recordset[0].EndPoint)
            console.log('JSON Val', val)
            return {...state,WorkoutDetails: val}
        })
    }

    console.log('default Red',state)
    return state
}
export default reducer2;


问:
Getting an error while retrieving a blob using user assigned managed identity
We have a C# code which used to retrieve a blob from storage account. The authentication is done using user assigned service principal. These things works till December. But now we are getting some weird error as follows.

ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.

Status: 400 (Bad Request)

Content:

{"error":"invalid_request","error_description":"Identity not found"}

The managed identity has storage data blob contributor access in the storage account.

Attaching the code for reference:

```<code>public static async Task<string> GetBlobAsync()
    {
        string storageName = "storage account name";

        Uri blobUri = new Uri("blob uri");

        TokenCredential cred = new ManagedIdentityCredential("client id");

        var blobClient = new BlobClient(blobUri, cred, null);

        try
        {

            var downloadInfo = await blobClient.DownloadAsync();
            using (TextReader reader = new StreamReader(downloadInfo.Value.Content))
            {
                string metadataBlob = await reader.ReadToEndAsync();

                return metadataBlob;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine("");
            return null;
        }
</code>```

P:S: the three environmental variables such as app id, app secret and tenant id are correct.

I have been stuck here for almost a month. Nothing works.

答:
This document demonstrates how to use managed identity to access App Configuration from App Service, but you can replace the App Service with any other Azure services that support managed identity. https://learn.microsoft.com/en-us/azure/azure-app-configuration/howto-integrate-azure-managed-service-identity

Here are a few things I'd like to call out

Make sure the managed identity is enabled in the Azure service where your application runs.
When you are using system assigned managed identity, you don't need to provide the client Id. You only need to provide the client Id when you use user assigned managed identity.
Make sure the managed identity is granted either App Configuration Data Reader or App Configuration Data Owner role in the access control of your App Configuration instance.
Wait for at least 15 minutes after the role assignment for the permission to propagate.
Managed identity can ONLY work when your code is running in the Azure service. It will NOT work when running locally

Body:
We have a C# code which used to retrieve a blob from storage account. The authentication is done using user assigned service principal. These things works till December. But now we are getting some weird error as follows.

ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.

Status: 400 (Bad Request)

Content:

{"error":"invalid_request","error_description":"Identity not found"}

The managed identity has storage data blob contributor access in the storage account.

Attaching the code for reference:

public static async Task<string> GetBlobAsync()
    {
        string storageName = "storage account name";

        Uri blobUri = new Uri("blob uri");

        TokenCredential cred = new ManagedIdentityCredential("client id");

        var blobClient = new BlobClient(blobUri, cred, null);

        try
        {

            var downloadInfo = await blobClient.DownloadAsync();
            using (TextReader reader = new StreamReader(downloadInfo.Value.Content))
            {
                string metadataBlob = await reader.ReadToEndAsync();

                return metadataBlob;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine("");
            return null;
        }

P:S: the three environmental variables such as app id, app secret and tenant id are correct.

I have been stuck here for almost a month. Nothing works.


问:
Passing props to MUI drawer
In my Setup component I have some input fields. Each input field has some data of their own which I've stored in a separate object dropdowns. With each input field there's a drawer component where there's a ID of that input field. I have a handleClick handler where I'm passing that ID to look for the object properties. Later setting that property in a state and passing that state as prop to MyDrawer component. But I'm getting [] when passed as a props. When I use a separate button and passed the handleClick, then I'm getting the data that I'm passing. But how do I send the input data as props in MyDrawer component. On clicking the MyDrawer it is returning me an empty array each time.

Setup

```<code>const dropdowns = {
  group: [
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
  ],
  supplier: [
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
  ],
  attribute: [
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
  ],
  unit: [
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
  ],
  uses: [
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
  ],
};

const SetupBar = () => {

  const [fieldData, setFieldData] = useState([]);

  const handleClick = (value) => {
    setFieldData(dropdowns[value]);
    toggleDrawer();
  };
  const [state, setState] = React.useState({
    right: false,
  });

  const toggleDrawer = (anchor, open) => (event) => {
    if (
      event.type === "keydown" &&
      (event.key === "Tab" || event.key === "Shift")
    ) {
      return;
    }

    setState({ ...state, [anchor]: open });
  };
  console.log(fieldData);

  return (
    <div className="parent">

        <div className="input-fields">
          <label htmlFor="group">Group Code</label>
          <div className="input-grp">
            <input type="text" />
            <MyDrawer
              id="group"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />
          </div>
        </div>
        <div className="input-fields">
          <label htmlFor="supplier">Supplier</label>
          <div className="input-grp">
            <input type="text" />
            <MyDrawer
              id="supplier"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />
          </div>
        </div>

        <div className="input-fields">
          <label htmlFor="attribute">Attribute ID</label>
          <div className="input-grp">
            <input type="text" />
            <MyDrawer
              id="attribute"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />
          </div>
        </div>
        <div className="input-fields">
          <label htmlFor="unit">Unit</label>
          <div className="input-grp">
            <input type="text" />

            <MyDrawer
              id="unit"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />
          </div>
        </div>
        <div className="input-fields">
          <label htmlFor="uses">Uses</label>
          <div className="input-grp">
            <input type="text" />

            <MyDrawer
              id="uses"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default SetupBar;
</code>```

MyDrawer

```<code>export default function MyDrawer({ data, toggleDrawer, state }) {
  const list = (anchor) => (
    <Box
      role="presentation"
      onClick={toggleDrawer(anchor, false)}
      onKeyDown={toggleDrawer(anchor, false)}
    >
      <List>
        {data?.map((item, index) => (
          <ListItem button key={index}>
            <ListItemText primary={item.code} />
          </ListItem>
        ))}
      </List>
    </Box>
  );

  return (
    <div>
      <React.Fragment key="right">
        <Button
          onClick={toggleDrawer("right", true)}
          style={{
            fontSize: "25px",
            cursor: "pointer",
          }}
        >
          <CgArrowRightR />
        </Button>
        <Drawer
          anchor="right"
          open={state["right"]}
          onClose={toggleDrawer("right", false)}
        >
          {list("right")}
        </Drawer>
      </React.Fragment>
    </div>
  );
}
</code>```

答:
You need to pass the onClick event listener to a actual DOM element. So pass it to any top level DOM element in your drawer component.

```<code>           <MyDrawer
              id="supplier"
              onClick={(id) => handleClick(id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />
</code>```

That onClick will be passed to MyDrawer component as a prop.

```<code>export default function MyDrawer({ data, toggleDrawer, state, onClick, id }) {
  const list = (anchor) => (
    <Box
      role="presentation"
      onClick={toggleDrawer(anchor, false)}
      onKeyDown={toggleDrawer(anchor, false)}
    >
      <List>
        {data?.map((item, index) => (
          <ListItem button key={index}>
            <ListItemText primary={item.code} />
          </ListItem>
        ))}
      </List>
    </Box>
  );

  return (
    <div onClick={()=>onClick(id)}>
      <React.Fragment key="right">
        <Button
          onClick={toggleDrawer("right", true)}
          style={{
            fontSize: "25px",
            cursor: "pointer",
          }}
        >
          <CgArrowRightR />
        </Button>
        <Drawer
          anchor="right"
          open={state["right"]}
          onClose={toggleDrawer("right", false)}
        >
          {list("right")}
        </Drawer>
      </React.Fragment>
    </div>
  );
}
</code>```

Title: Passing props to MUI drawer

Body:
In my Setup component I have some input fields. Each input field has some data of their own which I've stored in a separate object dropdowns. With each input field there's a drawer component where there's a ID of that input field. I have a handleClick handler where I'm passing that ID to look for the object properties. Later setting that property in a state and passing that state as prop to MyDrawer component. But I'm getting [] when passed as a props. When I use a separate button and passed the handleClick, then I'm getting the data that I'm passing. But how do I send the input data as props in MyDrawer component. On clicking the MyDrawer it is returning me an empty array each time.

Setup

const dropdowns = {
  group: [
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
    { code: "10202", description: "10202 - 10202 - 10202 - 10202 - 10202" },
  ],
  supplier: [
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
    { code: "3039", name: "3039 - 3039 - 3039 - 3039 - 3039" },
  ],
  attribute: [
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
    { code: "274", name: "274 - 274 - 274 - 274 - 274" },
  ],
  unit: [
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
    { code: "EA", name: "EA - EA - EA - EA - EA" },
  ],
  uses: [
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
    { code: "1", name: "1 - 1 - 1 - 1 - 1" },
  ],
};

const SetupBar = () => {

  const [fieldData, setFieldData] = useState([]);

  const handleClick = (value) => {
    setFieldData(dropdowns[value]);
    toggleDrawer();
  };
  const [state, setState] = React.useState({
    right: false,
  });

  const toggleDrawer = (anchor, open) => (event) => {
    if (
      event.type === "keydown" &&
      (event.key === "Tab" || event.key === "Shift")
    ) {
      return;
    }

    setState({ ...state, [anchor]: open });
  };
  console.log(fieldData);

  return (

          Group Code

            <input type="text" />
            <MyDrawer
              id="group"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />

          Supplier

            <input type="text" />
            <MyDrawer
              id="supplier"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />

          Attribute ID

            <input type="text" />
            <MyDrawer
              id="attribute"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />

          Unit

            <input type="text" />

            <MyDrawer
              id="unit"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />

          Uses

            <input type="text" />

            <MyDrawer
              id="uses"
              onClick={(e) => handleClick(e.currentTarget.id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />

  );
};

export default SetupBar;

MyDrawer

export default function MyDrawer({ data, toggleDrawer, state }) {
  const list = (anchor) => (
    <Box
      role="presentation"
      onClick={toggleDrawer(anchor, false)}
      onKeyDown={toggleDrawer(anchor, false)}
    >
      <List>
        {data?.map((item, index) => (
          <ListItem button key={index}>
            <ListItemText primary={item.code} />
          </ListItem>
        ))}
      </List>
    </Box>
  );

  return (

      <React.Fragment key="right">
        <Button
          onClick={toggleDrawer("right", true)}
          style={{
            fontSize: "25px",
            cursor: "pointer",
          }}
        >
          <CgArrowRightR />
        </Button>
        <Drawer
          anchor="right"
          open={state["right"]}
          onClose={toggleDrawer("right", false)}
        >
          {list("right")}
        </Drawer>
      </React.Fragment>

  );
}

Body:
You need to pass the onClick event listener to a actual DOM element. So pass it to any top level DOM element in your drawer component.

           <MyDrawer
              id="supplier"
              onClick={(id) => handleClick(id)}
              data={fieldData}
              toggleDrawer={toggleDrawer}
              state={state}
            />

That onClick will be passed to MyDrawer component as a prop.

export default function MyDrawer({ data, toggleDrawer, state, onClick, id }) {
  const list = (anchor) => (
    <Box
      role="presentation"
      onClick={toggleDrawer(anchor, false)}
      onKeyDown={toggleDrawer(anchor, false)}
    >
      <List>
        {data?.map((item, index) => (
          <ListItem button key={index}>
            <ListItemText primary={item.code} />
          </ListItem>
        ))}
      </List>
    </Box>
  );

  return (
    <div onClick={()=>onClick(id)}>
      <React.Fragment key="right">
        <Button
          onClick={toggleDrawer("right", true)}
          style={{
            fontSize: "25px",
            cursor: "pointer",
          }}
        >
          <CgArrowRightR />
        </Button>
        <Drawer
          anchor="right"
          open={state["right"]}
          onClose={toggleDrawer("right", false)}
        >
          {list("right")}
        </Drawer>
      </React.Fragment>
    </div>
  );
}


问:
Has anybody actually used PackageMaker for creating MacOSX install packages? If so am I just using it wrong?
I'm using PackageMaker 3.0.4 to make an install package that includes .kext and .plugin files that need to be installed to system directories. My goal is to create a .pmdoc

I just can't believe that anybody is actually using it because I have hit so many bugs that I don't know how anybody has managed to get it working for them. I don't believe I'm doing anything particularly unusual, but almost every time I open a .pmdoc to edit (or even when building it from the commandline) PackageMaker will arbitrarily change my settings. Particularly permissions, but also paths.

It is particularly infuriating from the commandline because we're using the .pmdoc when building the installers... so we end up with a broken installer because PackageMaker has gone and messed up the various (important!) permissions - meaning .kext files cannot load and the like.

At this stage the best workaround seems to be writing a postflight script that will modify the permissions on the commandline, and just leave PackageMaker to break the permissions however it wants to. This doesn't address the other changes it makes (sometimes even causing the files to be corrupt to the point I can't even open the .pmdoc anymore.

So... has anybody actually managed to successfully integrate PackageMaker as part of their build process? Or is it really as fundamentally broken as it seems and everyone else is too wise to even touch it?

答:
You could try commandline option [--no-recommend, -m]. However, you will have to set correct permissions on all your files before packaging.
ref: man packagemaker</p>


问:
How to view a cron job running currently?
I have a cron job set up for daily execution (on my own ubuntu, just for trial) like so:

```<code>0 0 * * * /path/exec.sh
</code>```

It is been set for daily execution. I usually open my machine around 8a.m. I would like to find out

 - what time my cron job ran, if it has already run ?

 - I would also like to see if any of my cron job is running at the moment?

Is there a way to find out IF a cron job is actually running at the moment?

答:
you can display all active cron jobs using

```<code>crontab -l
</code>```

To vie cron job history, you can show logs by-

```<code>grep CRON /var/log/syslog
</code>```

You can find cron demon is running or not by-

```<code>pgrep cron
</code>```

or all about cron status by-

```<code>systemctl status cron
</code>```

Body:
I have a cron job set up for daily execution (on my own ubuntu, just for trial) like so:

0 0 * * * /path/exec.sh

It is been set for daily execution. I usually open my machine around 8a.m. I would like to find out

 - what time my cron job ran, if it has already run ?

 - I would also like to see if any of my cron job is running at the moment?

Is there a way to find out IF a cron job is actually running at the moment?

Body:
you can display all active cron jobs using

crontab -l

To vie cron job history, you can show logs by-

grep CRON /var/log/syslog

You can find cron demon is running or not by-

pgrep cron

or all about cron status by-

systemctl status cron


问:
How do I configure Google BigQuery command line tool to use a Service Account?
I've created a service account using the Google API Console and wish to use this service account with the Google BigQuery CLI (bq) tool.

I've been using the command line tool to successfully access the BigQuery service using my valid OAuth2 credentials in ~/.bigquery.v2.token, however I can't seem to find any documentation on how to modify this file (or otherwise configure the tool) to use a service account instead.

Here is my current .bigquery.v2.token file

```<code>{
    "_module": "oauth2client.client",
    "_class": "OAuth2Credentials",
    "access_token": "--my-access-token--",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "invalid": false,
    "client_id": "--my-client-id--.apps.googleusercontent.com",
    "id_token": null,
    "client_secret": "--my-client-secret--",
    "token_expiry": "2012-11-06T15:57:12Z",
    "refresh_token": "--my-refresh-token--",
    "user_agent": "bq/2.0"
}
</code>```

My other file: ~/.bigqueryrc generally looks like this:

```<code>project_id = --my-project-id--
credential_file = ~/.bigquery.v2.token
</code>```

I've tried setting the credential_file paramater to the .p12 private key file for my service account but with no luck, it gives me back the following error

```<code>******************************************************************
** No OAuth2 credentials found, beginning authorization process **
******************************************************************
</code>```

And asks me to go to a link in my browser to set up my OAuth2 credentials again.

The command line tools' initial configuration option "init":

```<code>bq help init
</code>```

displays no helpful information about how to set up this tool to use a service account.

答:
For anyone else who comes along struggling to use bq with a service account... I had a seriously hard time getting this to work inside of a CI/CD pipeline using the Google Cloud SDK docker images on gitlab-ci. Turns out the missing bit for me was making sure to set the default project. On my laptop gcloud was happy inferring the default project from the service account, but for some reason the version within the docker image was defaulting to a public free project.

- gcloud auth activate-service-account --key-file=${PATH_TO_SVC_ACCT_JSON};
- gcloud config set project ${GOOGLE_BIGQUERY_PROJECT}
```

after this I was able to use the bq utility as the service account. I imagine setting the default project in the .bigqueryrc file does the trick too, which is why the OP didn't run into this issue.

Body:
I've created a service account using the Google API Console and wish to use this service account with the Google BigQuery CLI (bq) tool.

I've been using the command line tool to successfully access the BigQuery service using my valid OAuth2 credentials in ~/.bigquery.v2.token, however I can't seem to find any documentation on how to modify this file (or otherwise configure the tool) to use a service account instead.

Here is my current .bigquery.v2.token file

{
    "_module": "oauth2client.client",
    "_class": "OAuth2Credentials",
    "access_token": "--my-access-token--",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "invalid": false,
    "client_id": "--my-client-id--.apps.googleusercontent.com",
    "id_token": null,
    "client_secret": "--my-client-secret--",
    "token_expiry": "2012-11-06T15:57:12Z",
    "refresh_token": "--my-refresh-token--",
    "user_agent": "bq/2.0"
}

My other file: ~/.bigqueryrc generally looks like this:

project_id = --my-project-id--
credential_file = ~/.bigquery.v2.token

I've tried setting the credential_file paramater to the .p12 private key file for my service account but with no luck, it gives me back the following error

******************************************************************
** No OAuth2 credentials found, beginning authorization process **
******************************************************************

And asks me to go to a link in my browser to set up my OAuth2 credentials again.

The command line tools' initial configuration option "init":

bq help init

displays no helpful information about how to set up this tool to use a service account.

Body:
For anyone else who comes along struggling to use bq with a service account... I had a seriously hard time getting this to work inside of a CI/CD pipeline using the Google Cloud SDK docker images on gitlab-ci. Turns out the missing bit for me was making sure to set the default project. On my laptop gcloud was happy inferring the default project from the service account, but for some reason the version within the docker image was defaulting to a public free project.

- gcloud auth activate-service-account --key-file=${PATH_TO_SVC_ACCT_JSON};
- gcloud config set project ${GOOGLE_BIGQUERY_PROJECT}

after this I was able to use the bq utility as the service account. I imagine setting the default project in the .bigqueryrc file does the trick too, which is why the OP didn't run into this issue.


问:
Media query not changing margin
I have css that should make the div margin go to 10% if the screen is 1920px wide or less, and 20% margin-left if the screen width is any higher. For some reason though, the media query is not working. Here is the code for it. Thanks!</p>
```<code>.about-me-header{
    width: 200px;
    margin-left: 20%;
    height: 20%;
}

@media only screen and (max-width:1920){
    .about-me-header{
        margin-left: 10%;
    }
}
</code>```

答:
You must specify the type of length. Like 1920px

```<code>@media only screen and (max-width:1920px){
    .about-me-header{
        margin-left: 10%;
    }
}
</code>```

Title: Media query not changing margin

Body:
I have css that should make the div margin go to 10% if the screen is 1920px wide or less, and 20% margin-left if the screen width is any higher. For some reason though, the media query is not working. Here is the code for it. Thanks!

.about-me-header{
    width: 200px;
    margin-left: 20%;
    height: 20%;
}

@media only screen and (max-width:1920){
    .about-me-header{
        margin-left: 10%;
    }
}

Body:
You must specify the type of length. Like 1920px

@media only screen and (max-width:1920px){
    .about-me-header{
        margin-left: 10%;
    }
}


问:
Struts1 - Passing objects between servlets and jsp
What is the best way to pass objects between servlets and JSP when using Struts1? Help needed.</p>

答:
Just put the objects in your ActionForm and define getters for them, or put them in request attributes directly.

In the JSP, use ${myActionForm.myObject} of ${myAttributeName} (respectively) to get the object.


问:
Video Preview before Upload is not working in React JS
Goal: Trying to upload a video to the server and display the video preview before the upload.

Bug:The video preview is working fine for the first time but when I try to upload the video again the new video preview does not display and but the old video keeps on playing.

My Code: I have a state videoPreview and I am using it as a source to my video tag source. The setVideoPreview is set to the uploaded file. This only works the first time but if I upload the video again it does not get rerendered again and the preview of the previous video keeps on playing. Here is my code snippet

                  <video
                    width="400"
                    height="150"
                    style={{ height: "143px", objectFit: "contain" }}
                    autoPlay
                    loop
                  >
                    <source src={videoPreview} />
                  </video>

            <input
              type="file"
              id="videos"
              accept="video/*"
              className="text-transparent -ml-52"

              onChange={(e) => {
                const files = e.target.files;
                let myFiles = Array.from(files);

                const fileReader = new FileReader();
                fileReader.onload = () => {
                  if (fileReader.readyState === 2) {
                    formik.setFieldValue("video", myFiles);
                    setVideoPreview(fileReader.result);//this is my state
                  }
                };
                if (e.target.files[0]) {
                  fileReader.readAsDataURL(e.target.files[0]);
                }
              }}
              value={formik.values.video.name}
            />

```

I have no idea why the state is not updating or if it's updating the preview is not changing.

答:
After some research, I was able to solve the bug via the onloadstart and onloadend event listeners of the FileReader object. I set the videoPreview to null on the onloadstart and to the FileReader.result on  the onloadend.

Here is the code I used in the onChange function

onChange={(e) => {
                  const files = e.target.files;

                  let myFiles = Array.from(files);

                  const fileReader = new FileReader();

                  fileReader.onload = () => {
                    if (fileReader.readyState === 2) {
                      formik.setFieldValue("video", myFiles);
                    }
                  };
                  fileReader.onloadstart = () => {
                    setVideoPreview(null);
                  };
                  fileReader.onloadend = () => {
                    setVideoPreview(fileReader.result);
                  };
                  if (e.target.files[0]) {
                    fileReader.readAsDataURL(e.target.files[0]);
                  }
                }}
```

Body:
Goal: Trying to upload a video to the server and display the video preview before the upload.

Bug:The video preview is working fine for the first time but when I try to upload the video again the new video preview does not display and but the old video keeps on playing.

My Code: I have a state videoPreview and I am using it as a source to my video tag source. The setVideoPreview is set to the uploaded file. This only works the first time but if I upload the video again it does not get rerendered again and the preview of the previous video keeps on playing. Here is my code snippet

                  <video
                    width="400"
                    height="150"
                    style={{ height: "143px", objectFit: "contain" }}
                    autoPlay
                    loop
                  >
                    <source src={videoPreview} />
                  </video>

            <input
              type="file"
              id="videos"
              accept="video/*"
              className="text-transparent -ml-52"

              onChange={(e) => {
                const files = e.target.files;
                let myFiles = Array.from(files);

                const fileReader = new FileReader();
                fileReader.onload = () => {
                  if (fileReader.readyState === 2) {
                    formik.setFieldValue("video", myFiles);
                    setVideoPreview(fileReader.result);//this is my state
                  }
                };
                if (e.target.files[0]) {
                  fileReader.readAsDataURL(e.target.files[0]);
                }
              }}
              value={formik.values.video.name}
            />

I have no idea why the state is not updating or if it's updating the preview is not changing.


问:
Amazon AWS ECS Container Docker Port not binding correctly
I have deployed a docker Image via ECS Task Definitions picked up from ECR.
The Task definition json is given below.

I have mapped container port as 80 &
Network Mode : awsvpc

But when the ECS service is started and docker runs in an EC2 instance but the ports are not mapped. I verified the same by logging into the EC2 instance and triggering

docker ps

I am using Load Balancer as of now. Wanted to first get the containers working and accessible
via 80 port.

Kindly help me figure out what is wrong in the given config

答:
With awsvpc the Security Group >> Inbound rules are important.
You need to make sure that the Container port mapping is actually allowed in the Security Group >> Inbound rules of your ECS Service


问:
Flutter new Image.network foreach in ListView
I'm totally new to Flutter and Java based languages in general, coming from PHP background myself. This is going to be a very beginner question:

I'm creating a new Network.image via ListView like this:

```<code>new Image.network(snapshot.data[index].imageurl.toString() ?? ''),
</code>```

ok, works great as the snapshot.data[index].imageurl is taken as:

```<code>data ['content'][0]['imageurl']
</code>```

and defined as:

```<code>String imageurl;
</code>```

However what I'd like to do is to take the whole array:

```<code> data ['content']['imageurl']
</code>```

which I suppose should be defined as:

```<code>List imageurl;
</code>```

and loop through it to create own Image.network for each entry in array.

I have tried multiple things, including:

```<code>return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
   children: <Widget>[
      snapshot.data[index].imageurl.forEach((data) {
        new Image.network(snapshot.data[index].imageurl.toString() ?? ''),
}
</code>```

But foreEach loop is giving me an error:

"The expression here has a type of 'void', and therefore  cannot be used.

How can I actually achieve this? Out of ideas here.

答:
```<code>ListView(
    children: snapshot.data.docs.map((DocumentSnapshot document) {
          return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
                  height: 500.h,
                  width: screenSized.width,
                  decoration: BoxDecoration(
                  image: DecorationImage(
                  image:NetworkImage(
                   document["userImage"]),
                  fit: BoxFit.cover
                  ),
                ),
             ),
           );
         }).toList(),
        );
</code>```

Body:
I'm totally new to Flutter and Java based languages in general, coming from PHP background myself. This is going to be a very beginner question:

I'm creating a new Network.image via ListView like this:

new Image.network(snapshot.data[index].imageurl.toString() ?? ''),

ok, works great as the snapshot.data[index].imageurl is taken as:

data ['content'][0]['imageurl']

and defined as:

String imageurl;

However what I'd like to do is to take the whole array:

 data ['content']['imageurl']

which I suppose should be defined as:

List imageurl;

and loop through it to create own Image.network for each entry in array.

I have tried multiple things, including:

return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
   children: <Widget>[
      snapshot.data[index].imageurl.forEach((data) {
        new Image.network(snapshot.data[index].imageurl.toString() ?? ''),
}

But foreEach loop is giving me an error:

"The expression here has a type of 'void', and therefore  cannot be used.

How can I actually achieve this? Out of ideas here.


问:
How to group values in a column (R)
I'm creating a summary table that groups my records by country of destination:

```<code>SummarybyLocation <- PSTNRecords %>%
                           group_by(Destination) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(durationMinutes),
                                  MaxDuration = max(durationMinutes),
                                  AverageDuration = mean(durationMinutes),
                                  Charges = sum(charge),
                                  Fees = sum(connectionCharge)
                                )

SummarybyLocation
</code>```

The resulting table is as follows:

I realized that the Destination values are inconsistent (for example,  "France" and "FR" both refer to the same area, and then I have a "North America" that I presume gathers USA and Canada.

I was wondering if there's a way of creating custom groups for these values, so that the aggregation would make more sense. I tried to use the countrycode package to add an iso2c column, but that doesn't resolve the problem of managing other area aggregations like "North America".

I would really appreciate some suggestions on how to handle this.

Thanks in advance!

答:
The {countrycode} package can deal with custom names/codes easily...

library(tidyverse)
library(countrycode)

PSTNRecords <- tibble::tribble(
  ~Destination,    ~durationMinutes, ~charge, ~connectionCharge,
  "FR",            1,                2.5,     0.3,
  "France",        1,                2.5,     0.3,
  "United States", 1,                2.5,     0.3,
  "USA",           1,                2.5,     0.3,
  "North America", 1,                2.5,     0.3
)

# see what special codes/country names you have to deal with
iso3cs <- countrycode(PSTNRecords$Destination, "country.name", "iso3c", warn = FALSE)
unique(PSTNRecords$Destination[is.na(iso3cs)])
#> [1] "FR"            "North America"

# decde how to deal with them
custom_matches <- c("FR" = "FRA", "North America" = "USA")

# use your custom codes
PSTNRecords %>%
  mutate(iso3c = countrycode(Destination, "country.name", "iso3c", custom_match = custom_matches))
#> # A tibble: 5 × 5
#>   Destination   durationMinutes charge connectionCharge iso3c
#>   <chr>                   <dbl>  <dbl>            <dbl> <chr>
#> 1 FR                          1    2.5              0.3 FRA
#> 2 France                      1    2.5              0.3 FRA
#> 3 United States               1    2.5              0.3 USA
#> 4 USA                         1    2.5              0.3 USA
#> 5 North America               1    2.5              0.3 USA
```

Title: How to group values in a column (R)

Body:
I'm creating a summary table that groups my records by country of destination:

SummarybyLocation <- PSTNRecords %>%
                           group_by(Destination) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(durationMinutes),
                                  MaxDuration = max(durationMinutes),
                                  AverageDuration = mean(durationMinutes),
                                  Charges = sum(charge),
                                  Fees = sum(connectionCharge)
                                )

SummarybyLocation

The resulting table is as follows:

I realized that the Destination values are inconsistent (for example,  "France" and "FR" both refer to the same area, and then I have a "North America" that I presume gathers USA and Canada.

I was wondering if there's a way of creating custom groups for these values, so that the aggregation would make more sense. I tried to use the countrycode package to add an iso2c column, but that doesn't resolve the problem of managing other area aggregations like "North America".

I would really appreciate some suggestions on how to handle this.

Thanks in advance!


问:
Can I validate a password before encryption in Springboot?
I made a SpringBoot application and now I'm at the login part.
I've made some custom restrictions with a custom annotation.
The problem is that this custom annotation is applied to the user after the password has been ecncripted.

This is the PasswordConstraint

```<code>public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, User>{

@Override
public void initialize(final ValidPassword arg0){}

@SneakyThrows
@Override
public boolean isValid(User user, ConstraintValidatorContext context) {

    Properties props         = new Properties();
    InputStream inputStream  = getClass().getClassLoader().getResourceAsStream("passay.properties");
    props.load(inputStream);
    MessageResolver resolver = new PropertiesMessageResolver(props);

    PasswordValidator validator = new PasswordValidator(resolver, Arrays.asList(
            new LengthRule(8, 16),
            new CharacterRule(EnglishCharacterData.UpperCase, 1),
            new CharacterRule(EnglishCharacterData.LowerCase, 1),
            new CharacterRule(EnglishCharacterData.Digit, 1),
            new CharacterRule(EnglishCharacterData.Special, 1),
            new WhitespaceRule(),
            new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 5, false),
            new IllegalSequenceRule(EnglishSequenceData.Numerical, 5, false)
    ));

    RuleResult result = validator.validate(new PasswordData(user.getPasswordHash()));
    if (result.isValid()) {
        return true;
    }

    List<String> messages  = validator.getMessages(result);
    String messageTemplate = String.join(",", messages);

    context.buildConstraintViolationWithTemplate(messageTemplate)
            .addConstraintViolation()
            .disableDefaultConstraintViolation();

    return false;

}
</code>```

}

This is where I encrypt the password

```<code> @Qualifier("getPasswordEncoder")
@Autowired
private PasswordEncoder passwordEncoder;

public void registerNewUserAccount(User user){
    Optional<User> userOptional= userRepository.findUserByEmailAddress(user.getEmailAddress());
    if(userOptional.isPresent()){
        throw new IllegalStateException("email taken!");
    }

    // Se comenteaza pentru ca: Validarea parolei se face pe hashPassword
    //Dupa rezolvarea problemei, se decomenteaza
    user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));

    user.setEnabled(false);

    Optional<User> saved = Optional.of(user);
    saved.ifPresent(u -> {
        try {
            String token = UUID.randomUUID().toString();
            verificationTokenService.save(user, token);

            try {
                emailService.sendHtmlMail(u);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    });

    userRepository.save(user);
    System.out.println(user);

    saved.get();

}
</code>```

Here is the user:

```<code>@Entity
@Table
@ValidPassword
public class User implements UserDetails {
    @Id
    @SequenceGenerator( //se auto-incrementeaza pkul ?
            name = "user_sequence",
            sequenceName = "user_sequence",
            allocationSize = 1
    )
    @GeneratedValue( ///??????????
            strategy = GenerationType.SEQUENCE,//maybe auto if not working
            generator = "user_sequence"
    )
    //TODO Change camelCase to python_format
    private Long id;
    private String userName;
    @NonNull
    @NotBlank(message = "New password is mandatory")
    private String passwordHash;
    private String firstName;
    private String lastName;
    private String phoneNumber;
    @Email
    private String emailAddress;
    public String address1;
    public String address2;
    private String city;
    private String country;
    private String zipcode;
    private boolean enabled;
</code>```

答:
The issue here is that when you save an entity to the database, the validation annotations are also checked, which will then trigger the ConstraintViolationException.

So the best approach is to follow the Data Transfer Object pattern. I suggest you create a new class say UserDto which will be similar or even a replica of your User entity, ideally your UserDto class should only contain the field that the controller needs inclusive of all the necessary validation annotations.

In the service class where you encrypted your password, before saving the user, convert the UserDto instance to a User entity but remember to remove the @ValidPassword annotation from the User entity since you don't want to validate the encrypted password and you've already checked for the validations from your UserDto class

Remember: UserDto should not be an entity class since we don't want it in our database, we only need it for validation purpose.

Body:
I made a SpringBoot application and now I'm at the login part.
I've made some custom restrictions with a custom annotation.
The problem is that this custom annotation is applied to the user after the password has been ecncripted.

This is the PasswordConstraint

public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, User>{

@Override
public void initialize(final ValidPassword arg0){}

@SneakyThrows
@Override
public boolean isValid(User user, ConstraintValidatorContext context) {

    Properties props         = new Properties();
    InputStream inputStream  = getClass().getClassLoader().getResourceAsStream("passay.properties");
    props.load(inputStream);
    MessageResolver resolver = new PropertiesMessageResolver(props);

    PasswordValidator validator = new PasswordValidator(resolver, Arrays.asList(
            new LengthRule(8, 16),
            new CharacterRule(EnglishCharacterData.UpperCase, 1),
            new CharacterRule(EnglishCharacterData.LowerCase, 1),
            new CharacterRule(EnglishCharacterData.Digit, 1),
            new CharacterRule(EnglishCharacterData.Special, 1),
            new WhitespaceRule(),
            new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 5, false),
            new IllegalSequenceRule(EnglishSequenceData.Numerical, 5, false)
    ));

    RuleResult result = validator.validate(new PasswordData(user.getPasswordHash()));
    if (result.isValid()) {
        return true;
    }

    List<String> messages  = validator.getMessages(result);
    String messageTemplate = String.join(",", messages);

    context.buildConstraintViolationWithTemplate(messageTemplate)
            .addConstraintViolation()
            .disableDefaultConstraintViolation();

    return false;

}

}

This is where I encrypt the password

 @Qualifier("getPasswordEncoder")
@Autowired
private PasswordEncoder passwordEncoder;

public void registerNewUserAccount(User user){
    Optional<User> userOptional= userRepository.findUserByEmailAddress(user.getEmailAddress());
    if(userOptional.isPresent()){
        throw new IllegalStateException("email taken!");
    }

    // Se comenteaza pentru ca: Validarea parolei se face pe hashPassword
    //Dupa rezolvarea problemei, se decomenteaza
    user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));

    user.setEnabled(false);

    Optional<User> saved = Optional.of(user);
    saved.ifPresent(u -> {
        try {
            String token = UUID.randomUUID().toString();
            verificationTokenService.save(user, token);

            try {
                emailService.sendHtmlMail(u);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    });

    userRepository.save(user);
    System.out.println(user);

    saved.get();

}

Here is the user:

@Entity
@Table
@ValidPassword
public class User implements UserDetails {
    @Id
    @SequenceGenerator( //se auto-incrementeaza pkul ?
            name = "user_sequence",
            sequenceName = "user_sequence",
            allocationSize = 1
    )
    @GeneratedValue( ///??????????
            strategy = GenerationType.SEQUENCE,//maybe auto if not working
            generator = "user_sequence"
    )
    //TODO Change camelCase to python_format
    private Long id;
    private String userName;
    @NonNull
    @NotBlank(message = "New password is mandatory")
    private String passwordHash;
    private String firstName;
    private String lastName;
    private String phoneNumber;
    @Email
    private String emailAddress;
    public String address1;
    public String address2;
    private String city;
    private String country;
    private String zipcode;
    private boolean enabled;


问:
Find the last value in a "rolled-over" sequence with a stored procedure?
Suppose I had a set of alpha-character identifiers of a set length, e.g. always five letters, and they are assigned in such a way that they are always incremented sequentially (GGGGZ --> GGGHA, etc.).   Now, if I get to ZZZZZ, since the length is fixed, I must "roll over" to AAAAA.  I might have a contiguous block from ZZZAA through AAAAM.  I want to write a sproc that will give me the "next" identifier, in this case AAAAN.

If I didn't have this "rolling over" issue, of course, I'd just ORDER BY DESC and grab the top result.  But I'm at a bit of a loss now -- and it doesn't help at all that SQL is not my strongest language.

If I have to I can move this to my C# calling code, but a sproc would be a better fit.

ETA: I would like to avoid changing the schema (new column or new table); I'd rather just be able to "figure it out".  I might even prefer to do it brute force (e.g. start at the lowest value and increment until I find a "hole"), even though that could get expensive.  If you have an answer that does not modify the schema, it'd be a better solution for my needs.

答:
You'd have to store the last allocated identifier in the sequence.

For example, store it in another table that has one column & one row.

```<code>CREATE TABLE CurrentMaxId (
    Id CHAR(6) NOT NULL
);

INSERT INTO CurrentMaxId (Id) VALUES ('AAAAAA');
</code>```

Each time you allocate a new identifier, you'd fetch the value in that tiny table, increment it, and store that value in your main table as well as updating the value in CurrentMaxId.

The usual caveats apply with respect to concurrency, table-locking, etc.

OwnerDisplayName: Coderer

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Coderer

Body:
You'd have to store the last allocated identifier in the sequence.

For example, store it in another table that has one column & one row.

CREATE TABLE CurrentMaxId (
    Id CHAR(6) NOT NULL
);

INSERT INTO CurrentMaxId (Id) VALUES ('AAAAAA');

Each time you allocate a new identifier, you'd fetch the value in that tiny table, increment it, and store that value in your main table as well as updating the value in CurrentMaxId.

The usual caveats apply with respect to concurrency, table-locking, etc.

OwnerDisplayName: Bill Karwin