问:
Axios is caching somehow my get user request react native
I'm using Axios ("axios": "^0.19.0") to do a GET request to my backend which works as I already tested it by sending the same token through Postman macOS app, and returns the correct user object.

But from my React Native app, whenever I do the get request and pass the same bearer token, I get the last user I logged in as a response.

This is how I'm sending the request:

```<code>getUserByToken: function(token) {
        var headers = [
            { key: 'Authorization', value: 'Bearer ' + token},
            { key: 'Content-Type', value: 'application/x-www-form-urlencoded'},
            { key: 'Cache-Control', value: 'no-cache'}
        ];

        setHeaders('get', headers);
        return AxiosInstance.get('/user');
    },
</code>```

The setHeaders method is used to set the headers to the request, I reset all http methods to an empty object and set the proper key-values for the following request.

```<code>export const setHeaders = (type, props) => {
    AxiosInstance.interceptors.request.use(config => {
        config.headers[type] = {};

        props.forEach((prop) => {
            config.headers[type][prop.key] = prop.value;
        });
        return config;
    });
}
</code>```

As you can see, I even attempted to use Cache-Control: no-cache but still, keeps caching for no reason.

This is how I'm calling this function from my AuthView.js

```<code> UserServices.getUserByToken(loginData.access_token)
        .then(userResponse => {
   // here userResponse is the previous user!
   // even though i'm passing the correct token
            this.props.onSetUserInfo(userResponse.data);
            this.setState({
                loading: false
            }, () => {
                startMainTabs();
            });
        });
</code>```

Why could this be happening?

Thanks.

答:
Please check with below code i have already tested same on my project and it's working fine.

```<code>getUserByToken: function(token) {
        var headers = [
            { key: 'Authorization', value: 'Bearer ' + token},
            { key: 'Content-Type', value: 'application/x-www-form-urlencoded'},
            { key: 'Cache-Control', value: 'no-store'}
        ];

        setHeaders('get', headers);
        return AxiosInstance.get('/user');
    },
</code>```

Use same above code it will solved your problem.

Body:
I'm using Axios ("axios": "^0.19.0") to do a GET request to my backend which works as I already tested it by sending the same token through Postman macOS app, and returns the correct user object.

But from my React Native app, whenever I do the get request and pass the same bearer token, I get the last user I logged in as a response.

This is how I'm sending the request:

getUserByToken: function(token) {
        var headers = [
            { key: 'Authorization', value: 'Bearer ' + token},
            { key: 'Content-Type', value: 'application/x-www-form-urlencoded'},
            { key: 'Cache-Control', value: 'no-cache'}
        ];

        setHeaders('get', headers);
        return AxiosInstance.get('/user');
    },

The setHeaders method is used to set the headers to the request, I reset all http methods to an empty object and set the proper key-values for the following request.

export const setHeaders = (type, props) => {
    AxiosInstance.interceptors.request.use(config => {
        config.headers[type] = {};

        props.forEach((prop) => {
            config.headers[type][prop.key] = prop.value;
        });
        return config;
    });
}

As you can see, I even attempted to use Cache-Control: no-cache but still, keeps caching for no reason.

This is how I'm calling this function from my AuthView.js

 UserServices.getUserByToken(loginData.access_token)
        .then(userResponse => {
   // here userResponse is the previous user!
   // even though i'm passing the correct token
            this.props.onSetUserInfo(userResponse.data);
            this.setState({
                loading: false
            }, () => {
                startMainTabs();
            });
        });

Why could this be happening?

Thanks.

Body:
Please check with below code i have already tested same on my project and it's working fine.

getUserByToken: function(token) {
        var headers = [
            { key: 'Authorization', value: 'Bearer ' + token},
            { key: 'Content-Type', value: 'application/x-www-form-urlencoded'},
            { key: 'Cache-Control', value: 'no-store'}
        ];

        setHeaders('get', headers);
        return AxiosInstance.get('/user');
    },

Use same above code it will solved your problem.


来源: stackexchange

问:
Handling lack of executor memory exception in spark run time
I have a spark application and there might be a scenario that unexpected amount of data is flowing into the application and fall into a memory exception at run time.

How can I handle this scenario.

答:
This error occurs when the executor runs out of memory.

Error Msg:

Java.lang.OutOfMemory: GC overhead

Solution: Increase your executor memory by
setting up:

```<code>conf spark.executor.memory= <XY>g
</code>```

Also increase the shuffle partitions as

```<code>spark.sql.shuffle.partitions = <XY>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This error occurs when the executor runs out of memory.

Error Msg:

Java.lang.OutOfMemory: GC overhead

Solution: Increase your executor memory by
setting up:

conf spark.executor.memory= <XY>g

Also increase the shuffle partitions as

spark.sql.shuffle.partitions = <XY>

ContentLicense: CC BY-SA 4.0


问:
SQL migration in Azure Pipelines with transactions
We have a build pipeline running that creates a sql script using dotnet ef migrations script -Idempotent
and this is executed in our release pipeline using the task "Azure SQL Database deployment" using  Invoke-Sqlcmd -ServerInstance "XXXXXXXXX" -Database "XXXXXX" -Username "XXXXXXX"  -Password ******  -Inputfile "XXXXXXXXXX" -ConnectionTimeout 1800

However we would like to run the migration in a transaction, because now, if the migration fail, we end up in a state were the migration is half-completed.

Any ideas?

答:
There is something called SqlServerMigrationsSqlGenerator that helps you to customize the migration script generation.
Thank you @yang-shen-msft!

This is the code required in EF core:

```<code>    public class SqlMigrationScriptGenerator : SqlServerMigrationsSqlGenerator
{
    public SqlMigrationScriptGenerator(MigrationsSqlGeneratorDependencies dependencies, IMigrationsAnnotationProvider migrationsAnnotations) : base(dependencies, migrationsAnnotations)
    {
    }

    public override IReadOnlyList<MigrationCommand> Generate(IReadOnlyList<MigrationOperation> operations, IModel model)
    {
        var beginTransaction = new SqlOperation { Sql = "BEGIN TRANSACTION" };
        var overriddenOperations = operations.ToList();
        overriddenOperations.Insert(0, beginTransaction);
        overriddenOperations.Add(new SqlOperation { Sql = "COMMIT TRANSACTION" });
        return base.Generate(overriddenOperations, model);
    }
}
</code>```

Body:
There is something called SqlServerMigrationsSqlGenerator that helps you to customize the migration script generation.
Thank you @yang-shen-msft!

This is the code required in EF core:

    public class SqlMigrationScriptGenerator : SqlServerMigrationsSqlGenerator
{
    public SqlMigrationScriptGenerator(MigrationsSqlGeneratorDependencies dependencies, IMigrationsAnnotationProvider migrationsAnnotations) : base(dependencies, migrationsAnnotations)
    {
    }

    public override IReadOnlyList<MigrationCommand> Generate(IReadOnlyList<MigrationOperation> operations, IModel model)
    {
        var beginTransaction = new SqlOperation { Sql = "BEGIN TRANSACTION" };
        var overriddenOperations = operations.ToList();
        overriddenOperations.Insert(0, beginTransaction);
        overriddenOperations.Add(new SqlOperation { Sql = "COMMIT TRANSACTION" });
        return base.Generate(overriddenOperations, model);
    }
}


问:
How to get date time from UTC date time fromat?
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

```<code>String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}
</code>```

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"

答:
Use yyyy-MM-dd'T'HH:mm:ss.SS as format instead of yyyy-MM-dd'T'HH:mm:ss'Z'

```<code>SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);
</code>```

java.time

You can also achieve this with java.time, the modern Java date and time API because the old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues:

```<code>String sourceDateTime = "2020-02-13T16:57:13.04";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SS").withZone(DateTimeZone.UTC);

LocalDateTime localDateTime = LocalDateTime.parse(sourceDateTime, dateTimeFormatter);

LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();

System.out.println(localDate.toString() + " -> " + localTime.toString());
//Output should be: 2020-02-13 -> 16:57:13.040
</code>```

Question: Can I use java.time on Android?

From Android 8.0 (API level 26) the modern API comes built-in.

For older android version, you can use ThreeTenABP, Android edition of ThreeTen Backport

Body:
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"

Body:
Use yyyy-MM-dd'T'HH:mm:ss.SS as format instead of yyyy-MM-dd'T'HH:mm:ss'Z'

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);

java.time

You can also achieve this with java.time, the modern Java date and time API because the old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues:

String sourceDateTime = "2020-02-13T16:57:13.04";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SS").withZone(DateTimeZone.UTC);

LocalDateTime localDateTime = LocalDateTime.parse(sourceDateTime, dateTimeFormatter);

LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();

System.out.println(localDate.toString() + " -> " + localTime.toString());
//Output should be: 2020-02-13 -> 16:57:13.040

Question: Can I use java.time on Android?

From Android 8.0 (API level 26) the modern API comes built-in.

For older android version, you can use ThreeTenABP, Android edition of ThreeTen Backport


问:
Actionscript 3 Sound ioError Problem
i am having trouble with sound. i am loading it dynamically, url comes from flashvars.
App is working actually but stil gives error, unhandled ioError. but i already handled it.

`
        var sound:Sound = new Sound()

```<code>try{
    sound.load(new URLRequest(req));
} catch(e:IOError){
    trace("catch ioerror");
}
sound.addEventListener(IOErrorEvent.IO_ERROR, function(evt:IOErrorEvent):void { trace("error:",evt) } );

sound.addEventListener(Event.COMPLETE, function(e:Event):void{
    channel = sound.play(0,int.MAX_VALUE);
});`
</code>```

答:
Try a neater approach in terms of code, might just have issues with your layout and such:</p>

```<code>var request:URLRequest = new URLRequest(req);
sound.load(request);

sound.addEventListener(IOErrorEvent.IO_ERROR, _ioError);
sound.addEventListener(Event.COMPLETE, _complete);

function _ioError(e:IOErrorEvent):void
{
    trace("File was not found");
    _removeListeners();
}

function _complete(e:Event):void
{
    channel = sound.play(0,int.MAX_VALUE);
    _removeListeners();
}

function _removeListeners():void
{
    sound.removeEventListener(IOErrorEvent.IO_ERROR, _ioError);
    sound.removeEventListener(Event.COMPLETE, _complete);
}
</code>```

Title: Actionscript 3 Sound ioError Problem

Body:
i am having trouble with sound. i am loading it dynamically, url comes from flashvars.
App is working actually but stil gives error, unhandled ioError. but i already handled it.

`
        var sound:Sound = new Sound()

try{
    sound.load(new URLRequest(req));
} catch(e:IOError){
    trace("catch ioerror");
}
sound.addEventListener(IOErrorEvent.IO_ERROR, function(evt:IOErrorEvent):void { trace("error:",evt) } );

sound.addEventListener(Event.COMPLETE, function(e:Event):void{
    channel = sound.play(0,int.MAX_VALUE);
});`

Body:
Try a neater approach in terms of code, might just have issues with your layout and such:

var request:URLRequest = new URLRequest(req);
sound.load(request);

sound.addEventListener(IOErrorEvent.IO_ERROR, _ioError);
sound.addEventListener(Event.COMPLETE, _complete);

function _ioError(e:IOErrorEvent):void
{
    trace("File was not found");
    _removeListeners();
}

function _complete(e:Event):void
{
    channel = sound.play(0,int.MAX_VALUE);
    _removeListeners();
}

function _removeListeners():void
{
    sound.removeEventListener(IOErrorEvent.IO_ERROR, _ioError);
    sound.removeEventListener(Event.COMPLETE, _complete);
}


问:
How can I check if I have internet connectivity before logging to Cosmos DB?
I have this code that I use to log activity to the Cosmos DB.

```<code>protected override async void OnStart()
{
   await Helper.LogActivity("OnStart");

public static partial class Helper
{
    public static async Task LogActivity(string activity)
    {
        var logItem = new LogItem()
        {
            Activity = activity,
        };
        await CosmosDBService.InsertLogItem(logItem);
    }
}

public class CosmosDBService
{
    static DocumentClient docClient = null;

    static readonly string databaseName = "Test";
    static readonly string collectionName = "Logs";

    static async Task<bool> Initialize()
    {
        if (docClient != null)
            return true;
        try
        {
            docClient = new DocumentClient(new Uri(APIKeys.CosmosEndpointUrl), APIKeys.CosmosAuthKey);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            docClient = null;
            return false;
        }
        return true;
    }

    public async static Task InsertLogItem(LogItem item)
    {
        if (!await Initialize())
            return;
        await docClient.CreateDocumentAsync(
            UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
            item);
    }

}
</code>```

What I am concerned with is if there was no internet connection. Would it be a good idea to somehow test for this first or should I add some try catch exception to the code for the logging?

Would appreciate any suggestions on how I could make this code bullet proof so that even if there is no connection then there is no exception thrown in the OnStart.

If the logging fails then it's not a problem for me but I want to be sure the code will not fail if there is no internet connection or if the cosmos db call fails.

答:
Maybe make a checklist of concerned cases:

1) No Internet
2) Internet but database is offline
3) etc..

Then test your code and see how it behaves, and ensure you are handling the cases.
Then you can be (somewhat) sure how your code behaves under these circumstances.
It will also show you where the exception occures, so you might want to add a try..catch block to prevent other failures.

UPDATE - Regarding Handling error cases:

So if your program fails to initialize the docClient it would mean that it will not be able to write any logs.

So there might be a few ways to handle this,

1) you could have a "fallback" logging method, meaning if docClient == null log to console. (So that later you can investigate on the server what went wrong) This allows you to keep crucial logs saved if the server keeps these logs.

2) Another fallback method would be to buffer the events in a memory list, and retry to connect every 10 minutes to the database. If connection was succesfull you empty your buffer into the database.

3) You can implement a retry count, like retry to connect X times at startup, if it fails you can fallback to another method or combination of above ideas. Additionally you could have a system that alerts you via E-MAIL or SMS, depending how critical this service is.

These ideas center around issues with connecting to the database.
This will however still not help you to much with the actual insert, for example if your DB connection dies midway.

So you might still need a try catch inside the InsertLogItem-method around the actual insert code. So that would hide the try catch around every await Helper.LogActivity("OnStart"); statement, as it is integrated. and if that log fails you could again concider fallback methods or actions

UPDATE2)
Looking at CreateDocumentAsync return object here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.documents.client.resourceresponse-1?view=azure-dotnet

```<code>ResourceResponse<Document> response = await client.CreateDocumentAsync(collectionLink, document);
Console.WriteLine(response.RequestCharge);
Console.WriteLine(response.ActivityId);
Console.WriteLine(response.StatusCode); // HttpStatusCode.Created or 201
</code>```

It seems you are able to get a status code indicating the result, I would try to close the server midway and observe if the async response returns with an appropriate error code or if it throws. If it does not throw you might not need a try catch and just check return code and then take actions.

Body:
I have this code that I use to log activity to the Cosmos DB.

protected override async void OnStart()
{
   await Helper.LogActivity("OnStart");

public static partial class Helper
{
    public static async Task LogActivity(string activity)
    {
        var logItem = new LogItem()
        {
            Activity = activity,
        };
        await CosmosDBService.InsertLogItem(logItem);
    }
}

public class CosmosDBService
{
    static DocumentClient docClient = null;

    static readonly string databaseName = "Test";
    static readonly string collectionName = "Logs";

    static async Task<bool> Initialize()
    {
        if (docClient != null)
            return true;
        try
        {
            docClient = new DocumentClient(new Uri(APIKeys.CosmosEndpointUrl), APIKeys.CosmosAuthKey);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            docClient = null;
            return false;
        }
        return true;
    }

    public async static Task InsertLogItem(LogItem item)
    {
        if (!await Initialize())
            return;
        await docClient.CreateDocumentAsync(
            UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
            item);
    }

}

What I am concerned with is if there was no internet connection. Would it be a good idea to somehow test for this first or should I add some try catch exception to the code for the logging?

Would appreciate any suggestions on how I could make this code bullet proof so that even if there is no connection then there is no exception thrown in the OnStart.

If the logging fails then it's not a problem for me but I want to be sure the code will not fail if there is no internet connection or if the cosmos db call fails.

Body:
Maybe make a checklist of concerned cases:

1) No Internet
2) Internet but database is offline
3) etc..

Then test your code and see how it behaves, and ensure you are handling the cases.
Then you can be (somewhat) sure how your code behaves under these circumstances.
It will also show you where the exception occures, so you might want to add a try..catch block to prevent other failures.

UPDATE - Regarding Handling error cases:

So if your program fails to initialize the docClient it would mean that it will not be able to write any logs.

So there might be a few ways to handle this,

1) you could have a "fallback" logging method, meaning if docClient == null log to console. (So that later you can investigate on the server what went wrong) This allows you to keep crucial logs saved if the server keeps these logs.

2) Another fallback method would be to buffer the events in a memory list, and retry to connect every 10 minutes to the database. If connection was succesfull you empty your buffer into the database.

3) You can implement a retry count, like retry to connect X times at startup, if it fails you can fallback to another method or combination of above ideas. Additionally you could have a system that alerts you via E-MAIL or SMS, depending how critical this service is.

These ideas center around issues with connecting to the database.
This will however still not help you to much with the actual insert, for example if your DB connection dies midway.

So you might still need a try catch inside the InsertLogItem-method around the actual insert code. So that would hide the try catch around every await Helper.LogActivity("OnStart"); statement, as it is integrated. and if that log fails you could again concider fallback methods or actions

UPDATE2)
Looking at CreateDocumentAsync return object here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.documents.client.resourceresponse-1?view=azure-dotnet

ResourceResponse<Document> response = await client.CreateDocumentAsync(collectionLink, document);
Console.WriteLine(response.RequestCharge);
Console.WriteLine(response.ActivityId);
Console.WriteLine(response.StatusCode); // HttpStatusCode.Created or 201

It seems you are able to get a status code indicating the result, I would try to close the server midway and observe if the async response returns with an appropriate error code or if it throws. If it does not throw you might not need a try catch and just check return code and then take actions.


问:
Flutter in VSCode Interpreting package as URI
I'm trying to get started using flutter from VSCode.
I think I've done all the proper setup:

1) Downloaded extensions for flutter and dart and codeRunner on VS code

2) Downloaded the flutter SDK and added it the path

3) Run flutter doctor with no doctor with no errors

After all the setup I tried clicking "Run Code", and received the error: 'dart' is not recognized as an internal or external command. After reading other online posts, I figured it was because I only added flutter SDK to my path and not dart SDK, so I added dart SDK to my path as well.

From there, I tried running the code again and got the following error:

```<code>lib/main.dart: Warning: Interpreting this as package URI, 'package:tranfer_app/main.dart'.
../../flutter/packages/flutter/lib/src/material/animated_icons.dart:9:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui show Paint, Path, Canvas;
       ^
../../flutter/packages/flutter/lib/src/material/animated_icons.dart:10:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/app.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui;
       ^
../../flutter/packages/flutter/lib/src/material/app_bar_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/arc.dart:6:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/bottom_sheet_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/button_bar_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/card_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/chip_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
</code>```

From my readings online, it sounds like VS Code might be trying to run as a dart app rather than a flutter app, and although I've found how to change this in Android Studio, I'm not sure how to change it in VSCode (which is where I'd like to do my development). Notably, if instead of running code with Ctrl+Alt+N, I use F5, the app will run just fine on an emulator, but I'd rather figure out these warnings before continuing as they seem important.

I expect my code to be runnable using the usual Ctrl+Alt+N Code Runner.

Thanks so much for the help!

答:
I expect my code to be runnable using the usual Ctrl+Alt+N Code Runner.

Code Runner doesn't understand what Flutter is (or how to run it), so pressing this key combination will just run the Dart script in the VM. The warnings are because dart:ui is not available in the standalone VM (only via Flutter).

Using F5 (or the Debug menu) is the correct way to run a Flutter app, as it will be handled by the Dart/Flutter extensions that automatically detect which tool to run the app with (as well as provide lots of other functionality like hot-reload-on-save).

If there's a reason running with F5 doesn't work for you, I'd be interested in understanding why (you can file issues on GitHub). Thanks!

Body:
I'm trying to get started using flutter from VSCode.
I think I've done all the proper setup:

1) Downloaded extensions for flutter and dart and codeRunner on VS code

2) Downloaded the flutter SDK and added it the path

3) Run flutter doctor with no doctor with no errors

After all the setup I tried clicking "Run Code", and received the error: 'dart' is not recognized as an internal or external command. After reading other online posts, I figured it was because I only added flutter SDK to my path and not dart SDK, so I added dart SDK to my path as well.

From there, I tried running the code again and got the following error:

lib/main.dart: Warning: Interpreting this as package URI, 'package:tranfer_app/main.dart'.
../../flutter/packages/flutter/lib/src/material/animated_icons.dart:9:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui show Paint, Path, Canvas;
       ^
../../flutter/packages/flutter/lib/src/material/animated_icons.dart:10:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/app.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui;
       ^
../../flutter/packages/flutter/lib/src/material/app_bar_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/arc.dart:6:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/bottom_sheet_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/button_bar_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/card_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^
../../flutter/packages/flutter/lib/src/material/chip_theme.dart:5:8: Error: Not found: 'dart:ui'
import 'dart:ui' show lerpDouble;
       ^

From my readings online, it sounds like VS Code might be trying to run as a dart app rather than a flutter app, and although I've found how to change this in Android Studio, I'm not sure how to change it in VSCode (which is where I'd like to do my development). Notably, if instead of running code with Ctrl+Alt+N, I use F5, the app will run just fine on an emulator, but I'd rather figure out these warnings before continuing as they seem important.

I expect my code to be runnable using the usual Ctrl+Alt+N Code Runner.

Thanks so much for the help!


问:
How Can I Solve Permission Denied in React Native Project?
anyone faced this issue after a run

```<code>react-native run-android/ios
</code>```

android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java
  (Permission denied)

when i write sudo before any command like npm install/yarn add etc it's work very well

otherways i got errors related to Permission

答:
It looks like you have no permission- try this

sudo chmod -R 777 {path}

Body:
anyone faced this issue after a run

react-native run-android/ios

android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java
  (Permission denied)

when i write sudo before any command like npm install/yarn add etc it's work very well

otherways i got errors related to Permission


问:
Installing Ubuntu on windows
I have partitioned my drive and now I want to install ubuntu into my drive c:. Would it erase my files in drive D:?

I was currently running windows 10

答:
When you launch a installation in Ubuntu you will be prompted with the installation location that you want for the OS, make sure that the disk that you select in that step is the one you have for Ubuntu.

As always i recommend you to make a full backup of all your important files before doing any installation of any new OS on your system.

I hope i have helped you, have a great day.

Title: Installing Ubuntu on windows


问:
Is there any method to run perf under WSL?
When I wanted to run perf under WSL, I met the follow question:

WARNING: perf not found for kernel 4.4.0-18362

You may need to install the following packages for this specific kernel:

linux-tools-4.4.0-18362-Microsoft

linux-cloud-tools-4.4.0-18362-Microsoft

You may also want to install one of the following packages to keep up to date:

linux-tools-Microsoft

linux-cloud-tools-Microsoft

But I can't find packages called linux-tools-4.4.0-18362-Microsoft or linux-cloud-tools-4.4.0-18362-Microsoft. I guess the package names are generated automatically.

I also tried to use perf in docker container. However, docker container use the same kernel as the hosts.

Is there any method to run perf under WSL?

I heard that perf can be used in WSL2. But after I upgraded to WSL2, it shows the similar error message:

WARNING: perf not found for kernel 4.19.84-microsoft

You may need to install the following packages for this specific
  kernel:

```<code>linux-tools-4.19.84-microsoft-standard

linux-cloud-tools-4.19.84-microsoft-standard
</code>```

You may also want to install one of the following packages to keep
  up to date:

```<code>linux-tools-standard

linux-cloud-tools-standard
</code>```

答:
WARNING: perf not found for kernel 4.19.84-microsoft

Because WSL2 uses custom Linux kernel. Its source code can be found here
microsoft/WSL2-Linux-Kernel. We have to compile perf tools from it.

Procedure

Install required build packages. If you are using Ubuntu in WSL2 this is the
required command:

```<code>sudo apt install build-essential flex bison libssl-dev libelf-dev
</code>```

Clone the WSL2 Linux kernel repository:

```<code>git clone --depth=1 https://github.com/microsoft/WSL2-Linux-Kernel.git
</code>```

Go to perf folder and compile it:

```<code>cd WSL2-Linux-Kernel/tools/perf
make
</code>```

perf executable file will be in that folder.

Body:
When I wanted to run perf under WSL, I met the follow question:

WARNING: perf not found for kernel 4.4.0-18362

You may need to install the following packages for this specific kernel:

linux-tools-4.4.0-18362-Microsoft

linux-cloud-tools-4.4.0-18362-Microsoft

You may also want to install one of the following packages to keep up to date:

linux-tools-Microsoft

linux-cloud-tools-Microsoft

But I can't find packages called linux-tools-4.4.0-18362-Microsoft or linux-cloud-tools-4.4.0-18362-Microsoft. I guess the package names are generated automatically.

I also tried to use perf in docker container. However, docker container use the same kernel as the hosts.

Is there any method to run perf under WSL?

I heard that perf can be used in WSL2. But after I upgraded to WSL2, it shows the similar error message:

WARNING: perf not found for kernel 4.19.84-microsoft

You may need to install the following packages for this specific
  kernel:

linux-tools-4.19.84-microsoft-standard

linux-cloud-tools-4.19.84-microsoft-standard

You may also want to install one of the following packages to keep
  up to date:

linux-tools-standard

linux-cloud-tools-standard

Body:
WARNING: perf not found for kernel 4.19.84-microsoft

Because WSL2 uses custom Linux kernel. Its source code can be found here
microsoft/WSL2-Linux-Kernel. We have to compile perf tools from it.

Procedure

Install required build packages. If you are using Ubuntu in WSL2 this is the
required command:

sudo apt install build-essential flex bison libssl-dev libelf-dev

Clone the WSL2 Linux kernel repository:

git clone --depth=1 https://github.com/microsoft/WSL2-Linux-Kernel.git

Go to perf folder and compile it:

cd WSL2-Linux-Kernel/tools/perf
make

perf executable file will be in that folder.


问:
jquery form validation ajaxSubmit()
I am getting very frustrated with this jquery form validation ajaxSubmit();

In chrome, it seems to fail silently without even hitting the submitHandler, firefox does, but still goes on to the action="contact.php" page. I was expecting it to just post in the background and possibly return results, but can't get it to work that way.

Edit: Found a fix for this if anyone else is interested, put this line of code somewhere in your dom ready.

```<code>// disable HTML5 native validation and let jquery handle it.
    $('form').attr('novalidate','novalidate');
</code>```

HTML form:

```<code><form method="post" action="contact.php" id="contact">
    <fieldset>
        <input type="text" id="email" class="required email" name="email"  maxlength="30" value="youremail @ example.com" />
        <input type="text" id="subject" class="required" name="subject" maxlength="24" value="Enter your subject" />
        <textarea id="msg" class="required textarea" name="msg" cols="30" rows="5">Reason for contact.</textarea>
        <input type="submit" class="formBtn" value="Punch me an Email" />
    </fieldset>
</form>
</code>```

JQuery:

```<code>$(window).load(function(){
    $('#contact').validate({
            rules:{
                email:{required: true, email:true},
                subject:{required: true, minlength: 5},
                msg:{required: true, minlength: 50}
            },
            messages:{
                email:'',
                subject: '',
                msg: ''
            },
            invalidHandler:function(){
                $('div.error').hide();
            },
            focusInvalid:true,
            onfocusout:false,
            submitHandler: function() {
               // never hits with chrome, and alert works in FF4,
               // but still goes to contact.php
               $('#contact').ajaxSubmit();
           }
        });
});
</code>```

答:
submitHandler is called after a submit event is fired, thus ajaxForm registers its own submit event handler after the submit event, which is probably too late to catch it.

You don't have to nest the two plugins, just validate first and ajaxify second:

```<code>$('#contact').validate({...});
$('#contact').ajaxForm();
</code>```

That way, the validation event handler is called first, and the event is stopped before getting to the ajax submit handler if it is invalid.

Title: jquery form validation ajaxSubmit()

Body:
I am getting very frustrated with this jquery form validation ajaxSubmit();

In chrome, it seems to fail silently without even hitting the submitHandler, firefox does, but still goes on to the action="contact.php" page. I was expecting it to just post in the background and possibly return results, but can't get it to work that way.

Edit: Found a fix for this if anyone else is interested, put this line of code somewhere in your dom ready.

// disable HTML5 native validation and let jquery handle it.
    $('form').attr('novalidate','novalidate');

HTML form:

<form method="post" action="contact.php" id="contact">
    <fieldset>
        <input type="text" id="email" class="required email" name="email"  maxlength="30" value="youremail @ example.com" />
        <input type="text" id="subject" class="required" name="subject" maxlength="24" value="Enter your subject" />
        <textarea id="msg" class="required textarea" name="msg" cols="30" rows="5">Reason for contact.</textarea>
        <input type="submit" class="formBtn" value="Punch me an Email" />
    </fieldset>
</form>

JQuery:

$(window).load(function(){
    $('#contact').validate({
            rules:{
                email:{required: true, email:true},
                subject:{required: true, minlength: 5},
                msg:{required: true, minlength: 50}
            },
            messages:{
                email:'',
                subject: '',
                msg: ''
            },
            invalidHandler:function(){
                $('div.error').hide();
            },
            focusInvalid:true,
            onfocusout:false,
            submitHandler: function() {
               // never hits with chrome, and alert works in FF4,
               // but still goes to contact.php
               $('#contact').ajaxSubmit();
           }
        });
});

Body:
submitHandler is called after a submit event is fired, thus ajaxForm registers its own submit event handler after the submit event, which is probably too late to catch it.

You don't have to nest the two plugins, just validate first and ajaxify second:

$('#contact').validate({...});
$('#contact').ajaxForm();

That way, the validation event handler is called first, and the event is stopped before getting to the ajax submit handler if it is invalid.


问:
How can I access random point without full reading?
I have a huge data set to train word2vec.

example is as follows.

```<code>15 24 0
22 23 1
11 15 0
22 27 1
...
</code>```

I want to randomly sample it.

I tried with codecs function and split function.

But that file is too big, so that code make memory error.

To avoid memory error, I use for and open(). for example,

```<code>for line in open(fileNM):
    train(line)
</code>```

But in this way, I can access data only in a sequential way.

How can I randomly access data with out full reading?

答:
You can use the python built-in linecache library for getting a line from file:

https://docs.python.org/3.7/library/linecache.html

Body:
I have a huge data set to train word2vec.

example is as follows.

15 24 0
22 23 1
11 15 0
22 27 1
...

I want to randomly sample it.

I tried with codecs function and split function.

But that file is too big, so that code make memory error.

To avoid memory error, I use for and open(). for example,

for line in open(fileNM):
    train(line)

But in this way, I can access data only in a sequential way.

How can I randomly access data with out full reading?


问:
Action Required Switch to the Play Referrer API by March 1, 2020
I got the email from Google as follows: -

Hello Google Play Developer,

We recently announced that we’ll be deprecating the install_referrer
  intent broadcast mechanism. Because one or more of your apps uses this
  intent to track referrals, we wanted to ensure you make the switch
  before March 1, 2020. After this date, new versions of the Play Store
  app will no longer broadcast the install_referrer intent after app
  installs.

Action required

Migrate to the Play Install Referrer API to track your app installs
  for the following apps and/or games.

But in my application I am not using it any where. What could be the possible reason for this warning?

答:
Exclude all measurement modules form firebase </p>

```<code>    implementation ('com.google.firebase:firebase-core:17.2.2'){
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-api'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-sdk'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-impl'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-sdk-api'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-base'
}
</code>```

Body:
Exclude all measurement modules form firebase

    implementation ('com.google.firebase:firebase-core:17.2.2'){
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-api'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-sdk'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-impl'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-sdk-api'
    exclude group: 'com.google.android.gms', module: 'play-services-measurement-base'
}


问:
How do I get Terraform to throw a specific error message depending on what account the user is in?
I have a terraform module that does domain delegation. For several variables there is some validation  against a hard-coded value to check that a user is using valid inputs, for example:

```<code>resource "null_resource" "validate_region" {
  count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"
}
</code>```

with local.regions being hard-coded and var.region being a user-set variable. The above code works in that when a user sets the variable wrong, it throws an error like this:

```<code>Error: Incorrect value type

  on .terraform/foo/main.tf line 46, in resource "null_resource" "validate_region":
  46:   count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"

Invalid expression value: a number is required.
</code>```

I now need to validate that the AWS account the user is currently using is the correct one. In this case it's up to the user to set the account id of the correct account in their variables, and my code needs to pull the account id of the account that's running the module and compare it against the user's variable. I've tried something like this:

```<code>data "aws_caller_identity" "account" {}

resource "null_resource" "validate_account" {
  count = data.aws_caller_identity.account.account_id == var.primary_account_id ? 0 : "Please check that you are using the AWS creds for the primary account for this domain."
}

data "aws_route53_zone" "primary" {
  name = local.primary_name
}
</code>```

with various syntax changes on the "{data.aws_caller_identity.account.account_id == var.primary_account_id}" ? 0 part in an effort to get the logic to work, but no luck. I would like it to throw an error like the region validation does, where it will show the error message I wrote. Instead(depending on syntax), it will work as expected for the correct account and throw a Error: no matching Route53Zone found error for the incorrect account, OR it will throw a completely different error presumably because the syntax is screwing things up.

How do I get this to work? is it possible?

答:
An alternative option here that should simplify what you are doing is to set the region and account constraints up so that Terraform will automatically use the correct region and fail if the credentials are not for the correct account.

You can define this in the aws provider block. An example might look like this:

```<code>provider "aws" {
  region              = "eu-west-1"
  allowed_account_ids = ["123456789012"]
}
</code>```

Now if you attempt to use credentials for a different AWS account then Terraform will fail during the plan stage:

```<code>Error: AWS Account ID not allowed: 234567890123
</code>```

Body:
I have a terraform module that does domain delegation. For several variables there is some validation  against a hard-coded value to check that a user is using valid inputs, for example:

resource "null_resource" "validate_region" {
  count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"
}

with local.regions being hard-coded and var.region being a user-set variable. The above code works in that when a user sets the variable wrong, it throws an error like this:

Error: Incorrect value type

  on .terraform/foo/main.tf line 46, in resource "null_resource" "validate_region":
  46:   count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"

Invalid expression value: a number is required.

I now need to validate that the AWS account the user is currently using is the correct one. In this case it's up to the user to set the account id of the correct account in their variables, and my code needs to pull the account id of the account that's running the module and compare it against the user's variable. I've tried something like this:

data "aws_caller_identity" "account" {}

resource "null_resource" "validate_account" {
  count = data.aws_caller_identity.account.account_id == var.primary_account_id ? 0 : "Please check that you are using the AWS creds for the primary account for this domain."
}

data "aws_route53_zone" "primary" {
  name = local.primary_name
}

with various syntax changes on the "{data.aws_caller_identity.account.account_id == var.primary_account_id}" ? 0 part in an effort to get the logic to work, but no luck. I would like it to throw an error like the region validation does, where it will show the error message I wrote. Instead(depending on syntax), it will work as expected for the correct account and throw a Error: no matching Route53Zone found error for the incorrect account, OR it will throw a completely different error presumably because the syntax is screwing things up.

How do I get this to work? is it possible?

Body:
An alternative option here that should simplify what you are doing is to set the region and account constraints up so that Terraform will automatically use the correct region and fail if the credentials are not for the correct account.

You can define this in the aws provider block. An example might look like this:

provider "aws" {
  region              = "eu-west-1"
  allowed_account_ids = ["123456789012"]
}

Now if you attempt to use credentials for a different AWS account then Terraform will fail during the plan stage:

Error: AWS Account ID not allowed: 234567890123


问:
Bypassing WindowsApps folder protection other than ACLs
I noticed today that on windows 10
some apps in the folder C:\ProgramFiles\WindowsApps... are protected in some way other than just the access permissions.

When installing Microsoft.MicrosoftEmulator_1.1.39.0_x64__8wekyb3d8bbwe.msix or Microsoft.253890156C685_1.0.0.0_x64__8wekyb3d8bbwe.Msix
as well as it seams other apps from the store

the Folders for those created in under C:\ProgramFiles\WindowsApps\ have some additional write protection.

While a cmd prompt started as TrustedInstaller can create and delete folders in the apps that come pre-installed in the folders fo these apps this fails with an access denied error.
Taking Ownership of those folders and files as well as adding full access permission does not solve the issue.

With a cmd prompt started as system it is at least possible to create or delete folders but for the existing folders created by the package installer its still not able to create a file within those.

This protection remains in place even when the system partition in question is mounted by an other windows 10 system.

The only way I found to gain full access to these files is to mount the partition in a windows 7 installation.

So it seams to me that MSFT has added som additional layer or patronizing the administrators which needs to be understood and broken.

Any ideas how to get around this issue?

答:
Well however the restrictions are implemented with this driver: https://github.com/DavidXanatos/IgnoreACLs you can gain access to everything everywhere.
With minor limitations, renaming of files in protected locations does not work and creating of directories.
Other than that, modifying, creating and deleting files and folders works fine.

Power back to the owners of the devices.


问:
How do you map routes according to the following schema?
How do you map this url

/Topic/topicName/action?topicId=someInt

Where Topic is the controller name (this is const - it always reads "Topic"),

topicName is being ignored

action is action name,

and someInt is the topicId argument for "action".

Here are couple of examples:

/Topic/c-sharp/AddQuestion?topicId=1

To invoke:

Controller: Topic

Action: AddQuestion

topicId =1

Where this is the action's singnature in TopicConroller

```<code>public ActionResult AddQuestion(int topicId)
</code>```

Another example:

/Topic/MySql-queries/AddSubTopic?topicId=1

To invoke:

Controller: Topic

Action: AddSubTopic

topicId =1

Where this is the action's singnature in TopicConroller

```<code>public ActionResult AddSubTopic(int topicId)
</code>```

etc. (all actions in Topic controller receive only one argument - that is the topic's id).

答:
Have you tried:

```<code>            routes.MapRoute(
                "Default",
                "{controller}/{topic}/{action}/{id}",
                new { controller = "Home", action = "Index" }
            );
</code>```

Another way is to do it like stackoverflow. Take a look at question url, question is after id and is probably ignored.

```<code>            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}/{*catchall}",
                new { controller = "Home", action = "Index" }
            );
</code>```

Body:
How do you map this url

/Topic/topicName/action?topicId=someInt

Where Topic is the controller name (this is const - it always reads "Topic"),

topicName is being ignored

action is action name,

and someInt is the topicId argument for "action".

Here are couple of examples:

/Topic/c-sharp/AddQuestion?topicId=1

To invoke:

Controller: Topic

Action: AddQuestion

topicId =1

Where this is the action's singnature in TopicConroller

public ActionResult AddQuestion(int topicId)

Another example:

/Topic/MySql-queries/AddSubTopic?topicId=1

To invoke:

Controller: Topic

Action: AddSubTopic

topicId =1

Where this is the action's singnature in TopicConroller

public ActionResult AddSubTopic(int topicId)

etc. (all actions in Topic controller receive only one argument - that is the topic's id).

Body:
Have you tried:

            routes.MapRoute(
                "Default",
                "{controller}/{topic}/{action}/{id}",
                new { controller = "Home", action = "Index" }
            );

Another way is to do it like stackoverflow. Take a look at question url, question is after id and is probably ignored.

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}/{*catchall}",
                new { controller = "Home", action = "Index" }
            );


问:
Form CCS Style Request
The form right at the top of this page was made with aweber. I want to create a form like this, but I cannot get the sign up part to the right of the email field as in the example page. (mean horizontal form)

Sample page: https://www.backlinko.com/

I want to be able to do the same form you see in the sample page. How can I change where?

<form method="post" class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" target="_blank" >

<input type="hidden" name="meta_web_form_id" value="586791810" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="awlist5545047" />
<input type="hidden" name="redirect" value="https://www.aweber.com/form/thankyou_vo.html" id="redirect_06888bc1326c8dabe3e277c31b9118ce" />

<input type="hidden" name="meta_adtracking" value="My Web Form" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />
<input type="hidden" name="meta_forward_vars" value="1" />
<input type="hidden" name="meta_tooltip" value="" />

Email:

<input class="text" id="awf_field-105496004" type="text" name="email" value="" tabindex="500" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " />

<input name="submit" class="submit" type="submit" value="Abone Ol!" tabindex="501" />

</form>

```

thanks for helping

答:
Just change the class name "refat" to anyname you want.

Add the CSS and add the class name to the parent div with id af-form-586791810

Example:

// CSS

```<code>      .refat {
        display: flex;
      }
      .refat .af-element {
          padding: 0 !important;
      }
      .refat .buttonContainer {
        align-self: flex-end;
      }
</code>```

// HTML

```<code>      <div id="af-form-586791810" class="af-form"><div id="af-body-586791810" class="af-body af-standards refat">
</code>```

Title: Form CCS Style Request

Body:
The form right at the top of this page was made with aweber. I want to create a form like this, but I cannot get the sign up part to the right of the email field as in the example page. (mean horizontal form)

Sample page: https://www.backlinko.com/

I want to be able to do the same form you see in the sample page. How can I change where?

<form method="post" class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" target="_blank" >

<input type="hidden" name="meta_web_form_id" value="586791810" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="awlist5545047" />
<input type="hidden" name="redirect" value="https://www.aweber.com/form/thankyou_vo.html" id="redirect_06888bc1326c8dabe3e277c31b9118ce" />

<input type="hidden" name="meta_adtracking" value="My Web Form" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />
<input type="hidden" name="meta_forward_vars" value="1" />
<input type="hidden" name="meta_tooltip" value="" />

Email:

<input class="text" id="awf_field-105496004" type="text" name="email" value="" tabindex="500" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " />

<input name="submit" class="submit" type="submit" value="Abone Ol!" tabindex="501" />

</form>

thanks for helping

Body:
Just change the class name "refat" to anyname you want.

Add the CSS and add the class name to the parent div with id af-form-586791810

Example:

// CSS

      .refat {
        display: flex;
      }
      .refat .af-element {
          padding: 0 !important;
      }
      .refat .buttonContainer {
        align-self: flex-end;
      }

// HTML

      <div id="af-form-586791810" class="af-form"><div id="af-body-586791810" class="af-body af-standards refat">


问:
ASP.NET Web API returns NULL for object when using XML
I've tried to follow the instructions I found, but still it does not work.

I have following class

```<code>public class TodoItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }
    public TodoItem() { }
}
</code>```

My server has following POST Method

```<code>public IHttpActionResult Post([FromBody]TodoItem item)
    {
        if (item != null)
        {
            TodoRepository.Current.Add(item);
            return Ok(item);
        }
        return BadRequest("Object is null");
    }
</code>```

In my WebApiConfig.cs I have added following line

```<code>config.Formatters.XmlFormatter.UseXmlSerializer = true;
</code>```

On the client side I am using HttpClient as follows:

```<code>var postTask = client.PostAsXmlAsync<TodoItem>("", item);
</code>```

My Post method on server receives null for the item object.

答:
I believe this answer could be also useful. PostAsXmlAsync uses XmlMediaTypeFormatter which internally uses DataContractSerializer, which creates XML from DataContract in alphabetical order(XmlSerializer - in defined order).
So, using "Order Parameter" in the DataMemberAttribute class could help with PostAsXmlAsync-deserialization-issue:

[DataMember(Order = index)]

Body:
I've tried to follow the instructions I found, but still it does not work.

I have following class

public class TodoItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }
    public TodoItem() { }
}

My server has following POST Method

public IHttpActionResult Post([FromBody]TodoItem item)
    {
        if (item != null)
        {
            TodoRepository.Current.Add(item);
            return Ok(item);
        }
        return BadRequest("Object is null");
    }

In my WebApiConfig.cs I have added following line

config.Formatters.XmlFormatter.UseXmlSerializer = true;

On the client side I am using HttpClient as follows:

var postTask = client.PostAsXmlAsync<TodoItem>("", item);

My Post method on server receives null for the item object.


问:
Using Selenium IDE for a test-case which includes backend call?
I add a new category in the admin panel and want to ensure that the category is available in the dropdown on the user's part of the website. Recorded test in the Selenium IDE works fine. But the thing is, the task that I execute is of course not a pure frontend thing - the category is saved in the database and is loaded from it to show it to the user. So if something goes wrong on the database-side, the test will fail.

My question is: is it bad practice to do such tests that depend on backend-behavior ? Should I go for Selenium Webdriver ?

答:
If you use Selenium Webdriver, your test will not change in a main thing. It still will check database side. Selenium Webdriver is just anouther tool for testing that is more flexible and allows to make more complex test then in Selenium IDE.

I don't think that it is bad practice, because it is just one of the tests that chould be executed to enshure you that this part of your project works correctly. In this case I would check back-end part(get all categories from DB or admin's panel and check that there is no extra or missing ones) and than check user's panel(all categories are the same as set in DB and admin's panel).


问:
Register event on object injected through constructor (PropertyChanged is always null)
Is it possible to have an object injected through the constructor and register an event on it? I am currently trying to implement something like this and my PropertyChanged even is always null. I think it has to do with the fact that I am not instantiating the object in my class where I register the event, but I am not quite sure as I am still new to event driven code.

Anyway here is the relevant code:

Injected via dependency:

```<code>public static class ServiceCollectionExtensions
{
    public static void ConfigureWritable<T>(
        this IServiceCollection services,
        IConfigurationSection section,
        string file = "appsettings.json") where T : class, new()
    {
        services.Configure<T>(section);
        services.AddTransient<IWritableOptions<T>>(provider =>
        {
            var environment = provider.GetService<IHostingEnvironment>();
            var options = provider.GetService<IOptionsMonitor<T>>();
            return new WritableOptions<T>(environment, options, section.Key, file);
        });
    }
}

public interface IWritableOptions<out T> : IOptionsSnapshot<T> where T : class, new()
{
    void Update(Action<T> applyChanges);
    event PropertyChangedEventHandler PropertyChanged;
}

public class WritableOptions<T> : INotifyPropertyChanged, IWritableOptions<T> where T : class, new()
{
    private readonly IHostingEnvironment _environment;
    private readonly IOptionsMonitor<T> _options;
    private readonly string _section;
    private readonly string _file;

    public WritableOptions(
        IHostingEnvironment environment,
        IOptionsMonitor<T> options,
        string section,
        string file)
    {
        _environment = environment;
        _options = options;
        _section = section;
        _file = file;
    }

    public T Value
    {
        get
        {
            var fileProvider = _environment.ContentRootFileProvider;
            var fileInfo = fileProvider.GetFileInfo(_file);
            var physicalPath = fileInfo.PhysicalPath;

            var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
            var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
                JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

            return sectionObject;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public T Get(string name) => _options.Get(name);

    public void Update(Action<T> applyChanges)
    {
        var fileProvider = _environment.ContentRootFileProvider;
        var fileInfo = fileProvider.GetFileInfo(_file);
        var physicalPath = fileInfo.PhysicalPath;

        var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
        var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
            JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

        applyChanges(sectionObject);

        jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
        File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented));

        OnPropertyChanged("Value");
    }
}
</code>```

Class consuming the injected dependency:

```<code>public class ClientService : HostedService
{
    public ClientService(IWritableOptions<ClientSettings> clients)
    {
        clients.PropertyChanged += PropertyChanged;
    }

    private void PropertyChanged(object sender, PropertyChangedEventArgs e)
    {

    }
}
</code>```

EDIT: To further clarify, I all use this in a .Net Core WebAPI project. I register ClientService like this:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureWritable<ClientSettings>(Configuration.GetSection("ClientSettings"));
    services.AddSingleton<IHostedService, ClientService>();

    services.AddMvc();
}
</code>```

I then have a controller with which I can update these settings:

```<code>private IWritableOptions<ClientSettings> _clients;

public ClientController(IWritableOptions<ClientSettings> clients)
{
    _clients = clients;
}

[HttpPost]
[Route(CoreConfigClientRoutes.UpdateRoute)]
public void UpdateClients([FromBody] IEnumerable<ModuleSetting> updatedClients)
{
    var clients = _clients.Value.Clients.ToList();
    foreach (var updatedClient in updatedClients)
    {
        var index = clients.IndexOf(clients.Where(c => c.Id == updatedClient.Id).First());
        clients[index] = updatedClient;
    }
    _clients.Update(c => c.Clients = clients.ToArray());
}
</code>```

Sources: IHostedService, IWritableOptions

Am I missing something here or is this not possible?

Working GitHub Repo: EventDI

答:
I was getting above in the WPF app.

You probably shouldn't use code below if you care. However, for a quick 'patch and move on' I did the following.

I castrated the above solution since it was failing with dependency injection bits. Just manually described where to get appsettings.json and removed the failing to bind components.

```<code>public class WritableOptions<T> : IWritableOptions<T> where T : class, new()
{
    private readonly IOptionsMonitor<T> _options;
    private readonly string _section;

    public WritableOptions(
        IOptionsMonitor<T> options,
        string section,
        string file)
    {
        _options = options;
        _section = section;
    }

    public T Value => _options.CurrentValue;
    public T Get(string name) => _options.Get(name);

    public void Update(Action<T> applyChanges)
    {
        var physicalPath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName+ "\\appsettings.json";

        var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
        var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
            JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

        applyChanges(sectionObject);

        jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
        File.SetAttributes(physicalPath, FileAttributes.Normal);
        File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
    }
}
</code>```

Body:
Is it possible to have an object injected through the constructor and register an event on it? I am currently trying to implement something like this and my PropertyChanged even is always null. I think it has to do with the fact that I am not instantiating the object in my class where I register the event, but I am not quite sure as I am still new to event driven code.

Anyway here is the relevant code:

Injected via dependency:

public static class ServiceCollectionExtensions
{
    public static void ConfigureWritable<T>(
        this IServiceCollection services,
        IConfigurationSection section,
        string file = "appsettings.json") where T : class, new()
    {
        services.Configure<T>(section);
        services.AddTransient<IWritableOptions<T>>(provider =>
        {
            var environment = provider.GetService<IHostingEnvironment>();
            var options = provider.GetService<IOptionsMonitor<T>>();
            return new WritableOptions<T>(environment, options, section.Key, file);
        });
    }
}

public interface IWritableOptions<out T> : IOptionsSnapshot<T> where T : class, new()
{
    void Update(Action<T> applyChanges);
    event PropertyChangedEventHandler PropertyChanged;
}

public class WritableOptions<T> : INotifyPropertyChanged, IWritableOptions<T> where T : class, new()
{
    private readonly IHostingEnvironment _environment;
    private readonly IOptionsMonitor<T> _options;
    private readonly string _section;
    private readonly string _file;

    public WritableOptions(
        IHostingEnvironment environment,
        IOptionsMonitor<T> options,
        string section,
        string file)
    {
        _environment = environment;
        _options = options;
        _section = section;
        _file = file;
    }

    public T Value
    {
        get
        {
            var fileProvider = _environment.ContentRootFileProvider;
            var fileInfo = fileProvider.GetFileInfo(_file);
            var physicalPath = fileInfo.PhysicalPath;

            var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
            var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
                JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

            return sectionObject;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    public T Get(string name) => _options.Get(name);

    public void Update(Action<T> applyChanges)
    {
        var fileProvider = _environment.ContentRootFileProvider;
        var fileInfo = fileProvider.GetFileInfo(_file);
        var physicalPath = fileInfo.PhysicalPath;

        var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
        var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
            JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

        applyChanges(sectionObject);

        jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
        File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented));

        OnPropertyChanged("Value");
    }
}

Class consuming the injected dependency:

public class ClientService : HostedService
{
    public ClientService(IWritableOptions<ClientSettings> clients)
    {
        clients.PropertyChanged += PropertyChanged;
    }

    private void PropertyChanged(object sender, PropertyChangedEventArgs e)
    {

    }
}

EDIT: To further clarify, I all use this in a .Net Core WebAPI project. I register ClientService like this:

public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureWritable<ClientSettings>(Configuration.GetSection("ClientSettings"));
    services.AddSingleton<IHostedService, ClientService>();

    services.AddMvc();
}

I then have a controller with which I can update these settings:

private IWritableOptions<ClientSettings> _clients;

public ClientController(IWritableOptions<ClientSettings> clients)
{
    _clients = clients;
}

[HttpPost]
[Route(CoreConfigClientRoutes.UpdateRoute)]
public void UpdateClients([FromBody] IEnumerable<ModuleSetting> updatedClients)
{
    var clients = _clients.Value.Clients.ToList();
    foreach (var updatedClient in updatedClients)
    {
        var index = clients.IndexOf(clients.Where(c => c.Id == updatedClient.Id).First());
        clients[index] = updatedClient;
    }
    _clients.Update(c => c.Clients = clients.ToArray());
}

Sources: IHostedService, IWritableOptions

Am I missing something here or is this not possible?

Working GitHub Repo: EventDI

Body:
I was getting above in the WPF app.

You probably shouldn't use code below if you care. However, for a quick 'patch and move on' I did the following.

I castrated the above solution since it was failing with dependency injection bits. Just manually described where to get appsettings.json and removed the failing to bind components.

public class WritableOptions<T> : IWritableOptions<T> where T : class, new()
{
    private readonly IOptionsMonitor<T> _options;
    private readonly string _section;

    public WritableOptions(
        IOptionsMonitor<T> options,
        string section,
        string file)
    {
        _options = options;
        _section = section;
    }

    public T Value => _options.CurrentValue;
    public T Get(string name) => _options.Get(name);

    public void Update(Action<T> applyChanges)
    {
        var physicalPath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName+ "\\appsettings.json";

        var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
        var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
            JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

        applyChanges(sectionObject);

        jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
        File.SetAttributes(physicalPath, FileAttributes.Normal);
        File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
    }
}


问:
python is not reading the conditional statement?
```<code>import cv2
import numpy as np
import speech_recognition as sr
import winsound
from time import sleep

vish_image = cv2.imread(r'C:\Users\priyanka\Pictures\Camera Roll\WIN_20200209_13_14_33_Pro.jpg')
vish_image_gray = cv2.cvtColor(vish_image, cv2.COLOR_BGR2GRAY)
priya_image = cv2.imread(r'C:\Users\priyanka\Desktop\harr cascade\p\s.jpg')
priya_image_gray = cv2.cvtColor(priya_image, cv2.COLOR_BGR2GRAY)
def convertToRGB(image):
    return cv2.cvtColor(vish_image, cv2.COLOR_BGR2RGB)
    return cv2.cvtColor(priya_image, cv2.COLOR_BGR2RGB)

priya = cv2.CascadeClassifier('C:/Users/priyanka/Desktop/harr cascade/classifier/cascade.xml')
vish = cv2.CascadeClassifier('C:/Users/priyanka/Desktop/harr cascade/vishneshv_frontal_face.xml')
vish_face = vish.detectMultiScale(vish_image_gray, scaleFactor = 1.05, minNeighbors = 7)
priya_face = priya.detectMultiScale(priya_image_gray, scaleFactor = 1.01, minNeighbors = 1)
no_vish_face = vish_face
no_priya_face = priya_face
r = sr.Recognizer()

print("faces found: "+str(len(no_vish_face)))
print("faces found: "+str(len(no_priya_face)))

if np.all(len(no_priya_face) > 1):
    print("yes")
elif np.all(len(no_vish_face) > 1):
    print("Yes")

sleep(1)
winsound.PlaySound('how are you.wav', winsound.SND_FILENAME)
sleep(0.5)
with sr.Microphone() as source:
    audio_data = r.record(source, duration=5)
    print("Recognizing...")
    text = r.recognize_google(audio_data, language ="en-AU")
    print(text)

if 'good' in text:
    winsound.PlaySound('i too feel good.wav', winsound.SND_FILENAME)
elif 'bad' in text:
    winsound.PlaySound('that is okay.wav', winsound.SND_FILENAME)

for(x,y,w,h)in vish_face:
    vish_img = cv2.rectangle(vish_image,(x,y),(x+w,y+h),(255,0,0),2)
for(x,y,w,h)in priya_face:
    img = cv2.rectangle(priya_image,(x,y),(x+w,y+h),(255,0,0),2)

img = cv2.resize(vish_image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)

cv2.imshow('test_image',vish_img)
cv2.imshow('hello_image',img)

</code>```

So tried a lot of stuff from the internet, but still no luck. I am a primary student and i am programming on a machine learning. I hope you help me. The conditional statement above that play the sound were not playing and i thought it was the problem with the WAV file, I played it in a new python file, fortunately it worked, so I added the print function to test if they were working. I found out it was the problem with the placement of the conditional statement, but I'm not for sure what was the error.

The console displayed:

```<code>faces found: 1
faces found: 1
</code>```

Then the recordings

答:
The reason for condition statement failure is the condition itself.
if you look closely,

the length of no_vish_face and no_priya_face is exactly equal to 1.

```<code>if np.all(len(no_priya_face) > 1):   # 1 > 1 --> condition False
    print("yes")
elif np.all(len(no_vish_face) > 1):  # # 1 > 1 --> condition False
    print("Yes")
</code>```

you need to change your code too,

```<code>if np.all(len(no_priya_face) >= 1):   # 1 >= 1 --> condition True
    print("yes")
elif np.all(len(no_vish_face) >= 1):  # # 1 >= 1 --> condition True
    print("Yes")
</code>```

Body:
import cv2
import numpy as np
import speech_recognition as sr
import winsound
from time import sleep

vish_image = cv2.imread(r'C:\Users\priyanka\Pictures\Camera Roll\WIN_20200209_13_14_33_Pro.jpg')
vish_image_gray = cv2.cvtColor(vish_image, cv2.COLOR_BGR2GRAY)
priya_image = cv2.imread(r'C:\Users\priyanka\Desktop\harr cascade\p\s.jpg')
priya_image_gray = cv2.cvtColor(priya_image, cv2.COLOR_BGR2GRAY)
def convertToRGB(image):
    return cv2.cvtColor(vish_image, cv2.COLOR_BGR2RGB)
    return cv2.cvtColor(priya_image, cv2.COLOR_BGR2RGB)

priya = cv2.CascadeClassifier('C:/Users/priyanka/Desktop/harr cascade/classifier/cascade.xml')
vish = cv2.CascadeClassifier('C:/Users/priyanka/Desktop/harr cascade/vishneshv_frontal_face.xml')
vish_face = vish.detectMultiScale(vish_image_gray, scaleFactor = 1.05, minNeighbors = 7)
priya_face = priya.detectMultiScale(priya_image_gray, scaleFactor = 1.01, minNeighbors = 1)
no_vish_face = vish_face
no_priya_face = priya_face
r = sr.Recognizer()

print("faces found: "+str(len(no_vish_face)))
print("faces found: "+str(len(no_priya_face)))

if np.all(len(no_priya_face) > 1):
    print("yes")
elif np.all(len(no_vish_face) > 1):
    print("Yes")

sleep(1)
winsound.PlaySound('how are you.wav', winsound.SND_FILENAME)
sleep(0.5)
with sr.Microphone() as source:
    audio_data = r.record(source, duration=5)
    print("Recognizing...")
    text = r.recognize_google(audio_data, language ="en-AU")
    print(text)

if 'good' in text:
    winsound.PlaySound('i too feel good.wav', winsound.SND_FILENAME)
elif 'bad' in text:
    winsound.PlaySound('that is okay.wav', winsound.SND_FILENAME)

for(x,y,w,h)in vish_face:
    vish_img = cv2.rectangle(vish_image,(x,y),(x+w,y+h),(255,0,0),2)
for(x,y,w,h)in priya_face:
    img = cv2.rectangle(priya_image,(x,y),(x+w,y+h),(255,0,0),2)

img = cv2.resize(vish_image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)

cv2.imshow('test_image',vish_img)
cv2.imshow('hello_image',img)

So tried a lot of stuff from the internet, but still no luck. I am a primary student and i am programming on a machine learning. I hope you help me. The conditional statement above that play the sound were not playing and i thought it was the problem with the WAV file, I played it in a new python file, fortunately it worked, so I added the print function to test if they were working. I found out it was the problem with the placement of the conditional statement, but I'm not for sure what was the error.

The console displayed:

faces found: 1
faces found: 1

Then the recordings

Body:
The reason for condition statement failure is the condition itself.
if you look closely,

the length of no_vish_face and no_priya_face is exactly equal to 1.

if np.all(len(no_priya_face) > 1):   # 1 > 1 --> condition False
    print("yes")
elif np.all(len(no_vish_face) > 1):  # # 1 > 1 --> condition False
    print("Yes")

you need to change your code too,

if np.all(len(no_priya_face) >= 1):   # 1 >= 1 --> condition True
    print("yes")
elif np.all(len(no_vish_face) >= 1):  # # 1 >= 1 --> condition True
    print("Yes")


问:
How to configure Conditional Mapping in AutoMapper?
Suppose I have the following entities (classes)

```<code>public class Target
{
    public string Value;
}

public class Source
{
    public string Value1;
    public string Value2;
}
</code>```

Now I want to configure Auto Map, to Map Value1 to Value if Value1 starts with "A", but otherwise I want to map Value2 to Value.

This is what I have so far:

```<code>Mapper
    .CreateMap<Source,Target>()
    .ForMember(t => t.Value,
        o =>
            {
                o.Condition(s =>
                    s.Value1.StartsWith("A"));
                o.MapFrom(s => s.Value1);
                  <<***But then how do I supply the negative clause!?***>>
            })
</code>```

However the part the still eludes me is how to tell AutoMapper to go take s.Value2 should the earlier condition fails.

It just seems to me the API was not designed as well as it could be... but may be it's my lack of knowledge getting in the way.

答:
AutoMapper allows adding conditions to properties that must be met before that property will be mapped.</p>

```<code>Mapper.CreateMap<Source,Target>()
      .ForMember(t => t.Value, opt =>
            {
                opt.PreCondition(s => s.Value1.StartsWith("A"));
                opt.MapFrom(s => s.Value1);
            })
</code>```

Body:
Suppose I have the following entities (classes)

public class Target
{
    public string Value;
}

public class Source
{
    public string Value1;
    public string Value2;
}

Now I want to configure Auto Map, to Map Value1 to Value if Value1 starts with "A", but otherwise I want to map Value2 to Value.

This is what I have so far:

Mapper
    .CreateMap<Source,Target>()
    .ForMember(t => t.Value,
        o =>
            {
                o.Condition(s =>
                    s.Value1.StartsWith("A"));
                o.MapFrom(s => s.Value1);
                  <<***But then how do I supply the negative clause!?***>>
            })

However the part the still eludes me is how to tell AutoMapper to go take s.Value2 should the earlier condition fails.

It just seems to me the API was not designed as well as it could be... but may be it's my lack of knowledge getting in the way.

Body:
AutoMapper allows adding conditions to properties that must be met before that property will be mapped.

Mapper.CreateMap<Source,Target>()
      .ForMember(t => t.Value, opt =>
            {
                opt.PreCondition(s => s.Value1.StartsWith("A"));
                opt.MapFrom(s => s.Value1);
            })


问:
In Azure DevOps is there a way to restrict a member of a Team to create Work Items only for specific Area Paths and Iterations?
We're looking to use a DevOps project per customer and within each customer run multiple projects.

To do this we can set up multiple Teams/Areas and have associated Iterations and choose the default Iterations for each Area, that's all good.

However if you choose to create a new Work Item, you can still choose any Area and any Iteration.  Ideally we'd want to limit members of each specific Team/Area to only be able to choose the Area and Iterations for their project.

答:
For this issue , you can set the permission in the Team configuration of project settings.

Team configuration -> Areas -> the specific area -> Security -> Deny Edit work items in this node permission


问:
Is it possible to use AWS Route 53 as a DNS provider for a bare-metal K8s cluster?
I would like to use Route 53 as the DNS provider of a bare-metal k8s cluster. I've found a few guides on the internet, but they are all for cloud k8s clusters. </p>

<p>Have anyone done this before? </p>

答: Yes, the config for external-dns is totally separate from how/where you run Kubernetes. The only thing you’ll need to do differently is create a dedicated IAM user with the right perms and plug the credentials into the right env vars. We do the same for our GKE clusters.</p>

Body:
I would like to use Route 53 as the DNS provider of a bare-metal k8s cluster. I've found a few guides on the internet, but they are all for cloud k8s clusters.

Have anyone done this before?


问:
Simulation Speed of Nonlinear Solver in Modelica
Why does Modelica's nonlinear solver Modelica.Math.Nonlinear.solveOneNonlinearEquation take more time to solve a nonlinear equation than traditional fixed point iterative (FPI) scheme?
The equation

```<code>y= arctan(1-x/1+x)-x
</code>```

solved by the solveOneNonlinearEquation solver (which basically uses Brent's Method) solves the above equation in 6 iterations whereas traditional iterative approach takes 111 iterations. However, the CPU time taken by the iterative scheme is lesser than that taken by the solveOneNonlinearEquation solver (see image).

Why is this? Could be due to computational efficiency of the iterative scheme i.e., to say lesser event generation in the iterative scheme?

答:
The different root finding methods have different properties. Convergence speed is just one, and it can be counted in number of iterations, or in CPU time. Both will greatly depend on start values, curvature and monotonicity of the function, bounds, cost to evaluate the function, availability of analytic derivatives etc.. Other interesting properties could be guarantee of convergence, or whether derivatives are required.

The Wikipedia article on root finding algorithms gives a good overview of the advantages and disadvantages of the different methods:

https://en.wikipedia.org/wiki/Root-finding_algorithm

If one method works much better than others for your special case, you should just implement and use it! Be careful when benchmarking, it is very easy to find examples where each method can shine. For this reason, you should test each algorithm on a variety of functions, maybe 10 different ones, and each one with different intervals. Bisection will perform worse for the same function but larger start interval. Brent is a good and proven method, that is why it is used in the MSL. You could even think about sending a Pull Request to the MSL and add alternatives.

Body:
Why does Modelica's nonlinear solver Modelica.Math.Nonlinear.solveOneNonlinearEquation take more time to solve a nonlinear equation than traditional fixed point iterative (FPI) scheme?
The equation

y= arctan(1-x/1+x)-x

solved by the solveOneNonlinearEquation solver (which basically uses Brent's Method) solves the above equation in 6 iterations whereas traditional iterative approach takes 111 iterations. However, the CPU time taken by the iterative scheme is lesser than that taken by the solveOneNonlinearEquation solver (see image).

Why is this? Could be due to computational efficiency of the iterative scheme i.e., to say lesser event generation in the iterative scheme?


问:
.NET units class, inches to millimeters
Does .NET has Units conversion class? I need to convert inches to millimeters and vise versa. </p>

答: No, there is no such unit conversions built into the framework. Should be easy enough to implement yourself, though.</p>

Title: .NET units class, inches to millimeters


问:
Want to know how to make a request to HTTPS appl with Basic Auth enabled
My application is running on HTTPS. So, I have made 3 citrus-clients that talks to HTTPS Application. I've done similar to citrus-sample-https. I'm able to get response from some endpoints that doesn't have Basic Auth enabled. But some other endpoints has Basic-Authentication enabled.
Similar to :

```<code>.client().requestFactory( <SSLRequestFactory >)
</code>```

I have referred citrus-http-basic-auth sample. Basic-Auth object is also passed to requestFactory() method. How can I achieve both SSL & Basic-Auth?

答:
I suggest to only keep using the SSL enabled request factory on the client and add Basic auth header in the test send actions (only for those calls that require Basic auth).

You can add the Basic auth header in your request by doing something like:

```<code>http().client("sslClient")
    .send()
    .post()
    .header("Authorization", "Basic citrus:encodeBase64('username:password')")
</code>```

You can also use variables for username and password

```<code>.header("Authorization", "Basic citrus:encodeBase64('${username}:${password}')")
</code>```

Body:
My application is running on HTTPS. So, I have made 3 citrus-clients that talks to HTTPS Application. I've done similar to citrus-sample-https. I'm able to get response from some endpoints that doesn't have Basic Auth enabled. But some other endpoints has Basic-Authentication enabled.
Similar to :

.client().requestFactory( <SSLRequestFactory >)

I have referred citrus-http-basic-auth sample. Basic-Auth object is also passed to requestFactory() method. How can I achieve both SSL & Basic-Auth?

Body:
I suggest to only keep using the SSL enabled request factory on the client and add Basic auth header in the test send actions (only for those calls that require Basic auth).

You can add the Basic auth header in your request by doing something like:

http().client("sslClient")
    .send()
    .post()
    .header("Authorization", "Basic citrus:encodeBase64('username:password')")

You can also use variables for username and password

.header("Authorization", "Basic citrus:encodeBase64('${username}:${password}')")


答:
This is my solution, but not sure it resolved.
https://codesandbox.io/s/priceless-frost-5129t</p>

Title: Calculate how long user stop at indicator position on a website

Body:
I want to detect attention of users on a website. And I've data includes:

The scroll positions array (from top = 0): [982,1023,1125,1191,1193,1196,1228,1288,1359,1428,1476,1509,1511,1541,1625,1731,1814,1871,1882,1855,1812,1750,1661,1582,1564,1561,1504,1390,1281,1246,1216,1135,1043,985,981]

The time array in millisecond: (corresponding to scroll positions array):
[2514,2588,2687,2789,2883,3410,3490,3590,3691,3794,3890,3992,4083,4591,4692,4795,4894,4990,5082,8382,8482,8592,8691,8790,8882,9190,9291,9392,9489,9590,10090,10188,10289,10392,10482]

That's mean user scroll to 982px at 2514ms (origin 0 when user access the website); 1023px at 2588ms, ......

So I want to calculate how long user stop at specific point, example 1000px

Please note that user maybe scroll from TOP to BOTTOM, then BOTTOM to TOP

thanks!


问:
How can CodeMirror display an 'javascript object' string with object structure
I start use code mirror, and i want to display an object with object structure.

I have a file with this content

```<code>{ property1: 'value', property2: { property3: 'value' }}
</code>```

This is written in one line in .txt file.

Now i want to use code mirror so user can edit this file content.
I get the file content using HTTP call and after that i have this code

```<code>        var editor = CodeMirror(document.getElementById('reportEditor'), {
            mode: { name: "javascript", json: true },
            theme: "default",
            lineNumbers: true,
            readOnly: false,
            value: JSON.stringify(response.data),
        });
</code>```

This works fine, i get the content but code mirror display it in one line.

How can force Code Mirror to display this value like an object structure like

```<code> {
      property1: 'value',
      property2: {
           property3: 'value'
      }
 }
</code>```

I found on this  site  a very good json prettifier

答:
var editor = CodeMirror(document.getElementById('reportEditor'), {
            mode: { name: "javascript", json: true },
            theme: "default",
            lineNumbers: true,
            readOnly: false,
            value: JSON.stringify(response.data,null,2),
        });
```

this works for me, setting replacer to null and indentation as 2 when changing the JSON to string.

Body:
I start use code mirror, and i want to display an object with object structure.

I have a file with this content

{ property1: 'value', property2: { property3: 'value' }}

This is written in one line in .txt file.

Now i want to use code mirror so user can edit this file content.
I get the file content using HTTP call and after that i have this code

        var editor = CodeMirror(document.getElementById('reportEditor'), {
            mode: { name: "javascript", json: true },
            theme: "default",
            lineNumbers: true,
            readOnly: false,
            value: JSON.stringify(response.data),
        });

This works fine, i get the content but code mirror display it in one line.

How can force Code Mirror to display this value like an object structure like

 {
      property1: 'value',
      property2: {
           property3: 'value'
      }
 }

I found on this  site  a very good json prettifier

Body:
var editor = CodeMirror(document.getElementById('reportEditor'), {
            mode: { name: "javascript", json: true },
            theme: "default",
            lineNumbers: true,
            readOnly: false,
            value: JSON.stringify(response.data,null,2),
        });

this works for me, setting replacer to null and indentation as 2 when changing the JSON to string.


问:
WinDbg get addresses of all functions from symbols
Executing command x ShittyProject!* I am getting such output

```<code><MSIL:00250014         > ShittyProject!Main (void)
<MSIL:00250098         > ShittyProject!.ctor (void)
<MSIL:00250037         > ShittyProject!.ctor (void)
<MSIL:002500ed         > ShittyProject!get_Default (void)
<MSIL:002500a1         > ShittyProject!get_ResourceManager (void)
<MSIL:002500f8         > ShittyProject!.cctor (void)
<MSIL:0025002a         > ShittyProject!Foo (void)
<MSIL:0025006e         > ShittyProject!InitializeComponent (void)
<MSIL:00250000         > ShittyProject!InitializeComponent (void)
<MSIL:002500da         > ShittyProject!get_Culture (void)
<MSIL:002500e5         > ShittyProject!set_Culture (void)
</code>```

If I understand correct MSIL:* it is only adress of function in pdb file?
Is it possible somehow to get addresses of the function to place breakpoints on them?

答:
Managed code is different from native code. To set breakpoints the "native way" (bp), you would need to wait until the method is JIT-compiled and then use the native address of the method.

Normally, one would not do that, but use .NET specific equivalents instead. There is SOS (Microsoft docs) !bpmd or SOSEX (probably no longer maintained) !mbm.

Given the code

```<code>using System;

namespace JittyProject
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("You want to stop before this shows up.");
            Console.ReadLine();
        }
    }
}
</code>```

You want to stop at the initial breakpoint and tell it to wait until .NET is loaded, e.g.

```<code>0:000> sxe ld clr
0:000> g
</code>```

Once the .NET runtime is loaded, you can load the SOS extension for .NET specific debugging commands.

```<code>0:000> .loadby sos clr
</code>```

And the SOSEX extension:

```<code>0:000> .load c:\wherever\SOSEX.dll
</code>```

And then add a breakpoint:

```<code>0:000> !mbm JittyProject.Program.Main
</code>```

Using the regular g, you'll eventually hit the breakpoint:

```<code>0:000> g
ModLoad: 76650000 766e2000   C:\Windows\SysWOW64\OLEAUT32.dll
Breakpoint: JIT notification received for method JittyProject.Program.Main() in AppDomain 00960db0.
Breakpoint set at JittyProject.Program.Main() in AppDomain 00960db0.
Breakpoint 2 hit

0:000> !clrstack
OS Thread Id: 0x3ff8 (0)
Child SP       IP Call Site
003eeda0 77601ffc [PrestubMethodFrame: 003eeda0] JittyProject.Program.Main() [C:\...\JittyProject\Program.cs @ 8]
003eef74 77601ffc [GCFrame: 003eef74]
</code>```

Body:
Executing command x ShittyProject!* I am getting such output

<MSIL:00250014         > ShittyProject!Main (void)
<MSIL:00250098         > ShittyProject!.ctor (void)
<MSIL:00250037         > ShittyProject!.ctor (void)
<MSIL:002500ed         > ShittyProject!get_Default (void)
<MSIL:002500a1         > ShittyProject!get_ResourceManager (void)
<MSIL:002500f8         > ShittyProject!.cctor (void)
<MSIL:0025002a         > ShittyProject!Foo (void)
<MSIL:0025006e         > ShittyProject!InitializeComponent (void)
<MSIL:00250000         > ShittyProject!InitializeComponent (void)
<MSIL:002500da         > ShittyProject!get_Culture (void)
<MSIL:002500e5         > ShittyProject!set_Culture (void)

If I understand correct MSIL:* it is only adress of function in pdb file?
Is it possible somehow to get addresses of the function to place breakpoints on them?

Body:
Managed code is different from native code. To set breakpoints the "native way" (bp), you would need to wait until the method is JIT-compiled and then use the native address of the method.

Normally, one would not do that, but use .NET specific equivalents instead. There is SOS (Microsoft docs) !bpmd or SOSEX (probably no longer maintained) !mbm.

Given the code

using System;

namespace JittyProject
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("You want to stop before this shows up.");
            Console.ReadLine();
        }
    }
}

You want to stop at the initial breakpoint and tell it to wait until .NET is loaded, e.g.

0:000> sxe ld clr
0:000> g

Once the .NET runtime is loaded, you can load the SOS extension for .NET specific debugging commands.

0:000> .loadby sos clr

And the SOSEX extension:

0:000> .load c:\wherever\SOSEX.dll

And then add a breakpoint:

0:000> !mbm JittyProject.Program.Main

Using the regular g, you'll eventually hit the breakpoint:

0:000> g
ModLoad: 76650000 766e2000   C:\Windows\SysWOW64\OLEAUT32.dll
Breakpoint: JIT notification received for method JittyProject.Program.Main() in AppDomain 00960db0.
Breakpoint set at JittyProject.Program.Main() in AppDomain 00960db0.
Breakpoint 2 hit

0:000> !clrstack
OS Thread Id: 0x3ff8 (0)
Child SP       IP Call Site
003eeda0 77601ffc [PrestubMethodFrame: 003eeda0] JittyProject.Program.Main() [C:\...\JittyProject\Program.cs @ 8]
003eef74 77601ffc [GCFrame: 003eef74]