问:
Loop for multiple buttons in Python, Kivy
I have creating multiple buttons via for loop in Python/Kivy. I can't figureout how to implement for each button on_press and on_release function, so each button (having it's defined color) will come back to its original color after releasing.

Below You will find part of code in python and kivy.

Python:

```<code>class PrButton(GridLayout):

def __init__(self, **kwargs):
    super(PrButton, self).__init__(**kwargs)
    self.build_grid()

def build_grid(self):
    for i in hi_cat():
        btn = ButtonDD(text=i[0].upper())
        btn.background_color = i[1]
        self.ids[i[0]] = btn
        self.add_widget(btn)
</code>```

kivy file:

```<code><ButtonDD>
bold: True
</code>```

答:
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

KV = """
<MainWidget>:
    size : root.size

"""

class MainWidget(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

        for i in range(5):

            btn = Button(text = str(i))
            btn.bind(on_release = lambda i=i:self.clicked(i))
            self.add_widget(btn)

    def clicked(self,text):
        print(text)

class MainApp(MDApp):
    def build(self):

        Builder.load_string(KV)

        return MainWidget()

MainApp().run()
```

It is achieved by changing lambda x: self.clicked() To lambda i=i:self.clicked()

I've been stuck with this kind of problem for some time now.  But I got my answer recently. So I hope this helps you

Body:
I have creating multiple buttons via for loop in Python/Kivy. I can't figureout how to implement for each button on_press and on_release function, so each button (having it's defined color) will come back to its original color after releasing.

Below You will find part of code in python and kivy.

Python:

class PrButton(GridLayout):

def __init__(self, **kwargs):
    super(PrButton, self).__init__(**kwargs)
    self.build_grid()

def build_grid(self):
    for i in hi_cat():
        btn = ButtonDD(text=i[0].upper())
        btn.background_color = i[1]
        self.ids[i[0]] = btn
        self.add_widget(btn)

kivy file:

<ButtonDD>
bold: True

Body:
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

KV = """
<MainWidget>:
    size : root.size

"""

class MainWidget(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

        for i in range(5):

            btn = Button(text = str(i))
            btn.bind(on_release = lambda i=i:self.clicked(i))
            self.add_widget(btn)

    def clicked(self,text):
        print(text)

class MainApp(MDApp):
    def build(self):

        Builder.load_string(KV)

        return MainWidget()

MainApp().run()

It is achieved by changing lambda x: self.clicked() To lambda i=i:self.clicked()

I've been stuck with this kind of problem for some time now.  But I got my answer recently. So I hope this helps you


来源: stackexchange

问:
Constant expression required in Java switch statement
I have ths piece of code in Java

```<code> final String workFlowKey = getProcessDefinitionKey();

        switch (workFlowKey) {
            case WorkflowKey.DOG_WORKFLOW.getKey():
                return "A";
                break;
            default: return null;
        }
</code>```

but I have this compilation error: Constant expression required

答:
The error tells you exactly what is wrong.

Case labels must be compile-time constants. This:

```<code>case WorkflowKey.DOG_WORKFLOW.getKey():
</code>```

has a method call, which is not known at compile time (according to the rules for determining what is constant).

Is WorkflowKey an enum type?  Then you should just be switching on the enumerated constants:

```<code>case DOG_WORKFLOW:
</code>```

You'll need a way to get the enum value from the 'process definition' instead of the String you're getting, of course.

ContentLicense: CC BY-SA 4.0

Body:
I have ths piece of code in Java

 final String workFlowKey = getProcessDefinitionKey();

        switch (workFlowKey) {
            case WorkflowKey.DOG_WORKFLOW.getKey():
                return "A";
                break;
            default: return null;
        }

but I have this compilation error: Constant expression required

Body:
The error tells you exactly what is wrong.

Case labels must be compile-time constants. This:

case WorkflowKey.DOG_WORKFLOW.getKey():

has a method call, which is not known at compile time (according to the rules for determining what is constant).

Is WorkflowKey an enum type?  Then you should just be switching on the enumerated constants:

case DOG_WORKFLOW:

You'll need a way to get the enum value from the 'process definition' instead of the String you're getting, of course.


问:
SQL Server User define function giving error
I Create the below UDF IN SQL Server

```<code>CREATE Function [Fn_dd]
(@InputstartDate Date, @InputendDate Date)
returns @AllDates Table
    (AllDate Date)
As
Begin
    Declare @startDate date
    Declare @endDate date
    Declare @rDate date
    set @startDate  = @InputstartDate
    set @EndDate  = @InputendDate

    while (@startDate <=  @endDate)
    Begin
        insert into @AllDates values (@startDate )
        set @startDate = DATEADD(dd,1,@startDate)
    End
return
End
GO
</code>```

But when I use it in my data it gives an error

```<code>select
 dbo.Fn_dd('2020-01-02','2020-02-08')
from dbo.Txns
</code>```

error message

```<code>Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Fn_dd", or the name is ambiguous.
</code>```

Any Idea why?

答:
Your function returns a table. You cannot use it in SELECT; you must use it in FROM:

select * FROM dbo.Fn_dd('2020-01-02','2020-02-08')

Body:
I Create the below UDF IN SQL Server

CREATE Function [Fn_dd]
(@InputstartDate Date, @InputendDate Date)
returns @AllDates Table
    (AllDate Date)
As
Begin
    Declare @startDate date
    Declare @endDate date
    Declare @rDate date
    set @startDate  = @InputstartDate
    set @EndDate  = @InputendDate

    while (@startDate <=  @endDate)
    Begin
        insert into @AllDates values (@startDate )
        set @startDate = DATEADD(dd,1,@startDate)
    End
return
End
GO

But when I use it in my data it gives an error

select
 dbo.Fn_dd('2020-01-02','2020-02-08')
from dbo.Txns

error message

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Fn_dd", or the name is ambiguous.

Any Idea why?


问:
Flatlist with multiple checkbox React Native
I am using flatlist with checkboxes and I want to save the data of selected item into an array but can't be able to save the data in array

my json response

```<code>{
 "tS_CT_CODE": "ELC",
 "tS_TASK_CODE": "ELC001",
 "tS_TITLE": "Light Problem",
 "tS_TITLE_AR": "",
 "tS_PRICE": 100.0,
 "tS_STATUS": "A",
 "tS_USER_ID": "",
 "tS_SYSTEM_DATE": ""
}
</code>```

I want to save tsPrice in different array and tsTitle in different array I am just able to do save only ts_title in taskName as you can see below how can I save ts_price in different array?

here is my CheckBox

```<code>const [toggleCheckBox, setToggleCheckBox] = useState([]);

<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>

const handleListTap = async item => {
  const taskName = [...toggleCheckBox];
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
   } else {
     taskName.push(item.tS_TITLE);
   }
  console.log(taskName);
  setToggleCheckBox(taskName);
  // navigation.navigate('MaintenanceTimeSlot');
};
</code>```

答:
From above code I am assuming that your are passing an array with JSON response object mentioned above to a Flatlist component and CheckBox is Flatlist's child component. So in that case you can create another array for prices like shown below

```<code>...
const [toggleCheckBox, setToggleCheckBox] = useState([]);
const [priceArray, setPriceArray] = useState([]);   // add this
...
<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>
...
const handleListTap = async item => {
  let taskName = [...toggleCheckBox];
  let taskPrice = [...priceArray];    // add this
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
     taskPrice.splice(index, 1);     // add this
   } else {
     taskName.push(item.tS_TITLE);
     taskPrice.push(item.tS_TITLE);  // add this
   }
  console.log(taskName, taskPrice);
  setToggleCheckBox(taskName);
  setPriceArray(taskPrice);          // add this
  // navigation.navigate('MaintenanceTimeSlot');
};
...
</code>```

Body:
I am using flatlist with checkboxes and I want to save the data of selected item into an array but can't be able to save the data in array

my json response

{
 "tS_CT_CODE": "ELC",
 "tS_TASK_CODE": "ELC001",
 "tS_TITLE": "Light Problem",
 "tS_TITLE_AR": "",
 "tS_PRICE": 100.0,
 "tS_STATUS": "A",
 "tS_USER_ID": "",
 "tS_SYSTEM_DATE": ""
}

I want to save tsPrice in different array and tsTitle in different array I am just able to do save only ts_title in taskName as you can see below how can I save ts_price in different array?

here is my CheckBox

const [toggleCheckBox, setToggleCheckBox] = useState([]);

<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>

const handleListTap = async item => {
  const taskName = [...toggleCheckBox];
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
   } else {
     taskName.push(item.tS_TITLE);
   }
  console.log(taskName);
  setToggleCheckBox(taskName);
  // navigation.navigate('MaintenanceTimeSlot');
};

Body:
From above code I am assuming that your are passing an array with JSON response object mentioned above to a Flatlist component and CheckBox is Flatlist's child component. So in that case you can create another array for prices like shown below

...
const [toggleCheckBox, setToggleCheckBox] = useState([]);
const [priceArray, setPriceArray] = useState([]);   // add this
...
<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>
...
const handleListTap = async item => {
  let taskName = [...toggleCheckBox];
  let taskPrice = [...priceArray];    // add this
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
     taskPrice.splice(index, 1);     // add this
   } else {
     taskName.push(item.tS_TITLE);
     taskPrice.push(item.tS_TITLE);  // add this
   }
  console.log(taskName, taskPrice);
  setToggleCheckBox(taskName);
  setPriceArray(taskPrice);          // add this
  // navigation.navigate('MaintenanceTimeSlot');
};
...


问:
How to encrypt PartitionKey and RowKey in an azure table when storing data?
I have an azure table with multiple columns and I am able to successfully encrypt the data in those columns. The only issue I have is that I am not able to encrypt the PartitionKey and RowKey.

I have used this document https://learn.microsoft.com/en-us/azure/storage/common/storage-client-side-encryption to set up the encryption. It works fine except for PartitionKey and RowKey.

```<code>[EncryptProperty]
public new string PartitionKey { get; set; }
[EncryptProperty]
public new string RowKey { get; set; }
</code>```

Tried the above but it is not encrypting the Partition and Row keys.

Any help is appreciated.

答:
Not sure why this answer got accepted as the correct one. You can encrypt your Rowkey in c# code and send it to the Table storage. Something like:

```<code>BitConverter.ToString(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(RowKeyData)))
            .Replace("-", string.Empty)
            .ToLower();
</code>```

Then you can InsertOrReplace the entity with your Rowkey encrypted.

Body:
I have an azure table with multiple columns and I am able to successfully encrypt the data in those columns. The only issue I have is that I am not able to encrypt the PartitionKey and RowKey.

I have used this document https://learn.microsoft.com/en-us/azure/storage/common/storage-client-side-encryption to set up the encryption. It works fine except for PartitionKey and RowKey.

[EncryptProperty]
public new string PartitionKey { get; set; }
[EncryptProperty]
public new string RowKey { get; set; }

Tried the above but it is not encrypting the Partition and Row keys.

Any help is appreciated.

Body:
Not sure why this answer got accepted as the correct one. You can encrypt your Rowkey in c# code and send it to the Table storage. Something like:

BitConverter.ToString(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(RowKeyData)))
            .Replace("-", string.Empty)
            .ToLower();

Then you can InsertOrReplace the entity with your Rowkey encrypted.


问:
Change background-image with jQuery - doesn´t work
```<code>$('#areaView').css('background-image', 'url(/areaNr1.jpg)');
</code>```

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

答:
If the html file that is running the jQuery is in the same folder as your image try:

```<code>$('#areaView').css("background", "url('areaNr1.jpg')");
</code>```

If the image is in a folder it would be

```<code>$('#areaView').css("background", "url('folder/areaNr1.jpg')");
</code>```

or if its in the directory above

```<code>$('#areaView').css("background", "url('../areaNr1.jpg')");
</code>```

If the image is in /JQuery where is the html file?

ContentLicense: CC BY-SA 3.0

Body:
$('#areaView').css('background-image', 'url(/areaNr1.jpg)');

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

Body:
If the html file that is running the jQuery is in the same folder as your image try:

$('#areaView').css("background", "url('areaNr1.jpg')");

If the image is in a folder it would be

$('#areaView').css("background", "url('folder/areaNr1.jpg')");

or if its in the directory above

$('#areaView').css("background", "url('../areaNr1.jpg')");

If the image is in /JQuery where is the html file?


问:
Flutter/Dart : Parsing 'yyyy-MM-dd HH:MM:SS' producing wrong output?
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

```<code>final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");
</code>```

Actual Output:

```<code>DATE_CALC 7 - 2 - 2021 5 : 0 : 0
</code>```

Expected :

```<code>DATE_CALC 07 - 12 - 2022 05 : 00 : 11
</code>```

Why I am getting some wrong date ? Am I doing anything wrong ?

答: it should be final datm =  DateFormat('yyyy-MM-dd HH:mm:ss').parse(dt);

Body:
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");

Actual Output:

DATE_CALC 7 - 2 - 2021 5 : 0 : 0

Expected :

DATE_CALC 07 - 12 - 2022 05 : 00 : 11

Why I am getting some wrong date ? Am I doing anything wrong ?


问:
Returning cells as a Matrix VBA
I have a bunch of cells in a sheet that look like this:

Each rows has a gap of 3, and columns a gap of 5.

Id like to extract these values and copy it to some area:

How would I grab each cell and create a matrix like so. Im trying to use a VBA sub() for this, as the initial table size can vary but Im not sure how to do it. Any thoughts appreciated.

答:
If you dispose of the newer dynamic functions of MS 365 it suffices to enter
the following formula in any target range to get a spilling result:

```<code>    =LET(data,A1:P10,r,SEQUENCE(4,1,1,3),c,SEQUENCE(1,4,1,5),INDEX(data,r,c))

</code>```

If you prefer a VBA approach you might use the following procedure;
it

gets the needed data into a 2-dim data field array (see 1.)

calculates the needed row & column indices via Sequence() (see 2.a)) and

passes them
to the Index() function executing the transformation into a 4x4 matrix (see 2.b)):

```<code>Sub transform(rng As Range, _
       Optional ByVal rowOffset As Long = 3, _
       Optional ByVal colOffset As Long = 5)
'Note: assumes 4x4 matrix with start in first row/column element
'1. get data (1-based 2-dim datafield array)
    Dim data: data = rng.Value2
'2. transform data
    With Application
    'a) define row/column indices to be maintained
        Dim r: r = .Sequence(4, 1, 1, rowOffset) ' vert 1 ..4 ..7 ..10
        Dim c: c = .Sequence(1, 4, 1, colOffset) ' flat Array(1,6,11,16)
    'b) transform data
        data = .Index(data, r, c)        ' reduce to 4x4 matrix
    End With
'3. write data to any target             ' change to your needs
    Sheet2.Range("A1").resize(UBound(data), UBound(data, 2)) =  data
End Sub

</code>```

Example call

```<code>Sub ExampleCall()
    Dim rng As Range
    Set rng = Sheet1.Range("A1:P10")
    transform rng
End Sub
</code>```

For more backwards compatibility you could replace the sequence function by your own udf

Title: Returning cells as a Matrix VBA

Body:
If you dispose of the newer dynamic functions of MS 365 it suffices to enter
the following formula in any target range to get a spilling result:

    =LET(data,A1:P10,r,SEQUENCE(4,1,1,3),c,SEQUENCE(1,4,1,5),INDEX(data,r,c))

If you prefer a VBA approach you might use the following procedure;
it

gets the needed data into a 2-dim data field array (see 1.)

calculates the needed row & column indices via Sequence() (see 2.a)) and

passes them
to the Index() function executing the transformation into a 4x4 matrix (see 2.b)):

Sub transform(rng As Range, _
       Optional ByVal rowOffset As Long = 3, _
       Optional ByVal colOffset As Long = 5)
'Note: assumes 4x4 matrix with start in first row/column element
'1. get data (1-based 2-dim datafield array)
    Dim data: data = rng.Value2
'2. transform data
    With Application
    'a) define row/column indices to be maintained
        Dim r: r = .Sequence(4, 1, 1, rowOffset) ' vert 1 ..4 ..7 ..10
        Dim c: c = .Sequence(1, 4, 1, colOffset) ' flat Array(1,6,11,16)
    'b) transform data
        data = .Index(data, r, c)        ' reduce to 4x4 matrix
    End With
'3. write data to any target             ' change to your needs
    Sheet2.Range("A1").resize(UBound(data), UBound(data, 2)) =  data
End Sub

Example call

Sub ExampleCall()
    Dim rng As Range
    Set rng = Sheet1.Range("A1:P10")
    transform rng
End Sub

For more backwards compatibility you could replace the sequence function by your own udf


问:
How to add more context into panick_info when catching?
In my project I have a panic hook which sends an HTTP request reporting an issue when some unplanned unwrap occurs. I am executing some function 100 times and I would like to somehow know when the panic occurs which of the executions it was in case the panic happened inside the function. Is it possible to somehow add a string to an intercepted unrolling of panic_info or how do people handle this?

I was thinking something along the lines of using catch_unwind, modifying the caught err and resuming the unwind, but the err is of opaque type so I don't see a way to add something to it. I see that panic_info has payload, is it somehow possible to add to it?

I would like to avoid having some global mutex which I can then modify when catching the unwind

答: You can use std::panic::PanicInfo::location to get the file, line number, and column of the panic.


问:
How can I run a command or script in rosetta from terminal on M1 Mac?
How can I run a program or shell script in Rosetta from Terminal? I don't want to run the whole terminal in Rosetta. Just the parts I need.</p>

答:
The arch command is useful for that purpose

```<code>arch -arch_name binary args ...
</code>```

See man arch for more details

Example without rosetta:

```<code>echo "arch" > build.sh
arch -arm64 /bin/bash ./build.sh
</code>```

Output:

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

(could run this with /bin/bash ./build.sh directly)

Example with rosetta:

```<code>echo "arch" > build.sh
arch -x86_64 /bin/bash ./build.sh
</code>```

Output:

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

Body:
The arch command is useful for that purpose

arch -arch_name binary args ...

See man arch for more details

Example without rosetta:

echo "arch" > build.sh
arch -arm64 /bin/bash ./build.sh

Output:

arm64

(could run this with /bin/bash ./build.sh directly)

Example with rosetta:

echo "arch" > build.sh
arch -x86_64 /bin/bash ./build.sh

Output:

i386


问:
'No frame for given id found' in puppetter
i am using puppetter for web scrapping ;
matchesLinks is an array that contains urls of some games.
my code looks like :

```<code>for (let i = 0; i < matchesLinks.length; i++) {
   await page.goto(matchesLinks[i]);
   await page.goto(matchesLinks[i]);
   await new Promise((r) => setTimeout(r, 6000));
 }
</code>```

after going to 1 or 2 URL i get error: originalMessage: 'No frame for given id found'
anyone can help my why i am getting this error

答:
I have been trying to solve the issue since 3 days now.. no luck at all..
Though the issue disappears completely if you set "headless: true" at browser's launch options.. So this issue is only associated with "headless: false" setting.

For those who try to help. The issue happens when using "page.goto" to access a website that have iframes, and redirect requests (Trying to abort those requests, or waituntil domcontentloaded won't solve the issue if you were wondering). E.g. it happens every time when trying to access "https://www.whatismyip.com/"

Body:
i am using puppetter for web scrapping ;
matchesLinks is an array that contains urls of some games.
my code looks like :

for (let i = 0; i < matchesLinks.length; i++) {
   await page.goto(matchesLinks[i]);
   await page.goto(matchesLinks[i]);
   await new Promise((r) => setTimeout(r, 6000));
 }

after going to 1 or 2 URL i get error: originalMessage: 'No frame for given id found'
anyone can help my why i am getting this error


问:
TypeScript error after upgrading version 4 useParams () from react-router-dom Property 'sumParams' does not exist on type '{}'
I get a typeScript error after upgrading to  version 4
Used in useParams ()  from react-router-dom

"typescript": "^4.0.2"

```<code>import { useParams } from 'react-router-dom';

const { sumParams } = useParams();

</code>```
```<code>Property 'sumParams' does not exist on type '{}'.
</code>```

The project worked great and only after the upgrade does it throw an error

答:
For newer versions of the router, generic is changed from object to union of strings.

const { param1, param2 } = useParams<'param1' | 'param2'>();
```
<p>Current <code>useParams</code> type in the <code>react-router</code> types looks like this:</p>
<pre class="lang-js prettyprint-override"><code>export declare function useParams<Key extends string = string>(): Readonly<Params<Key>>;
</code>```

Body:
I get a typeScript error after upgrading to  version 4
Used in useParams ()  from react-router-dom

"typescript": "^4.0.2"

import { useParams } from 'react-router-dom';

const { sumParams } = useParams();

Property 'sumParams' does not exist on type '{}'.

The project worked great and only after the upgrade does it throw an error

Body:
For newer versions of the router, generic is changed from object to union of strings.

const { param1, param2 } = useParams<'param1' | 'param2'>();

Current useParams type in the react-router types looks like this:

export declare function useParams<Key extends string = string>(): Readonly<Params<Key>>;


问:
What is the proper Resource value in AWS Step Function SendTaskSuccess task
I am creating an async task using AWS Step Functions. I created a Step Function calling another Step Function with .waitForTaskToken and stored Task Token in DB.
Now I'm creating another Step Function that processes a message from API Gateway and calls SendTaskSuccess. Here is the exact state, the Workflow Studio generated for me:

```<code>    "SendTaskSuccess": {
      "Type": "Task",
      "End": true,
      "Parameters": {
        "output": "{}",
        "taskToken.$": "$.taskToken"
      },
      "Resource": "arn:aws:states:::aws-sdk:states:sendTaskSuccess"
    },
</code>```

My problem is that when I'm saving the Step Function, it tells me this:

```<code>There are Amazon States Language errors in your state machine definition. Fix the errors to continue.
The resource provided arn:aws:states:::aws-sdk:states:sendTaskSuccess is not recognized. The value is not a valid resource ARN, or the resource is not available in this region.
For more information, see Amazon States Language
</code>```

So my question is - what would be the proper Resource value for this task? In the Workflow Studio, there is no way to specify any resource to use, it generates the ARN above automatically

答:
I ran into a similar issue and it appears
arn:aws:states:::aws-sdk:sfn:sendTaskSuccess (sfn instead of states) is the correct arn.
Furthermore, the parameters should start with an uppercase letter:

```<code>"Parameters": {
  "TaskToken.$": "$.taskToken",
  "Output.$": "$.outputs"
}
</code>```

I also checked the Workflow Studio, which produced the above arn in my case.

Body:
I am creating an async task using AWS Step Functions. I created a Step Function calling another Step Function with .waitForTaskToken and stored Task Token in DB.
Now I'm creating another Step Function that processes a message from API Gateway and calls SendTaskSuccess. Here is the exact state, the Workflow Studio generated for me:

    "SendTaskSuccess": {
      "Type": "Task",
      "End": true,
      "Parameters": {
        "output": "{}",
        "taskToken.$": "$.taskToken"
      },
      "Resource": "arn:aws:states:::aws-sdk:states:sendTaskSuccess"
    },

My problem is that when I'm saving the Step Function, it tells me this:

There are Amazon States Language errors in your state machine definition. Fix the errors to continue.
The resource provided arn:aws:states:::aws-sdk:states:sendTaskSuccess is not recognized. The value is not a valid resource ARN, or the resource is not available in this region.
For more information, see Amazon States Language

So my question is - what would be the proper Resource value for this task? In the Workflow Studio, there is no way to specify any resource to use, it generates the ARN above automatically

Body:
I ran into a similar issue and it appears
arn:aws:states:::aws-sdk:sfn:sendTaskSuccess (sfn instead of states) is the correct arn.
Furthermore, the parameters should start with an uppercase letter:

"Parameters": {
  "TaskToken.$": "$.taskToken",
  "Output.$": "$.outputs"
}

I also checked the Workflow Studio, which produced the above arn in my case.


问:
Setting center of borderpane form another controller class
I have Borderpane as homePane (its fxml file is home.fxml). At first in center of homePane i have a HBox which contains a button   called delivery. When the user clicks this button, the center of homePane switchs to display the list of customers.
It works !

The code of homeController :

```<code>public class HomeController {

@FXML
private BorderPane homePane;

@FXML
public void deliveryBtnClicked (){
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fragments/customers.fxml"));
    homePane.getChildren().remove(homePane.getCenter());
    try {
        Pane pane = loader.load();
        homePane.setCenter(pane);

    }catch (IOException e){
        System.out.println(e.getMessage());
    }
}

public BorderPane getHomePane() {
    return homePane;
}
}
</code>```

The new Pane contains the table of customers and a button called order. It has own Controller :

```<code>public class CustomerController {

    @FXML
    public void loadOrderView() throws IOException {
        Customer customer = customerTable.getSelectionModel().getSelectedItem();
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("/home.fxml"));
        loader.load();

        HomeController homeController =  loader.getController();
        BorderPane homePane = homeController.getHomePane();

        homePane.getChildren().remove(homePane.getCenter());
        System.out.println(homePane.getCenter());
        FXMLLoader loader1 = new FXMLLoader(getClass().getResource("/fragments/order.fxml"));
        Pane orderView = loader1.load();
        homePane.setCenter(orderView);
        System.out.println(homePane.getCenter());
     }
}
</code>```

When user clicks the button order, the order-view have to be loaded in the center of homePane.
the print command shows that the homePane center after removed is null and then after loaded gets new view.

```<code>null
AnchorPane@755b1503
</code>```

But in running Programm its doen't show the order view. I have set onAction of button order to loadOrderView. This is definitive not the problem.

答:
As James has pointed out, you should not load the home fxml again.

Instead:

Define the orderButton in your controller and in your fxml (via a fx:id and @FXML injection).

Use the scene graph to find the home pane so that you can replace its center.

```<code>public class CustomerController {

    @FXML Button orderButton

    @FXML
    public void loadOrderView() throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fragments/order.fxml"));
        Pane orderView = loader.load();
        BorderPane homePane = (BorderPane) orderButton.getScene().getRoot();
        homePane.setCenter(orderView);
     }
}
</code>```

An alternate method in a small framework is defined in the answer to:

Loading new fxml in the same scene

Body:
I have Borderpane as homePane (its fxml file is home.fxml). At first in center of homePane i have a HBox which contains a button   called delivery. When the user clicks this button, the center of homePane switchs to display the list of customers.
It works !

The code of homeController :

public class HomeController {

@FXML
private BorderPane homePane;

@FXML
public void deliveryBtnClicked (){
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fragments/customers.fxml"));
    homePane.getChildren().remove(homePane.getCenter());
    try {
        Pane pane = loader.load();
        homePane.setCenter(pane);

    }catch (IOException e){
        System.out.println(e.getMessage());
    }
}

public BorderPane getHomePane() {
    return homePane;
}
}

The new Pane contains the table of customers and a button called order. It has own Controller :

public class CustomerController {

    @FXML
    public void loadOrderView() throws IOException {
        Customer customer = customerTable.getSelectionModel().getSelectedItem();
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("/home.fxml"));
        loader.load();

        HomeController homeController =  loader.getController();
        BorderPane homePane = homeController.getHomePane();

        homePane.getChildren().remove(homePane.getCenter());
        System.out.println(homePane.getCenter());
        FXMLLoader loader1 = new FXMLLoader(getClass().getResource("/fragments/order.fxml"));
        Pane orderView = loader1.load();
        homePane.setCenter(orderView);
        System.out.println(homePane.getCenter());
     }
}

When user clicks the button order, the order-view have to be loaded in the center of homePane.
the print command shows that the homePane center after removed is null and then after loaded gets new view.

null
AnchorPane@755b1503

But in running Programm its doen't show the order view. I have set onAction of button order to loadOrderView. This is definitive not the problem.

Body:
As James has pointed out, you should not load the home fxml again.

Instead:

Define the orderButton in your controller and in your fxml (via a fx:id and @FXML injection).

Use the scene graph to find the home pane so that you can replace its center.

public class CustomerController {

    @FXML Button orderButton

    @FXML
    public void loadOrderView() throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fragments/order.fxml"));
        Pane orderView = loader.load();
        BorderPane homePane = (BorderPane) orderButton.getScene().getRoot();
        homePane.setCenter(orderView);
     }
}

An alternate method in a small framework is defined in the answer to:

Loading new fxml in the same scene


问:
Get the nearest location from start location
I want to get the nearest location of predefined locations to the start location.

for example :
Post https://geocode.search.hereapi.com/v1/
geocode

Body:

```<code>{
from:{
counrtyCode:"US",
city:"NewYouk",
Postcode:"55555"
},
to:[
{
counrtyCode:"US",
city:"NewYouk",
Postcode:"66666"
},
{
counrtyCode:"US",
city:"NewYouk",
Postcode:"77777"
}
]
</code>```

I want to check which one in the TO List is the nearest to The FROM location.
Do we have something like this in HERE Rest API ?

答: you can do something like geocoordinate1.distanceTo(geocoordinate2) to get the distance between any two geocoordinates and do this for a list of geocoordinates and take the least one.</p>

Body:
I want to get the nearest location of predefined locations to the start location.

for example :
Post https://geocode.search.hereapi.com/v1/
geocode

Body:

{
from:{
counrtyCode:"US",
city:"NewYouk",
Postcode:"55555"
},
to:[
{
counrtyCode:"US",
city:"NewYouk",
Postcode:"66666"
},
{
counrtyCode:"US",
city:"NewYouk",
Postcode:"77777"
}
]

I want to check which one in the TO List is the nearest to The FROM location.
Do we have something like this in HERE Rest API ?


问:
Sending erc20 tokens using Web3js
I have tried to send erc20 (Bela) from one address to another got tx id in a result, but this transaction is not appearing in any tx check services and no funds sent from my address.
code at the moment looks like this:

web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/PKEY'));

var myAddress = "0x4d0...";
var toAddress = "0xce6...";
var amount = web3.utils.toHex(5);

var count = web3.eth.getTransactionCount(myAddress).then(function(v){console.log(v); count = v});

var privateKey = new Buffer('pkey', 'hex');

//got from https://etherscan.io/address/0x2e98a6804e4b6c832ed0ca876a943abd3400b224#code
var abiArray = '';

var contractAddress = '0x2e98a6804e4b6c832ed0ca876a943abd3400b224';
var contract = new web3.eth.Contract(abiArray, contractAddress, {from: myAddress});

var rawTransaction = {
    "from":myAddress,
    "gasPrice":"0x098bca5a00",
    "gasLimit":"0xcb05",
    "to":contractAddress,
    "value":"0x0",
    "data":contract.methods.transfer(toAddress, amount).encodeABI(),
    "nonce":web3.utils.toHex(count)
};
var transaction = new Tx(rawTransaction);
transaction.sign(privateKey);

web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'), function (err, hash) {
    console.log(err, hash);
});```

答: Update the "to" address within the transaction object using contract._address</p>

Title: Sending erc20 tokens using Web3js


问:
SwiftUI Previews w/Mock Realm
I am running into a problem trying to use an in memory realm configuration with previews. When the preview executes it returns an error. The diagnostics gives the following error:

MessageError: Connection interrupted

I have the following class defined to mock the realm data.

```<code>class MockRealms {
   static var previewRealm: Realm {
      get {
         var realm: Realm
         let identifier = "previewRealm"
         let config = Realm.Configuration(inMemoryIdentifier: identifier)
         do {
            realm = try Realm(configuration: config)
            try realm.write {
               for category in Categories.allCases {
                  _ = Category(name: category.rawValue)
               }
            }
            try realm.write {
               _ = Settings(type: .fixed, int: 3.375, dp: 25.0, term: 30)
            }
            return realm
         } catch let error {
            fatalError("Error: \(error.localizedDescription)")
         }
      }
   }
}
</code>```

In the view we are using the @ObservedResults to get the categories from the Realm.

```<code>struct PropertyListView: View {
   @ObservedResults(Category.self) var categories
   @Binding var showInfo: Bool
   @Binding var showInfoButton: Bool
   @Binding var showGuide: Bool
   @Binding var showGuideButtton: Bool

   var body: some View {
      NavigationView {
         ScrollView {
            VStack {
               ForEach(categories) { category in
                  PropertyCategoryView(category: category)
               }
            }
         }
      }
      .navigationBarTitle("Property List")
      .navigationBarBackButtonHidden(false)
   }
   .navigationViewStyle(.stack)
}
</code>```

The preview section is as follows:

```<code>struct PropertyListView_Previews: PreviewProvider {
   static var previews: some View {
      Group {
         PropertyListView(showInfo: .constant(false), showInfoButton:
            .constant(true), showGuide: .constant(false), showGuideButton:
            .constant(false))
            .environment(\.realm, MockRealms.previewRealm)
         PropertyListView(showInfo: .constant(false), showInfoButton:
            .constant(true), showGuide: .constant(false), showGuideButton:
            .constant(false))
            .environment(\.realm, MockRealms.previewRealm)
            .preferredColorScheme(.dark)
      }
   }
}
</code>```

Any help would be most appreciated.

答:
On the main content view I call the PropertyListView with an environment setting realmConfiguration and pass that into the PropertyListView. So I changed the PreviewProvider to pass simply the in-memory Realm configuration and then everything seems to work just fine.

```<code>struct PropertyListView_Previews: PreviewProvider {
   static var previews: some View {
      Group {
         PropertyListView(showInfo: .constant(false), showInfoButton:
           .constant(true), showGuide: .constant(false), showGuideButton:
           .constant(false))
           .environment(\.realmConfiguration, Realm.Configuration(inMemoryIdentifier: "previewRealm", schemaVersion: 1))
        PropertyListView(showInfo: .constant(false), showInfoButton:
           .constant(true), showGuide: .constant(false), showGuideButton:
           .constant(false))
           .environment(\.realmConfiguration, Realm.Configuration(inMemoryIdentifier: "previewRealm", schemaVersion: 1))
           .preferredColorScheme(.dark)
     }
  }
</code>```

}

With Realm changing almost every other day it is like walking on quicksand. It is a wonderful DB for mobile development because they are constantly making it better, but boy you really have to stay on top of the changes.

Title: SwiftUI Previews w/Mock Realm

Body:
I am running into a problem trying to use an in memory realm configuration with previews. When the preview executes it returns an error. The diagnostics gives the following error:

MessageError: Connection interrupted

I have the following class defined to mock the realm data.

class MockRealms {
   static var previewRealm: Realm {
      get {
         var realm: Realm
         let identifier = "previewRealm"
         let config = Realm.Configuration(inMemoryIdentifier: identifier)
         do {
            realm = try Realm(configuration: config)
            try realm.write {
               for category in Categories.allCases {
                  _ = Category(name: category.rawValue)
               }
            }
            try realm.write {
               _ = Settings(type: .fixed, int: 3.375, dp: 25.0, term: 30)
            }
            return realm
         } catch let error {
            fatalError("Error: \(error.localizedDescription)")
         }
      }
   }
}

In the view we are using the @ObservedResults to get the categories from the Realm.

struct PropertyListView: View {
   @ObservedResults(Category.self) var categories
   @Binding var showInfo: Bool
   @Binding var showInfoButton: Bool
   @Binding var showGuide: Bool
   @Binding var showGuideButtton: Bool

   var body: some View {
      NavigationView {
         ScrollView {
            VStack {
               ForEach(categories) { category in
                  PropertyCategoryView(category: category)
               }
            }
         }
      }
      .navigationBarTitle("Property List")
      .navigationBarBackButtonHidden(false)
   }
   .navigationViewStyle(.stack)
}

The preview section is as follows:

struct PropertyListView_Previews: PreviewProvider {
   static var previews: some View {
      Group {
         PropertyListView(showInfo: .constant(false), showInfoButton:
            .constant(true), showGuide: .constant(false), showGuideButton:
            .constant(false))
            .environment(\.realm, MockRealms.previewRealm)
         PropertyListView(showInfo: .constant(false), showInfoButton:
            .constant(true), showGuide: .constant(false), showGuideButton:
            .constant(false))
            .environment(\.realm, MockRealms.previewRealm)
            .preferredColorScheme(.dark)
      }
   }
}

Any help would be most appreciated.

Body:
On the main content view I call the PropertyListView with an environment setting realmConfiguration and pass that into the PropertyListView. So I changed the PreviewProvider to pass simply the in-memory Realm configuration and then everything seems to work just fine.

struct PropertyListView_Previews: PreviewProvider {
   static var previews: some View {
      Group {
         PropertyListView(showInfo: .constant(false), showInfoButton:
           .constant(true), showGuide: .constant(false), showGuideButton:
           .constant(false))
           .environment(\.realmConfiguration, Realm.Configuration(inMemoryIdentifier: "previewRealm", schemaVersion: 1))
        PropertyListView(showInfo: .constant(false), showInfoButton:
           .constant(true), showGuide: .constant(false), showGuideButton:
           .constant(false))
           .environment(\.realmConfiguration, Realm.Configuration(inMemoryIdentifier: "previewRealm", schemaVersion: 1))
           .preferredColorScheme(.dark)
     }
  }

}

With Realm changing almost every other day it is like walking on quicksand. It is a wonderful DB for mobile development because they are constantly making it better, but boy you really have to stay on top of the changes.


问:
EF Simple insert
This is the strangest thing ... maybe i'm having a blonde moment or something but why doesn't this work ...

```<code>FLMCommsEntities dal = new FLMCommsEntities();
foreach (Email email in mail)
{
    dal.EmailReceiveds.AddObject(new EmailReceived
    {
        FromAddress = email.From,
        ToAddress = email.To,
        EmailSubject = email.Subject,
        EmailBodyHtml = email.BodyHtml,
        EmailBodyPlain = email.BodyPlain,
        ReceivedOn = (DateTime)email.Date,
        AttachmentPath = email.AttachmentPath,
        EmailSize = email.Size,
        CreatedDate = DateTime.Now,
        DownloadComplete = true,
        ServerEmailID = email.ServerId
    });
}
// ask dal to save the new mail batch locally
dal.SaveChanges();
</code>```

It returns a sql exception saying i can't insert a duplicate primary key value ... clearly i'm not trying to insert a primary key value at all but make a new one instead !!!

GRRR ...

答:
Turns out i'm a dumbass and forgot to set "Identity Specifiction" on the PK field in the DB so EF didn't know that it was auto populated with a generated ID from the SQL Server.

Never mind ...

Got there in the end :)

Title: EF Simple insert

Body:
This is the strangest thing ... maybe i'm having a blonde moment or something but why doesn't this work ...

FLMCommsEntities dal = new FLMCommsEntities();
foreach (Email email in mail)
{
    dal.EmailReceiveds.AddObject(new EmailReceived
    {
        FromAddress = email.From,
        ToAddress = email.To,
        EmailSubject = email.Subject,
        EmailBodyHtml = email.BodyHtml,
        EmailBodyPlain = email.BodyPlain,
        ReceivedOn = (DateTime)email.Date,
        AttachmentPath = email.AttachmentPath,
        EmailSize = email.Size,
        CreatedDate = DateTime.Now,
        DownloadComplete = true,
        ServerEmailID = email.ServerId
    });
}
// ask dal to save the new mail batch locally
dal.SaveChanges();

It returns a sql exception saying i can't insert a duplicate primary key value ... clearly i'm not trying to insert a primary key value at all but make a new one instead !!!

GRRR ...


问:
Render Error: TypeError: -- undefined is not an object-- (evaluating 'asset.scales')
I am new to react-native I have this weird error I tried to solve but unable. I already checked all the same issue posted on GitHub and stack overflow but didn't solve my problem following is my code.
react-native (react-native-cli: 2.0.1)
node (v14.18.2)

```<code>import React from "react";
import { Image, ImageBackground, StyleSheet, View  } from 'react-native-web';

function WelcomeScreen(props) {
return (
    <ImageBackground
        style={styles.background}
        source={require("../assets/background.jpg")}>
        <Image style={styles.logo} source={require("../assets/logo-red.png")} />
        <View style={styles.loginButton}></View>
        <View style={styles.registerButton}></View>
    </ImageBackground>
);
}

const styles = StyleSheet.create({
background:{
    flex:1,
    justifyContent: "flex-end",
},
loginButton:{
    width: "100%",
    height: 70,
    backgroundColor: '#fc5c65',
},
registerButton:{
    width: "100%",
    height: 70,
    backgroundColor: '#4ecdc4  ',
},
logo:{
    width: 100,
    height: 100
},
});

export default WelcomeScreen;
</code>```

enter image description here

答:
It was the file import problem I have to use

```<code>react-native
</code>```

instead of

```<code>react-native-web
</code>```

if anyone has the above error use the below import

```<code>import { Image, StyleSheet, ImageBackground, View, Text} from 'react-native';
</code>```

Body:
I am new to react-native I have this weird error I tried to solve but unable. I already checked all the same issue posted on GitHub and stack overflow but didn't solve my problem following is my code.
react-native (react-native-cli: 2.0.1)
node (v14.18.2)

import React from "react";
import { Image, ImageBackground, StyleSheet, View  } from 'react-native-web';

function WelcomeScreen(props) {
return (
    <ImageBackground
        style={styles.background}
        source={require("../assets/background.jpg")}>
        <Image style={styles.logo} source={require("../assets/logo-red.png")} />
        <View style={styles.loginButton}></View>
        <View style={styles.registerButton}></View>
    </ImageBackground>
);
}

const styles = StyleSheet.create({
background:{
    flex:1,
    justifyContent: "flex-end",
},
loginButton:{
    width: "100%",
    height: 70,
    backgroundColor: '#fc5c65',
},
registerButton:{
    width: "100%",
    height: 70,
    backgroundColor: '#4ecdc4  ',
},
logo:{
    width: 100,
    height: 100
},
});

export default WelcomeScreen;

enter image description here

Body:
It was the file import problem I have to use

react-native

instead of

react-native-web

if anyone has the above error use the below import

import { Image, StyleSheet, ImageBackground, View, Text} from 'react-native';


问:
if [ $inst != "GPS" && $inst != "USRP" ] results in error: missing `]'
```<code>if [ $inst != "GPS" && $inst != "USRP" && $inst != "GCSM" &&  $inst != "EFMS" && $inst != "instAR" && $inst != "CRF" && $inst != "DBOR" && $inst != "PAL"     &&  $inst != "GRDB" && $inst != "GIOM" && $inst != "FA" && $inst != "WS" ]
then
    help
fi
</code>```

Error message:

```<code>30: [: missing `]'
</code>```

What does this mean and how do I fix it?

答:
Bash's error messages can be cryptic. Why does it say there's a missing ] when you have one at the end of the line? I don't blame you for finding that confusing.

Shell Check is a great tool for linting shell scripts, often producing much better diagnostics with links to detailed writeups. For your script it reports:

SC2107 (error): Instead of [ a && b ], use [ a ] && [ b ].

The full explanation for SC2107 reads:

Instead of [ a && b ], use [ a ] && [ b ].

Problematic code:

[ "$1" = "-v" && -z "$2" ]
```
<h3>Correct code:</h3>
<pre class="lang-sh prettyprint-override"><code>[ "$1" = "-v" ] && [ -z "$2" ]
</code>```

Rationale:

&& can not be used in a [ .. ] test expression. Instead, make two [ .. ] expressions and put the && between them.

Exceptions:

None.

Related resources:

Bash Pitfalls: [ "$foo" = bar && "$bar" = foo ]

StackOverflow: using and (&&) operator in if statement bash script

An alternative way to write the check is to use a case block.

```<code>case "$inst" in
    GPS|USRP|GCSM|EFMS|instAR|CRF|DBOR|PAL|GRDB|GIOM|FA|WS)
        # match
        ;;

    *)
        # no match
        help
        ;;
esac
</code>```

Or you could use =~ to match against a regular expression. Note that this requires the use of double square brackets [[ as well, and therefore requires a #!/bin/bash shebang. It won't work in a plain #!/bin/sh script.

```<code>#!/bin/bash

if ! [[ $inst =~ ^(GPS|USRP|GCSM|EFMS|instAR|CRF|DBOR|PAL|GRDB|GIOM|FA|WS)$ ]]
    help
fi
</code>```

Body:
if [ $inst != "GPS" && $inst != "USRP" && $inst != "GCSM" &&  $inst != "EFMS" && $inst != "instAR" && $inst != "CRF" && $inst != "DBOR" && $inst != "PAL"     &&  $inst != "GRDB" && $inst != "GIOM" && $inst != "FA" && $inst != "WS" ]
then
    help
fi

Error message:

30: [: missing `]'

What does this mean and how do I fix it?

Body:
Bash's error messages can be cryptic. Why does it say there's a missing ] when you have one at the end of the line? I don't blame you for finding that confusing.

Shell Check is a great tool for linting shell scripts, often producing much better diagnostics with links to detailed writeups. For your script it reports:

SC2107 (error): Instead of [ a && b ], use [ a ] && [ b ].

The full explanation for SC2107 reads:

Instead of [ a && b ], use [ a ] && [ b ].

Problematic code:

[ "$1" = "-v" && -z "$2" ]

Correct code:

[ "$1" = "-v" ] && [ -z "$2" ]

Rationale:

&& can not be used in a [ .. ] test expression. Instead, make two [ .. ] expressions and put the && between them.

Exceptions:

None.

Related resources:

Bash Pitfalls: [ "$foo" = bar && "$bar" = foo ]

StackOverflow: using and (&&) operator in if statement bash script

An alternative way to write the check is to use a case block.

case "$inst" in
    GPS|USRP|GCSM|EFMS|instAR|CRF|DBOR|PAL|GRDB|GIOM|FA|WS)
        # match
        ;;

    *)
        # no match
        help
        ;;
esac

Or you could use =~ to match against a regular expression. Note that this requires the use of double square brackets [[ as well, and therefore requires a #!/bin/bash shebang. It won't work in a plain #!/bin/sh script.

#!/bin/bash

if ! [[ $inst =~ ^(GPS|USRP|GCSM|EFMS|instAR|CRF|DBOR|PAL|GRDB|GIOM|FA|WS)$ ]]
    help
fi


问:
How to fix "Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass?
I've started a project using java 16 and I'm getting errors in the project all over the place:

```<code>An error has occurred. See error log for more details.
Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @6dfcffb5
</code>```

It looks like the code I have from different version of java is not working in this particular
version. Any idea what I need to change maybe in the pojo class.
I have only 1 pojo in the application cause it is micro service.

Thanks.

答:
You can just define the JRE system library by precising the path following the next steps: Project Folder -> Properties -> Java build path -> double clicks on JRE system library and choose your installed JRE, it works for me.
And sorry for my bad English</p>

Body:
I've started a project using java 16 and I'm getting errors in the project all over the place:

An error has occurred. See error log for more details.
Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @6dfcffb5

It looks like the code I have from different version of java is not working in this particular
version. Any idea what I need to change maybe in the pojo class.
I have only 1 pojo in the application cause it is micro service.

Thanks.


问:
"Dotting" in JSON using Gson on Android
I'm trying to parse a JSON feed using Gson in Android. I know the JSON is valid. I suspect that it is because the format is like this:

```<code> "Info":[
 {

"Id":"",
"Name":"",
"Description":"",
"Date":""
 }
</code>```

In order to parse this I need to "dot" in. Ex: Info.Name

How can I do this in a serialized DTO?

```<code>@SerializedName("Name")
public String name;

@SerializedName("Description")
public String desc;

@SerializedName("Date")
public String date;
</code>```

I tried to put "Info." in front of each serializedName but that didn't work either. I also know my JSON parsing method works properly, because it's used somewhere else with a different DTO. But in that parsing, I don't have to "dotting" issue.

Can anyone help?

EDIT: I have tried everything you guys posted, and nothing works. The error says:

```<code>The JsonDeserializer failed to deserialize json object {"Info":[{".......
</code>```

SECOND EDIT:
I was able to get rid of the error, but now it returns null. Haha, getting pretty damn frustrated right about now!

答:
I am assuming that the actual JSON you are intaking is valid because the example you provided is not. In your JSON example, you have "Info":[ but there is no outer object containing the "Info" property, which is a must. The valid JSON would be:

```<code>{
 "Info": [
           {
             "Id":"",
             "Name":"",
             "Description":"",
             "Date":"",
           }
         ]
}
</code>```

This is a JSON object that has a property "Info" which has a value that is a list of objects. This list of objects contains one object that has the properties "Id", "Name", "Description", and "Date", all of which have empty-string values.

Here is a quick tutorial on how to use GSON to parse a JSON feed such as the above JSON:

You will need a class to represent the items in the list:

```<code>public class InfoItem {
     public String Id;
     public String Name;
     public String Description;
     public String Date;
     public InfoItem() {}
}
</code>```

And one to represent the list of Items:

```<code>public class InfoItemList extends LinkedList<InfoItem> {
    public InfoItemList() { super() };
}
</code>```

This added complexity is because GSON cannot otherwise get the type of a generic collection from the class data.

And one to represent the overall JSON message:

```<code>public class InfoMessage {
    public InfoItemList Info;
    public InfoMessage() {};
}
</code>```

And then just:

```<code>gson.fromJson(jsonString, InfoMessage.getClass());
</code>```

If just de-serializing a collection:

```<code>Type listType = new TypeToken<List<InfoItem>>() {}.getType();
gson.fromJson(jsonString2, listType);
</code>```

Title: "Dotting" in JSON using Gson on Android

Body:
I'm trying to parse a JSON feed using Gson in Android. I know the JSON is valid. I suspect that it is because the format is like this:

 "Info":[
 {

"Id":"",
"Name":"",
"Description":"",
"Date":""
 }

In order to parse this I need to "dot" in. Ex: Info.Name

How can I do this in a serialized DTO?

@SerializedName("Name")
public String name;

@SerializedName("Description")
public String desc;

@SerializedName("Date")
public String date;

I tried to put "Info." in front of each serializedName but that didn't work either. I also know my JSON parsing method works properly, because it's used somewhere else with a different DTO. But in that parsing, I don't have to "dotting" issue.

Can anyone help?

EDIT: I have tried everything you guys posted, and nothing works. The error says:

The JsonDeserializer failed to deserialize json object {"Info":[{".......

SECOND EDIT:
I was able to get rid of the error, but now it returns null. Haha, getting pretty damn frustrated right about now!

Body:
I am assuming that the actual JSON you are intaking is valid because the example you provided is not. In your JSON example, you have "Info":[ but there is no outer object containing the "Info" property, which is a must. The valid JSON would be:

{
 "Info": [
           {
             "Id":"",
             "Name":"",
             "Description":"",
             "Date":"",
           }
         ]
}

This is a JSON object that has a property "Info" which has a value that is a list of objects. This list of objects contains one object that has the properties "Id", "Name", "Description", and "Date", all of which have empty-string values.

Here is a quick tutorial on how to use GSON to parse a JSON feed such as the above JSON:

You will need a class to represent the items in the list:

public class InfoItem {
     public String Id;
     public String Name;
     public String Description;
     public String Date;
     public InfoItem() {}
}

And one to represent the list of Items:

public class InfoItemList extends LinkedList<InfoItem> {
    public InfoItemList() { super() };
}

This added complexity is because GSON cannot otherwise get the type of a generic collection from the class data.

And one to represent the overall JSON message:

public class InfoMessage {
    public InfoItemList Info;
    public InfoMessage() {};
}

And then just:

gson.fromJson(jsonString, InfoMessage.getClass());

If just de-serializing a collection:

Type listType = new TypeToken<List<InfoItem>>() {}.getType();
gson.fromJson(jsonString2, listType);


问:
Flutter type 'String' is not a subtype of type 'Duration' problem
I use simpletimer package, and it has required duration. So when I try to set Duration(minutes: 5, hours: 1) for example, it shows 65 minutes. So I want to show to user 01:05:00 or 1:05:00 like this. How can I do this?

I found somethings like:

```<code> format(Duration d) => d.toString().split('.').first.padLeft(8, "0");
</code>```

but it gives

"string is not subtype of duration."

So I am stuck. Help.

My simleTimer:

```<code>     SimpleTimer(
progressTextStyle: const TextStyle(fontSize: 35),
status: TimerStatus.pause,
duration: format(Duration(hours: 1, minutes: 3))),
</code>```

答:
I think you should use the progressTextFormatter argument of the default SimpleTimer constructor.
You can look at the source code to have an example of how to do it: here's the link

A quick example:

```<code>SimpleTimer(
  progressTextFormatter: (Duration d) => "${duration.inMinutes % 60}:${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, "0")}",
//...rest of the constructor
</code>```

Body:
I use simpletimer package, and it has required duration. So when I try to set Duration(minutes: 5, hours: 1) for example, it shows 65 minutes. So I want to show to user 01:05:00 or 1:05:00 like this. How can I do this?

I found somethings like:

 format(Duration d) => d.toString().split('.').first.padLeft(8, "0");

but it gives

"string is not subtype of duration."

So I am stuck. Help.

My simleTimer:

     SimpleTimer(
progressTextStyle: const TextStyle(fontSize: 35),
status: TimerStatus.pause,
duration: format(Duration(hours: 1, minutes: 3))),

Body:
I think you should use the progressTextFormatter argument of the default SimpleTimer constructor.
You can look at the source code to have an example of how to do it: here's the link

A quick example:

SimpleTimer(
  progressTextFormatter: (Duration d) => "${duration.inMinutes % 60}:${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, "0")}",
//...rest of the constructor


问:
Code not generating when changing active file
I am writing a vscode extension that generates a prettier config based on your chosen language. Javascript and JSON. The code runs fine on the first document but if you change to another file and try generating clicking the button again. The code fails to start. Is there a way to check if the current document has changed thanks.</p>
```<code>import * as vscode from "vscode";
import { TextDocument } from "vscode";
import {
    activeEditor
} from "./constants";

var statusBar: vscode.StatusBarItem;

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(
        vscode.commands.registerCommand("prettier-config.prettierConfig", async () => {
            var changedDocument = false;
            const fileType = await vscode.window.showInformationMessage(
                "Which file to generate the Prettier Config for?",
                "Javascript",
                "JSON"
            );
            if (fileType === "Javascript" && changedDocument === false) {
                const javascript = activeEditor.edit(
                    (edit: { insert: (arg0: any, arg1: string) => void }) => {
                        edit.insert(
                            new vscode.Position(0, 0),
                            `module.exports = {\n   singleQuote: true,\n   printWidth: 120,\n   tabWidth: 4,\n   trailingComma: all,\n   endOfLine: auto\n};`,
                        );
                    }
                );
            }
            else if (fileType === "JSON" && changedDocument === false) {
                const json = activeEditor.edit(
                    (edit: { insert: (arg0: any, arg1: string) => void }) => {
                        edit.insert(
                            new vscode.Position(0, 0),
                            `{\n   "singleQuote": true,\n   "printWidth": 120,\n   "tabWidth": 4,\n   "trailingComma": "all",\n   "endOfLine": "auto"\n}`,
                        );
                    }
                );
            }
        })
    );
    statusBar = vscode.window.createStatusBarItem(
        vscode.StatusBarAlignment.Right,
        100,
    );
    statusBar.command = "prettier-config.prettierConfig";
    context.subscriptions.push(statusBar);
    context.subscriptions.push(
        vscode.window.onDidChangeActiveTextEditor(updateStatusBar),
        vscode.window.onDidChangeTextEditorSelection(updateStatusBar),
    );
    updateStatusBar();
}

function updateStatusBar(): void {
    statusBar.text = `$(edit) Prettier Config`;
    statusBar.show();
}

function deactivate() {
    statusBar.dispose();
}
</code>```

答:
if you need the active editor just get it with:

```<code>const editor = vscode.window.activeTextEditor;
</code>```

or use

```<code>vscode.commands.registerTextEditorCommand
</code>```

it has the active editor as an argument.

To get the changed state of a document use:

```<code>editor.document.isDirty
</code>```

Body:
I am writing a vscode extension that generates a prettier config based on your chosen language. Javascript and JSON. The code runs fine on the first document but if you change to another file and try generating clicking the button again. The code fails to start. Is there a way to check if the current document has changed thanks.

import * as vscode from "vscode";
import { TextDocument } from "vscode";
import {
    activeEditor
} from "./constants";

var statusBar: vscode.StatusBarItem;

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(
        vscode.commands.registerCommand("prettier-config.prettierConfig", async () => {
            var changedDocument = false;
            const fileType = await vscode.window.showInformationMessage(
                "Which file to generate the Prettier Config for?",
                "Javascript",
                "JSON"
            );
            if (fileType === "Javascript" && changedDocument === false) {
                const javascript = activeEditor.edit(
                    (edit: { insert: (arg0: any, arg1: string) => void }) => {
                        edit.insert(
                            new vscode.Position(0, 0),
                            `module.exports = {\n   singleQuote: true,\n   printWidth: 120,\n   tabWidth: 4,\n   trailingComma: all,\n   endOfLine: auto\n};`,
                        );
                    }
                );
            }
            else if (fileType === "JSON" && changedDocument === false) {
                const json = activeEditor.edit(
                    (edit: { insert: (arg0: any, arg1: string) => void }) => {
                        edit.insert(
                            new vscode.Position(0, 0),
                            `{\n   "singleQuote": true,\n   "printWidth": 120,\n   "tabWidth": 4,\n   "trailingComma": "all",\n   "endOfLine": "auto"\n}`,
                        );
                    }
                );
            }
        })
    );
    statusBar = vscode.window.createStatusBarItem(
        vscode.StatusBarAlignment.Right,
        100,
    );
    statusBar.command = "prettier-config.prettierConfig";
    context.subscriptions.push(statusBar);
    context.subscriptions.push(
        vscode.window.onDidChangeActiveTextEditor(updateStatusBar),
        vscode.window.onDidChangeTextEditorSelection(updateStatusBar),
    );
    updateStatusBar();
}

function updateStatusBar(): void {
    statusBar.text = `$(edit) Prettier Config`;
    statusBar.show();
}

function deactivate() {
    statusBar.dispose();
}

Body:
if you need the active editor just get it with:

const editor = vscode.window.activeTextEditor;

or use

vscode.commands.registerTextEditorCommand

it has the active editor as an argument.

To get the changed state of a document use:

editor.document.isDirty


问:
How to Remove HTML Elements from Post Excerpt?
I am Using the Following Code and want to remove HTML All Elements.</p>
```<code><?php $exerpttext = substr(get_post_field('post_content', $post->ID), 0, 300);
if (!empty($exerpttext)) { echo $exerpttext.'....'; }  ?>
</code>```

答:
Instead of using get_post_field you can use get_the_excerpt which give you a string and will remove all the HTML tags. (https://developer.wordpress.org/reference/functions/get_the_excerpt/)

However you can use wp_strip_all_tags to strip all HTML tags including script and style.
You can read more about wp_strip_all_tags: https://developer.wordpress.org/reference/functions/wp_strip_all_tags/

```<code><?php $excerpttext = substr( wp_strip_all_tags( get_post_field( 'post_content', $post->ID ) ), 0, 300 );
if ( !empty( $excerpttext )) { echo $excerpttext).'....'; }  ?>
</code>```

Body:
I am Using the Following Code and want to remove HTML All Elements.

<?php $exerpttext = substr(get_post_field('post_content', $post->ID), 0, 300);
if (!empty($exerpttext)) { echo $exerpttext.'....'; }  ?>

Body:
Instead of using get_post_field you can use get_the_excerpt which give you a string and will remove all the HTML tags. (https://developer.wordpress.org/reference/functions/get_the_excerpt/)

However you can use wp_strip_all_tags to strip all HTML tags including script and style.
You can read more about wp_strip_all_tags: https://developer.wordpress.org/reference/functions/wp_strip_all_tags/

<?php $excerpttext = substr( wp_strip_all_tags( get_post_field( 'post_content', $post->ID ) ), 0, 300 );
if ( !empty( $excerpttext )) { echo $excerpttext).'....'; }  ?>


问:
Copy cell to word file and save
Run time error 4248 while copying a cell in a new word file and saving it in VBA...I am getting error in the saveas part</p>
```<code>Sub CreateWordDoc()
    Dim ExcRange As Range
    Dim i As Integer
    i = 2
    Dim tosavefilename As Variant
    Dim dateformat As Variant
    Dim middle As String
    Dim creationtime As Date
    Dim Msubject As String
    MsgBox "The value of Msubject is" & ActiveSheet.Cells(1, i).Value
    Msubject = ActiveSheet.Cells(1, i).Value
    creationtime = ActiveSheet.Cells(2, i).Value
    dateformat = VBA.Format(creationtime, "yyyy.mm.dd   hh.mm")
    middle = Replace(Msubject, ":", "_")
    middle = Replace(middle, "/", "_")
    middle = Replace(middle, "", "_")
    middle = Replace(middle, "?", "_")
    middle = Replace(middle, "Chr(34)", "_")
    middle = Replace(middle, "<", "_")
    middle = Replace(middle, ">", "_")
    middle = Replace(middle, "|", "_")
    MsgBox "The value of the dateformat and middle is" & dateformat & middle
    tosavefilename = dateformat & "_" & middle
    MsgBox "The file name to be saved is " & tosavefilename
    Set ExcRange = ActiveSheet.Cells.Range("F" & i)
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    wdApp.Visible = True
    wdApp.Activate
    ExcRange.Copy
    wdApp.Documents.Add
    wdApp.Selection.Paste
    'saveasname = Environ("Userprofile")
    'Application.Wait Second(Now) + 10
    'wdApp.Activate
    ActiveDocument.SaveAs "test"

    ActiveDocument.Close
    wdApp.Quit

End Sub
</code>```

答:
Try to use the Document.SaveAs2 method instead. It saves the specified document with a new name or format. Some of the arguments for this method correspond to the options in the Save As dialog box (File tab).

The filename parameter stands for the name for the document. The default is the current folder and file name. If the document has never been saved, the default name is used (for example, Doc1.doc). If a document with the specified file name already exists, the document is overwritten without prompting the user.

Title: Copy cell to word file and save

Body:
Run time error 4248 while copying a cell in a new word file and saving it in VBA...I am getting error in the saveas part

Sub CreateWordDoc()
    Dim ExcRange As Range
    Dim i As Integer
    i = 2
    Dim tosavefilename As Variant
    Dim dateformat As Variant
    Dim middle As String
    Dim creationtime As Date
    Dim Msubject As String
    MsgBox "The value of Msubject is" & ActiveSheet.Cells(1, i).Value
    Msubject = ActiveSheet.Cells(1, i).Value
    creationtime = ActiveSheet.Cells(2, i).Value
    dateformat = VBA.Format(creationtime, "yyyy.mm.dd   hh.mm")
    middle = Replace(Msubject, ":", "_")
    middle = Replace(middle, "/", "_")
    middle = Replace(middle, "", "_")
    middle = Replace(middle, "?", "_")
    middle = Replace(middle, "Chr(34)", "_")
    middle = Replace(middle, "<", "_")
    middle = Replace(middle, ">", "_")
    middle = Replace(middle, "|", "_")
    MsgBox "The value of the dateformat and middle is" & dateformat & middle
    tosavefilename = dateformat & "_" & middle
    MsgBox "The file name to be saved is " & tosavefilename
    Set ExcRange = ActiveSheet.Cells.Range("F" & i)
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    wdApp.Visible = True
    wdApp.Activate
    ExcRange.Copy
    wdApp.Documents.Add
    wdApp.Selection.Paste
    'saveasname = Environ("Userprofile")
    'Application.Wait Second(Now) + 10
    'wdApp.Activate
    ActiveDocument.SaveAs "test"

    ActiveDocument.Close
    wdApp.Quit

End Sub


问:
Do I need to pack/unpack data read from a binary file before performing bitwise operations?
I've read two bytes from a binary file into $data and now need to perform a bitwise and.

But when I do

```<code>if (($data & "\x100") != 0) {
</code>```

I get the error Argument "@\0" isn't numeric in numeric ne (!=)

Am I supposed to convert $data first?

答:
Why are you using strings for binary operations?

Use ($data & 0x100) != 0 and, if necessary, convert $data to a number.

Body:
I've read two bytes from a binary file into $data and now need to perform a bitwise and.

But when I do

if (($data & "\x100") != 0) {

I get the error Argument "@\0" isn't numeric in numeric ne (!=)

Am I supposed to convert $data first?


问:
Change URl tabs without page refresh NEXT.JS
I'm using material ui tabs, and I'm pushing the tabs to URL. I want to push the tab but not refresh the page every-time I change the tab. Here is my code, and I'm using shallow:true but the problem remains:</p>
```<code>const tabs = [
  { label: 'Details', value: 'details' },
  { label: 'Purchases', value: 'purchases' },
  { label: 'Money Transfer', value: 'moneyTransfer' },
  {label:'User Activity',value:'userActivity'},
  {label:'User Logs',value:'userLogs'}
];
const {
    query: { UsersId,tab },
  } = router
const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => {

  router.push({
    pathname: `/dashboard/twigUsers/${UsersId}`,query: { tab:value}},undefined,{ shallow: true });
};

             <Tabs
              indicatorColor="primary"
              onChange={handleTabsChange}
              scrollButtons="auto"
              sx={{ mt: 3 }}
              textColor="primary"
              value={tab}
              variant="scrollable"
            >
              {tabs.map((tab) => (
                <Tab
                  key={tab.value}
                  label={tab.label}
                  value={tab.value}
                />
              ))}
            </Tabs>

{tab === 'details' && (
             <UsersDetailsContainer user={user} userId={UsersId}/>
            )}
            {tab === 'purchases' && <PurchasesListTable userDetailsId={userDetailsId}/>}
            {tab === 'moneyTransfer' && <MoneyTransferListTable userDetailsIdMT={userDetailsIdMT} />}
            {tab==='userActivity' &&<UserActivity/>}
            {tab==='userLogs' &&<UserLogs user={user} userId={twigUsersId}/>}
</code>```

答:
I have changed the whole logic in order to work, I have stored the tabs in redux saga here is the code:
Redux part

```<code>// utils
import axios from 'axios';
import produce from 'immer';
import creator from '../../../utils/actionCreator';
import { put, takeLatest } from 'redux-saga/effects';
import { AnyAction } from 'redux';

// consts
export const REQUEST = '@app/tabs/get/getUsersDetailsTabs/REQUEST';
export const SUCCESS = '@app/tabs/get/getUsersDetailsTabs/SUCCESS';
export const FAILURE = '@app/tabs/get/getUsersDetailsTabs/FAILURE';

export const UPDATE_REQUEST = '@app/tabs/get/getUsersDetailsTabs/UPDATE_REQUEST';
export const UPDATE_SUCCESS = '@app/tabs/get/getUsersDetailsTabs/UPDATE_SUCCESS';
export const UPDATE_FAILURE = '@app/tabs/get/getUsersDetailsTabs/UPDATE_FAILURE';
export const CLEAR = '@app/tabs/get/getUsersDetailsTabs/CLEAR';

// initial state
const initalState = {
  error: '',
  loading: false,
  success: false,
  tabs:[]
};

// reducer
const reducer = (state = initalState, { payload, ...action }: AnyAction) =>
  produce(state, (draft) => {
    switch (action.type) {
      case REQUEST:
        draft.tabs = payload;
        break;
      case SUCCESS:
        draft.loading = false;
        draft.tabs = payload;
        break;
      case FAILURE:
        draft.loading = false;
        draft.error = payload;
        break;
      case UPDATE_REQUEST:
        draft.loading = true;
        break;
      case UPDATE_SUCCESS:
        draft.loading = false;
        draft.success = true;
        break;
      case UPDATE_FAILURE:
        draft.loading = false;
        draft.error = payload;
        break;
      case CLEAR:
        draft.loading = false;
        draft.error = '';
        draft.tabs = [];
        break;
      default:
        break;
    }
  });

// actions
const actions = {
  request: (tabs) => creator(REQUEST, tabs),
  success: (tabs) => creator(SUCCESS, tabs),
  failure: (tabs) => creator(FAILURE, tabs),

  updateRequest: (tabs) => creator(UPDATE_REQUEST, tabs),
  updateSuccess: (tabs) => creator(UPDATE_SUCCESS, tabs),
  updateFailure: (tabs) => creator(UPDATE_FAILURE, tabs),

  clear: () => creator(CLEAR)
};

// sagas
const sagas = {
    *getTabs(tabs){
    return{
        type:REQUEST,
        payload:tabs
    }
    }
};

// watcher
const watcher = function* watch() {
  yield takeLatest(REQUEST, sagas.getTabs);
};

// exports
export { actions, watcher };
export default reducer;

</code>```

Dispatch the tabs

```<code>const [value, setValue] = useState('details');
const handleTabsChange = (event: ChangeEvent<{}>,newValue): void => {
   console.log(newValue,"new value")
  setValue(newValue);
};
useEffect(() => {
    dispatch(getTabs.request(
      [ { label: 'Details', value: 'details' },
      { label: 'Purchases', value: 'purchases' },
      { label: 'Money Transfer', value: 'moneyTransfer' },
      {label:'User Activity',value:'userActivity'},
      {label:'User Logs',value:'userLogs'}]
    ));
  },[]);
  const { tabs:tabs } = useSelector((state: RootStateOrAny) => state.tabs);
</code>```

Tabs

```<code>  <Tabs
              indicatorColor="primary"
              onChange={handleTabsChange}
              scrollButtons="auto"
              sx={{ mt: 3 }}
              textColor="primary"
              value={value}
              variant="scrollable"
            >
              {tabs.map((tab) => (
                <Tab
                  key={tab.value}
                  label={tab.label}
                  value={tab.value}
                />
              ))}
            </Tabs>

{value === 'details' && (
             <UsersDetailsContainer user={user} userId={twigUsersId}/>
            )}
            {value === 'purchases' && <PurchasesListTable userDetailsId={userDetailsId}/>}
            {value === 'moneyTransfer' && <MoneyTransferListTable userDetailsIdMT={userDetailsIdMT} />}
            {value==='userActivity' &&<UserActivity/>}
            {value==='userLogs' &&<UserLogs user={user} userId={twigUsersId}/>}
</code>```

Body:
I'm using material ui tabs, and I'm pushing the tabs to URL. I want to push the tab but not refresh the page every-time I change the tab. Here is my code, and I'm using shallow:true but the problem remains:

const tabs = [
  { label: 'Details', value: 'details' },
  { label: 'Purchases', value: 'purchases' },
  { label: 'Money Transfer', value: 'moneyTransfer' },
  {label:'User Activity',value:'userActivity'},
  {label:'User Logs',value:'userLogs'}
];
const {
    query: { UsersId,tab },
  } = router
const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => {

  router.push({
    pathname: `/dashboard/twigUsers/${UsersId}`,query: { tab:value}},undefined,{ shallow: true });
};

             <Tabs
              indicatorColor="primary"
              onChange={handleTabsChange}
              scrollButtons="auto"
              sx={{ mt: 3 }}
              textColor="primary"
              value={tab}
              variant="scrollable"
            >
              {tabs.map((tab) => (
                <Tab
                  key={tab.value}
                  label={tab.label}
                  value={tab.value}
                />
              ))}
            </Tabs>

{tab === 'details' && (
             <UsersDetailsContainer user={user} userId={UsersId}/>
            )}
            {tab === 'purchases' && <PurchasesListTable userDetailsId={userDetailsId}/>}
            {tab === 'moneyTransfer' && <MoneyTransferListTable userDetailsIdMT={userDetailsIdMT} />}
            {tab==='userActivity' &&<UserActivity/>}
            {tab==='userLogs' &&<UserLogs user={user} userId={twigUsersId}/>}

Body:
I have changed the whole logic in order to work, I have stored the tabs in redux saga here is the code:
Redux part

// utils
import axios from 'axios';
import produce from 'immer';
import creator from '../../../utils/actionCreator';
import { put, takeLatest } from 'redux-saga/effects';
import { AnyAction } from 'redux';

// consts
export const REQUEST = '@app/tabs/get/getUsersDetailsTabs/REQUEST';
export const SUCCESS = '@app/tabs/get/getUsersDetailsTabs/SUCCESS';
export const FAILURE = '@app/tabs/get/getUsersDetailsTabs/FAILURE';

export const UPDATE_REQUEST = '@app/tabs/get/getUsersDetailsTabs/UPDATE_REQUEST';
export const UPDATE_SUCCESS = '@app/tabs/get/getUsersDetailsTabs/UPDATE_SUCCESS';
export const UPDATE_FAILURE = '@app/tabs/get/getUsersDetailsTabs/UPDATE_FAILURE';
export const CLEAR = '@app/tabs/get/getUsersDetailsTabs/CLEAR';

// initial state
const initalState = {
  error: '',
  loading: false,
  success: false,
  tabs:[]
};

// reducer
const reducer = (state = initalState, { payload, ...action }: AnyAction) =>
  produce(state, (draft) => {
    switch (action.type) {
      case REQUEST:
        draft.tabs = payload;
        break;
      case SUCCESS:
        draft.loading = false;
        draft.tabs = payload;
        break;
      case FAILURE:
        draft.loading = false;
        draft.error = payload;
        break;
      case UPDATE_REQUEST:
        draft.loading = true;
        break;
      case UPDATE_SUCCESS:
        draft.loading = false;
        draft.success = true;
        break;
      case UPDATE_FAILURE:
        draft.loading = false;
        draft.error = payload;
        break;
      case CLEAR:
        draft.loading = false;
        draft.error = '';
        draft.tabs = [];
        break;
      default:
        break;
    }
  });

// actions
const actions = {
  request: (tabs) => creator(REQUEST, tabs),
  success: (tabs) => creator(SUCCESS, tabs),
  failure: (tabs) => creator(FAILURE, tabs),

  updateRequest: (tabs) => creator(UPDATE_REQUEST, tabs),
  updateSuccess: (tabs) => creator(UPDATE_SUCCESS, tabs),
  updateFailure: (tabs) => creator(UPDATE_FAILURE, tabs),

  clear: () => creator(CLEAR)
};

// sagas
const sagas = {
    *getTabs(tabs){
    return{
        type:REQUEST,
        payload:tabs
    }
    }
};

// watcher
const watcher = function* watch() {
  yield takeLatest(REQUEST, sagas.getTabs);
};

// exports
export { actions, watcher };
export default reducer;

Dispatch the tabs

const [value, setValue] = useState('details');
const handleTabsChange = (event: ChangeEvent<{}>,newValue): void => {
   console.log(newValue,"new value")
  setValue(newValue);
};
useEffect(() => {
    dispatch(getTabs.request(
      [ { label: 'Details', value: 'details' },
      { label: 'Purchases', value: 'purchases' },
      { label: 'Money Transfer', value: 'moneyTransfer' },
      {label:'User Activity',value:'userActivity'},
      {label:'User Logs',value:'userLogs'}]
    ));
  },[]);
  const { tabs:tabs } = useSelector((state: RootStateOrAny) => state.tabs);

Tabs

  <Tabs
              indicatorColor="primary"
              onChange={handleTabsChange}
              scrollButtons="auto"
              sx={{ mt: 3 }}
              textColor="primary"
              value={value}
              variant="scrollable"
            >
              {tabs.map((tab) => (
                <Tab
                  key={tab.value}
                  label={tab.label}
                  value={tab.value}
                />
              ))}
            </Tabs>

{value === 'details' && (
             <UsersDetailsContainer user={user} userId={twigUsersId}/>
            )}
            {value === 'purchases' && <PurchasesListTable userDetailsId={userDetailsId}/>}
            {value === 'moneyTransfer' && <MoneyTransferListTable userDetailsIdMT={userDetailsIdMT} />}
            {value==='userActivity' &&<UserActivity/>}
            {value==='userLogs' &&<UserLogs user={user} userId={twigUsersId}/>}


问:
NiFi- how to http post a PDF document
I wanted to use NiFi's posthttp/invokeHttp processor to post a PDF to an API.

But considering the following cURL request to replicate in NiFi:

```<code>curl -X POST "http://ipaddress:port/api/" -H "accept: application/json" -H
        "Content-Type: multipart/form-data" -F "pdf_file=@sample.pdf;
        type=application/pdf"
</code>```

Which property takes the -F information in nifi attributes?

Configuration for invokehttp right now:

error:
"400 Bad Request: The browser (or proxy) sent a request that this server could not understand."

Configration for posthttp right now:

error:
server logs: readv() failed (104: Connection reset by peer) while reading upstream

答:
In older version of nifi you will have to use your own script to build a multipart request and then use invoke to create post request. You can refer to this post for a ExecuteGroovyScript example.
https://stackoverflow.com/a/57204862

Since Nifi 1.12 you can directly use invokeHTTP by setting content-type
https://stackoverflow.com/a/69284300

Title: NiFi- how to http post a PDF document

Body:
I wanted to use NiFi's posthttp/invokeHttp processor to post a PDF to an API.

But considering the following cURL request to replicate in NiFi:

curl -X POST "http://ipaddress:port/api/" -H "accept: application/json" -H
        "Content-Type: multipart/form-data" -F "pdf_file=@sample.pdf;
        type=application/pdf"

Which property takes the -F information in nifi attributes?

Configuration for invokehttp right now:

error:
"400 Bad Request: The browser (or proxy) sent a request that this server could not understand."

Configration for posthttp right now:

error:
server logs: readv() failed (104: Connection reset by peer) while reading upstream


问:
Contact form produces unwanted results from server
I finally found a contact form that works - inserted it into my three sites, and now the problem is I receive - daily - spammy, pointless mail from all three sites from my own web hosting server, Ionos (screenshot).

I contacted Ionos: "This is a mailing function sending emails from a webspace, the script that sends out the emails that was added needs to be stopped from this happening."

I asked how to stop it, and the answer was: "scripting is not within our scope of support," which is rich coming from a web-hosting site.

email screenshot

'send mail' php.

<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "legion@naturalblood.co";

/*
This bit sets the URLs of the supporting pages.
If you change the names of any of the pages, you will need to change the values here.
*/
$feedback_page = "feedback_form.html";
$error_page = "error_message.html";
$thankyou_page = "thank_you.html";

/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email_address = $_REQUEST['email_address'] ;
$comments = $_REQUEST['comments'] ;
$first_name = $_REQUEST['first_name'] ;
$msg =
"First Name: " . $first_name . "\r\n" .
"Email: " . $email_address . "\r\n" .
"Comments: " . $comments ;

/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
    $injections = array('(\n+)',
    '(\r+)',
    '(\t+)',
    '(%0A+)',
    '(%0D+)',
    '(%08+)',
    '(%09+)'
    );
    $inject = join('|', $injections);
    $inject = "/$inject/i";
    if(preg_match($inject,$str)) {
        return true;
    }
    else {
        return false;
    }
}

// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email_address'])) {
header( "Location: $feedback_page" );
}

// If the form fields are empty, redirect to the error page.
elseif (empty($first_name) || empty($email_address)) {
header( "Location: $error_page" );
}

/*
If email injection is detected, redirect to the error page.
If you add a form field, you should add it here.
*/
elseif ( isInjected($email_address) || isInjected($first_name)  || isInjected($comments) ) {
header( "Location: $error_page" );
}

// If we passed all previous tests, send the email then redirect to the thank you page.
else {

    mail( "$webmaster_email", "Message from amatoria.com", $msg );

    header( "Location: $thankyou_page" );
}
?>```

答:
Try to add google recaptcha to the contact form. This way robots or scripts cannot send you emails.

See: https://www.google.com/recaptcha/about/


问:
Is it possible to bind to a service inside a composable in android
I am working on an android application and currently binding to my location service from which i receive location updates while inside the activity, and i wanted to do so from inside a composable after a user has finished the authentication proces</p>

答:
I haven't tested this, but feel free to try, if required it could be adapted for remote services that expose a Messenger. Anyway here's the gist:

package com.example.app

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.IBinder
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisallowComposableCalls
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext

@Composable
inline fun <reified BoundService : Service, reified BoundServiceBinder : Binder> rememberBoundLocalService(
    crossinline getService: @DisallowComposableCalls BoundServiceBinder.() -> BoundService,
): BoundService? {
    val context: Context = LocalContext.current
    var boundService: BoundService? by remember(context) { mutableStateOf(null) }
    val serviceConnection: ServiceConnection = remember(context) {
        object : ServiceConnection {
            override fun onServiceConnected(className: ComponentName, service: IBinder) {
                boundService = (service as BoundServiceBinder).getService()
            }

            override fun onServiceDisconnected(arg0: ComponentName) {
                boundService = null
            }
        }
    }
    DisposableEffect(context, serviceConnection) {
        context.bindService(Intent(context, BoundService::class.java), serviceConnection, Context.BIND_AUTO_CREATE)
        onDispose { context.unbindService(serviceConnection) }
    }
    return boundService
}
```
<p>Then:</p>
<pre class="lang-kotlin prettyprint-override"><code>package com.example.app

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import kotlin.random.Random

class RandomNumberService : Service() {
    private val binder = LocalBinder()
    private val randomNumberGenerator = Random(seed = 100)
    val randomNumber: Int
        get() = randomNumberGenerator.nextInt()

    inner class LocalBinder : Binder() {
        val service: RandomNumberService
            get() = this@RandomNumberService
    }

    override fun onBind(intent: Intent): IBinder = binder
}

@Composable
fun RandomNumberServiceExample() {
    val randomNumberService = rememberBoundLocalService<RandomNumberService, RandomNumberService.LocalBinder> { service }
    Text(
        text = randomNumberService?.randomNumber?.toString().orEmpty(),
    )
}
</code>```

If it works I'll update this answer.

Body:
I haven't tested this, but feel free to try, if required it could be adapted for remote services that expose a Messenger. Anyway here's the gist:

package com.example.app

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.IBinder
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisallowComposableCalls
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext

@Composable
inline fun <reified BoundService : Service, reified BoundServiceBinder : Binder> rememberBoundLocalService(
    crossinline getService: @DisallowComposableCalls BoundServiceBinder.() -> BoundService,
): BoundService? {
    val context: Context = LocalContext.current
    var boundService: BoundService? by remember(context) { mutableStateOf(null) }
    val serviceConnection: ServiceConnection = remember(context) {
        object : ServiceConnection {
            override fun onServiceConnected(className: ComponentName, service: IBinder) {
                boundService = (service as BoundServiceBinder).getService()
            }

            override fun onServiceDisconnected(arg0: ComponentName) {
                boundService = null
            }
        }
    }
    DisposableEffect(context, serviceConnection) {
        context.bindService(Intent(context, BoundService::class.java), serviceConnection, Context.BIND_AUTO_CREATE)
        onDispose { context.unbindService(serviceConnection) }
    }
    return boundService
}

Then:

package com.example.app

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import kotlin.random.Random

class RandomNumberService : Service() {
    private val binder = LocalBinder()
    private val randomNumberGenerator = Random(seed = 100)
    val randomNumber: Int
        get() = randomNumberGenerator.nextInt()

    inner class LocalBinder : Binder() {
        val service: RandomNumberService
            get() = this@RandomNumberService
    }

    override fun onBind(intent: Intent): IBinder = binder
}

@Composable
fun RandomNumberServiceExample() {
    val randomNumberService = rememberBoundLocalService<RandomNumberService, RandomNumberService.LocalBinder> { service }
    Text(
        text = randomNumberService?.randomNumber?.toString().orEmpty(),
    )
}

If it works I'll update this answer.


问:
How to get the values of dictionary python?
I have the below python dictionary stored as dictPython

```<code>{
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",

        },
    ],
}
</code>```

I need to get the values of vanityName, localizedName and also the values from name->localized and name->preferredLocale.

I tried dictPython.keys() and it returned dict_keys(['paging', 'elements']).

Also I tried dictPython.values() and it returned me what is inside of the parenthesis({}).

I need to get [vv, ViV, ViV, US, en]

答:
What about:

dic = {
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",
        },
    ],
}
base = dic["elements"][0]["organizationalTarget~"]
c = base["name"]["localized"]
d = base["name"]["preferredLocale"]
output = [base["vanityName"], base["localizedName"]]
output.extend([c[key] for key in c])
output.extend([d[key] for key in d])

print(output)
```
<p>outputs:</p>
<pre class="lang-py prettyprint-override"><code>['vv', 'ViV', 'ViV', 'US', 'en']
</code>```

Body:
I have the below python dictionary stored as dictPython

{
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",

        },
    ],
}

I need to get the values of vanityName, localizedName and also the values from name->localized and name->preferredLocale.

I tried dictPython.keys() and it returned dict_keys(['paging', 'elements']).

Also I tried dictPython.values() and it returned me what is inside of the parenthesis({}).

I need to get [vv, ViV, ViV, US, en]

Body:
What about:

dic = {
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",
        },
    ],
}
base = dic["elements"][0]["organizationalTarget~"]
c = base["name"]["localized"]
d = base["name"]["preferredLocale"]
output = [base["vanityName"], base["localizedName"]]
output.extend([c[key] for key in c])
output.extend([d[key] for key in d])

print(output)

outputs:

['vv', 'ViV', 'ViV', 'US', 'en']