问:
i can't fix error in c using float type for car fee program example
I tried with this code but can't find way to resolve this problem.
I tried to change float type to int, or chaing indent doesn't fix either. If anyone can provide solution, that would be help me out.
my expectation is trying to get the right result for this code.

#include <stdio.h>

main()
{
  float hour, fee;
  hour = 5;
  fee = 20;

  if (hour > 4)
    fee = 20 + hour*30;

  printf ("Hour = %.2f\n",hour);
  printf ("Car Park Fee = %.2f",fee);
}
```

答:
If you are getting an error like this

```<code>    3 | main()
      | ^~~~
</code>```

then you have to specify a data type before main().
Your code will look like this

```<code>#include <stdio.h>

int main()
{
    float hour, fee;
    hour = 5;
    fee = 20;

    if (hour > 4)
        fee = 20 + hour*30;

    printf ("Hour = %.2f\n",hour);
    printf ("Car Park Fee = %.2f",fee);
}
</code>```

Body:
If you are getting an error like this

    3 | main()
      | ^~~~

then you have to specify a data type before main().
Your code will look like this

#include <stdio.h>

int main()
{
    float hour, fee;
    hour = 5;
    fee = 20;

    if (hour > 4)
        fee = 20 + hour*30;

    printf ("Hour = %.2f\n",hour);
    printf ("Car Park Fee = %.2f",fee);
}


来源: stackexchange

问:
Angualar - change object into array with specific structure
Good morning,
could someone help me with changing Object like this

```<code>    {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
    }
</code>```

And i need to get this format of array

```<code>[
 {
  id: item1, value: "this is string field value"
 },
 {
  id: item2, value: "FF FF A2 C4"
 }
]
</code>```

I know how I could solve this, for example, using it
Object.keys() or Object.values().

But I always get only one parameter out of two. And then the combination of these two results I am not able to put together. Therefore, I want to ask if anyone knows about a better / simpler solution. Or if someone could show me what I'm doing wrong and what is solution for this.

Thanks in advance

答:
With Object.keys(), you can work as below:

let input = {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
};

let result: {id: string, value: string}[] = [];

Object.keys(input).forEach(function(k) {
    let key = k as keyof typeof input;
    result.push({
        id: k,
        value: input[key]
    });
});
```

Sample Typescript Playground

ContentLicense: CC BY-SA 4.0

Body:
Good morning,
could someone help me with changing Object like this

    {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
    }

And i need to get this format of array

[
 {
  id: item1, value: "this is string field value"
 },
 {
  id: item2, value: "FF FF A2 C4"
 }
]

I know how I could solve this, for example, using it
Object.keys() or Object.values().

But I always get only one parameter out of two. And then the combination of these two results I am not able to put together. Therefore, I want to ask if anyone knows about a better / simpler solution. Or if someone could show me what I'm doing wrong and what is solution for this.

Thanks in advance

Body:
With Object.keys(), you can work as below:

let input = {
    item1: "this is string field value",
    item2: "FF FF A2 C4h"
};

let result: {id: string, value: string}[] = [];

Object.keys(input).forEach(function(k) {
    let key = k as keyof typeof input;
    result.push({
        id: k,
        value: input[key]
    });
});

Sample Typescript Playground


问:
Connecting Spring Boot REST API Backend to Angular Front End
I am trying to connect a Spring Boot Backend to an Angular front end. The application is supposed to ask the user for two numbers via two forms, and then adds them when they click the 'submit' button.

I have done both the front end and back end, but am having trouble integrating them both together. I have tried to make a UserService on the angular end to account for user interaction, but have been stuck on that. I have no idea what to put on the Spring Boot back end for the Controller, either. I've searched up several YouTube tutorials, but most of them are catered to the specific application the Youtuber is creating, and doesn't explain what each line of code does, so I can't take the code and edit it accordingly to my own project.

答:
Are you exposing any REST apis on your Spring back end project?
Your Angular front end project should use the Angular HTTPClient to make a call to any RESTful endpoint your Spring back end is exposing

https://angular.io/guide/http


问:
Calculate the 15 min time bin the current time falls into using go
So I am unaware on how to calculate the 15 min time bin for the current time.
A day has 1440 minutes. So 96 - 15 min bins. So how can i calculate the time bin in golang?

```<code>func getCurrentMinutes(current time.Time) (int, error) {
   min, err := strconv.Atoi(current.Format("04"))
   if err != nil {
      return 0, err
   }
   return min, nil
}
func GetTimeBin(current time.Time, binDuration float64) float64 {
     min, _ := getCurrentMinutes(current)
     bin := float64(min) / binDuration
     return math.Ceil(bin)
}
</code>```

The above implementation I have done is wrong as I am considering 15 min bins for an hour. I need to find the 15 min bin for the current time in the context of the day.

Thanks in advance!

答:
This is the working example I came up with.</p>
```<code>func GetTimeBin(current time.Time, binDuration float64) float64 {
  hours := current.Hour()
  min := current.Minute() + hours*60
  bin := float64(min) / binDuration
  return math.Ceil(bin)
}
</code>```

Body:
So I am unaware on how to calculate the 15 min time bin for the current time.
A day has 1440 minutes. So 96 - 15 min bins. So how can i calculate the time bin in golang?

func getCurrentMinutes(current time.Time) (int, error) {
   min, err := strconv.Atoi(current.Format("04"))
   if err != nil {
      return 0, err
   }
   return min, nil
}
func GetTimeBin(current time.Time, binDuration float64) float64 {
     min, _ := getCurrentMinutes(current)
     bin := float64(min) / binDuration
     return math.Ceil(bin)
}

The above implementation I have done is wrong as I am considering 15 min bins for an hour. I need to find the 15 min bin for the current time in the context of the day.

Thanks in advance!

Body:
This is the working example I came up with.

func GetTimeBin(current time.Time, binDuration float64) float64 {
  hours := current.Hour()
  min := current.Minute() + hours*60
  bin := float64(min) / binDuration
  return math.Ceil(bin)
}


问:
Why map or reduce keeps running without any condition given?
```<code>const array = [7, 2, 4, 1, 10, 6, 5, 11]

const max = array.reduce((acc, val) => {
    console.log(val, acc)

    return val > acc ? val : acc
}, 0)

console.log(max)
</code>```

I was looking at this code of reduce array method, one thing I couldn't understand at all is, How the reducer function is going to the next iteration? There is no condition that forces the reducer function to go to the next element in the array. In the first iteration, the val is 7, the first element of the array, and acc is 0, the reducer function returns 7 as per the condition written.
My question is how the number 7 as being the new accumulator is going to be called on the reducer function. I thought the normal procedure is you have to meet some kind of condition to iterate over again and again. Is there something written in the reduce method itself? Can you explain me please?

答:
The reduce method's implementation resembles something like this:

```<code>Array.prototype.reduce = function(callback, initialValue) {
    var acc = initialValue;
    for(var i = 0; i < this.length; i++) {
        acc = callback(acc, this[i], i);
    }
    return acc;
}
</code>```

The reduce methods iteration condition is the array length.
The same goes for map.

Body:
const array = [7, 2, 4, 1, 10, 6, 5, 11]

const max = array.reduce((acc, val) => {
    console.log(val, acc)

    return val > acc ? val : acc
}, 0)

console.log(max)

I was looking at this code of reduce array method, one thing I couldn't understand at all is, How the reducer function is going to the next iteration? There is no condition that forces the reducer function to go to the next element in the array. In the first iteration, the val is 7, the first element of the array, and acc is 0, the reducer function returns 7 as per the condition written.
My question is how the number 7 as being the new accumulator is going to be called on the reducer function. I thought the normal procedure is you have to meet some kind of condition to iterate over again and again. Is there something written in the reduce method itself? Can you explain me please?

Body:
The reduce method's implementation resembles something like this:

Array.prototype.reduce = function(callback, initialValue) {
    var acc = initialValue;
    for(var i = 0; i < this.length; i++) {
        acc = callback(acc, this[i], i);
    }
    return acc;
}

The reduce methods iteration condition is the array length.
The same goes for map.


问:
Azure Synapse - How to catch SparkException
I tried below things:

```<code>import org.apache.spark.SparkException
from org.apache.spark.SparkException import SparkException
from org.apache.spark import SparkException
</code>```

These all give ModuleNotFoundError: No module named 'org.apache.spark.SparkException'.

I need to handle PySpark exceptions in Azure Synapse like below:

```<code>except (Py4JJavaError, SparkException, TypeError) as e:
   print(e)
</code>```

答: org.apache.spark.SparkException is the scala exception thrown in JVM process, you can't and don't need to handle this in pyspark

Body:
I tried below things:

import org.apache.spark.SparkException
from org.apache.spark.SparkException import SparkException
from org.apache.spark import SparkException

These all give ModuleNotFoundError: No module named 'org.apache.spark.SparkException'.

I need to handle PySpark exceptions in Azure Synapse like below:

except (Py4JJavaError, SparkException, TypeError) as e:
   print(e)


问:
Stripe Checkout: moving from Node to Firebase Functions
My Angular 11 app uses Stripe Checkout with an Express server to handle the payment.  Everything works fine with Angular & Node. I'd like to use Firebase Functions instead of Node, but when I call my Firebase Function, I get the error:

IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.

Angular code:

```<code>checkout(): void {
    var stripe = Stripe(environment.stripe.key);

    var productName = 'T-shirt!!';
    var price = '2000';

    const options = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8'
        },
        body: JSON.stringify({
            productName: productName,
            price: price
        })
    };
    var url = 'http://localhost:4242/create-checkout-session';                      // Node server
    //var url = 'http://localhost:5000/MY_FIREBASE_PROJECT/us-central1/stripeTest'; // Firebase emulation
    fetch(url, options)
        .then(function (response) {
            return response.json();
        })
        .then(function (session) {
            return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
            if (result.error) {                                                    // redirect fails due to browser or network error
                alert(result.error.message);
            }
        })
        .catch(function (error) {
            console.error('Error:', error);
        });
}
</code>```

Node server:

```<code>const express = require('express');
const app = express();
const stripe = require('stripe')('MY_SECRET_KEY')
const port = 4242;

app.use(express.json())                                                          // parse request body as JSON

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');       // website you wish to allow to connect
    // res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');                                                                            // request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();                                                                      // pass to next layer of middleware
});

app.post('/create-checkout-session', async (req, res) => {
    var productName = req.body.productName;
    var price = req.body.price;

    console.log('body = ', req.body);
    console.log('price = ', req.body.price);

    const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [
            {
                price_data: {
                    currency: 'usd',
                    product_data: {
                        name: productName,
                    },
                    unit_amount: price,
                },
                quantity: 1,
            },
        ],
        mode: 'payment',
        success_url: 'http://localhost:4200/home?action=success',
        cancel_url: 'http://localhost:4200/home?action=cancel',
    });

    res.json({ id: session.id });
});
app.listen(port, () => console.log('Listening on port ' + port + '!'));
</code>```

Firebase Function:

```<code>const stripe = require('stripe')('MY_SECRET_KEY')
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.stripeTest = functions.https.onCall((data, context) => {
    var productName = data['productName'];
    var price = data['price'];
    console.log('data: ', data);
    console.log('product name = ', productName);
    console.log('price = ', price);

    const session = stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [
            {
                price_data: {
                    currency: 'usd',
                    product_data: {
                        name: productName,
                    },
                    unit_amount: price,
                },
                quantity: 1,
            },
        ],
        mode: 'payment',
        success_url: 'http://localhost:4200/home?action=success',
        cancel_url: 'http://localhost:4200/home?action=cancel',
    }, async (err, data) => {});

    return { id: session.id };
})
</code>```

I don't understand the issue because I pass in line_items. Thanks!

答:
Rebounding Ryan Loggerythm's updated answer.

After about half an hour or so of fiddling with Stripe's docs solutions (which seem more geared towards getting devs to try out the demo instead of actually implementing the technology) and other guides on Medium, I loaded up your updated answer and lo and behold it worked absolutely flawlessly and all that within 2 paragraphs, 1 for Angular, 1 for Firebase functions, hence the whole point of using Stripe's Checkout product instead of making our own checkout (or turning towards Shopify's): turnkey simplicity.

Meanwhile Stripe's API docs felt like a maze for this simple solution. Maybe Ryan should be the one making Stripe's documentation

Body:
My Angular 11 app uses Stripe Checkout with an Express server to handle the payment.  Everything works fine with Angular & Node. I'd like to use Firebase Functions instead of Node, but when I call my Firebase Function, I get the error:

IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.

Angular code:

checkout(): void {
    var stripe = Stripe(environment.stripe.key);

    var productName = 'T-shirt!!';
    var price = '2000';

    const options = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8'
        },
        body: JSON.stringify({
            productName: productName,
            price: price
        })
    };
    var url = 'http://localhost:4242/create-checkout-session';                      // Node server
    //var url = 'http://localhost:5000/MY_FIREBASE_PROJECT/us-central1/stripeTest'; // Firebase emulation
    fetch(url, options)
        .then(function (response) {
            return response.json();
        })
        .then(function (session) {
            return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
            if (result.error) {                                                    // redirect fails due to browser or network error
                alert(result.error.message);
            }
        })
        .catch(function (error) {
            console.error('Error:', error);
        });
}

Node server:

const express = require('express');
const app = express();
const stripe = require('stripe')('MY_SECRET_KEY')
const port = 4242;

app.use(express.json())                                                          // parse request body as JSON

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');       // website you wish to allow to connect
    // res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');                                                                            // request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();                                                                      // pass to next layer of middleware
});

app.post('/create-checkout-session', async (req, res) => {
    var productName = req.body.productName;
    var price = req.body.price;

    console.log('body = ', req.body);
    console.log('price = ', req.body.price);

    const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [
            {
                price_data: {
                    currency: 'usd',
                    product_data: {
                        name: productName,
                    },
                    unit_amount: price,
                },
                quantity: 1,
            },
        ],
        mode: 'payment',
        success_url: 'http://localhost:4200/home?action=success',
        cancel_url: 'http://localhost:4200/home?action=cancel',
    });

    res.json({ id: session.id });
});
app.listen(port, () => console.log('Listening on port ' + port + '!'));

Firebase Function:

const stripe = require('stripe')('MY_SECRET_KEY')
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.stripeTest = functions.https.onCall((data, context) => {
    var productName = data['productName'];
    var price = data['price'];
    console.log('data: ', data);
    console.log('product name = ', productName);
    console.log('price = ', price);

    const session = stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [
            {
                price_data: {
                    currency: 'usd',
                    product_data: {
                        name: productName,
                    },
                    unit_amount: price,
                },
                quantity: 1,
            },
        ],
        mode: 'payment',
        success_url: 'http://localhost:4200/home?action=success',
        cancel_url: 'http://localhost:4200/home?action=cancel',
    }, async (err, data) => {});

    return { id: session.id };
})

I don't understand the issue because I pass in line_items. Thanks!


问:
How to remove everything excluding what's between given characters?
I am automating a task, where I need it to open a .csv or .txt file, that will have a bunch of information I don't need. I want to remove everything excluding what's in a specific range.

For example: adhjnwadk'symbol:xxx'abcahjda.

So I would want to keep everything in 'symbol:xxx' and remove everything outside of it. Please note that xxx is a variable and is different in every line.

Is this possible?

答: Is this a dataset? If yes, then you can use pandas module in python to get the data in tabular format and segregate accordingly.</p>


问:
Entity Framework OrderBy multiple properties generic
I have this project in .NET Core, and we use Entity Framework. I'm trying to create a method for orderby, I know you can do it by with multiple properties like this:

```<code>context.MyObject.OrderBy(x => new
        {
            x.Property1,
            x.Property2,
            x.Property3
        });
</code>```

Without installing Linq.Dynamic, I would like to achieve something like that by passing strings, I don't know if with reflection maybe I could do something similar.

```<code>public IQueryable<T> OrderByMultiple(string[] myProperties) where T : class
{
    ///some code here
    context.Set<T>.OrderBy(x => new
    {
        ///Get the properties by the strings
        ///"Property1",
        ///"Propety2",
        ///"Property3"
    });
}
</code>```

答:
Try to use

context.MyObject.OrderBy(x => x.propertyA).ThenBy(x=> x.propertyB)

Body:
I have this project in .NET Core, and we use Entity Framework. I'm trying to create a method for orderby, I know you can do it by with multiple properties like this:

context.MyObject.OrderBy(x => new
        {
            x.Property1,
            x.Property2,
            x.Property3
        });

Without installing Linq.Dynamic, I would like to achieve something like that by passing strings, I don't know if with reflection maybe I could do something similar.

public IQueryable<T> OrderByMultiple(string[] myProperties) where T : class
{
    ///some code here
    context.Set<T>.OrderBy(x => new
    {
        ///Get the properties by the strings
        ///"Property1",
        ///"Propety2",
        ///"Property3"
    });
}


问:
Print() for breaking line in python
I had to write a program to print the below pattern.

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Now , the code which is given is as :

num = int(input())

for i in range (1,num+1):
     for j in range (1 , i +1):
          print(j, end = " ")
     print()
```

But I don't understand that how a new line will be started after each loop without using \n  . My teacher told that the print() in the last is used to break line . But I don't understand that what is going on .

答:
print() is a function in python 3.x. It works kinda like System.out.println(); in Java, in that it prints to a new line by default:

```<code>>>> print('line 1')
>>> print()
>>> print('line2')
line 1

line 2
</code>```

You can control this via the end keyword ('\n' by default). Example:

```<code>>>> print('something', end = ' ')
>>> print('some other thing')
something some other thing
</code>```

So when someone says print() is used to break line, it's the same as adding a newline char.

Title: Print() for breaking line in python

Body:
I had to write a program to print the below pattern.

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Now , the code which is given is as :

num = int(input())

for i in range (1,num+1):
     for j in range (1 , i +1):
          print(j, end = " ")
     print()

But I don't understand that how a new line will be started after each loop without using \n  . My teacher told that the print() in the last is used to break line . But I don't understand that what is going on .

Body:
print() is a function in python 3.x. It works kinda like System.out.println(); in Java, in that it prints to a new line by default:

>>> print('line 1')
>>> print()
>>> print('line2')
line 1

line 2

You can control this via the end keyword ('\n' by default). Example:

>>> print('something', end = ' ')
>>> print('some other thing')
something some other thing

So when someone says print() is used to break line, it's the same as adding a newline char.


问:
Angular *ngFor Howto stack element tag with left and right on respective sides?
Expected left to be stacked top left and right top right

[Need to stack elements with name left in left side and right in right side
Using single *ngFor div/ ul /table any means .....
Sample play around provided below]
https://stackblitz.com/edit/ngfor-index-example-wntaie?file=app%2Fapp.component.html

答:
You could add class based on condition.

So with your stackblitz example I would write it like this.

```<code><div class="container" *ngFor="let course of courses; index as i">
  <div [ngClass]="{'leftsec': courses[i].name == 'left',
  'rightsec': courses[i].name == 'right'}">
    {{course.name}}
  </div>
</div>
</code>```

Body:
You could add class based on condition.

So with your stackblitz example I would write it like this.

<div class="container" *ngFor="let course of courses; index as i">
  <div [ngClass]="{'leftsec': courses[i].name == 'left',
  'rightsec': courses[i].name == 'right'}">
    {{course.name}}
  </div>
</div>


问:
Flutter Plugin 'permission_handler' causing errors during build
I'm trying to build my Flutter app and I keep running into an issue where the build fails and throws the following errors:

```<code>Task :permission_handler:compileDebugJavaWithJavac FAILED
/Users/ralph/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-6.1.3/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java:152: warning: [deprecation] getDefaultAdapter() in BluetoothAdapter has been deprecated
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                                                                  ^
error: warnings found and -Werror specified
1 error
1 warning

warnings found and -Werror specified
</code>```

Below is my output from flutter doctor -v:

```<code>[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-arm, locale en-US)
    • Flutter version 2.10.0 at /Users/ralph/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (11 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/ralph/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.64.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (1 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
</code>```

The thing is I am not even using permission_handler in my project dependencies.
Below are my project dependencies:

```<code>cupertino_icons: ^1.0.2
  get: 4.1.4
  image_picker: any
  image_cropper: any
  flutter_image_compress: any
  universal_html: any
  intl_phone_number_input: 0.7.0+2
  step_progress_indicator: 1.0.1
  intl: 0.17.0
  shared_preferences: any
  otp_text_field: 1.1.1
  connectivity: 3.0.6
  readmore: 2.1.0
  google_fonts: 2.1.0
  otp_count_down: 1.0.6
  firebase_messaging: any
  flutter_local_notifications: any
  firebase_core: any
  flutter_svg: 0.22.0
  table_calendar: 3.0.1
  flutter_time_picker_spinner: 2.0.0
  google_maps_flutter: any
  custom_info_window: any
  bubble: 1.2.1
  double_back_to_close_app: 2.0.1
  group_radio_button: 1.1.0
  graphql_flutter: 5.0.0
  hive: any
  hive_flutter: any
  path_provider: any
  google_maps_place_picker: any
  flutter_speed_dial: 4.2.0
  emoji_picker: any
  emoji_picker_flutter: 1.0.6
  flutter_slidable: 0.6.0
  firebase_auth: any
  amplify_auth_cognito: any
  amplify_flutter: any
  amplify_datastore: any
  amplify_api: any
  amplify_storage_s3: 0.2.2
  crypto: 3.0.1
  latlong: 0.6.1
  geolocator: 7.7.1
  flutter_native_splash: 1.2.2
  skeleton_loader: 2.0.0+4
  cached_network_image: 3.1.0
  emojis: 0.9.3
  autocomplete_textfield: 1.7.3
  mqtt_client: 9.6.0
  pull_to_refresh: 2.0.0
  flutter_cache_manager: 3.1.2
  wc_flutter_share: 0.4.0
  custom_refresh_indicator: 1.0.0
  flutter_contacts: 1.1.1+2
  grouped_list: 4.1.0
  full_screen_image: 1.0.2
  loadmore: 2.0.1
  flutter_dotenv: 5.0.2
  stamp_image: 0.0.2
  proste_bezier_curve: 2.0.2
  screenshot: 1.2.3
  flutter_autolink_text: 1.0.0+1
  url_launcher: any
  flutter_offline: 2.0.0
  internet_connection_checker: 0.0.1+3
  flutter_rating_bar: 4.0.0
  get_storage: 2.0.3
  twilio_flutter: 0.0.9
  upgrader: any
  google_ml_vision: 0.0.7
</code>```

How do I resolve this issue ??

答:
Actually google_maps_place_picker uses permission_handler see attached image

try override package to lates version
user

```<code>dependency_overrides:
 permission_handler: latest version
</code>```

current latest version for permission_handler ^ 8.3.0

then do flutter clean && flutter pub get

Solution 2 : use other updated package as google_maps_place_picker last update 14 month ago

Body:
I'm trying to build my Flutter app and I keep running into an issue where the build fails and throws the following errors:

Task :permission_handler:compileDebugJavaWithJavac FAILED
/Users/ralph/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-6.1.3/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java:152: warning: [deprecation] getDefaultAdapter() in BluetoothAdapter has been deprecated
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                                                                  ^
error: warnings found and -Werror specified
1 error
1 warning

warnings found and -Werror specified

Below is my output from flutter doctor -v:

[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-arm, locale en-US)
    • Flutter version 2.10.0 at /Users/ralph/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (11 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/ralph/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.64.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (1 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

The thing is I am not even using permission_handler in my project dependencies.
Below are my project dependencies:

cupertino_icons: ^1.0.2
  get: 4.1.4
  image_picker: any
  image_cropper: any
  flutter_image_compress: any
  universal_html: any
  intl_phone_number_input: 0.7.0+2
  step_progress_indicator: 1.0.1
  intl: 0.17.0
  shared_preferences: any
  otp_text_field: 1.1.1
  connectivity: 3.0.6
  readmore: 2.1.0
  google_fonts: 2.1.0
  otp_count_down: 1.0.6
  firebase_messaging: any
  flutter_local_notifications: any
  firebase_core: any
  flutter_svg: 0.22.0
  table_calendar: 3.0.1
  flutter_time_picker_spinner: 2.0.0
  google_maps_flutter: any
  custom_info_window: any
  bubble: 1.2.1
  double_back_to_close_app: 2.0.1
  group_radio_button: 1.1.0
  graphql_flutter: 5.0.0
  hive: any
  hive_flutter: any
  path_provider: any
  google_maps_place_picker: any
  flutter_speed_dial: 4.2.0
  emoji_picker: any
  emoji_picker_flutter: 1.0.6
  flutter_slidable: 0.6.0
  firebase_auth: any
  amplify_auth_cognito: any
  amplify_flutter: any
  amplify_datastore: any
  amplify_api: any
  amplify_storage_s3: 0.2.2
  crypto: 3.0.1
  latlong: 0.6.1
  geolocator: 7.7.1
  flutter_native_splash: 1.2.2
  skeleton_loader: 2.0.0+4
  cached_network_image: 3.1.0
  emojis: 0.9.3
  autocomplete_textfield: 1.7.3
  mqtt_client: 9.6.0
  pull_to_refresh: 2.0.0
  flutter_cache_manager: 3.1.2
  wc_flutter_share: 0.4.0
  custom_refresh_indicator: 1.0.0
  flutter_contacts: 1.1.1+2
  grouped_list: 4.1.0
  full_screen_image: 1.0.2
  loadmore: 2.0.1
  flutter_dotenv: 5.0.2
  stamp_image: 0.0.2
  proste_bezier_curve: 2.0.2
  screenshot: 1.2.3
  flutter_autolink_text: 1.0.0+1
  url_launcher: any
  flutter_offline: 2.0.0
  internet_connection_checker: 0.0.1+3
  flutter_rating_bar: 4.0.0
  get_storage: 2.0.3
  twilio_flutter: 0.0.9
  upgrader: any
  google_ml_vision: 0.0.7

How do I resolve this issue ??

Body:
Actually google_maps_place_picker uses permission_handler see attached image

try override package to lates version
user

dependency_overrides:
 permission_handler: latest version

current latest version for permission_handler ^ 8.3.0

then do flutter clean && flutter pub get

Solution 2 : use other updated package as google_maps_place_picker last update 14 month ago


问:
Twitter callback not working with Cloud Run
I'm trying to create a website to make F1 predictions with flask
We started developing in Heroku, and the twitter API is already configured, you can check
https://demoflaskdance.herokuapp.com/
But now we are moving to Cloud Run as Heroku does not support pyodbc. We deployed our project, with the same code, and added to apps.twitter.com the urls, but when trying to log in with the link that google provided https://demo-flask-dance-kjomqyaifq-ew.a.run.app
we get an error and says that the URL is not authorized

Any help? Thanks

答:
If your Cloud Run application does not require authenticated access, enable public access.

Go to the Google Cloud Console.

Select the service you want to make public.

Click Show Info Panel in the top right corner to show the Permissions tab.

In the Add members field, allUsers

Select the Cloud Run Invoker role from the Select a role drop-down menu.

Click Add.

Allowing public (unauthenticated) access

If you require authenticated access see this document:

Authentication overview


问:
how to count the records in a query
i want to include the rows also in the query instead of doing a different query to count its record, how can i do in mysql

my query looks like this

```<code>SELECT
  tblItems.ItemsID,
  tblItems.ItemsTitle,
  tblItems.ItemsManager_ContactID,
  tblItems.EndDate_Scheduled,
  tblItems.ItemsViews_Target,
  tblviews.viewsName,
  tblcontact.FirstName,
  tblcontact.LastName
FROM
  tblItems
  LEFT OUTER JOIN tblviews ON (tblItems.Items_viewsID = tblviews.viewsID)
  LEFT OUTER JOIN tblcontact ON (tblItems.ItemsManager_ContactID = tblcontact.ContactID)
WHERE (tblItems.ItemsStatusID = 7)
ORDER BY tblItems.EndDate_Scheduled ASC, Items_viewsID ASC
</code>```

i am not sure where i can add count, in SQL we can do but in mYsql i have no idea

答:
If you want to determine the count of the returned rows, you will have to execute the same query again, but instead of selecting the rows, select the count:</p>
```<code>SELECT count(*)
FROM
  tblItems
  LEFT OUTER JOIN tblviews ON (tblItems.Items_viewsID = tblviews.viewsID)
  LEFT OUTER JOIN tblcontact ON (tblItems.ItemsManager_ContactID = tblcontact.ContactID)
WHERE (tblItems.ItemsStatusID = 7)
ORDER BY tblItems.EndDate_Scheduled ASC, Items_viewsID ASC
</code>```

Title: how to count the records in a query

Body:
i want to include the rows also in the query instead of doing a different query to count its record, how can i do in mysql

my query looks like this

SELECT
  tblItems.ItemsID,
  tblItems.ItemsTitle,
  tblItems.ItemsManager_ContactID,
  tblItems.EndDate_Scheduled,
  tblItems.ItemsViews_Target,
  tblviews.viewsName,
  tblcontact.FirstName,
  tblcontact.LastName
FROM
  tblItems
  LEFT OUTER JOIN tblviews ON (tblItems.Items_viewsID = tblviews.viewsID)
  LEFT OUTER JOIN tblcontact ON (tblItems.ItemsManager_ContactID = tblcontact.ContactID)
WHERE (tblItems.ItemsStatusID = 7)
ORDER BY tblItems.EndDate_Scheduled ASC, Items_viewsID ASC

i am not sure where i can add count, in SQL we can do but in mYsql i have no idea

Body:
If you want to determine the count of the returned rows, you will have to execute the same query again, but instead of selecting the rows, select the count:

SELECT count(*)
FROM
  tblItems
  LEFT OUTER JOIN tblviews ON (tblItems.Items_viewsID = tblviews.viewsID)
  LEFT OUTER JOIN tblcontact ON (tblItems.ItemsManager_ContactID = tblcontact.ContactID)
WHERE (tblItems.ItemsStatusID = 7)
ORDER BY tblItems.EndDate_Scheduled ASC, Items_viewsID ASC


问:
AJAX-generated
 becomes just the text content in firefox/chrome
First, I request some HTML via AJAX.

Example response:

```<code><tr class="recordRow">
  <td class="first recordType" id="recordType">holder</td>
  <td class="recordAmount" id="recordAmount">holder</td>
  <td class="recordDescription" id="recordDescription">holder</td>
  <td class="last recordDate" id="recordDate">holder</td>
</tr>
</code>```

And I'm trying to make a DOM Object.

```<code>var d = document.createElement("div");
d.innerHTML = templateListItem;
alert(d.innerHTML);
alert(d.firstChild);
</code>```

I thought this should add the row to the
, but I only get the text. When I append the response to an element, I only get the text content, e.g holder holder holder holder.

Why does the HTML seem to get squashed in firefox and chrome?

Added:
If example response are like:

```<code><tr><td><span>something here..</span></td></tr>
</code>```

It will alert "HTMLSpanElement"  in firefox. All tags like tr/td/ are removed.

答:
If you are trying to insert a
 into a
, it is possible that the browser will not render this properly as it is illegal HTML.
Try placing your
 into a
 element or a
 element nested inside of a
 element.

ContentLicense: CC BY-SA 3.0

Title: AJAX-generated <tr> becomes just the text content in firefox/chrome

Body:
First, I request some HTML via AJAX.

Example response:

  holder
  holder
  holder
  holder

And I'm trying to make a DOM Object.

var d = document.createElement("div");
d.innerHTML = templateListItem;
alert(d.innerHTML);
alert(d.firstChild);

I thought this should add the row to the
, but I only get the text. When I append the response to an element, I only get the text content, e.g holder holder holder holder.

Why does the HTML seem to get squashed in firefox and chrome?

Added:
If example response are like:

something here..

It will alert "HTMLSpanElement"  in firefox. All tags like tr/td/ are removed.

Body:
If you are trying to insert a <tr> into a <div>, it is possible that the browser will not render this properly as it is illegal HTML.
Try placing your <tr> into a <table> element or a <tbody> element nested inside of a <table> element.


问:
ClickListener added to view of MotionLayout prevents layout from responding to events
I have ImageViews in a MotionLayout to animate moving the ImageView across the screen. I want to also add a ClickListener to the ImageView so that there can be functionality when the ImageView is simply clicked/tapped instead of moved.

I followed the advice here to write a custom MotionLayout which only handles ACTION_MOVE but after adding the ClickListener to the ImageView in onCreate() only the ClickListener code would run and the MotionLayout would not respond. I've also tried overriding onTouchEvent() in a custom ImageView but that hasn't worked.

Inside Custom MotionLayout

```<code>       <FrameLayout
            android:id="@+id/bottomCard"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TapImageView
                android:id="@+id/bottom"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </FrameLayout>

        <FrameLayout
            android:id="@+id/topCard"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TapImageView
                android:id="@+id/top"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </FrameLayout>
</code>```

Inside Custom ImageView

```<code>override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_UP -> {
                super.onTouchEvent(event)
                Toast.makeText(context, "Works", Toast.LENGTH_LONG)
                    .show()
                return false
            }

        }
        return super.onTouchEvent(event)
    }
</code>```

I've also tried in activity onCreate()

```<code>  binding.topCard.setOnClickListener {
            Toast.makeText(applicationContext, "Works", Toast.LENGTH_LONG)
                .show()
        }
</code>```

Thanks for your attention!

答:
obviously, when MotionEvent is draging, it shouldn't allow children view to consume the event, so. i intercept the motionevent as underlying code . it works.</p>
```<code> private var touchDownX = 0f
private var touchDownY = 0f
private var mScrolling = false
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            touchDownX = event.x
            touchDownY = event.y
            mScrolling = false
        }
        MotionEvent.ACTION_MOVE -> mScrolling = abs(touchDownY - event.y) >= touchSlop
        MotionEvent.ACTION_UP -> mScrolling = false
    }
    return if (mScrolling) true else super.onInterceptTouchEvent(event)
}
</code>```

Body:
I have ImageViews in a MotionLayout to animate moving the ImageView across the screen. I want to also add a ClickListener to the ImageView so that there can be functionality when the ImageView is simply clicked/tapped instead of moved.

I followed the advice here to write a custom MotionLayout which only handles ACTION_MOVE but after adding the ClickListener to the ImageView in onCreate() only the ClickListener code would run and the MotionLayout would not respond. I've also tried overriding onTouchEvent() in a custom ImageView but that hasn't worked.

Inside Custom MotionLayout

       <FrameLayout
            android:id="@+id/bottomCard"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TapImageView
                android:id="@+id/bottom"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </FrameLayout>

        <FrameLayout
            android:id="@+id/topCard"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TapImageView
                android:id="@+id/top"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </FrameLayout>

Inside Custom ImageView

override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_UP -> {
                super.onTouchEvent(event)
                Toast.makeText(context, "Works", Toast.LENGTH_LONG)
                    .show()
                return false
            }

        }
        return super.onTouchEvent(event)
    }

I've also tried in activity onCreate()

  binding.topCard.setOnClickListener {
            Toast.makeText(applicationContext, "Works", Toast.LENGTH_LONG)
                .show()
        }

Thanks for your attention!

Body:
obviously, when MotionEvent is draging, it shouldn't allow children view to consume the event, so. i intercept the motionevent as underlying code . it works.

 private var touchDownX = 0f
private var touchDownY = 0f
private var mScrolling = false
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            touchDownX = event.x
            touchDownY = event.y
            mScrolling = false
        }
        MotionEvent.ACTION_MOVE -> mScrolling = abs(touchDownY - event.y) >= touchSlop
        MotionEvent.ACTION_UP -> mScrolling = false
    }
    return if (mScrolling) true else super.onInterceptTouchEvent(event)
}


问:
RA translation to natural language
so im stuck in this exercise where I need to translate relational algebra (unary relational operations) expressions based on the Mondial III database to natural language and I need help for the last two and if I have any errors in the ones I answered. BTW i used 6 for sigma (SELECT operation) and |><| for the THETA JOIN operation (couldn't find the sigma or the real theta join operator on my keyboard sorry about that) Any help is much appreciated!Thanks in advance.
Here's the meaning for symbols :
SELECT :
Selects all tuples that satisfy the selection condition from a relation R :

6selection condition(R)

PROJECT : Produces a new relation with only some of the attributes of R, and removes duplicates tuples :

πattribute list(R)

THETHA JOIN : Produces all combinations of tuples from R1 and R2 that satisfy the join condition :

R1< |><|join condition >(R2)

πname(6elevation>1000(MOUNTAIN)) -> Find the name of all mountains whose elevation is higher than 1000.

6elevation>1000(6population>100000(CITY)) -> Select the city's tuples whose elevation is higher than 1000 with a population greater than 100000

6population>100000(6elevation>1000(CITY)) -> Select the city's tuples whose population is greater than 100000 with an elevation higher than 1000

COUNTRY|><|code=country(LANGUAGE) -> ?

πCountry.name(COUNTRY|><|code=country(6Language.name='English' AND percentage>50(LANGUAGE)) -> ?

答:
The fourth expression returns all the informations about the countries together with all the languages spoken (the information about the country is repeated for each different language spoken).

The fifth expression return the name of all the countries where the prevalent language is English.

Title: RA translation to natural language


问:
Mongoose/NodeJS shuffle and limit collection in Controller
I have the below code in my Mongoose/NodeJS controller, which is used to shuffle the records in a collection. The shuffle is working as expected.

In the 'Sliders' collection, I only want to display 4 shuffled records in the front end; however, I want to limit the number of records in the controller rather than slice them in the front end, because there are a lot of records in the collection.

At the moment, my code limits them before it shuffles them, hence it always displays the same 4 records. How can I shuffle the collection in the controller, then subsequently limit to 4 records in the controller, so I can then display them in the front end?

```<code>function shuffleArray(array) {
   for (let i = array.length - 1; i > 0; i--) {
       const j = Math.floor(Math.random() * (i + 1));
       [array[i], array[j]] = [array[j], array[i]];
   }
}

const sliders = await Slider.find({ "category": "Slider" }).limit(4);
    shuffleArray(sliders);
</code>```

答:
Try aggregation with $match and $sample https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

const agg = Slider.aggregate([
      {$match: {"category": "Slider"}},
      {$sample: { size : 4 }}
]);

const sliders = await agg.exec();
```

Body:
I have the below code in my Mongoose/NodeJS controller, which is used to shuffle the records in a collection. The shuffle is working as expected.

In the 'Sliders' collection, I only want to display 4 shuffled records in the front end; however, I want to limit the number of records in the controller rather than slice them in the front end, because there are a lot of records in the collection.

At the moment, my code limits them before it shuffles them, hence it always displays the same 4 records. How can I shuffle the collection in the controller, then subsequently limit to 4 records in the controller, so I can then display them in the front end?

function shuffleArray(array) {
   for (let i = array.length - 1; i > 0; i--) {
       const j = Math.floor(Math.random() * (i + 1));
       [array[i], array[j]] = [array[j], array[i]];
   }
}

const sliders = await Slider.find({ "category": "Slider" }).limit(4);
    shuffleArray(sliders);


问:
Automatically play sound in IPython notebook
I often run long-running cells in my IPython notebook. I'd like the notebook to automatically beep or play a sound when the cell is finished executing. Is there some way to do this in iPython notebook, or maybe some command I can put at the end of a cell that will automatically play a sound?

I'm using Chrome if that makes any difference.

答:
If you don't want to rely on any external modules, you could just use this code snippet in the Python Notebook. You can run this cell subsequently after the first one, making a beep noise after your current running cell has finished execution.

```<code>from IPython.display import Audio
import numpy as np

beep = np.sin(2*np.pi*400*np.arange(30000*2)/10000)
Audio(beep, rate=10000, autoplay=True)
</code>```

Body:
If you don't want to rely on any external modules, you could just use this code snippet in the Python Notebook. You can run this cell subsequently after the first one, making a beep noise after your current running cell has finished execution.

from IPython.display import Audio
import numpy as np

beep = np.sin(2*np.pi*400*np.arange(30000*2)/10000)
Audio(beep, rate=10000, autoplay=True)


问:
The variable declared in for-loop of c++ is not initialised
```<code>#include <iostream>
#include <Windows.h>

void selection_sort(int*,int);
void output_array(int*, int);

int main() {
    using namespace std;
    int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
    int length = 10;

    selection_sort(numbers, length);
    output_array(numbers, length);

    Sleep(10000);
    return 0;
}

void output_array(int* start, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << *(start + i) << " ";
    }
    std::cout << std::endl;
}

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
            *(start + k) = *(start + k + 1);
        }
        *(start + length - i) = max;
    }
}
</code>```

Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn't make sense to me.

When it comes to the second largest number, k behaves as expected.

答:
It seems I have got it. length is 10, max_i is 9, i is 0 till 9. Your loop becomes

```<code>for (int k = 9; k < (10 - i -1); k++) {
    *(start + k) = *(start + k + 1);
}
</code>```

k < 9 - i never gets true and the loop never runs. You have an error in the program logic.

Body:
#include <iostream>
#include <Windows.h>

void selection_sort(int*,int);
void output_array(int*, int);

int main() {
    using namespace std;
    int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
    int length = 10;

    selection_sort(numbers, length);
    output_array(numbers, length);

    Sleep(10000);
    return 0;
}

void output_array(int* start, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << *(start + i) << " ";
    }
    std::cout << std::endl;
}

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
            *(start + k) = *(start + k + 1);
        }
        *(start + length - i) = max;
    }
}

Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn't make sense to me.

When it comes to the second largest number, k behaves as expected.

Body:
It seems I have got it. length is 10, max_i is 9, i is 0 till 9. Your loop becomes

for (int k = 9; k < (10 - i -1); k++) {
    *(start + k) = *(start + k + 1);
}

k < 9 - i never gets true and the loop never runs. You have an error in the program logic.


答:
Are you looking for:</p>
```<code>library(tidyverse)
hwk %>%
  rename_with(.cols = everything(),
              .fn   = ~str_c(., c(rep('_Anxiety', 3), rep('_Depression', 9)))) %>%
  pivot_longer(cols = everything(),
               names_to = c('Test', 'Test_Type'),
               names_pattern = '(.*)_(.*)',
               values_to = 'Score')

# A tibble: 1,116 x 3
   Test  Test_Type  Score
   <chr> <chr>      <dbl>
 1 V1    Anxiety        4
 2 V2    Anxiety        4
 3 V3    Anxiety        4
 4 V4    Depression     4
 5 V5    Depression     3
 6 V6    Depression     4
 7 V7    Depression     4
 8 V8    Depression     4
 9 V9    Depression     4
10 V10   Depression     4
# ... with 1,106 more rows
</code>```

Title: How to pivot_longer same columns multiple times?

Body:
Data

I tried Googling and searching SO for the answer for this, but the answers typically just state how you can separate columns into two, but not group the columns separate by specific criterion. First, here is the dput for my data called hwk:

structure(list(V1 = structure(c(4, 4, 2, 2, 2, 2, 2, 2, 4, 4,
2, 3, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 1, 3, 3, 3, 3, 4, 1, 2, 4,
1, 2, 3, 2, 3, 1, 1, 2, 2, 4, 3, 2, 1, 2, 3, 3, 4, 3, 3, 2, 3,
1, 4, 3, 2, 3, 4, 1, 3, 3, 3, 2, 2, 1, 2, 3, 4, 4, 2, 4, 3, 2,
3, 3, 3, 3, 2, 4, 3, 3, 3, 2, 2, 3, 4, 2, 4, 4, 2, 2, 3, 3), format.spss = "F8.0"),
    V2 = structure(c(4, 4, 3, 4, 3, 4, 3, 2, 4, 1, 3, 3, 3, 4,
    3, 3, 2, 3, 4, 3, 1, 4, 2, 3, 4, 2, 4, 3, 3, 2, 3, 2, 3,
    3, 4, 3, 3, 3, 3, 3, 3, 2, 4, 2, 2, 2, 4, 3, 4, 4, 2, 4,
    2, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 4, 4, 4,
    3, 4, 3, 3, 3, 4, 2, 4, 3, 4, 3, 3, 2, 3, 3, 4, 3, 4, 3,
    4, 4, 3), format.spss = "F8.0"), V3 = structure(c(4, 4, 4,
    4, 4, 4, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
    3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4), format.spss = "F8.0"),
    V4 = structure(c(4, 4, 3, 4, 3, 4, 2, 1, 3, 2, 3, 1, 4, 4,
    2, 3, 2, 2, 2, 4, 1, 2, 2, 2, 3, 2, 3, 2, 2, 1, 3, 1, 1,
    2, 4, 1, 1, 2, 3, 2, 2, 1, 1, 1, 3, 2, 4, 3, 3, 3, 3, 3,
    3, 4, 3, 1, 4, 3, 4, 3, 2, 3, 2, 1, 4, 1, 4, 1, 2, 4, 4,
    4, 3, 3, 3, 2, 2, 1, 4, 3, 2, 3, 2, 1, 3, 4, 1, 2, 4, 3,
    4, 2, 2), format.spss = "F8.0"), V5 = structure(c(3, 3, 3,
    4, 3, 4, 3, 1, 1, 1, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 2,
    2, 2, 2, 4, 2, 3, 2, 3, 4, 1, 4, 2, 3, 3, 2, 2, 3, 2, 2,
    3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 2, 3, 3, 2, 2, 3, 3, 2, 3,
    2, 2, 3, 3, 3, 2, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 3, 4,
    3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3), format.spss = "F8.0"),
    V6 = structure(c(4, 4, 3, 4, 3, 4, 4, 1, 3, 3, 3, 3, 2, 3,
    4, 2, 4, 3, 3, 3, 3, 4, 4, 3, 3, 3, 4, 4, 4, 3, 4, 4, 3,
    3, 3, 4, 2, 2, 3, 3, 3, 4, 2, 4, 3, 4, 4, 4, 3, 4, 2, 4,
    3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 1, 4, 4, 4, 4, 4, 4,
    4, 3, 4, 4, 4, 4, 2, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 3,
    4, 4, 4), format.spss = "F8.0"), V7 = structure(c(4, 4, 2,
    4, 2, 4, 4, 3, 3, 3, 2, 2, 4, 4, 3, 3, 1, 4, 3, 3, 1, 2,
    4, 3, 4, 2, 4, 4, 3, 3, 2, 2, 3, 2, 4, 3, 3, 3, 3, 3, 3,
    1, 4, 3, 2, 2, 4, 3, 4, 4, 2, 4, 2, 3, 4, 3, 3, 3, 4, 3,
    4, 4, 3, 4, 4, 3, 4, 4, 4, 4, 3, 4, 4, 4, 3, 3, 4, 3, 4,
    3, 3, 3, 3, 2, 2, 4, 4, 4, 4, 2, 4, 4, 3), format.spss = "F8.0"),
    V8 = structure(c(4, 4, 2, 1, 2, 1, 1, 1, 3, 3, 2, 3, 2, 3,
    4, 2, 2, 2, 3, 3, 2, 3, 1, 3, 3, 3, 3, 4, 1, 2, 4, 1, 2,
    3, 2, 3, 1, 1, 2, 2, 3, 1, 1, 1, 2, 3, 3, 4, 3, 3, 2, 3,
    1, 3, 4, 2, 3, 4, 1, 3, 3, 3, 2, 2, 1, 2, 3, 4, 4, 2, 4,
    3, 4, 4, 4, 4, 3, 2, 4, 3, 3, 3, 2, 2, 3, 4, 2, 4, 4, 2,
    1, 3, 4), format.spss = "F8.0"), V9 = structure(c(4, 4, 4,
    4, 4, 4, 4, 4, 3, 3, 2, 3, 3, 3, 3, 2, 3, 3, 2, 3, 4, 4,
    4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 4, 3, 2, 4, 3, 4,
    4, 4, 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 4, 3, 4, 3, 2, 4,
    3, 3, 4, 4, 4, 3, 4, 4, 4, 4, 4, 3, 4, 3, 4, 3, 4, 4, 4,
    4, 3, 4, 4, 4, 4, 4, 3, 2, 4, 4, 4, 4, 4), format.spss = "F8.0"),
    V10 = structure(c(4, 4, 2, 4, 2, 4, 3, 2, 3, 3, 3, 2, 4,
    4, 2, 2, 1, 3, 4, 4, 1, 4, 2, 3, 3, 2, 4, 3, 2, 3, 3, 1,
    3, 2, 4, 3, 2, 3, 3, 3, 3, 1, 2, 4, 2, 3, 4, 4, 3, 3, 2,
    4, 2, 4, 3, 3, 4, 3, 4, 3, 4, 4, 4, 1, 4, 3, 3, 4, 3, 4,
    4, 3, 3, 3, 3, 3, 4, 1, 4, 3, 3, 3, 3, 2, 3, 4, 4, 2, 4,
    2, 4, 4, 3), format.spss = "F8.0"), V11 = structure(c(3,
    3, 1, 4, 1, 4, 1, 1, 1, 1, 2, 1, 1, 1, 3, 2, 2, 2, 2, 1,
    2, 3, 1, 2, 3, 3, 2, 1, 2, 2, 2, 3, 2, 2, 3, 2, 1, 2, 2,
    1, 1, 4, 3, 1, 3, 2, 3, 1, 2, 1, 2, 1, 2, 2, 1, 2, 2, 3,
    2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 4, 2, 1, 2, 2, 3, 3, 3,
    3, 4, 3, 2, 3, 3, 2, 2, 2, 2, 1, 3, 1, 4, 1, 3), format.spss = "F8.0"),
    V12 = structure(c(4, 4, 3, 2, 3, 2, 3, 1, 3, 3, 3, 3, 2,
    3, 3, 2, 4, 3, 3, 4, 4, 3, 3, 4, 4, 3, 3, 3, 4, 3, 4, 4,
    3, 3, 3, 4, 2, 2, 3, 3, 3, 4, 2, 4, 3, 4, 4, 4, 3, 4, 2,
    4, 3, 3, 3, 3, 4, 3, 3, 2, 2, 1, 1, 3, 1, 4, 4, 4, 4, 4,
    4, 4, 3, 3, 2, 2, 2, 2, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
    3, 2, 3, 4), format.spss = "F8.0")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -93L))

Solution So Far

So I want the first variables to be questions for an anxiety scale with their scores for each:

hwk2 <- hwk %>%
  pivot_longer(cols = 1:3,
               names_to = "Anxiety Test",
               values_to = "Anxiety Score")
hwk2

Which gives me this:

# A tibble: 279 x 11
      V4    V5    V6    V7    V8    V9   V10   V11   V12 `Anxiety Test` `Anxiety Score`
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>                    <dbl>
 1     4     3     4     4     4     4     4     3     4 V1                           4
 2     4     3     4     4     4     4     4     3     4 V2                           4
 3     4     3     4     4     4     4     4     3     4 V3                           4
 4     4     3     4     4     4     4     4     3     4 V1                           4
 5     4     3     4     4     4     4     4     3     4 V2                           4
 6     4     3     4     4     4     4     4     3     4 V3                           4
 7     3     3     3     2     2     4     2     1     3 V1                           2
 8     3     3     3     2     2     4     2     1     3 V2                           3
 9     3     3     3     2     2     4     2     1     3 V3                           4
10     4     4     4     4     1     4     4     4     2 V1                           2
# ... with 269 more rows

But I want the rest to be depression, so I pivot again:

hwk3 <- hwk2 %>%
  pivot_longer(cols = 1:9,
               names_to = "Depression Test",
               values_to = "Depression Score")
hwk3

Which now gives me this:

  `Anxiety Test` `Anxiety Score` `Depression Test` `Depression Score`
   <chr>                    <dbl> <chr>                          <dbl>
 1 V1                           4 V4                                 4
 2 V1                           4 V5                                 3
 3 V1                           4 V6                                 4
 4 V1                           4 V7                                 4
 5 V1                           4 V8                                 4
 6 V1                           4 V9                                 4
 7 V1                           4 V10                                4
 8 V1                           4 V11                                3
 9 V1                           4 V12                                4
10 V2                           4 V4                                 4
# ... with 2,501 more rows

What I Want

Well now I want to group a single column that designates the test as either an anxiety test or a depression test, and a single column for the score. So basically it would look something like this:

 Test                          Test_Type                        Score
 V1                            Anxiety                          4
 V4                            Depression                       3

If there is a less roundabout way to do this, that would be great. Equally important is a solution that doesn't change the actual values of the scores but simply groups them into the categories I mentioned above.

Body:
Are you looking for:

library(tidyverse)
hwk %>%
  rename_with(.cols = everything(),
              .fn   = ~str_c(., c(rep('_Anxiety', 3), rep('_Depression', 9)))) %>%
  pivot_longer(cols = everything(),
               names_to = c('Test', 'Test_Type'),
               names_pattern = '(.*)_(.*)',
               values_to = 'Score')

# A tibble: 1,116 x 3
   Test  Test_Type  Score
   <chr> <chr>      <dbl>
 1 V1    Anxiety        4
 2 V2    Anxiety        4
 3 V3    Anxiety        4
 4 V4    Depression     4
 5 V5    Depression     3
 6 V6    Depression     4
 7 V7    Depression     4
 8 V8    Depression     4
 9 V9    Depression     4
10 V10   Depression     4
# ... with 1,106 more rows


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

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

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

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

答:
Since I don't feel like writing code to increment letters, I'd create a table of all valid IDs (AAAAAA through ZZZZZZ) with an integer from 1 to X for those IDs. Then you can use the following:

```<code>SELECT @max_id = MAX(id) FROM Possible_Silly_IDs

SELECT
    COALESCE(MAX(PSI2.silly_id), 'AAAAAA')
FROM
    My_Table T1
INNER JOIN Possible_Silly_IDs PSI1 ON
    PSI1.silly_id = T1.silly_id
INNER JOIN Possible_Silly_IDs PSI2 ON
    PSI2.id = CASE WHEN PSI1.id = @max_id THEN 1 ELSE PSI1.id + 1 END
LEFT OUTER JOIN My_Table T2 ON
    T2.silly_id = PSI2.silly_id
WHERE
    T2.silly_id IS NULL
</code>```

The COALESCE is there in case the table is empty. To be truly robust you should calculate the 'AAAAAA' (SELECT @min_silly_id = silly_id WHERE id = 1) in case your "numbering" algorithm changes.

If you really wanted to do things right, you'd redo the database design as has been suggested.

OwnerDisplayName: Coderer

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Coderer

Body:
Since I don't feel like writing code to increment letters, I'd create a table of all valid IDs (AAAAAA through ZZZZZZ) with an integer from 1 to X for those IDs. Then you can use the following:

SELECT @max_id = MAX(id) FROM Possible_Silly_IDs

SELECT
    COALESCE(MAX(PSI2.silly_id), 'AAAAAA')
FROM
    My_Table T1
INNER JOIN Possible_Silly_IDs PSI1 ON
    PSI1.silly_id = T1.silly_id
INNER JOIN Possible_Silly_IDs PSI2 ON
    PSI2.id = CASE WHEN PSI1.id = @max_id THEN 1 ELSE PSI1.id + 1 END
LEFT OUTER JOIN My_Table T2 ON
    T2.silly_id = PSI2.silly_id
WHERE
    T2.silly_id IS NULL

The COALESCE is there in case the table is empty. To be truly robust you should calculate the 'AAAAAA' (SELECT @min_silly_id = silly_id WHERE id = 1) in case your "numbering" algorithm changes.

If you really wanted to do things right, you'd redo the database design as has been suggested.

OwnerDisplayName: Tom H.


问:
distance between two longitude and latitude
How should I write query for this?
Consider P1(a, b)  and P2(c, d) to be two points on a 2D plane.

a happens to equal the minimum value in Northern Latitude (LAT_N in
STATION).

b happens to equal the maximum value in Northern Latitude
(LAT_N in STATION)

c happens to equal the minimum value in Western
Longitude (LONG_W in STATION)

d happens to equal the maximum value
in Western Longitude (LONG_W in STATION)

Query the Manhattan Distance between points P1 and P2 and round it to a scale of 4 decimal places.

Table STATION(ID number, CITY varchar2(21), STATE varchar2(2), LAT_N number, LONG_W number)

this is my try but returns NULL

```<code>select
    2 * 3961 * asin(power(sqrt((sin(radians(MAX(LAT_N) - MIN(LAT_N)) / 2) )) , 2 ) + cos(radians(MAX(LAT_N))) * cos(radians(MIN(LAT_N))) * power(sqrt((sin(radians(MAX(LONG_W) - MIN(LONG_W)) / 2) )) , 2 )) as distance from station where city like 'manhattan';
</code>```

any idea will be appreciated

答:
Euclidean distance between two points. Both of them are different.

Manhattan Distance:

```<code>|X1 - X2| + |Y1 - Y2|

select round((max(lat_n)-min(lat_n))+(max(long_w)-min(long_w)),4)
from station
</code>```

Body:
How should I write query for this?
Consider P1(a, b)  and P2(c, d) to be two points on a 2D plane.

a happens to equal the minimum value in Northern Latitude (LAT_N in
STATION).

b happens to equal the maximum value in Northern Latitude
(LAT_N in STATION)

c happens to equal the minimum value in Western
Longitude (LONG_W in STATION)

d happens to equal the maximum value
in Western Longitude (LONG_W in STATION)

Query the Manhattan Distance between points P1 and P2 and round it to a scale of 4 decimal places.

Table STATION(ID number, CITY varchar2(21), STATE varchar2(2), LAT_N number, LONG_W number)

this is my try but returns NULL

select
    2 * 3961 * asin(power(sqrt((sin(radians(MAX(LAT_N) - MIN(LAT_N)) / 2) )) , 2 ) + cos(radians(MAX(LAT_N))) * cos(radians(MIN(LAT_N))) * power(sqrt((sin(radians(MAX(LONG_W) - MIN(LONG_W)) / 2) )) , 2 )) as distance from station where city like 'manhattan';

any idea will be appreciated

Body:
Euclidean distance between two points. Both of them are different.

Manhattan Distance:

|X1 - X2| + |Y1 - Y2|

select round((max(lat_n)-min(lat_n))+(max(long_w)-min(long_w)),4)
from station


问:
How to return multiple views without being page reloaded?

Blockquote

I have "Login" view and controller with multiple condition that any condition returns a view. but my "Login" controller is in just one view. so, I want to return conditions without being page refresh or reload. can someone help and provide on my code?
what should I change in the view? or what should i add?
COntroller code:

```<code>[HttpPost]
        [AllowAnonymous]
        public virtual async Task<ActionResult> Login(LoginViewModel model, string ReturnUrl = "")
        {
            if (!ModelState.IsValid)
            {
                ViewBag.ErrorMessage = "لطفا فلید های * دار را کامل کنید.";
                return View("Login");
            }
            //اگرعدد ها را فارسی وارد کند آن ها رو به انگلیسی تبدیل می کنیم
            var UserName = Helper.Helper.NumberFN_To_EN(model.UserName);
            var Password = Helper.Helper.NumberFN_To_EN(model.Password);

            // به دنبال کاربری با نام کاربر وارد شده میگردیم
            var user = await _userManager.FindByNameAsync(UserName).ConfigureAwait(false);
            var isUserPasswordCorrect = false;
            // اگر کاربر وجود داشت
            if (user != null)
            {
                isUserPasswordCorrect = await _userManager.CheckPasswordAsync(user, Password).ConfigureAwait(false);
                // اگر کاربر رمزش  را درست وارد کرده بود
                if (isUserPasswordCorrect)
                {
                    // اگر کاربر غیر فعال کامل یا غیر فعال
                    if (user.IsDisabled)
                    {
                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "حساب کاربری شما غیرفعال می‌باشد لطفا با پشتیبان سایت در تماس باشید";
                        return View();
                    }
                    // اگر هیچ نقشی نداشت
                    // جلوی ورود او را میگیریم
                    if (!user.Roles.Any())
                    {
                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "کاربر گرامی! شما در سیستم هیچ پستی ندارید";
                        return View();
                    }
                }
            }
            var result = SignInStatus.Failure;
            if (user != null)
            {
                // آیا کاربر رمز عبورش را درست وارد کرده است ؟
                if (isUserPasswordCorrect)
                {
                    // عملیات لاگین را انجام میدهیم
                    result = await _signInManager
                                   .PasswordSignInAsync(UserName, Password, true, true)
                                   .ConfigureAwait(false);
                }
            }
            // نتیجه عملیات لاگین
            switch (result)
            {
                // اگر ورود موفقیت آمیز بود
                case SignInStatus.Success:
                    //اطلاعات لازم رو میگیریم و یه لاگ برای کاربر ثبت میشود
                    _logService.Add(new Log { UserId = user.Id, IP = Request.UserHostAddress, LogType = LogType.Login, CreatedDate = DateTime.Now });
                    _uow.SaveAllChanges();
                    var roleuser = await _applicationRoleManager.FindByIdAsync(user.Roles.SingleOrDefault().RoleId).ConfigureAwait(false);

                    if (string.IsNullOrWhiteSpace(ReturnUrl))
                    {
                        ReturnUrl = AuthenticationHelper.GetDashboardForRole(roleuser.Name);
                    }
                    else
                    {
                        if (!Url.IsLocalUrl(ReturnUrl))
                        {
                            ReturnUrl = AuthenticationHelper.GetDashboardForRole(roleuser.Name);
                        }
                    }

                    return Redirect(ReturnUrl);
                // اگر اکانت قفل شده است
                case SignInStatus.LockedOut:
                    // زمان رفع محدودیت کاربر برای ورود
                    // زمان خروجی
                    // UTC
                    // است پس آن را به تاریخ عادی تبدیل می کینم
                    var theTimeOfUnBanUser = user.LockoutEndDateUtc.Value.UtcToLocalTime().ToString("HH:mm:ss");
                    ViewBag.ShowSupport = true;
                    ViewBag.ErrorMessage = $"حساب کاربری شما قفل شده است، لطفا بعد از ساعت {theTimeOfUnBanUser} دوباره تلاش نمایید";
                    return View();
                // اگر نام کاربری یا رمز عبور اشتباه است
                case SignInStatus.Failure:
                default:
                    // اگر نام کاربری وارد شده صحیح بود
                    if (user != null)
                    {
                        // تعداد حداکثر تلاش برای ورود ناموفق
                        var maxFailedAccessAttemptsBeforeLockout = _userManager.MaxFailedAccessAttemptsBeforeLockout;
                        // تعداد ورود های ناموفق کاربر جاری
                        var accessFailedCount = await _userManager.GetAccessFailedCountAsync(user.Id).ConfigureAwait(false);
                        // تعداد تلاش مانده برای ورود
                        var numberOfAttemptsLeft = maxFailedAccessAttemptsBeforeLockout - accessFailedCount;

                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "رمز عبور اشتباه است" + System.Environment.NewLine + $"تعداد دفعات تلاش مجدد برای ورود {numberOfAttemptsLeft} بار";
                        return View();
                    }
                    else
                    {
                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "نام کاربری یا رمز عبور صحیح نمی باشد";
                        return View();
                    }

            }
        }
</code>```

答:
you have to use ajax call and send some json to client from server and then make decision base on json props like IsSuccess, Message, DefaultPageUrl and ....
this can help you : https://www.infinetsoft.com/Post/How-to-implement-Login-using-Ajax-in-asp-net-mvc/2469</p>

Body:
Blockquote

I have "Login" view and controller with multiple condition that any condition returns a view. but my "Login" controller is in just one view. so, I want to return conditions without being page refresh or reload. can someone help and provide on my code?
what should I change in the view? or what should i add?
COntroller code:

[HttpPost]
        [AllowAnonymous]
        public virtual async Task<ActionResult> Login(LoginViewModel model, string ReturnUrl = "")
        {
            if (!ModelState.IsValid)
            {
                ViewBag.ErrorMessage = "لطفا فلید های * دار را کامل کنید.";
                return View("Login");
            }
            //اگرعدد ها را فارسی وارد کند آن ها رو به انگلیسی تبدیل می کنیم
            var UserName = Helper.Helper.NumberFN_To_EN(model.UserName);
            var Password = Helper.Helper.NumberFN_To_EN(model.Password);

            // به دنبال کاربری با نام کاربر وارد شده میگردیم
            var user = await _userManager.FindByNameAsync(UserName).ConfigureAwait(false);
            var isUserPasswordCorrect = false;
            // اگر کاربر وجود داشت
            if (user != null)
            {
                isUserPasswordCorrect = await _userManager.CheckPasswordAsync(user, Password).ConfigureAwait(false);
                // اگر کاربر رمزش  را درست وارد کرده بود
                if (isUserPasswordCorrect)
                {
                    // اگر کاربر غیر فعال کامل یا غیر فعال
                    if (user.IsDisabled)
                    {
                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "حساب کاربری شما غیرفعال می‌باشد لطفا با پشتیبان سایت در تماس باشید";
                        return View();
                    }
                    // اگر هیچ نقشی نداشت
                    // جلوی ورود او را میگیریم
                    if (!user.Roles.Any())
                    {
                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "کاربر گرامی! شما در سیستم هیچ پستی ندارید";
                        return View();
                    }
                }
            }
            var result = SignInStatus.Failure;
            if (user != null)
            {
                // آیا کاربر رمز عبورش را درست وارد کرده است ؟
                if (isUserPasswordCorrect)
                {
                    // عملیات لاگین را انجام میدهیم
                    result = await _signInManager
                                   .PasswordSignInAsync(UserName, Password, true, true)
                                   .ConfigureAwait(false);
                }
            }
            // نتیجه عملیات لاگین
            switch (result)
            {
                // اگر ورود موفقیت آمیز بود
                case SignInStatus.Success:
                    //اطلاعات لازم رو میگیریم و یه لاگ برای کاربر ثبت میشود
                    _logService.Add(new Log { UserId = user.Id, IP = Request.UserHostAddress, LogType = LogType.Login, CreatedDate = DateTime.Now });
                    _uow.SaveAllChanges();
                    var roleuser = await _applicationRoleManager.FindByIdAsync(user.Roles.SingleOrDefault().RoleId).ConfigureAwait(false);

                    if (string.IsNullOrWhiteSpace(ReturnUrl))
                    {
                        ReturnUrl = AuthenticationHelper.GetDashboardForRole(roleuser.Name);
                    }
                    else
                    {
                        if (!Url.IsLocalUrl(ReturnUrl))
                        {
                            ReturnUrl = AuthenticationHelper.GetDashboardForRole(roleuser.Name);
                        }
                    }

                    return Redirect(ReturnUrl);
                // اگر اکانت قفل شده است
                case SignInStatus.LockedOut:
                    // زمان رفع محدودیت کاربر برای ورود
                    // زمان خروجی
                    // UTC
                    // است پس آن را به تاریخ عادی تبدیل می کینم
                    var theTimeOfUnBanUser = user.LockoutEndDateUtc.Value.UtcToLocalTime().ToString("HH:mm:ss");
                    ViewBag.ShowSupport = true;
                    ViewBag.ErrorMessage = $"حساب کاربری شما قفل شده است، لطفا بعد از ساعت {theTimeOfUnBanUser} دوباره تلاش نمایید";
                    return View();
                // اگر نام کاربری یا رمز عبور اشتباه است
                case SignInStatus.Failure:
                default:
                    // اگر نام کاربری وارد شده صحیح بود
                    if (user != null)
                    {
                        // تعداد حداکثر تلاش برای ورود ناموفق
                        var maxFailedAccessAttemptsBeforeLockout = _userManager.MaxFailedAccessAttemptsBeforeLockout;
                        // تعداد ورود های ناموفق کاربر جاری
                        var accessFailedCount = await _userManager.GetAccessFailedCountAsync(user.Id).ConfigureAwait(false);
                        // تعداد تلاش مانده برای ورود
                        var numberOfAttemptsLeft = maxFailedAccessAttemptsBeforeLockout - accessFailedCount;

                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "رمز عبور اشتباه است" + System.Environment.NewLine + $"تعداد دفعات تلاش مجدد برای ورود {numberOfAttemptsLeft} بار";
                        return View();
                    }
                    else
                    {
                        ViewBag.ShowSupport = true;
                        ViewBag.ErrorMessage = "نام کاربری یا رمز عبور صحیح نمی باشد";
                        return View();
                    }

            }
        }


问:
Laravel 403 THIS ACTION IS UNAUTHORIZED. when email verifying
I looked up in Laravel/8.x docs and setup routes for email verification. Here are the routes:

```<code>Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');
Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');
Route::post('/email/verification-notification', function (Request $request) {
    $request->user()->sendEmailVerificationNotification();

    return back()->with('message', 'Verification link sent!');
})->middleware(['auth', 'throttle:6,1'])->name('verification.send');
</code>```

When i click on this  \Illuminate\Support\Facades\Auth::id(), 'hash' => \Illuminate\Support\Facades\Auth::user()->password]) }}" class="text-sm text-gray-700 underline">Verify email It gives me this error: 403 INVALID SIGNATURE.

EDIT:

I switched to signedRoute in my a tag and now i get 403 THIS ACTION IS UNAUTHORIZED..

Here is mechanism that leads to verification.verify route:

```<code>@if (Route::has('login'))
        <div class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
            @auth
            <a href="{{ url('/') }}" class="text-sm text-gray-700 underline">Home</a>
            <a href="{{ URL::signedRoute('verification.verify', [
                            'id' =>Auth::id(),
                            'hash' => Auth::user()->password,
                        ])}}" class="text-sm text-gray-700 underline">Verify email</a>
            <a href="{{ route('logout') }}" class="text-sm text-gray-700 underline">Logout</a>
            @else
            <a href="{{ route('login') }}" class="text-sm text-gray-700 underline">Login</a>
            @if (Route::has('register'))
            <a href="{{ route('register') }}" class="ml-4 text-sm text-gray-700 underline">Register</a>
            @endif
            @endauth
        </div>
        @endif
</code>```

In EmailVerificationRequest i've changed nothing:

under vendor\Laravel\Framework\src\Illuminate\Founndation\Auth\EmailVerificationRequest

```<code><?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Http\FormRequest;

class EmailVerificationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (! hash_equals((string) $this->route('id'),
                          (string) $this->user()->getKey())) {
            return false;
        }

        if (! hash_equals((string) $this->route('hash'),
                          sha1($this->user()->getEmailForVerification()))) {
            return false;
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }

    /**
     * Fulfill the email verification request.
     *
     * @return void
     */
    public function fulfill()
    {
        if (! $this->user()->hasVerifiedEmail()) {
            $this->user()->markEmailAsVerified();

            event(new Verified($this->user()));
        }
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        return $validator;
    }
}
</code>```

答:
I know this topic is very old, but in case anyone is stuck here same me.
I'm using Laravel 8 too and using the laravel/ui as my web auth scaffold.
I searched the internet some says it about the Nginx's rewrite and some say it about the TrustProxies, but actually the issue for me is the verify link inside the email is:

```<code>https://test.com/email/verify/2?expires=1644740715&hash=b0f4f567f00280291e508b44f882f6efd494eb32&signature=2f998b6895ef7721b2905fbb432872b6181672de5aaf6e7f4be443d8184f6fc2
</code>```

but the VerifiesEmails trait's verify function is

```<code>        if (! hash_equals((string) $request->route('id'), (string) $request->user()->getKey())) {
            throw new AuthorizationException;
        }

        if (! hash_equals((string) $request->route('hash'), sha1($request->user()->getEmailForVerification()))) {
            throw new AuthorizationException;
        }
</code>```

Just change the $request->route('hash') to $request->get('hash') my problem solved.

Body:
I looked up in Laravel/8.x docs and setup routes for email verification. Here are the routes:

Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');
Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');
Route::post('/email/verification-notification', function (Request $request) {
    $request->user()->sendEmailVerificationNotification();

    return back()->with('message', 'Verification link sent!');
})->middleware(['auth', 'throttle:6,1'])->name('verification.send');

When i click on this  \Illuminate\Support\Facades\Auth::id(), 'hash' => \Illuminate\Support\Facades\Auth::user()->password]) }}" class="text-sm text-gray-700 underline">Verify email It gives me this error: 403 INVALID SIGNATURE.

EDIT:

I switched to signedRoute in my a tag and now i get 403 THIS ACTION IS UNAUTHORIZED..

Here is mechanism that leads to verification.verify route:

@if (Route::has('login'))

            @auth
            Home
            Auth::id(),
                            'hash' => Auth::user()->password,
                        ])}}" class="text-sm text-gray-700 underline">Verify email
            Logout
            @else
            Login
            @if (Route::has('register'))
            Register
            @endif
            @endauth

        @endif

In EmailVerificationRequest i've changed nothing:

under vendor\Laravel\Framework\src\Illuminate\Founndation\Auth\EmailVerificationRequest

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Http\FormRequest;

class EmailVerificationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (! hash_equals((string) $this->route('id'),
                          (string) $this->user()->getKey())) {
            return false;
        }

        if (! hash_equals((string) $this->route('hash'),
                          sha1($this->user()->getEmailForVerification()))) {
            return false;
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }

    /**
     * Fulfill the email verification request.
     *
     * @return void
     */
    public function fulfill()
    {
        if (! $this->user()->hasVerifiedEmail()) {
            $this->user()->markEmailAsVerified();

            event(new Verified($this->user()));
        }
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        return $validator;
    }
}

Body:
I know this topic is very old, but in case anyone is stuck here same me.
I'm using Laravel 8 too and using the laravel/ui as my web auth scaffold.
I searched the internet some says it about the Nginx's rewrite and some say it about the TrustProxies, but actually the issue for me is the verify link inside the email is:

https://test.com/email/verify/2?expires=1644740715&hash=b0f4f567f00280291e508b44f882f6efd494eb32&signature=2f998b6895ef7721b2905fbb432872b6181672de5aaf6e7f4be443d8184f6fc2

but the VerifiesEmails trait's verify function is

        if (! hash_equals((string) $request->route('id'), (string) $request->user()->getKey())) {
            throw new AuthorizationException;
        }

        if (! hash_equals((string) $request->route('hash'), sha1($request->user()->getEmailForVerification()))) {
            throw new AuthorizationException;
        }

Just change the $request->route('hash') to $request->get('hash') my problem solved.


问:
Macro definition conflict
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

```<code>test1.h
#define TEST 123
test2.h
#define TEST 456
</code>```

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

答:
Try this:

```<code>#include "test2.h"
#undef TEST
#include "test1.h"
</code>```

This first includes test2, discards its TEST and then includes test1.

Title: Macro definition conflict

Body:
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

test1.h
#define TEST 123
test2.h
#define TEST 456

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

Body:
Try this:

#include "test2.h"
#undef TEST
#include "test1.h"

This first includes test2, discards its TEST and then includes test1.


问:
Python Iterate through rows, run and save
I have a pandas dataframe where I want to loop over its rows, run and save output, if any error then ingore it and move to next row.

```<code>import pandas as pd
from nsepy import get_history #can be install by "pip install nsepy"
from datetime import date

data = {'script': ['SBIN = get_history(symbol="SBIN", start=date(1985,1,1), end=date(2022,1,31))',
'SAIL = get_history(symbol="SAIL", start=date(1985,1,1), end=date(2022,1,31))',
'20MICRONS = get_history(symbol="20MICRONS", start=date(1985,1,1), end=date(2022,1,31))',
'RELIANCE = get_history(symbol="RELIANCE", start=date(1985,1,1), end=date(2022,1,31))']}

df = pd.DataFrame(data)
</code>```

Now I want to run each line one by one
I can do it by

```<code>#run each row
#1
SBIN = get_history(symbol="SBIN", start=date(1985,1,1), end=date(2022,1,31))
df1.to_csv('SBIN', sep="\t")
#2
SAIL = get_history(symbol="SAIL", start=date(1985,1,1), end=date(2022,1,31))'
df1.to_csv('SAIL', sep="\t")
#3
20MICRONS = get_history(symbol="20MICRONS", start=date(1985,1,1), end=date(2022,1,31))
df1.to_csv('20MICRONS', sep="\t")
#4
RELIANCE = get_history(symbol="RELIANCE", start=date(1985,1,1), end=date(2022,1,31))
df1.to_csv('RELIANCE', sep="\t")
</code>```

But it is going to take huge time. so how can it be done by for loop or while loop

Please note I would like to run each row and save the output as a character extracted before = sign of same row for example "SBIN" for first row. In case if there is any error on any line then ignore the error and move to the next line (line 3 is going to return an error which is due to the unavailability of data)

答:
As your process is IO-Bounded, you can use Threading to increase the speed.
You can try this:

```<code>import pandas as pd
from nsepy import get_history
from datetime import date
import concurrent.futures

history = {
    "SBIN": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
    "SAIL": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
    "20MICRONS": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
    "RELIANCE": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
}

def get_historical_data(symbol, /, **kwds):
    print(symbol)
    df = get_history(symbol, **kwds)
    df.to_csv(f'{symbol}.csv', sep='\t')
    return df

data = []
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
    future_history = [
        executor.submit(get_historical_data, symbol, **data)
        for symbol, data in history.items()
    ]

    data = []
    for future in concurrent.futures.as_completed(future_history):
        data.append(future.result())
    df = pd.concat(data)
</code>```

Body:
I have a pandas dataframe where I want to loop over its rows, run and save output, if any error then ingore it and move to next row.

import pandas as pd
from nsepy import get_history #can be install by "pip install nsepy"
from datetime import date

data = {'script': ['SBIN = get_history(symbol="SBIN", start=date(1985,1,1), end=date(2022,1,31))',
'SAIL = get_history(symbol="SAIL", start=date(1985,1,1), end=date(2022,1,31))',
'20MICRONS = get_history(symbol="20MICRONS", start=date(1985,1,1), end=date(2022,1,31))',
'RELIANCE = get_history(symbol="RELIANCE", start=date(1985,1,1), end=date(2022,1,31))']}

df = pd.DataFrame(data)

Now I want to run each line one by one
I can do it by

#run each row
#1
SBIN = get_history(symbol="SBIN", start=date(1985,1,1), end=date(2022,1,31))
df1.to_csv('SBIN', sep="\t")
#2
SAIL = get_history(symbol="SAIL", start=date(1985,1,1), end=date(2022,1,31))'
df1.to_csv('SAIL', sep="\t")
#3
20MICRONS = get_history(symbol="20MICRONS", start=date(1985,1,1), end=date(2022,1,31))
df1.to_csv('20MICRONS', sep="\t")
#4
RELIANCE = get_history(symbol="RELIANCE", start=date(1985,1,1), end=date(2022,1,31))
df1.to_csv('RELIANCE', sep="\t")

But it is going to take huge time. so how can it be done by for loop or while loop

Please note I would like to run each row and save the output as a character extracted before = sign of same row for example "SBIN" for first row. In case if there is any error on any line then ignore the error and move to the next line (line 3 is going to return an error which is due to the unavailability of data)

Body:
As your process is IO-Bounded, you can use Threading to increase the speed.
You can try this:

import pandas as pd
from nsepy import get_history
from datetime import date
import concurrent.futures

history = {
    "SBIN": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
    "SAIL": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
    "20MICRONS": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
    "RELIANCE": {"start": date(2021, 1, 1), "end": date(2022, 1, 31)},
}

def get_historical_data(symbol, /, **kwds):
    print(symbol)
    df = get_history(symbol, **kwds)
    df.to_csv(f'{symbol}.csv', sep='\t')
    return df

data = []
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
    future_history = [
        executor.submit(get_historical_data, symbol, **data)
        for symbol, data in history.items()
    ]

    data = []
    for future in concurrent.futures.as_completed(future_history):
        data.append(future.result())
    df = pd.concat(data)