问:
my python code comes up with errors if I define the variable people and if i don't define the variable people
```<code>import random
people=0
def intake (testage):
    if testage <= 18:
        print("Person accepted!")
        people=people+1
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")
</code>```

on line 2 the variable people comes up with errors if I define it or if I don't define it

答:
```<code>import random;

people=0;

def intake (testage):
    global people
    if testage <= 18:
        print("Person accepted!");
        people += 1;
    else:
        print("Person Denied!");

while people <= 150:
    age=random.randint(0,81);
    intake(age);
print("At capacity!")
</code>```

Body:
import random
people=0
def intake (testage):
    if testage <= 18:
        print("Person accepted!")
        people=people+1
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")

on line 2 the variable people comes up with errors if I define it or if I don't define it


来源: stackexchange

问:
How to eliminate if-else with same condition but different actions inside another if-else?
Suppose I have the code like following:

```<code>int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}
</code>```

the problem is that the code pattern:

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

```<code>if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}
</code>```

and

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

would appear once only?

答:
Actually age and weight are 2 independent dimensions, all we need to do is to collect different combinations and then determine which function to call. So let's preset combinations in a map and just get the handler and call, not a single if/else is needed.

```<code>import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public enum Section {

    AGE(20, 60),
    WEIGHT(40, 100);

    private int[] points;

    Section(int... points) {
        this.points = points;
    }

    public int indexOf(int value) throws Exception {
        List<Integer> points = Arrays.stream(this.points).boxed().collect(Collectors.toList());
        points.add(value);
        Collections.sort(points);
        return IntStream.range(0, points.size())
                .filter(index -> Objects.equals(points.get(index), value))
                .findFirst()
                .orElseThrow(() -> new Exception("Value not found"));
    }
}

class MyTest {
    private static Map<String, Function<Object, Object>> sectionHandlerMapper = new HashMap<>();

    private static Object function1(Object obj) {
        return "function1";
    }
    private static Object function2(Object obj) {
        return "function2";
    }
    private static Object function3(Object obj) {
        return "function3";
    }
    private static Object function4(Object obj) {
        return "function4";
    }
    private static Object function5(Object obj) {
        return "function5";
    }
    private static Object function6(Object obj) {
        return "function6";
    }
    private static Object function7(Object obj) {
        return "function7";
    }
    private static Object function8(Object obj) {
        return "function8";
    }
    private static Object function9(Object obj) {
        return "function9";
    }

    static {
        sectionHandlerMapper.put("2-2", MyTest::function1);
        sectionHandlerMapper.put("2-0", MyTest::function2);
        sectionHandlerMapper.put("2-1", MyTest::function3);
        sectionHandlerMapper.put("0-2", MyTest::function4);
        sectionHandlerMapper.put("0-0", MyTest::function5);
        sectionHandlerMapper.put("0-1", MyTest::function6);
        sectionHandlerMapper.put("1-2", MyTest::function7);
        sectionHandlerMapper.put("1-0", MyTest::function8);
        sectionHandlerMapper.put("1-1", MyTest::function9);
    }

    public static Object call(Object obj, int... indices) {
        String key = Arrays.stream(indices).boxed().map(String::valueOf).collect(Collectors.joining("-"));
        return sectionHandlerMapper.get(key).apply(obj);
    }

    public static void main(String[] args) throws Exception {
        int age = 19;
        int weight = 39;
        int ageIndex = Section.AGE.indexOf(age);
        int weightIndex = Section.WEIGHT.indexOf(weight);
        System.out.println(call("obj", ageIndex, weightIndex));
    }
}
</code>```

As enum is used, it would be rather convenient to add more dimensions, just adding new enums, reconstructing 'sectionHandlerMapper' and modifying main() would work. It's easy to expand.

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have the code like following:

int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}

the problem is that the code pattern:

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}

and

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

would appear once only?

Body:
Actually age and weight are 2 independent dimensions, all we need to do is to collect different combinations and then determine which function to call. So let's preset combinations in a map and just get the handler and call, not a single if/else is needed.

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public enum Section {

    AGE(20, 60),
    WEIGHT(40, 100);

    private int[] points;

    Section(int... points) {
        this.points = points;
    }

    public int indexOf(int value) throws Exception {
        List<Integer> points = Arrays.stream(this.points).boxed().collect(Collectors.toList());
        points.add(value);
        Collections.sort(points);
        return IntStream.range(0, points.size())
                .filter(index -> Objects.equals(points.get(index), value))
                .findFirst()
                .orElseThrow(() -> new Exception("Value not found"));
    }
}

class MyTest {
    private static Map<String, Function<Object, Object>> sectionHandlerMapper = new HashMap<>();

    private static Object function1(Object obj) {
        return "function1";
    }
    private static Object function2(Object obj) {
        return "function2";
    }
    private static Object function3(Object obj) {
        return "function3";
    }
    private static Object function4(Object obj) {
        return "function4";
    }
    private static Object function5(Object obj) {
        return "function5";
    }
    private static Object function6(Object obj) {
        return "function6";
    }
    private static Object function7(Object obj) {
        return "function7";
    }
    private static Object function8(Object obj) {
        return "function8";
    }
    private static Object function9(Object obj) {
        return "function9";
    }

    static {
        sectionHandlerMapper.put("2-2", MyTest::function1);
        sectionHandlerMapper.put("2-0", MyTest::function2);
        sectionHandlerMapper.put("2-1", MyTest::function3);
        sectionHandlerMapper.put("0-2", MyTest::function4);
        sectionHandlerMapper.put("0-0", MyTest::function5);
        sectionHandlerMapper.put("0-1", MyTest::function6);
        sectionHandlerMapper.put("1-2", MyTest::function7);
        sectionHandlerMapper.put("1-0", MyTest::function8);
        sectionHandlerMapper.put("1-1", MyTest::function9);
    }

    public static Object call(Object obj, int... indices) {
        String key = Arrays.stream(indices).boxed().map(String::valueOf).collect(Collectors.joining("-"));
        return sectionHandlerMapper.get(key).apply(obj);
    }

    public static void main(String[] args) throws Exception {
        int age = 19;
        int weight = 39;
        int ageIndex = Section.AGE.indexOf(age);
        int weightIndex = Section.WEIGHT.indexOf(weight);
        System.out.println(call("obj", ageIndex, weightIndex));
    }
}

As enum is used, it would be rather convenient to add more dimensions, just adding new enums, reconstructing 'sectionHandlerMapper' and modifying main() would work. It's easy to expand.

ContentLicense: CC BY-SA 4.0


问:
How do I format two different forms in the same stylesheet?
Looks simple but I'm losing my head.

I want to format two different forms independently. Here is the example.

```<code><h1>FORM 1</h1>
<form>
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>
<br>
<h1>FORM 2</h1>
<form id="form2">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>
</code>```
```<code>/* Form 1 style */
input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}

/* Form 2 style? */

input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 50%;
    margin-top: 1px;
    margin-bottom: 1px;
}
</code>```

https://jsfiddle.net/dtpoze0c/

I really appreciate any help.

答:
You can simply use the class or id CSS selector, so add an id like you did on the second to the first one: <form id="form1">

And then use it to create your style:

```<code>/* This will only affect the form with the form1 id */
#form1 input[type="text"],
#form1 input[type="password"],
#form1 input[type="email"],
#form1 select {
    display: block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}
</code>```

You can see some doc about id here: https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors

Body:
Looks simple but I'm losing my head.

I want to format two different forms independently. Here is the example.

FORM 1

<form>
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>

FORM 2

<form id="form2">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>

/* Form 1 style */
input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}

/* Form 2 style? */

input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 50%;
    margin-top: 1px;
    margin-bottom: 1px;
}

https://jsfiddle.net/dtpoze0c/

I really appreciate any help.

Body:
You can simply use the class or id CSS selector, so add an id like you did on the second to the first one: <form id="form1">

And then use it to create your style:

/* This will only affect the form with the form1 id */
#form1 input[type="text"],
#form1 input[type="password"],
#form1 input[type="email"],
#form1 select {
    display: block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}

You can see some doc about id here: https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors


问:
PHP Re-create Wordpress the_loop
I'm currently working on a basic, but bespoke CMS that we will be using across several of our sites. Before anyone flames me, I am well aware of other alternatives, however nothing we have tried is really flexible enough for our data.

With that out of the way, I shall begin.

One of the features I do like from Wordpress is the known as The Loop.

```<code>while(have_posts()) : the_content();
    the_content();
endwhile;
</code>```

I've studied the code and come up with a similar class, which you can see here.

From looking at the code, I've figured out that, has_posts() seems to be returning a boolean if there are still posts in an array.

the_article is saying that we're still in the loop, so set a variable for the articles(posts) with the data we need.

I've kind of got this working, however I only seem to be able to get one piece of information from the array:

```<code>while (have_articles()): the_article();
    echo "<h1 class='title'>" . the_title() . "</h1>";
endwhile;
</code>```

Where the_title is:

```<code>function the_title() {
    global $AC;

    return $AC->p_title;
}
</code>```

Thanks for the help!

答:
There is probably nothing that is that much unqualified to borrow concepts and implementations than from wordpress.

The Loop is the worst thing you can have when trying to understand how the system parts work together. The Loop introduces a vast number of global variables who are valid only within the loop but are still accessible from outside the loop. No one knows if and where these variables are valid to be used or not.

Implement your own "loop" in an OOP manner. Do not ever try to understand and copy wordpress code. Its bad.

How I would expect an iteration over the post to look like:

```<code>$iterator = new PostIterator($category, $page);
while ($iterator->hasNext()) {
   $post = $iterator->next();
   echo $post->title . ' ' . $post->getFormattedDate() . '<br />';
}
</code>```

Title: PHP Re-create Wordpress the_loop

Body:
I'm currently working on a basic, but bespoke CMS that we will be using across several of our sites. Before anyone flames me, I am well aware of other alternatives, however nothing we have tried is really flexible enough for our data.

With that out of the way, I shall begin.

One of the features I do like from Wordpress is the known as The Loop.

while(have_posts()) : the_content();
    the_content();
endwhile;

I've studied the code and come up with a similar class, which you can see here.

From looking at the code, I've figured out that, has_posts() seems to be returning a boolean if there are still posts in an array.

the_article is saying that we're still in the loop, so set a variable for the articles(posts) with the data we need.

I've kind of got this working, however I only seem to be able to get one piece of information from the array:

while (have_articles()): the_article();
    echo "
" . the_title() . "
";
endwhile;

Where the_title is:

function the_title() {
    global $AC;

    return $AC->p_title;
}

Thanks for the help!

Body:
There is probably nothing that is that much unqualified to borrow concepts and implementations than from wordpress.

The Loop is the worst thing you can have when trying to understand how the system parts work together. The Loop introduces a vast number of global variables who are valid only within the loop but are still accessible from outside the loop. No one knows if and where these variables are valid to be used or not.

Implement your own "loop" in an OOP manner. Do not ever try to understand and copy wordpress code. Its bad.

How I would expect an iteration over the post to look like:

$iterator = new PostIterator($category, $page);
while ($iterator->hasNext()) {
   $post = $iterator->next();
   echo $post->title . ' ' . $post->getFormattedDate() . '<br />';
}


问:
Convert nested list to JSON using Python
I'm using the following SQL query to get data for every month in a given year:

```<code>SELECT DATE_FORMAT(tour_date , '%M'), COUNT(*)
FROM _673338137185
WHERE tour_date LIKE '{tour_year}%'
GROUP BY DATE_FORMAT(tour_date , '%M')
</code>```

When I'm returning this via Python, I'm getting the following result:

```<code>[
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]
</code>```

Also, there are \n everywhere in the result.
I need the result in JSON format, but I can't get it right. How can I do it?

答:
I have a similar problem. I solved it using jsonpickle.
I expect it to be as easy as the following line:</p>
```<code>jsonObject = jsonpickle.encode(obj)
</code>```

Body:
I'm using the following SQL query to get data for every month in a given year:

SELECT DATE_FORMAT(tour_date , '%M'), COUNT(*)
FROM _673338137185
WHERE tour_date LIKE '{tour_year}%'
GROUP BY DATE_FORMAT(tour_date , '%M')

When I'm returning this via Python, I'm getting the following result:

[
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]

Also, there are \n everywhere in the result.
I need the result in JSON format, but I can't get it right. How can I do it?

Body:
I have a similar problem. I solved it using jsonpickle.
I expect it to be as easy as the following line:

jsonObject = jsonpickle.encode(obj)


问:
How to use WC_Order_Query class with custom order status
There is a new order status I created: packed.

I want to get orders with order status "packed". This order status must have been created at least 2 days ago. However, I have a problem with time. date_modified is not working according to local time. Has anyone encountered this problem and has a solution?

$two_days_ago           = date(strtotime('-2 day'), current_time('timestamp'));
$current_time           = current_time('timestamp');
$args = array(
  'limit'           => -1,
  'return'          => 'ids',
  'date_modified '  => $two_days_ago_tomorrow.'...'.current_time('timestamp'),
  'status'          => 'a-packed'
);
$query = new WC_Order_Query( $args );
```

答:
wc_get_orders and WC_Order_Query provide a standard way of retrieving orders that is safe to use and will not break due to database changes in future WooCommerce versions. You pass in an array of arguments defining the criteria for the search.

More information: wc_get_orders and WC_Order_Query

Since you mention "This order status must have been created at least 2 days ago" in your question, it seems to me that the use of date_created is more suitable compared to date_modified

So you get:

$days_delay = 2; // 48 hours
$one_day    = 24 * 60 * 60;
$today      = strtotime( date('Y-m-d') );

$orders = wc_get_orders( array(
    'status'       => array( 'your-custom-status' ),
    'orderby'      => 'date',
    'order'        => 'ASC',
    'date_created' => '<' . ( $today - ( $days_delay * $one_day ) ),
));

foreach ( $orders as $order ) {
    $order_id = $order->get_id();
    echo '
' . $order_id . '
';
}
```

Body:
wc_get_orders and WC_Order_Query provide a standard way of retrieving orders that is safe to use and will not break due to database changes in future WooCommerce versions. You pass in an array of arguments defining the criteria for the search.

More information: wc_get_orders and WC_Order_Query

Since you mention "This order status must have been created at least 2 days ago" in your question, it seems to me that the use of date_created is more suitable compared to date_modified

So you get:

$days_delay = 2; // 48 hours
$one_day    = 24 * 60 * 60;
$today      = strtotime( date('Y-m-d') );

$orders = wc_get_orders( array(
    'status'       => array( 'your-custom-status' ),
    'orderby'      => 'date',
    'order'        => 'ASC',
    'date_created' => '<' . ( $today - ( $days_delay * $one_day ) ),
));

foreach ( $orders as $order ) {
    $order_id = $order->get_id();
    echo '<p>' . $order_id . '</p>';
}


问:
Skip completely blank cell rows while using sheet_to_json
I have the following configuration to parse excel to json,which works fine in general:

```<code>const reader = require('xlsx');
let Data = [];
   Data.push(reader.utils.sheet_to_json(
            file.Sheets[file.SheetNames[0]]))
</code>```

However, If have an excel with 7000 rows. I deleted the values in all but one row for test (there is styling in empty rows such as borders and colors but no values). When parsing, sheetjs still attempts to parse all of 7000 rows for some reason.

How to avoid this and parse only rows that have values in it or avoid pushing such json to Data array ?

答:
see blankrows option

try:

```<code>Data.push(reader.utils.sheet_to_json(
    file.Sheets[file.SheetNames[0]]), {
    blankrows: false
})
</code>```

Body:
I have the following configuration to parse excel to json,which works fine in general:

const reader = require('xlsx');
let Data = [];
   Data.push(reader.utils.sheet_to_json(
            file.Sheets[file.SheetNames[0]]))

However, If have an excel with 7000 rows. I deleted the values in all but one row for test (there is styling in empty rows such as borders and colors but no values). When parsing, sheetjs still attempts to parse all of 7000 rows for some reason.

How to avoid this and parse only rows that have values in it or avoid pushing such json to Data array ?

Body:
see blankrows option

try:

Data.push(reader.utils.sheet_to_json(
    file.Sheets[file.SheetNames[0]]), {
    blankrows: false
})


问:
How to Multiply a value to the next value in a list in scheme?
Is there a way to multiply each value in a list,
however instead of getting another list (2 4 6) like so,
you get the multiplication of all values together.

```<code>(define (multi x y)
  (if (null? y)
     '()
     (* x (car y))))
(multi 2 '(1 2 3))
2 * 1 * 2 * 3
==> 6
</code>```

This may be very simple to some people, but I am having a coding block here, so please don't be rude in the comments. thank you.

答:
Use fold left or right, using this the system will iterate over the input without building a new list but only changing an accumulator.</p>
```<code>(fold-right * 1 '(2 3 4))
(fold-left * 1 '(2 3 4))
</code>```

Body:
Is there a way to multiply each value in a list,
however instead of getting another list (2 4 6) like so,
you get the multiplication of all values together.

(define (multi x y)
  (if (null? y)
     '()
     (* x (car y))))
(multi 2 '(1 2 3))
2 * 1 * 2 * 3
==> 6

This may be very simple to some people, but I am having a coding block here, so please don't be rude in the comments. thank you.

Body:
Use fold left or right, using this the system will iterate over the input without building a new list but only changing an accumulator.

(fold-right * 1 '(2 3 4))
(fold-left * 1 '(2 3 4))


问:
Session getting destroyed after cashfree payment gateway redirecting in laravel 8 (Mozilla browser)
I am trying to integrate the Cashfree payment gateway in my Laravel 8 project. The only issue I face is in the callback URL, where an active session is automatically destroyed after getting the post data from Payment Gateway. I have also added the CSRF exception to Middleware. I have added 'secure' => env('SESSION_SECURE_COOKIE', false) & 'same_site' => null.
I have tried with a redirect()->away($payment_link), iFrame tag, and form submits directly to payment link but still getting the same issue.
The session is getting destroyed in the Mozilla browser, but it works fine in the chrome browser.

Controller (Generate Payment Request, URL, and Process Callback)

```<code>class PaymentController extends Controller
{
    public function credits_add()
    {
        AuthCheck();
        $this->data['page_name'] = 'Add Credits';
        return view('merchant.payment.add_credits', $this->data);
    }

    public function credits_save(Request $request)
    {
        $request->validate([
            'credit_amount' => 'required',
            'credit_transaction_type' => 'required'
        ]);

        if (!empty($request->input('credit_transaction_type')) && $request->input('credit_transaction_type') == 'Cashfree') {
            $cashfreeDetails = $this->pay_with_cashfree($request);
            if (!empty($cashfreeDetails) && !empty($cashfreeDetails['paymentLink'])) {
                return Redirect::to($cashfreeDetails['paymentLink']);
            } else {
                return redirect('credits/add')->with('errorMessage', 'Sorry! Your transaction has failed.');
            }
        }

        return redirect('credits/add');
    }

    public function pay_with_cashfree($request)
    {
        $order = new Order();
        $od["orderId"] = "ORDER-84984941";
        $od["orderAmount"] = 10000;
        $od["orderNote"] = "Subscription";
        $od["customerPhone"] = "9000012345";
        $od["customerName"] = "Test Name";
        $od["customerEmail"] = "test@cashfree.com";
        $od["returnUrl"] = route('CreditsSuccess');
        $od["notifyUrl"] = route('CreditsSuccess');

        $order->create($od);
        $linkArray = $order->getLink($od['orderId']);
        $detailsArray = $order->getDetails($od['orderId']);

        if (!empty($order) && !empty($linkArray) && !empty($linkArray->status) && $linkArray->status == 'OK') {
            return array(
                'paymentLink' => $linkArray->paymentLink,
                'paymentDetails' => $detailsArray
            );
        } else {
            return array();
        }
    }

    public function credits_success(Request $request)
    {
        $orderId = $request->orderId;
        $orderAmount = $request->orderAmount;
        $referenceId = $request->referenceId;
        $txStatus = $request->txStatus;
        $paymentMode = $request->paymentMode;
        $txMsg = $request->txMsg;
        $txTime = $request->txTime;
        $signature = $request->signature;

        if ($txStatus == 'SUCCESS') {
            return redirect('credits/add')->with('successMessage', $txMsg);
        } else {
            return redirect('credits/add')->with('errorMessage', $txMsg);
        }
    }
}
</code>```

答:
OK I figured out the problem for myself.

The new versions of the browsers might be logging you out because of the new cookie policy.

References https://developers.google.com/search/blog/2020/01/get-ready-for-new-samesitenone-secure

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

Whenever the cookie is required to be sent to server, the browser sees the SameSite attribute to decide if the cookie to be sent to server or blocked. For user actions, it is sent to the server but for auto-redirects, it doesn't if SameSite is set to 'Strict' or 'Lax' (Lax is going to be the default value now).

Solution: The cookie attribute SameSite can be set to 'None' along with specifying the 'Secure' attribute to 'true'. Setting 'Secure' attribute to 'true' would require your site to run on https. Sites running with http:// protocol will not be able to set 'Secure' cookie. Please set the 'HttpOnly' attribute to 'true' for making it accessible for http requests to the server only.

Body:
I am trying to integrate the Cashfree payment gateway in my Laravel 8 project. The only issue I face is in the callback URL, where an active session is automatically destroyed after getting the post data from Payment Gateway. I have also added the CSRF exception to Middleware. I have added 'secure' => env('SESSION_SECURE_COOKIE', false) & 'same_site' => null.
I have tried with a redirect()->away($payment_link), iFrame tag, and form submits directly to payment link but still getting the same issue.
The session is getting destroyed in the Mozilla browser, but it works fine in the chrome browser.

Controller (Generate Payment Request, URL, and Process Callback)

class PaymentController extends Controller
{
    public function credits_add()
    {
        AuthCheck();
        $this->data['page_name'] = 'Add Credits';
        return view('merchant.payment.add_credits', $this->data);
    }

    public function credits_save(Request $request)
    {
        $request->validate([
            'credit_amount' => 'required',
            'credit_transaction_type' => 'required'
        ]);

        if (!empty($request->input('credit_transaction_type')) && $request->input('credit_transaction_type') == 'Cashfree') {
            $cashfreeDetails = $this->pay_with_cashfree($request);
            if (!empty($cashfreeDetails) && !empty($cashfreeDetails['paymentLink'])) {
                return Redirect::to($cashfreeDetails['paymentLink']);
            } else {
                return redirect('credits/add')->with('errorMessage', 'Sorry! Your transaction has failed.');
            }
        }

        return redirect('credits/add');
    }

    public function pay_with_cashfree($request)
    {
        $order = new Order();
        $od["orderId"] = "ORDER-84984941";
        $od["orderAmount"] = 10000;
        $od["orderNote"] = "Subscription";
        $od["customerPhone"] = "9000012345";
        $od["customerName"] = "Test Name";
        $od["customerEmail"] = "test@cashfree.com";
        $od["returnUrl"] = route('CreditsSuccess');
        $od["notifyUrl"] = route('CreditsSuccess');

        $order->create($od);
        $linkArray = $order->getLink($od['orderId']);
        $detailsArray = $order->getDetails($od['orderId']);

        if (!empty($order) && !empty($linkArray) && !empty($linkArray->status) && $linkArray->status == 'OK') {
            return array(
                'paymentLink' => $linkArray->paymentLink,
                'paymentDetails' => $detailsArray
            );
        } else {
            return array();
        }
    }

    public function credits_success(Request $request)
    {
        $orderId = $request->orderId;
        $orderAmount = $request->orderAmount;
        $referenceId = $request->referenceId;
        $txStatus = $request->txStatus;
        $paymentMode = $request->paymentMode;
        $txMsg = $request->txMsg;
        $txTime = $request->txTime;
        $signature = $request->signature;

        if ($txStatus == 'SUCCESS') {
            return redirect('credits/add')->with('successMessage', $txMsg);
        } else {
            return redirect('credits/add')->with('errorMessage', $txMsg);
        }
    }
}


问:
System.Data.SQLite Close() not releasing database file
I'm having a problem closing my database before an attempt to delete the file.   The code is just

```<code> myconnection.Close();
 File.Delete(filename);
</code>```

And the Delete throws an exception that the file is still in use. I've re-tried the Delete() in the debugger after a few minutes, so it's not a timing issue.

I have transaction code but it doesn't run at all before the Close() call. So I'm fairly sure it's not an open transaction.  The sql commands between open and close are just selects.

ProcMon shows my program and my antivirus looking at the database file.  It does not show my program releasing the db file after the close().

Visual Studio 2010, C#, System.Data.SQLite version 1.0.77.0, Win7

I saw a two year old bug just like this but the changelog says it's fixed.

Is there anything else I can check?  Is there a way to get a list of any open commands or transactions?

New, working code:

```<code> db.Close();
 GC.Collect();   // yes, really release the db

 bool worked = false;
 int tries = 1;
 while ((tries < 4) && (!worked))
 {
    try
    {
       Thread.Sleep(tries * 100);
       File.Delete(filename);
       worked = true;
    }
    catch (IOException e)   // delete only throws this on locking
    {
       tries++;
    }
 }
 if (!worked)
    throw new IOException("Unable to close file" + filename);
</code>```

答:
The reason for this seems to be a feature called "Pooling".
Appending "Pooling=false" to the connection string causes the DB-File to be released with "connection.Close()".

See the FAQ on connection pooling here:
https://www.devart.com/dotconnect/sqlite/docs/FAQ.html#q54

Body:
I'm having a problem closing my database before an attempt to delete the file.   The code is just

 myconnection.Close();
 File.Delete(filename);

And the Delete throws an exception that the file is still in use. I've re-tried the Delete() in the debugger after a few minutes, so it's not a timing issue.

I have transaction code but it doesn't run at all before the Close() call. So I'm fairly sure it's not an open transaction.  The sql commands between open and close are just selects.

ProcMon shows my program and my antivirus looking at the database file.  It does not show my program releasing the db file after the close().

Visual Studio 2010, C#, System.Data.SQLite version 1.0.77.0, Win7

I saw a two year old bug just like this but the changelog says it's fixed.

Is there anything else I can check?  Is there a way to get a list of any open commands or transactions?

New, working code:

 db.Close();
 GC.Collect();   // yes, really release the db

 bool worked = false;
 int tries = 1;
 while ((tries < 4) && (!worked))
 {
    try
    {
       Thread.Sleep(tries * 100);
       File.Delete(filename);
       worked = true;
    }
    catch (IOException e)   // delete only throws this on locking
    {
       tries++;
    }
 }
 if (!worked)
    throw new IOException("Unable to close file" + filename);


问:
When I enable uwsgi thread support and start the scheduler the api stops working
I'm new to python, flask, nginx and all that stuff.

I have a flask app that acts as API for a frontend. Also when the flask app is started I would like to start a scheduled task with APScheduler.

The problem is that when I enable uwsgi thread support and start the scheduler the api stops working (504 Gateway Time-out). But the scheduler works as seen in the logfile. When i remove the scheduler / thread support the api works but I obviously don't have the scheduler anymore.
Somehow I suspect the scheduler prevents the flask app from being run properly?

As I am new to those technologies I'll post my setup below. If you need any more file infos please tell me.(The whole thing is run on a raspberry pi and the api is accessed from my pc over lan)

app.service

```<code>[Unit]
Description=uWSGI instance to serve app
After=network.target

[Service]
User=pi
Group=www-data
WorkingDirectory=/home/pi/flask
Environment="PATH=/home/pi/flask/appenv/bin"
ExecStart=/home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads

[Install]
WantedBy=multi-user.target
</code>```

app.ini

```<code>[uwsgi]
module = wsgi:app

master = true
processes = 5

socket = /home/pi/flask/app.sock
chmod-socket = 660
vacuum = true

die-on-term = true
</code>```

app.py

```<code>#!/usr/bin/env python3

from flask import Flask, request
from apscheduler.schedulers.background import BackgroundScheduler

import logging
logging.basicConfig(filename='logfile.log',level=logging.DEBUG)

from api.Controller import Controller
from Handler.Handler import Handler
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor

api_controller = Controller()
handler = Handler()

def startHandlerJob():
    handler.ExecuteAllSensors()

app = Flask( __name__ )

@app.route('/app')
def apiDefinition():
    return 'API Definition: GetHumidityValues, TODO'

@app.route( "/app/GetHumidityValues", methods=["GET"] )
def GetHumidityValues():
    logging.info("app.py: API-call GetHumidityValues")
    return api_controller.GetHumidityValues()

if (__name__ == "__main__"):
    app.run(host='0.0.0.0')

executors = {
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 1
}

scheduler = BackgroundScheduler(daemon=True, executors=executors, job_defaults=job_defaults)
scheduler.start()
scheduler.add_job(startHandlerJob,'cron', minute='*')
</code>```

logfile.log

WARNING:apscheduler.scheduler:Execution of job "startHandlerJob (trigger: cron[minute=''], next run at: 2019-12-18 19:01:00 CET)" skipped: maximum number of running instances reached (1)
DEBUG:apscheduler.scheduler:Next wakeup is due at 2019-12-18 19:02:00+01:00 (in 59.980780 seconds)
DEBUG:apscheduler.scheduler:Looking for jobs to run
WARNING:apscheduler.scheduler:Execution of job "startHandlerJob (trigger: cron[minute=''], next run at: 2019-12-18 19:02:00 CET)" skipped: maximum number of running instances reached (1)
DEBUG:apscheduler.scheduler:Next wakeup is due at 2019-12-18 19:03:00+01:00 (in 59.979407 seconds)

systemctl status app

```<code>* app.service - uWSGI instance to serve app
   Loaded: loaded (/etc/systemd/system/app.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2019-12-18 18:40:57 CET; 23min ago
 Main PID: 21129 (uwsgi)
    Tasks: 8 (limit: 2200)
   Memory: 22.9M
   CGroup: /system.slice/app.service
           |-21129 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21148 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21149 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21150 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21151 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           `-21152 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads

Dec 18 18:40:57 raspberrypi uwsgi[21129]: mapped 386400 bytes (377 KB) for 5 cores
Dec 18 18:40:57 raspberrypi uwsgi[21129]: *** Operational MODE: preforking ***
Dec 18 18:40:59 raspberrypi uwsgi[21129]: WSGI app 0 (mountpoint='') ready in 2 seconds on interpreter 0xa6f900 pid: 21129 (default app)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: *** uWSGI is running in multiple interpreter mode ***
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI master process (pid: 21129)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 1 (pid: 21148, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 2 (pid: 21149, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 3 (pid: 21150, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 4 (pid: 21151, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 5 (pid: 21152, cores: 1)
</code>```

The logfile shows that the scheduler is active. But when I try to use http:/raspberryipaddress/app the answer is a 504 Gateway Time-out response. When I remove the scheduler and disable thread support this call works as desired.

Any help is appreciated. Probably I am missing something obvious, because I am new to all those things.
Thanks!

答:
I had exactly the same problem. The fix for me was to use ProcessPoolExecutor instead of ThreadPoolExecutor.

For some unknown reasons (at least unknown for me), when there were several threads in ThreadPoolExecutor, that damn problem showed itself.

After I changed most cpu-bound threads to processes (i.e. using ProcessPoolExecutor for those jobs), that damn problem disappeared ...

Body:
I'm new to python, flask, nginx and all that stuff.

I have a flask app that acts as API for a frontend. Also when the flask app is started I would like to start a scheduled task with APScheduler.

The problem is that when I enable uwsgi thread support and start the scheduler the api stops working (504 Gateway Time-out). But the scheduler works as seen in the logfile. When i remove the scheduler / thread support the api works but I obviously don't have the scheduler anymore.
Somehow I suspect the scheduler prevents the flask app from being run properly?

As I am new to those technologies I'll post my setup below. If you need any more file infos please tell me.(The whole thing is run on a raspberry pi and the api is accessed from my pc over lan)

app.service

[Unit]
Description=uWSGI instance to serve app
After=network.target

[Service]
User=pi
Group=www-data
WorkingDirectory=/home/pi/flask
Environment="PATH=/home/pi/flask/appenv/bin"
ExecStart=/home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads

[Install]
WantedBy=multi-user.target

app.ini

[uwsgi]
module = wsgi:app

master = true
processes = 5

socket = /home/pi/flask/app.sock
chmod-socket = 660
vacuum = true

die-on-term = true

app.py

#!/usr/bin/env python3

from flask import Flask, request
from apscheduler.schedulers.background import BackgroundScheduler

import logging
logging.basicConfig(filename='logfile.log',level=logging.DEBUG)

from api.Controller import Controller
from Handler.Handler import Handler
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor

api_controller = Controller()
handler = Handler()

def startHandlerJob():
    handler.ExecuteAllSensors()

app = Flask( __name__ )

@app.route('/app')
def apiDefinition():
    return 'API Definition: GetHumidityValues, TODO'

@app.route( "/app/GetHumidityValues", methods=["GET"] )
def GetHumidityValues():
    logging.info("app.py: API-call GetHumidityValues")
    return api_controller.GetHumidityValues()

if (__name__ == "__main__"):
    app.run(host='0.0.0.0')

executors = {
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 1
}

scheduler = BackgroundScheduler(daemon=True, executors=executors, job_defaults=job_defaults)
scheduler.start()
scheduler.add_job(startHandlerJob,'cron', minute='*')

logfile.log

WARNING:apscheduler.scheduler:Execution of job "startHandlerJob (trigger: cron[minute=''], next run at: 2019-12-18 19:01:00 CET)" skipped: maximum number of running instances reached (1)
DEBUG:apscheduler.scheduler:Next wakeup is due at 2019-12-18 19:02:00+01:00 (in 59.980780 seconds)
DEBUG:apscheduler.scheduler:Looking for jobs to run
WARNING:apscheduler.scheduler:Execution of job "startHandlerJob (trigger: cron[minute=''], next run at: 2019-12-18 19:02:00 CET)" skipped: maximum number of running instances reached (1)
DEBUG:apscheduler.scheduler:Next wakeup is due at 2019-12-18 19:03:00+01:00 (in 59.979407 seconds)

systemctl status app

* app.service - uWSGI instance to serve app
   Loaded: loaded (/etc/systemd/system/app.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2019-12-18 18:40:57 CET; 23min ago
 Main PID: 21129 (uwsgi)
    Tasks: 8 (limit: 2200)
   Memory: 22.9M
   CGroup: /system.slice/app.service
           |-21129 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21148 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21149 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21150 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           |-21151 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads
           `-21152 /home/pi/flask/appenv/bin/uwsgi --ini app.ini --enable-threads

Dec 18 18:40:57 raspberrypi uwsgi[21129]: mapped 386400 bytes (377 KB) for 5 cores
Dec 18 18:40:57 raspberrypi uwsgi[21129]: *** Operational MODE: preforking ***
Dec 18 18:40:59 raspberrypi uwsgi[21129]: WSGI app 0 (mountpoint='') ready in 2 seconds on interpreter 0xa6f900 pid: 21129 (default app)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: *** uWSGI is running in multiple interpreter mode ***
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI master process (pid: 21129)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 1 (pid: 21148, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 2 (pid: 21149, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 3 (pid: 21150, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 4 (pid: 21151, cores: 1)
Dec 18 18:40:59 raspberrypi uwsgi[21129]: spawned uWSGI worker 5 (pid: 21152, cores: 1)

The logfile shows that the scheduler is active. But when I try to use http:/raspberryipaddress/app the answer is a 504 Gateway Time-out response. When I remove the scheduler and disable thread support this call works as desired.

Any help is appreciated. Probably I am missing something obvious, because I am new to all those things.
Thanks!


问:
Mapping interval using map function in python
Given a sequence of numbers, first convert to interval and convert to dictionary as per sequence of number and then after that map it with a column in DataFrame as shown in DataFrame below.

Query-1 how to create interval from above sequence into dictionary

```<code>given_sequence = [-100, 2, 5, 8, 10, 15]# Given sequence

idict = {-100: '<2',
2:'2-5',
5:'5-8',
8:'8-10',
10:'10-15',
15:'>15'}
</code>```

Query-2 how to map to a column as shown in below screen shot with dictionary and map function

```<code>import pandas as pd
import random
# create an Empty DataFrame object
df = pd.DataFrame()
df['col1'] = [random.randint(1, 10) for i in range(0, 10)]
df['mapped']  = df['col1'].map(idict)
</code>```

** Expected Output**

答:
Your desired outcome can be obtained using pd.cut. It creates a categorical variable from a continuous variable.

```<code>df['mapped'] = pd.cut(df['col1'], right=False, bins=given_sequence+[float('inf')],
                      labels=['<2', '2-5', '5-8','8-10','10-15','>15'])
</code>```

Output:

```<code>   col1 mapped
0     6    5-8
1     1     <2
2    10  10-15
3     7    5-8
4     7    5-8
5     8   8-10
6     4    2-5
7     7    5-8
8    10  10-15
9     6    5-8
</code>```

Body:
Given a sequence of numbers, first convert to interval and convert to dictionary as per sequence of number and then after that map it with a column in DataFrame as shown in DataFrame below.

Query-1 how to create interval from above sequence into dictionary

given_sequence = [-100, 2, 5, 8, 10, 15]# Given sequence

idict = {-100: '<2',
2:'2-5',
5:'5-8',
8:'8-10',
10:'10-15',
15:'>15'}

Query-2 how to map to a column as shown in below screen shot with dictionary and map function

import pandas as pd
import random
# create an Empty DataFrame object
df = pd.DataFrame()
df['col1'] = [random.randint(1, 10) for i in range(0, 10)]
df['mapped']  = df['col1'].map(idict)

** Expected Output**

Body:
Your desired outcome can be obtained using pd.cut. It creates a categorical variable from a continuous variable.

df['mapped'] = pd.cut(df['col1'], right=False, bins=given_sequence+[float('inf')],
                      labels=['<2', '2-5', '5-8','8-10','10-15','>15'])

Output:

   col1 mapped
0     6    5-8
1     1     <2
2    10  10-15
3     7    5-8
4     7    5-8
5     8   8-10
6     4    2-5
7     7    5-8
8    10  10-15
9     6    5-8


问:
SwiftUI `swipeActions` and `confirmationDialog` delete the wrong item
I am trying to use iOS 15.0 swipeActions and confirmationDialog to delete an item in a List.

But what happens is that the wrong item gets deleted.

Here is my code:

```<code>struct ConversationsSection: View {

@State private var isShowingDeleteActions = false

let items = ["One", "Two", "Three", "Four", "Five"]

var body: some View {
    List(items, id: \.self) { item in
        Text(item)
            .swipeActions(edge: .trailing) {
                Button(role: .destructive) {
                    isShowingDeleteActions = true
                    print("Trying to delete: " + item)
                } label: {
                    Label("Delete", systemImage: "trash")
                }
            }
            .confirmationDialog("Delete item?", isPresented: $isShowingDeleteActions) {
                Button("Confirm Delete", role: .destructive) {
                    print("Actually deleting: " + item)
                    isShowingDeleteActions = false
                }
            }
    }
}
</code>```

}

The output is:

```<code>Trying to delete: Two
Actually deleting: Four
Trying to delete: Five
Actually deleting: Three
</code>```

So I swipe an item and confirmationDialog is presented. But inside confirmationDialog another item is passed. Why is that?

答:
The solution from Scott works fine, but when you want to show the confirmationDialog on an iPad, the attachment is off (as it is now using the List as attachment). See the screenshot below:

You can fix this by extracting the Text together with its modifiers and the @State property into a new view like follows:

```<code>import SwiftUI

struct ItemView: View {

    @State private var isShowingDeleteActions = false

    var item: String

    var body: some View {
        Text(item)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
            .swipeActions(edge: .trailing) {
                Button(role: .destructive) {
                    isShowingDeleteActions = true
                    print("Trying to delete: " + item)
                } label: {
                    Label("Delete", systemImage: "trash")
                }
            }
            .confirmationDialog("Delete item?", isPresented: $isShowingDeleteActions) {
                Button("Confirm Delete", role: .destructive) {
                    print("Actually deleting: " + item)
                    isShowingDeleteActions = false
                }
            }
    }
}

struct ConversationsSection: View {

    let items = ["One", "Two", "Three", "Four", "Five"]

    var body: some View {
        NavigationView {
            List(items, id: \.self) { item in
                ItemView(item: item)
            }
        }
    }
}
</code>```

Screenshot of this:

Body:
I am trying to use iOS 15.0 swipeActions and confirmationDialog to delete an item in a List.

But what happens is that the wrong item gets deleted.

Here is my code:

struct ConversationsSection: View {

@State private var isShowingDeleteActions = false

let items = ["One", "Two", "Three", "Four", "Five"]

var body: some View {
    List(items, id: \.self) { item in
        Text(item)
            .swipeActions(edge: .trailing) {
                Button(role: .destructive) {
                    isShowingDeleteActions = true
                    print("Trying to delete: " + item)
                } label: {
                    Label("Delete", systemImage: "trash")
                }
            }
            .confirmationDialog("Delete item?", isPresented: $isShowingDeleteActions) {
                Button("Confirm Delete", role: .destructive) {
                    print("Actually deleting: " + item)
                    isShowingDeleteActions = false
                }
            }
    }
}

}

The output is:

Trying to delete: Two
Actually deleting: Four
Trying to delete: Five
Actually deleting: Three

So I swipe an item and confirmationDialog is presented. But inside confirmationDialog another item is passed. Why is that?

Body:
The solution from Scott works fine, but when you want to show the confirmationDialog on an iPad, the attachment is off (as it is now using the List as attachment). See the screenshot below:

You can fix this by extracting the Text together with its modifiers and the @State property into a new view like follows:

import SwiftUI

struct ItemView: View {

    @State private var isShowingDeleteActions = false

    var item: String

    var body: some View {
        Text(item)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
            .swipeActions(edge: .trailing) {
                Button(role: .destructive) {
                    isShowingDeleteActions = true
                    print("Trying to delete: " + item)
                } label: {
                    Label("Delete", systemImage: "trash")
                }
            }
            .confirmationDialog("Delete item?", isPresented: $isShowingDeleteActions) {
                Button("Confirm Delete", role: .destructive) {
                    print("Actually deleting: " + item)
                    isShowingDeleteActions = false
                }
            }
    }
}

struct ConversationsSection: View {

    let items = ["One", "Two", "Three", "Four", "Five"]

    var body: some View {
        NavigationView {
            List(items, id: \.self) { item in
                ItemView(item: item)
            }
        }
    }
}

Screenshot of this:


问:
How to incorporate password along with passwordless login in ansible dynamic inventory
I give the end user to either provide username i.e dest_user for which ssh-keys is already setup on Linux for all destination hosts i.e dest_host.

Below is how I setup dynamic inventory for passwordless user

- add_host:
    name: "{{ item }}"
    groups: dest_nodes
    ansible_user: "{{ dest_user }}"
  with_items: "{{ dest_host.split() }}"
  when: dest_user != ""
```

All good. The second scenario is when the user does not provide any dest_user then his SSO username (I get this from their Jenkins login) and password i.e., dest_pass which he enters manually should be used for all hosts in the dynamic inventory.

How can I construct dest_nodes group to accommodate both username for passwordless login and both username-password for SSO login?

答:
You can conditionally prompt for a variable using the pause module, and use the special variable omit to make the ansible_password optional in your add_host task.

Note: as you seems to have a pretty good idea on the way to get the user from Jenkins, I assumed it in a variable dest_user_from_jenkins, here.

Here would be the two tasks to do so:

- pause:
    prompt: Please enter your password
    echo: no
  register: dest_pass
  when: dest_user | default('') == ''

- add_host:
    name: "{{ item }}"
    groups: dest_nodes
    ansible_user: "{{ dest_user | default(dest_user_from_jenkins) }}"
    ansible_password: "{{ dest_pass.user_input | default(omit) }}"
  loop: "{{ dest_host.split() }}"
```
<hr />
<p>Given the playbook:</p>
<pre class="lang-yaml prettyprint-override"><code>- hosts: localhost
  gather_facts: no
  vars:
    dest_host: foo bar
    dest_user_from_jenkins: dest_user_not_set

  tasks:
    - pause:
        prompt: Please enter your password
        echo: no
      register: dest_pass
      when: dest_user | default('') == ''

    - add_host:
        name: "{{ item }}"
        groups: dest_nodes
        ansible_user: "{{ dest_user | default(dest_user_from_jenkins) }}"
        ansible_password: "{{ dest_pass.user_input | default(omit) }}"
      loop: "{{ dest_host.split() }}"

    - debug:
        msg: |
          user: {{ hostvars[item].ansible_user }}
          password: {{
            hostvars[item].ansible_password
              | default('password has not been set!')
          }}
      loop: "{{ groups['dest_nodes'] }}"
</code>```

We end up having two possible paths:

When run without any extra parameter, this yields:

TASK [pause] ***********************************************************
[pause]
Please enter your password (output is hidden):
ok: [localhost]

TASK [add_host] ********************************************************
ok: [localhost] => (item=foo)
ok: [localhost] => (item=bar)

TASK [debug] ***********************************************************
ok: [localhost] => (item=foo) =>
  msg: |-
    user: dest_user_not_set
    password: password
ok: [localhost] => (item=bar) =>
  msg: |-
    user: dest_user_not_set
    password: password
```
</li>
<li>When run with <code>--extra-vars "dest_user=dest_user_set"</code>, this yields:
<pre class="lang-none prettyprint-override"><code>TASK [pause] ***********************************************************
skipping: [localhost]

TASK [add_host] ********************************************************
ok: [localhost] => (item=foo)
ok: [localhost] => (item=bar)

TASK [debug] ***********************************************************
ok: [localhost] => (item=foo) =>
  msg: |-
    user: dest_user_set
    password: password has not been set!
ok: [localhost] => (item=bar) =>
  msg: |-
    user: dest_user_set
    password: password has not been set!
</code>```

Body:
I give the end user to either provide username i.e dest_user for which ssh-keys is already setup on Linux for all destination hosts i.e dest_host.

Below is how I setup dynamic inventory for passwordless user

- add_host:
    name: "{{ item }}"
    groups: dest_nodes
    ansible_user: "{{ dest_user }}"
  with_items: "{{ dest_host.split() }}"
  when: dest_user != ""

All good. The second scenario is when the user does not provide any dest_user then his SSO username (I get this from their Jenkins login) and password i.e., dest_pass which he enters manually should be used for all hosts in the dynamic inventory.

How can I construct dest_nodes group to accommodate both username for passwordless login and both username-password for SSO login?

Body:
You can conditionally prompt for a variable using the pause module, and use the special variable omit to make the ansible_password optional in your add_host task.

Note: as you seems to have a pretty good idea on the way to get the user from Jenkins, I assumed it in a variable dest_user_from_jenkins, here.

Here would be the two tasks to do so:

- pause:
    prompt: Please enter your password
    echo: no
  register: dest_pass
  when: dest_user | default('') == ''

- add_host:
    name: "{{ item }}"
    groups: dest_nodes
    ansible_user: "{{ dest_user | default(dest_user_from_jenkins) }}"
    ansible_password: "{{ dest_pass.user_input | default(omit) }}"
  loop: "{{ dest_host.split() }}"

Given the playbook:

- hosts: localhost
  gather_facts: no
  vars:
    dest_host: foo bar
    dest_user_from_jenkins: dest_user_not_set

  tasks:
    - pause:
        prompt: Please enter your password
        echo: no
      register: dest_pass
      when: dest_user | default('') == ''

    - add_host:
        name: "{{ item }}"
        groups: dest_nodes
        ansible_user: "{{ dest_user | default(dest_user_from_jenkins) }}"
        ansible_password: "{{ dest_pass.user_input | default(omit) }}"
      loop: "{{ dest_host.split() }}"

    - debug:
        msg: |
          user: {{ hostvars[item].ansible_user }}
          password: {{
            hostvars[item].ansible_password
              | default('password has not been set!')
          }}
      loop: "{{ groups['dest_nodes'] }}"

We end up having two possible paths:

When run without any extra parameter, this yields:

TASK [pause] ***********************************************************
[pause]
Please enter your password (output is hidden):
ok: [localhost]

TASK [add_host] ********************************************************
ok: [localhost] => (item=foo)
ok: [localhost] => (item=bar)

TASK [debug] ***********************************************************
ok: [localhost] => (item=foo) =>
  msg: |-
    user: dest_user_not_set
    password: password
ok: [localhost] => (item=bar) =>
  msg: |-
    user: dest_user_not_set
    password: password

When run with --extra-vars "dest_user=dest_user_set", this yields:

TASK [pause] ***********************************************************
skipping: [localhost]

TASK [add_host] ********************************************************
ok: [localhost] => (item=foo)
ok: [localhost] => (item=bar)

TASK [debug] ***********************************************************
ok: [localhost] => (item=foo) =>
  msg: |-
    user: dest_user_set
    password: password has not been set!
ok: [localhost] => (item=bar) =>
  msg: |-
    user: dest_user_set
    password: password has not been set!


问:
Explicit wait utility
I am using one generic explicit wait utility which can be used in different places in my test case. Following is the code I have written for the same under Base Test. Here I am looking for a text to present in the screen.For that I have given the parameter "text" in the function VerifyTextPresence.

But after running the script, I am having the below error. How to make it generic so that for any text, I can use this utility. For example, here I am checking for the text "Get" to be present in the screen

Utility Code:

```<code>def VerifyTextPresence(self,text):
    wait = WebDriverWait(self.driver, 15)
    element = wait.until(EC.presence_of_element_located((AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text(text)'))).text
</code>```

Test Script:

```<code>def test_testcasename(self):
        self.VerifyTextPresence("Get")
</code>```

Error:

```<code>io.appium.uiautomator2.common.exceptions.UiSelectorSyntaxException: Could not parse expression `new UiSelector().textGet`: No opening parenthesis after method name at position
</code>```

答:
Based on Appium docs

https://appium.io/docs/en/writing-running-appium/android/uiautomator-uiselector/

UiSelector for text should look like:

```<code>new UiSelector().text("some text value")
</code>```

and in your example:

```<code>new UiSelector().text(text)
</code>```

I see 2 issues here:

no quotes for text

no reference to python method text arg

also

element = (...).text will put the text value to element, and looks not helpful.

Try this:

```<code>def VerifyTextPresence(self, text):
    WebDriverWait(self.driver, 15).until(EC.presence_of_element_located((AppiumBy.ANDROID_UIAUTOMATOR, f"new UiSelector().text(\"{text}\")")))
</code>```

Title: Explicit wait utility

Body:
I am using one generic explicit wait utility which can be used in different places in my test case. Following is the code I have written for the same under Base Test. Here I am looking for a text to present in the screen.For that I have given the parameter "text" in the function VerifyTextPresence.

But after running the script, I am having the below error. How to make it generic so that for any text, I can use this utility. For example, here I am checking for the text "Get" to be present in the screen

Utility Code:

def VerifyTextPresence(self,text):
    wait = WebDriverWait(self.driver, 15)
    element = wait.until(EC.presence_of_element_located((AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text(text)'))).text

Test Script:

def test_testcasename(self):
        self.VerifyTextPresence("Get")

Error:

io.appium.uiautomator2.common.exceptions.UiSelectorSyntaxException: Could not parse expression `new UiSelector().textGet`: No opening parenthesis after method name at position

Body:
Based on Appium docs

https://appium.io/docs/en/writing-running-appium/android/uiautomator-uiselector/

UiSelector for text should look like:

new UiSelector().text("some text value")

and in your example:

new UiSelector().text(text)

I see 2 issues here:

no quotes for text

no reference to python method text arg

also

element = (...).text will put the text value to element, and looks not helpful.

Try this:

def VerifyTextPresence(self, text):
    WebDriverWait(self.driver, 15).until(EC.presence_of_element_located((AppiumBy.ANDROID_UIAUTOMATOR, f"new UiSelector().text(\"{text}\")")))


问:
Await dosent wait?
I am currently trying to fetch something from an API. However, the fetch is quite big, and the fetch doesn't wait, so it returns undefined even though I am using await?
I know that the fetch works correctly and returns an object with over 2400 objects. However, it takes a while, and the problem is that it doesn't wait. It just returns undefined. So after 1 second, it consoles logs the result but then React is already done receiving the undefined.</p>
```<code>app.get("/api/v1/getfrostdata",async(req,res)=>{
    try{
        let response = await FetchTemp();
        console.log(response)
        res.status(200).json({
            status:"success",
            data:{
                timeSeries:response
            }
        })
    }
    catch(err){
        console.log(err)
    }
})
</code>```
```<code>async function FetchTemp(){
    fetch('https://frost.met.no/observations/availableTimeSeries/v0.jsonld?elements=air_temperature',{method:"get",
    body: JSON.stringify(),
    headers:{ Authorization: 'MY SECRET'}
    })
    .then(res=>res.json())
    .then(async(data)=>{
console.log(data)
        return data;
    })
}
</code>```

答:
Await/async or Promise serve the same purpose, you're mixing concepts.

You either create a promise which fetch indeed does and use the exposed methods Then/Catch:

```<code>fetch(...)
.then(response => response.json())
.then(success => your success code here)
.catch(error => error code here)
</code>```

Or you can use async await like this:

```<code>async function fetchTemp() {
  const response = await fetch(url);
  const json = await response.json();
  ...
}
</code>```

Title: Await dosent wait?

Body:
I am currently trying to fetch something from an API. However, the fetch is quite big, and the fetch doesn't wait, so it returns undefined even though I am using await?
I know that the fetch works correctly and returns an object with over 2400 objects. However, it takes a while, and the problem is that it doesn't wait. It just returns undefined. So after 1 second, it consoles logs the result but then React is already done receiving the undefined.

app.get("/api/v1/getfrostdata",async(req,res)=>{
    try{
        let response = await FetchTemp();
        console.log(response)
        res.status(200).json({
            status:"success",
            data:{
                timeSeries:response
            }
        })
    }
    catch(err){
        console.log(err)
    }
})

async function FetchTemp(){
    fetch('https://frost.met.no/observations/availableTimeSeries/v0.jsonld?elements=air_temperature',{method:"get",
    body: JSON.stringify(),
    headers:{ Authorization: 'MY SECRET'}
    })
    .then(res=>res.json())
    .then(async(data)=>{
console.log(data)
        return data;
    })
}

Body:
Await/async or Promise serve the same purpose, you're mixing concepts.

You either create a promise which fetch indeed does and use the exposed methods Then/Catch:

fetch(...)
.then(response => response.json())
.then(success => your success code here)
.catch(error => error code here)

Or you can use async await like this:

async function fetchTemp() {
  const response = await fetch(url);
  const json = await response.json();
  ...
}


问:
In scons, how can I inject a target to be built?
I want to inject a "Cleanup" target which depends on a number of other targets finishing before it goes off and gzip's some log files.  It's important that I not gzip early as this can cause some of the tools to fail.

How can I inject a cleanup target for Scons to execute?

e.g. I have targets foo and bar.   I want to inject a new custom target called 'cleanup' that depends on foo and bar and runs after they're both done, without the user having to specify

```<code>% scons foo cleanup
</code>```

I want them to type:

```<code>% scons foo
</code>```

but have scons execute as though the user had typed

```<code>% scons foo cleanup
</code>```

I've tried creating the cleanup target and appending to sys.argv, but it seems that scons has already processed sys.argv by the time it gets to my code so it doesn't process the 'cleanup' target that I manually append to sys.argv.

答:
In version 1.1.0.d20081104 of SCons, you can use the private internal SCons method:

```<code>SCons.Script._Add_Targets( [ 'MY_INJECTED_TARGET' ] )
</code>```

If the user types:

```<code>% scons foo bar
</code>```

The above code snippet will cause SCons to behave as though the user had typed:

```<code>% scons foo bar MY_INJECTED_TARGET
</code>```

OwnerDisplayName: Ross Rogers

ContentLicense: CC BY-SA 2.5

Body:
I want to inject a "Cleanup" target which depends on a number of other targets finishing before it goes off and gzip's some log files.  It's important that I not gzip early as this can cause some of the tools to fail.

How can I inject a cleanup target for Scons to execute?

e.g. I have targets foo and bar.   I want to inject a new custom target called 'cleanup' that depends on foo and bar and runs after they're both done, without the user having to specify

% scons foo cleanup

I want them to type:

% scons foo

but have scons execute as though the user had typed

% scons foo cleanup

I've tried creating the cleanup target and appending to sys.argv, but it seems that scons has already processed sys.argv by the time it gets to my code so it doesn't process the 'cleanup' target that I manually append to sys.argv.

Body:
In version 1.1.0.d20081104 of SCons, you can use the private internal SCons method:

SCons.Script._Add_Targets( [ 'MY_INJECTED_TARGET' ] )

If the user types:

% scons foo bar

The above code snippet will cause SCons to behave as though the user had typed:

% scons foo bar MY_INJECTED_TARGET


问:
how can i schedule expo notifications from python
react-native expo for application(android) and python[django] for backend , i have created an app and successfully sent notification from python to my app [i am using expo notifications for sending notifications] but i want to schedule them , its possible in react native directly but i want to do it from python for some other purpose.
can someone help me with this

this is my code for generating notification

```<code>@api_view(['GET'])
def sendNotification(request):
  token = StoreToken.objects.all().last()
  print(token)
  if token == None:
      return Response({'detail':'something went wrong'}, status=status.HTTP_400_BAD_REQUEST)

  message = {
    'to' :  token.token,
    'title' : 'hello',
    'body' : 'this is body'
  }
  return r.post('https://exp.host/--/api/v2/push/send', json = message)
</code>```

答:
i know this is not prefect way but this helped me and worked for me really well, may this work for you as well

https://somehowitworked.dev/push-notifications-react-native-expo-django/

this above written blog will help you to set up your code in expo and python and also will guide you through integration

Body:
react-native expo for application(android) and python[django] for backend , i have created an app and successfully sent notification from python to my app [i am using expo notifications for sending notifications] but i want to schedule them , its possible in react native directly but i want to do it from python for some other purpose.
can someone help me with this

this is my code for generating notification

@api_view(['GET'])
def sendNotification(request):
  token = StoreToken.objects.all().last()
  print(token)
  if token == None:
      return Response({'detail':'something went wrong'}, status=status.HTTP_400_BAD_REQUEST)

  message = {
    'to' :  token.token,
    'title' : 'hello',
    'body' : 'this is body'
  }
  return r.post('https://exp.host/--/api/v2/push/send', json = message)


问:
How to cumsum the elements of a vector under certain condition in R?
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

```<code>vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)
</code>```

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

```<code>vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)
</code>```

How can I achieve this?

答:
The approach that comes to mind is to find the runs (rle()) defined by the
condition (sign()) in the data, apply cumsum() on each run separately
(tapply()), and the concatenate back into a vector (unlist()). Something
like this:

vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

run_length <- rle(sign(vector_A))$lengths
run_id <- rep(seq_along(run_length), run_length)

unlist(tapply(vector_A, run_id, cumsum), use.names = FALSE)
#>  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1
```
<p>Wrapping the process up a bit, I’d maybe put finding the grouping factor (run
index) in a function? And then the grouped summary will need to be done using
existing tools, like <code>tapply()</code> above, or a creative <code>ave()</code>, or in the
context of data frames, a <code>group_by()</code> and <code>summarise()</code> with dplyr.</p>
<pre class="lang-r prettyprint-override"><code>run_index <- function(x) {
  with(rle(x), rep(seq_along(lengths), lengths))
}

ave(vector_A, run_index(sign(vector_A)), FUN = cumsum)
#>  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1
</code>```

Body:
My objective is to do a cumulative sum of the elements of a vector and assign the result to each element. But when certain condition is reached, then reset the cumulative sum.

For example:

vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

Now, suppose that the condition to reset the cumulative sum is that the next element has a different sign.

Then the desired output is:

vector_B <- c(1, 2, -1, -2, -3, 1, -1, -2, 1, -1)

How can I achieve this?

Body:
The approach that comes to mind is to find the runs (rle()) defined by the
condition (sign()) in the data, apply cumsum() on each run separately
(tapply()), and the concatenate back into a vector (unlist()). Something
like this:

vector_A <- c(1, 1, -1, -1, -1, 1, -1, -1, 1, -1)

run_length <- rle(sign(vector_A))$lengths
run_id <- rep(seq_along(run_length), run_length)

unlist(tapply(vector_A, run_id, cumsum), use.names = FALSE)
#>  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1

Wrapping the process up a bit, I’d maybe put finding the grouping factor (run
index) in a function? And then the grouped summary will need to be done using
existing tools, like tapply() above, or a creative ave(), or in the
context of data frames, a group_by() and summarise() with dplyr.

run_index <- function(x) {
  with(rle(x), rep(seq_along(lengths), lengths))
}

ave(vector_A, run_index(sign(vector_A)), FUN = cumsum)
#>  [1]  1  2 -1 -2 -3  1 -1 -2  1 -1


问:
Reading file only after function is done
I have a function doSmth that creates a file "data.json" by the end. (the file IS created by the end of running the script.) However, when I try to fs.readFileSync it using await and then, it says

```<code>Error: ENOENT: no such file or directory, open 'data.json'
</code>```

here is my code

```<code>const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        let fileExists = fs.existsSync('data.json');
        if (fileExists) {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
        }
    })
}

await doSmth().then(async () => {
    const fs = require("fs");
    console.log("reached")
    fs.readFileSync("data.json")
})
</code>```

how do I wait for the data.json file to be created before reading it

Edit:
from the comments changed my code to this and works

```<code>const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}
</code>```

but now I have an await inside and it causes the same data.file not found error

```<code>const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(async resolve => {
            const eachFile = await zip.file(file.name).async("string")
            const jsonObject = JSON.parse(eachFile)
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}
</code>```

答:
the problem is you are not writing the file synchronously in your catch block

const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        try {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } catch (error) {
            console.log("file didnt exist")
            fs.writeFileSync('data.json', JSON.stringify(""));
            // Yes, writeFileSync does create a new file when the file is not exists
            // So even this catch is redundant, use fs.existsSync if you really need to know the file exists or not
        }
    })
}
```

or you might want to do a proper primisify for every thing

Body:
I have a function doSmth that creates a file "data.json" by the end. (the file IS created by the end of running the script.) However, when I try to fs.readFileSync it using await and then, it says

Error: ENOENT: no such file or directory, open 'data.json'

here is my code

const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        let fileExists = fs.existsSync('data.json');
        if (fileExists) {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } else {
            console.log("file didnt exist")
            fs.writeFileSync("data.json", JSON.stringify(""))
        }
    })
}

await doSmth().then(async () => {
    const fs = require("fs");
    console.log("reached")
    fs.readFileSync("data.json")
})

how do I wait for the data.json file to be created before reading it

Edit:
from the comments changed my code to this and works

const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(resolve => {
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}

but now I have an await inside and it causes the same data.file not found error

const doSmth = async() => {
    await Promise.all(zip.forEach(async(relativePath: any, file: any) => {
        return new Promise(async resolve => {
            const eachFile = await zip.file(file.name).async("string")
            const jsonObject = JSON.parse(eachFile)
            const fs = require("fs");
            let fileExists = fs.existsSync('data.json');
            if (fileExists) {
               fs.readFileSync('data.json')
                console.log("file already exists")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            } else {
               console.log("file didnt exist")
               fs.writeFileSync("data.json", JSON.stringify(""))
               resolve()
            }
      })
    }))
}

Body:
the problem is you are not writing the file synchronously in your catch block

const doSmth = async() => {
    await zip.forEach(async(relativePath: any, file: any) => {
        const fs = require("fs");
        try {
            fs.readFileSync('data.json')
            console.log("file already exists")
            fs.writeFileSync("data.json", JSON.stringify(""))
        } catch (error) {
            console.log("file didnt exist")
            fs.writeFileSync('data.json', JSON.stringify(""));
            // Yes, writeFileSync does create a new file when the file is not exists
            // So even this catch is redundant, use fs.existsSync if you really need to know the file exists or not
        }
    })
}

or you might want to do a proper primisify for every thing


问:
Apache FOP in a Java Applet - No ImagePreloader found for data
I'm looking at an issue in a mature commercial product.

In a nutshell, we are using part of the Apache POI library to read in a Word .DOC or .DOCX file, and convert it into XSL-FO so that we can do token replacements.  We then use FOP – embedded into the Java program - to convert the FO data into a PDF for printing.  The catch is, all this is being done on the client inside a Java applet running inside Internet Explorer.

Originally we were using FOP 0.93, which worked reasonably well.  However, it was not able to utilise the fonts inside the DOC file when generating the PDF and would map everything to Times, which one of the customers did not like.  In theory it could be made to work by adding some kind of font metrics data, but that would require a relatively complex definition for every font it was likely to encounter and we can’t predict what the client is liable to use outside of the MS core fonts set.

To fix this, FOP was upgraded to 1.0, which added support for autodetecting the fonts from the operating system.  This worked, but we noticed that the image processing had stopped working and the letterheads had disappeared.
What appears to have happened is that the image loader inside FOP was rewritten at some point between 0.93 and 0.95 so that instead of using Jimi and JAI it now uses ImageIO.  The earlier implementation worked fine, but the new code doesn’t like being run as an applet.

Images are embedded in URIs in the FO data so we get an error like this:
2014-09-30 17:00:10,607 ERROR [org.apache.fop.apps.FOUserAgent] Image not available. URI:
data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAABSCAIAAABysmn6AAA...
...ggg==. Reason: org.apache.xmlgraphics.image.loader.ImageException: The file format is not supported. No ImagePreloader found for data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAABSCAIAAABysmn6AAAA...

When run through a test harness, the correct output is generated, but when run as an applet inside the browser we get the above error which makes me suspect that the browser applet security is jamming the ImageIO plugin loader somehow.

The guts of the FOP transformation, i.e. the bit which is triggering the error is this:

```<code>// Step 4: Setup JAXP using identity transformer
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // identity transformer

transformer.transform(src, res);
</code>```

...which is all being run inside a PrivilegedAction block since in FOP 1.0 it needed file I/O access to manage the font cache.

Running the standalone FOP 0.93 and 1.0 programs under linux and using strace shows that it is writing out temporary files for the image data, but both 0.93 and 1.0 do similar things, so it shouldn’t be that by itself, especially since it should have permission to create temp files already.

I've tried different versions of the JRE since some builds a few years back apparently had security issues with the ImageIO library, but to no avail.

Any ideas?

Thanks,

答:
thanks for the post!
I can assert that this also works by changing ordering in Eclipse!
in my case, under Windows it was working fine, but same JAR file in RHEL raised an error</p>

Body:
I'm looking at an issue in a mature commercial product.

In a nutshell, we are using part of the Apache POI library to read in a Word .DOC or .DOCX file, and convert it into XSL-FO so that we can do token replacements.  We then use FOP – embedded into the Java program - to convert the FO data into a PDF for printing.  The catch is, all this is being done on the client inside a Java applet running inside Internet Explorer.

Originally we were using FOP 0.93, which worked reasonably well.  However, it was not able to utilise the fonts inside the DOC file when generating the PDF and would map everything to Times, which one of the customers did not like.  In theory it could be made to work by adding some kind of font metrics data, but that would require a relatively complex definition for every font it was likely to encounter and we can’t predict what the client is liable to use outside of the MS core fonts set.

To fix this, FOP was upgraded to 1.0, which added support for autodetecting the fonts from the operating system.  This worked, but we noticed that the image processing had stopped working and the letterheads had disappeared.
What appears to have happened is that the image loader inside FOP was rewritten at some point between 0.93 and 0.95 so that instead of using Jimi and JAI it now uses ImageIO.  The earlier implementation worked fine, but the new code doesn’t like being run as an applet.

Images are embedded in URIs in the FO data so we get an error like this:
2014-09-30 17:00:10,607 ERROR [org.apache.fop.apps.FOUserAgent] Image not available. URI:
data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAABSCAIAAABysmn6AAA...
...ggg==. Reason: org.apache.xmlgraphics.image.loader.ImageException: The file format is not supported. No ImagePreloader found for data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAABSCAIAAABysmn6AAAA...

When run through a test harness, the correct output is generated, but when run as an applet inside the browser we get the above error which makes me suspect that the browser applet security is jamming the ImageIO plugin loader somehow.

The guts of the FOP transformation, i.e. the bit which is triggering the error is this:

// Step 4: Setup JAXP using identity transformer
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // identity transformer

transformer.transform(src, res);

...which is all being run inside a PrivilegedAction block since in FOP 1.0 it needed file I/O access to manage the font cache.

Running the standalone FOP 0.93 and 1.0 programs under linux and using strace shows that it is writing out temporary files for the image data, but both 0.93 and 1.0 do similar things, so it shouldn’t be that by itself, especially since it should have permission to create temp files already.

I've tried different versions of the JRE since some builds a few years back apparently had security issues with the ImageIO library, but to no avail.

Any ideas?

Thanks,


问:
Request image from WMS to local storage in Java
I have been trying to retrieve image from WMS in Java using the Geotools and save the image locally. I have simply followed this link https://gitlab.com/-/snippets/1883964 by Ian Turton and from the official documentation https://docs.geotools.org/latest/userguide/extension/wms/wms.html

My code is

```<code>package wmsexplore;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.geotools.ows.ServiceException;
import org.geotools.ows.wms.WebMapServer;
import org.geotools.ows.wms.request.GetMapRequest;
import org.geotools.ows.wms.response.GetMapResponse;

public class WMSConnector {
  public static void main(String[] args) {

    URL url = null;
    try {
      url = new URL("http://maps.heigit.org/osm-wms/service?service=WMS&request=GetCapabilities&version=1.1.0");
    } catch (MalformedURLException e) {
      // will not happen
    }

    WebMapServer wms = null;
    try {
      wms = new WebMapServer(url);
      GetMapRequest request = wms.createGetMapRequest();
      request.addLayer("osm_auto:all", "");
      String format = "image/png";
      request.setFormat(format);
      request.setDimensions("1000", "1000"); // sets the dimensions of the image
                                           // to be returned from the server
      request.setTransparent(true);
      request.setSRS("EPSG:4326");
      request.setBBox("-71.13,42.32,-71.03,42.42");

      try {
        GetMapResponse response = (GetMapResponse) wms.issueRequest(request);
        if (response.getContentType().equalsIgnoreCase(format)) {
          BufferedImage image = ImageIO.read(response.getInputStream());
          File outputfile = new File("saved.png");
          ImageIO.write(image, "png", outputfile);
        } else {
          StringWriter writer = new StringWriter();
          IOUtils.copy(response.getInputStream(), writer);
          String error = writer.toString();
          System.out.println(error);

        }
      } catch (ServiceException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

      }
    } catch (IOException e) {
      // There was an error communicating with the server
      // For example, the server is down
    } catch (ServiceException e) {
      // The server returned a ServiceException (unusual in this case)
    }

  }
}
</code>```

The error I have been getting is :

```<code>Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?REQUEST=GetCapabilities&VERSION=1.1.0&SERVICE=WMS
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?request=capabilities&service=WMS&wmtver=1.0.0
</code>```

What might have gone wrong here? Thanks for the help in advance !!

答:
From a quick check (and a google of the error message) it looks like the XML document returned by that server is "invalid" as it has no systemId set.

I've not seen this error before so it might be due to a recent upgrade of the XML parser used by GeoTools or some other change, or a change in MapServer behaviour.  Technically, this isn't a GeoTools bug, but it would be nice to find a way to fix it so we can continue to use MapServer WMS.

Body:
I have been trying to retrieve image from WMS in Java using the Geotools and save the image locally. I have simply followed this link https://gitlab.com/-/snippets/1883964 by Ian Turton and from the official documentation https://docs.geotools.org/latest/userguide/extension/wms/wms.html

My code is

package wmsexplore;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.geotools.ows.ServiceException;
import org.geotools.ows.wms.WebMapServer;
import org.geotools.ows.wms.request.GetMapRequest;
import org.geotools.ows.wms.response.GetMapResponse;

public class WMSConnector {
  public static void main(String[] args) {

    URL url = null;
    try {
      url = new URL("http://maps.heigit.org/osm-wms/service?service=WMS&request=GetCapabilities&version=1.1.0");
    } catch (MalformedURLException e) {
      // will not happen
    }

    WebMapServer wms = null;
    try {
      wms = new WebMapServer(url);
      GetMapRequest request = wms.createGetMapRequest();
      request.addLayer("osm_auto:all", "");
      String format = "image/png";
      request.setFormat(format);
      request.setDimensions("1000", "1000"); // sets the dimensions of the image
                                           // to be returned from the server
      request.setTransparent(true);
      request.setSRS("EPSG:4326");
      request.setBBox("-71.13,42.32,-71.03,42.42");

      try {
        GetMapResponse response = (GetMapResponse) wms.issueRequest(request);
        if (response.getContentType().equalsIgnoreCase(format)) {
          BufferedImage image = ImageIO.read(response.getInputStream());
          File outputfile = new File("saved.png");
          ImageIO.write(image, "png", outputfile);
        } else {
          StringWriter writer = new StringWriter();
          IOUtils.copy(response.getInputStream(), writer);
          String error = writer.toString();
          System.out.println(error);

        }
      } catch (ServiceException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

      }
    } catch (IOException e) {
      // There was an error communicating with the server
      // For example, the server is down
    } catch (ServiceException e) {
      // The server returned a ServiceException (unusual in this case)
    }

  }
}

The error I have been getting is :

Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?REQUEST=GetCapabilities&VERSION=1.1.0&SERVICE=WMS
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?request=capabilities&service=WMS&wmtver=1.0.0

What might have gone wrong here? Thanks for the help in advance !!


问:
Is it possible to dynamically change resources from XML-file?
I want to easily be able to change the UI apperance (colors & logo) of an app and thought to ask if someone has any suggestions on how best to do it.

What I want is simply to replace an XML-file in the project before compiling it and having the resources (i.e. the color values in colors.xml) set to the values of the XML.
The only problem seems to be that there is no way to change resources at runtime(?)

Is there any way of changing the resources automatically at authortime?

The whole point of simply replacing the XML file for different UI apperances is to save time and minimize the amount of editing different parts of the code.

答: At run time u can change the XML resource file using setcontentview(R.layout.yourfilename). You can put this line of code at any part of your execution in the project code.</p>