问:
Asp.Net Core: creating a new scoped IServiceProvider

Objective

Create a asp.net core based solution that permits plugins loaded in runtime, way after IServiceCollection/IServiceProvider have been locked down to change.

Issue

IServiceCollection is configured at startup, from which IServiceProvider is developed, then both are locked for change before run is started.

I'm sure there are great reasons to do this....but I rue the day they came up with it being the only way to do things... so:

Attempt #1

Was based on using Autofac's ability to make child containers, falling back to parent containers for whatever is not specific to the child container,

where, right after uploading the new plugin, I create a new ILifetimeScope so that I can add Services given its containerBuilder:

moduleLifetimeScope = _lifetimeScope.BeginLifetimeScope(autoFacContainerBuilder =>
{
  //can add services now
  autoFacContainerBuilder.AddSingleton(serviceType, tInterface);
}

```
<ul>
<li>save the scope and its Container in a dictionary, against controllerTypes found in the dll, so that:</li>
<li>later can use a custom implementation of <code>IControllerActivator</code> to first try with the default IServiceProvider before falling back to try in the child plugin's child container.</li>
<li>The upside was, Holy cow, with a bit of hacking around, slowly got Controllers to work, then DI into Controllers, then OData....</li>
<li>The downside was that its custom to a specific DI library, and the Startup extensions (<code>AddDbContext</code>, <code>AddOData</code>) were not available as <code>autoFacContainerBuilder</code> doesn't implement <code>IServiceCollection</code>, so it became a huge foray into innards...that sooner or later couldn't keep on being pushed uphill (eg: couldn't figure out how to port <code>AddDbContext</code>)</li>
</ul>
<h5>Attempts #2</h5>
<ul>
<li>At startup, save a <code>singleton copy of the original </code>ISourceCollection<code>in the</code>ISourceCollection` (to easily re-get it later)</li>
<li>Later, upon loading a new plugin,</li>
<li>Clone the original <code>ISourceCollection</code></li>
<li>Add to the <code>clonedServiceCollection</code> new Plugin Services/Controllers found in by Reflection</li>
<li>Use standard extension methods to <code>AddDbContext</code> and <code>AddOData</code>, etc.</li>
<li>Use a custom implementation of <code>IControllerActivator</code> as per above, falling back to the child <code>IServiceProvider</code></li>
<li>Holy cow. Controllers work, OData works, <code>DbContext</code> works...</li>
<li>Hum...it's not working perfectly. Whereas the Controllers and being created new on every request, it's the same <code>DbContext</code> every time, because it's not being disposed, because it's not scoped by some form of scopefactory.</li>
</ul>
<h5>Attempt #3</h5>
<ul>
<li>Same thing as #2, but instead of making the <code>IServiceProvider</code> when the module is loaded, now -- in the custom <code>IControllerActivator</code> making a new <code>IServiceProvider</code> on each request.
<ul>
<li>No idea how much memory/time this is wasting, but I'm guessing its ...not brilliant</li>
</ul>
</li>
<li>But sure...but I've really just pushed the problem a bit further along, not gotten rid of it:
<ul>
<li>A new <code>IServiceProvider</code> is being created...but nothing is actually disposing of it either.</li>
<li>backed by the fact that I'm watching memory usage increase slowly but surely....</li>
</ul>
</li>
</ul>
<h5>Attempt #4</h5>
<ul>
<li>Same as above, but instead of creating a new <code>IServiceProvider</code> on every request, I'm keeping the <code>IServiceProvider</code> that i first built when I uploaded the module, but</li>
<li>using it to built a new Scope, and get its nested <code>IServiceProvider</code>,</li>
<li>hold on to the scope for later disposal.</li>
</ul>
<p>It's a hack as follows:</p>
<pre class="lang-cs prettyprint-override"><code>public class AppServiceBasedControllerActivator : IControllerActivator {
       public object Create(ControllerContext actionContext)
        {
         ...
         find the cached (ControllerType->module Service Provider)
         ...
         var scope = scopeDictionaryEntry.ServiceProvider.CreateScope();
         httpController = serviceProvider.GetService(controllerType);
         actionContext.HttpContext.Items["SAVEMEFROMME"] = scope;
         return httpController;
        }
        public virtual void Release(ControllerContext context, object controller)
        {
            var scope = context.HttpContext.Items["SAVEMEFROMME"] as IServiceScope;
            if (scope == null){return;}
            context.HttpContext.Items.Remove("SAVEMEFROMME");
            scope.Dispose(); //Memory should go back down..but doesn't.
            }
        }
}
</code>```

Attempt #5

No idea. Hence this Question.

I feel like I'm a little further along...but just not closing the chasm to success.

What would you suggest to permit this, in a memory safe way?

Background Musings/Questions in case it helps?

As I understand it, the default IServiceProvider doesn't have a notion of child lifespan/containers, like Autofac can create.

I see a IServiceScopeFactory makes a new IServiceProvider.

I understand there is some middleware (what name?) that invokes IServiceScopeFactory to make a IServiceProvider on every single request (correct?)

are these per-request IServiceProviders really separate/duplicate, and don't 'descend' from a parent one and falls back to parent if a asked for a singleton?

What is the Middleware doing different to dispose/reduce memory at the end of the call?

Should I be thinking about replacing the middleware? But even if it could -- it's so early that I only would have an url, not yet a Controller Type, therefore don't know what Plugin Assembly the Controller came from, therefore don't know what IServiceProvider to use for it...therefore too early to be of use?

Thank you

Getting a real grip on adding plugin sourced scoped services/controllers/DbContexts would be...wow. Been looking for this capability for several months now.

Thanks.

Other Posts

some similarity to:

Use custom IServiceProvider implementation in asp.net core

but I don't see how his disposing is any different to what I'm doing, so are they too having memory issues?

Body:
Objective

Create a asp.net core based solution that permits plugins loaded in runtime, way after IServiceCollection/IServiceProvider have been locked down to change.

Issue

IServiceCollection is configured at startup, from which IServiceProvider is developed, then both are locked for change before run is started.

I'm sure there are great reasons to do this....but I rue the day they came up with it being the only way to do things... so:

Attempt #1

Was based on using Autofac's ability to make child containers, falling back to parent containers for whatever is not specific to the child container,

where, right after uploading the new plugin, I create a new ILifetimeScope so that I can add Services given its containerBuilder:

moduleLifetimeScope = _lifetimeScope.BeginLifetimeScope(autoFacContainerBuilder =>
{
  //can add services now
  autoFacContainerBuilder.AddSingleton(serviceType, tInterface);
}

save the scope and its Container in a dictionary, against controllerTypes found in the dll, so that:

later can use a custom implementation of IControllerActivator to first try with the default IServiceProvider before falling back to try in the child plugin's child container.

The upside was, Holy cow, with a bit of hacking around, slowly got Controllers to work, then DI into Controllers, then OData....

The downside was that its custom to a specific DI library, and the Startup extensions (AddDbContext, AddOData) were not available as autoFacContainerBuilder doesn't implement IServiceCollection, so it became a huge foray into innards...that sooner or later couldn't keep on being pushed uphill (eg: couldn't figure out how to port AddDbContext)

Attempts #2

At startup, save a singleton copy of the original ISourceCollectionin theISourceCollection` (to easily re-get it later)

Later, upon loading a new plugin,

Clone the original ISourceCollection

Add to the clonedServiceCollection new Plugin Services/Controllers found in by Reflection

Use standard extension methods to AddDbContext and AddOData, etc.

Use a custom implementation of IControllerActivator as per above, falling back to the child IServiceProvider

Holy cow. Controllers work, OData works, DbContext works...

Hum...it's not working perfectly. Whereas the Controllers and being created new on every request, it's the same DbContext every time, because it's not being disposed, because it's not scoped by some form of scopefactory.

Attempt #3

Same thing as #2, but instead of making the IServiceProvider when the module is loaded, now -- in the custom IControllerActivator making a new IServiceProvider on each request.

No idea how much memory/time this is wasting, but I'm guessing its ...not brilliant

But sure...but I've really just pushed the problem a bit further along, not gotten rid of it:

A new IServiceProvider is being created...but nothing is actually disposing of it either.

backed by the fact that I'm watching memory usage increase slowly but surely....

Attempt #4

Same as above, but instead of creating a new IServiceProvider on every request, I'm keeping the IServiceProvider that i first built when I uploaded the module, but

using it to built a new Scope, and get its nested IServiceProvider,

hold on to the scope for later disposal.

It's a hack as follows:

public class AppServiceBasedControllerActivator : IControllerActivator {
       public object Create(ControllerContext actionContext)
        {
         ...
         find the cached (ControllerType->module Service Provider)
         ...
         var scope = scopeDictionaryEntry.ServiceProvider.CreateScope();
         httpController = serviceProvider.GetService(controllerType);
         actionContext.HttpContext.Items["SAVEMEFROMME"] = scope;
         return httpController;
        }
        public virtual void Release(ControllerContext context, object controller)
        {
            var scope = context.HttpContext.Items["SAVEMEFROMME"] as IServiceScope;
            if (scope == null){return;}
            context.HttpContext.Items.Remove("SAVEMEFROMME");
            scope.Dispose(); //Memory should go back down..but doesn't.
            }
        }
}

Attempt #5

No idea. Hence this Question.

I feel like I'm a little further along...but just not closing the chasm to success.

What would you suggest to permit this, in a memory safe way?

Background Musings/Questions in case it helps?

As I understand it, the default IServiceProvider doesn't have a notion of child lifespan/containers, like Autofac can create.

I see a IServiceScopeFactory makes a new IServiceProvider.

I understand there is some middleware (what name?) that invokes IServiceScopeFactory to make a IServiceProvider on every single request (correct?)

are these per-request IServiceProviders really separate/duplicate, and don't 'descend' from a parent one and falls back to parent if a asked for a singleton?

What is the Middleware doing different to dispose/reduce memory at the end of the call?

Should I be thinking about replacing the middleware? But even if it could -- it's so early that I only would have an url, not yet a Controller Type, therefore don't know what Plugin Assembly the Controller came from, therefore don't know what IServiceProvider to use for it...therefore too early to be of use?

Thank you

Getting a real grip on adding plugin sourced scoped services/controllers/DbContexts would be...wow. Been looking for this capability for several months now.

Thanks.

Other Posts

some similarity to:

Use custom IServiceProvider implementation in asp.net core

but I don't see how his disposing is any different to what I'm doing, so are they too having memory issues?


来源: stackexchange

问:
Adding output of Keras model's layer output for a custom loss component
I have a convolutional Keras model written in Keras. I wanted to experiment adding another loss component which is based on the output of a dense layer called ‘z_mean’:

```<code>z_output = encoder.get_layer('z_mean').output
</code>```

and then use this output for another function:

```<code>silhouette_loss = - silhouette_coeff(z_output, names)
</code>```

This function (silhouette_coeff) expects a 2D array as an input, but since my 'z_mean' output shape is (None, 32), where None is the batch_size and 32 is output shape of the dense layer, I am getting the error:

```<code>TypeError: You are passing KerasTensor(type_spec=TensorSpec(shape=(None, 32), dtype=tf.float32, name=None), name='z/add:0', description="created by layer 'z'"), an intermediate Keras symbolic input/output, to a TF API that does not allow registering custom dispatchers, such as tf.cond, tf.function, gradient tapes, or tf.map_fn. Keras Functional model construction only supports TF API calls that *do* support dispatching, such as tf.math.addortf.reshape. Other APIs cannot be called directly on symbolic Kerasinputs/outputs. You can work around this limitation by putting the operation in a custom Keras layer call and calling that layer on this symbolic input/output.
</code>```

How can I use the output of layer ‘z_mean’ for my custom loss? The goal here is to maximize the output of the silhouette_coeff() during model training. Thank you in advance!

I tried to disable eager tensore execution, as it was suggested:

```<code>from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()
</code>```

as well as to compile a model with

```<code>experimental_run_tf_function=False
</code>```

flag, however it didn't help.

ContentLicense: CC BY-SA 4.0

Body:
I have a convolutional Keras model written in Keras. I wanted to experiment adding another loss component which is based on the output of a dense layer called ‘z_mean’:

z_output = encoder.get_layer('z_mean').output

and then use this output for another function:

silhouette_loss = - silhouette_coeff(z_output, names)

This function (silhouette_coeff) expects a 2D array as an input, but since my 'z_mean' output shape is (None, 32), where None is the batch_size and 32 is output shape of the dense layer, I am getting the error:

TypeError: You are passing KerasTensor(type_spec=TensorSpec(shape=(None, 32), dtype=tf.float32, name=None), name='z/add:0', description="created by layer 'z'"), an intermediate Keras symbolic input/output, to a TF API that does not allow registering custom dispatchers, such as tf.cond, tf.function, gradient tapes, or tf.map_fn. Keras Functional model construction only supports TF API calls that *do* support dispatching, such as tf.math.addortf.reshape. Other APIs cannot be called directly on symbolic Kerasinputs/outputs. You can work around this limitation by putting the operation in a custom Keras layer call and calling that layer on this symbolic input/output.

How can I use the output of layer ‘z_mean’ for my custom loss? The goal here is to maximize the output of the silhouette_coeff() during model training. Thank you in advance!

I tried to disable eager tensore execution, as it was suggested:

from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()

as well as to compile a model with

experimental_run_tf_function=False

flag, however it didn't help.


问:
Memory address out of bounds when trying to print user input out in MIPS
Screenshot of my code and registers from SPIM

Trying to make a Hello World program that deals with input, but I'm running into a "Memory address out of bounds" error when trying to print out said input.

I've tried changing line 14 to move $s0, $a0 and the program runs and exits successfully, except it's printing prompt in place of where I want user input... So I end up with "Hello... Nice to meet you, What is your name?\n!" instead of my desired outout: "Hello... Nice to meet you, \n!"


问:
Removing NA values from rows, without removing the rows in R
I have a dataset in which the data would look something like this:
a fragment dataframe with the data
So lot's of NA's per row, but also regular answers, that I want in the final version.
Is it possible to remove the NAs, but without removing the rows as a whole?
I thought about pivoting and removing rows with NA, but then it would just remove the occurences that have actual answers as well.
The data is coming form a decision making procedure in qualtrics, in which not every option is displayed to the participants (hence the NAs), but we do not want to exclude people in any step. I also thought about maybe recoding the values, and subsetting them somehow, but that doesn't seem to work out right in my mind when it comes to the actual analysis.

I tried removing the NAs, as well as pivoting the table and removing them later.
I do not yet have the full dataset, but want to experiment on strategies of data analysis before I have the data collected, to not get lost once I have it.


问:
split order and notify admin woocommerce
I have the following code to split an order and create a new order with a custom status.

What I require is to notify the administrator when that new order is generated. So far the notification codes for a custom order have not worked.

The code to divide it that I am using is this:

function action_woocommerce_checkout_order_processed( $order_id, $posted_data, $order ) {
// Initialize
$check_for_back_orders = false;

```<code>// Loop through order items
foreach ( $order->get_items() as $item_key => $item ) {
    // Get product
    $product = $item->get_product();

    // Product is on backorder
    if ( $product->is_on_backorder() ) {
        // Will only be executed once if the order contains back orders
        if ( $check_for_back_orders == false ) {
            $check_for_back_orders = true;

            // Create new order with backorders
            $backorder_order = wc_create_order();
        }

        // Add product to 'backorder' order
        $backorder_order->add_product( $product, $item['quantity'] );

        // Delete item from original order
        $order->remove_item( $item->get_id() );
    }
}

// If current order contains backorders, retrieve the necessary data from the existing order and apply it in the new order
if ( $check_for_back_orders ) {
    // Recalculate and save original order
    $order->calculate_totals();
    $order->save();

    // Obtain necessary information
    // Get address
    $address = array(
        'first_name' => $order->get_billing_first_name(),
        'last_name'  => $order->get_billing_last_name(),
        'email'      => $order->get_billing_email(),
        'phone'      => $order->get_billing_phone(),
        'address_1'  => $order->get_billing_address_1(),
        'address_2'  => $order->get_billing_address_2(),
        'city'       => $order->get_billing_city(),
        'state'      => $order->get_billing_state(),
        'postcode'   => $order->get_billing_postcode(),
        'country'    => $order->get_billing_country()
    );

    // Get shipping
    $shipping = array(
        'first_name' => $order->get_shipping_first_name(),
        'last_name'  => $order->get_shipping_last_name(),
        'address_1'  => $order->get_shipping_address_1(),
        'address_2'  => $order->get_shipping_address_2(),
        'city'       => $order->get_shipping_city(),
        'state'      => $order->get_shipping_state(),
        'postcode'   => $order->get_shipping_postcode(),
        'country'    => $order->get_shipping_country()
    );

    // Get order currency
    $currency = $order->get_currency();

    // Get order payment method
    $payment_gateway = $order->get_payment_method();

    // Required information has been obtained, assign it to the 'backorder' order
    // Set address
    $backorder_order->set_address( $address, 'billing' );
    $backorder_order->set_address( $shipping, 'shipping' );

    // Set the correct currency and payment gateway
    $backorder_order->set_currency( $currency );
    $backorder_order->set_payment_method( $payment_gateway );

    // Calculate totals
    $backorder_order->calculate_totals();

    // Set order note with original ID
    $backorder_order->add_order_note( 'Pedido a confirmar stock automatizado. Creado a partir del ID de pedido original: ' . $order_id );

    // Optional: give the new 'backorder' order the correct status
  $backorder_order->update_status( 'wc-shipping-progress' );
   // $backorder_order->update_status( 'on-hold' );

}
</code>```

}
add_action( 'woocommerce_checkout_order_processed', 'action_woocommerce_checkout_order_processed', 10, 3 );

```<code>
The code for the new custom status is this:

// Register New Order Statuses
function wpex_wc_register_post_statuses() {
    register_post_status( 'wc-shipping-progress', array(
        'label'                     => _x( 'Confirmar Stock', 'WooCommerce Order status', 'text_domain' ),
        'public'                    => true,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop( 'Approved (%s)', 'Approved (%s)', 'text_domain' )
    ) );
}
add_filter( 'init', 'wpex_wc_register_post_statuses' );

// Add New Order Statuses to WooCommerce
function wpex_wc_add_order_statuses( $order_statuses ) {
    $order_statuses['wc-shipping-progress'] = _x( 'Confirmar Stock', 'WooCommerce Order status', 'text_domain' );
    return $order_statuses;
}
add_filter( 'wc_order_statuses', 'wpex_wc_add_order_statuses' );

 So far the notification codes for a custom order have not worked.
</code>```

Body:
I have the following code to split an order and create a new order with a custom status.

What I require is to notify the administrator when that new order is generated. So far the notification codes for a custom order have not worked.

The code to divide it that I am using is this:

function action_woocommerce_checkout_order_processed( $order_id, $posted_data, $order ) {
// Initialize
$check_for_back_orders = false;

// Loop through order items
foreach ( $order->get_items() as $item_key => $item ) {
    // Get product
    $product = $item->get_product();

    // Product is on backorder
    if ( $product->is_on_backorder() ) {
        // Will only be executed once if the order contains back orders
        if ( $check_for_back_orders == false ) {
            $check_for_back_orders = true;

            // Create new order with backorders
            $backorder_order = wc_create_order();
        }

        // Add product to 'backorder' order
        $backorder_order->add_product( $product, $item['quantity'] );

        // Delete item from original order
        $order->remove_item( $item->get_id() );
    }
}

// If current order contains backorders, retrieve the necessary data from the existing order and apply it in the new order
if ( $check_for_back_orders ) {
    // Recalculate and save original order
    $order->calculate_totals();
    $order->save();

    // Obtain necessary information
    // Get address
    $address = array(
        'first_name' => $order->get_billing_first_name(),
        'last_name'  => $order->get_billing_last_name(),
        'email'      => $order->get_billing_email(),
        'phone'      => $order->get_billing_phone(),
        'address_1'  => $order->get_billing_address_1(),
        'address_2'  => $order->get_billing_address_2(),
        'city'       => $order->get_billing_city(),
        'state'      => $order->get_billing_state(),
        'postcode'   => $order->get_billing_postcode(),
        'country'    => $order->get_billing_country()
    );

    // Get shipping
    $shipping = array(
        'first_name' => $order->get_shipping_first_name(),
        'last_name'  => $order->get_shipping_last_name(),
        'address_1'  => $order->get_shipping_address_1(),
        'address_2'  => $order->get_shipping_address_2(),
        'city'       => $order->get_shipping_city(),
        'state'      => $order->get_shipping_state(),
        'postcode'   => $order->get_shipping_postcode(),
        'country'    => $order->get_shipping_country()
    );

    // Get order currency
    $currency = $order->get_currency();

    // Get order payment method
    $payment_gateway = $order->get_payment_method();

    // Required information has been obtained, assign it to the 'backorder' order
    // Set address
    $backorder_order->set_address( $address, 'billing' );
    $backorder_order->set_address( $shipping, 'shipping' );

    // Set the correct currency and payment gateway
    $backorder_order->set_currency( $currency );
    $backorder_order->set_payment_method( $payment_gateway );

    // Calculate totals
    $backorder_order->calculate_totals();

    // Set order note with original ID
    $backorder_order->add_order_note( 'Pedido a confirmar stock automatizado. Creado a partir del ID de pedido original: ' . $order_id );

    // Optional: give the new 'backorder' order the correct status
  $backorder_order->update_status( 'wc-shipping-progress' );
   // $backorder_order->update_status( 'on-hold' );

}

}
add_action( 'woocommerce_checkout_order_processed', 'action_woocommerce_checkout_order_processed', 10, 3 );

The code for the new custom status is this:

// Register New Order Statuses
function wpex_wc_register_post_statuses() {
    register_post_status( 'wc-shipping-progress', array(
        'label'                     => _x( 'Confirmar Stock', 'WooCommerce Order status', 'text_domain' ),
        'public'                    => true,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop( 'Approved (%s)', 'Approved (%s)', 'text_domain' )
    ) );
}
add_filter( 'init', 'wpex_wc_register_post_statuses' );

// Add New Order Statuses to WooCommerce
function wpex_wc_add_order_statuses( $order_statuses ) {
    $order_statuses['wc-shipping-progress'] = _x( 'Confirmar Stock', 'WooCommerce Order status', 'text_domain' );
    return $order_statuses;
}
add_filter( 'wc_order_statuses', 'wpex_wc_add_order_statuses' );

 So far the notification codes for a custom order have not worked.


问:
Obtaining libc function name (e.g., scanf) with Intel PIN Instrumentation
I'm trying to obtain a routine name for libc functions (e.g., scanf in this case) with the Intel PIN instrumentation. After trying a lot of ways, I am under the belief that this is difficult, but I figured to ask first.

For the sake of brevity, below is a minimal example of an input binary source code and Intel PIN instrumentation code of what I have tried, I feel that the result is close, yet missing the final detail.

Example source code (test.c):

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

void foo(char *buffer) {
    scanf("%s", buffer);
    printf("Unsafe gets: %s\n", buffer);

}

int main() {
    char *buf = malloc(sizeof(char)*50);
    foo(buf);
    return 0;
}
</code>```

Intel PIN instrumentation source code (test_pin.so):

```<code>VOID do_call(ADDRINT addr)
{
    printf("%p - %s\n", (void*)addr,  RTN_FindNameByAddress(addr).c_str());
    //fprintf(trace, "\n[%s]\n",  RTN_FindNameByAddress(addr).c_str()));
    //fflush(trace);
}

VOID Instruction(INS ins, VOID *v)
{
    if (INS_IsCall(ins))
    {
        if (INS_IsDirectBranchOrCall(ins))
        {
            const ADDRINT addr = INS_DirectBranchOrCallTargetAddress(ins);
            INS_InsertPredicatedCall(ins, IPOINT_BEFORE, AFUNPTR(do_call),
                IARG_PTR, addr, IARG_FUNCARG_CALLSITE_VALUE, 0, IARG_END);

        }
    }
}
int main(int argc, char **argv)
{
    /* initialize symbol processing */
    PIN_InitSymbols();
    /* initialize Pin; optimized branch */
    if (unlikely(PIN_Init(argc, argv)))
        /* Pin initialization failed */
        goto err;
    INS_AddInstrumentFunction(Instruction, 0);

    /* start Pin */
    PIN_StartProgram();

    /* typically not reached; make the compiler happy */
    return EXIT_SUCCESS;
}
</code>```

So the reason why I'm saying that I feel somewhat close is that running the above Intel PIN Instrumentation using the command pin -t test_pin.so -- ./test will result in the following output:

```<code>...
0x7f27aac14280 - brk
0x7f27aac142e0 - sbrk
0x7f27aab97a70 - pthread_attr_setschedparam
0x55a6dcbb8189 - foo
0x55a6dcbb8090 - .plt.sec
0x7f27aab63a00 - psiginfo
0x7f27aab91c30 - __uflow
0x7f27aab91e80 - _IO_doallocbuf
...
</code>```

where we can observe that two addresses start with 0x5 (to indicate that this is from the main application rather than calling from a shared library such as 0x7):

0x55a6dcbb8189 - foo

0x55a6dcbb8090 - .plt.sec

Doing additional investigation using objdump or gdb of the above source code example, it can be found that the entry address of foo function and the mystery target of .plt.sec from the Intel PIN is (after removing the relocation base address):

```<code>0000000000001189 <foo>:
   ...
 11ac:       e8 df fe ff ff          call   1090 <__isoc99_scanf@plt>
</code>```

So instead of getting the output of .plt.sec, is it possible to somehow resolve this mysterious .plt.sec name into __isoc99_scanf? I would appreciate any suggestions.

Body:
I'm trying to obtain a routine name for libc functions (e.g., scanf in this case) with the Intel PIN instrumentation. After trying a lot of ways, I am under the belief that this is difficult, but I figured to ask first.

For the sake of brevity, below is a minimal example of an input binary source code and Intel PIN instrumentation code of what I have tried, I feel that the result is close, yet missing the final detail.

Example source code (test.c):

#include <stdio.h>
#include <stdlib.h>

void foo(char *buffer) {
    scanf("%s", buffer);
    printf("Unsafe gets: %s\n", buffer);

}

int main() {
    char *buf = malloc(sizeof(char)*50);
    foo(buf);
    return 0;
}

Intel PIN instrumentation source code (test_pin.so):

VOID do_call(ADDRINT addr)
{
    printf("%p - %s\n", (void*)addr,  RTN_FindNameByAddress(addr).c_str());
    //fprintf(trace, "\n[%s]\n",  RTN_FindNameByAddress(addr).c_str()));
    //fflush(trace);
}

VOID Instruction(INS ins, VOID *v)
{
    if (INS_IsCall(ins))
    {
        if (INS_IsDirectBranchOrCall(ins))
        {
            const ADDRINT addr = INS_DirectBranchOrCallTargetAddress(ins);
            INS_InsertPredicatedCall(ins, IPOINT_BEFORE, AFUNPTR(do_call),
                IARG_PTR, addr, IARG_FUNCARG_CALLSITE_VALUE, 0, IARG_END);

        }
    }
}
int main(int argc, char **argv)
{
    /* initialize symbol processing */
    PIN_InitSymbols();
    /* initialize Pin; optimized branch */
    if (unlikely(PIN_Init(argc, argv)))
        /* Pin initialization failed */
        goto err;
    INS_AddInstrumentFunction(Instruction, 0);

    /* start Pin */
    PIN_StartProgram();

    /* typically not reached; make the compiler happy */
    return EXIT_SUCCESS;
}

So the reason why I'm saying that I feel somewhat close is that running the above Intel PIN Instrumentation using the command pin -t test_pin.so -- ./test will result in the following output:

...
0x7f27aac14280 - brk
0x7f27aac142e0 - sbrk
0x7f27aab97a70 - pthread_attr_setschedparam
0x55a6dcbb8189 - foo
0x55a6dcbb8090 - .plt.sec
0x7f27aab63a00 - psiginfo
0x7f27aab91c30 - __uflow
0x7f27aab91e80 - _IO_doallocbuf
...

where we can observe that two addresses start with 0x5 (to indicate that this is from the main application rather than calling from a shared library such as 0x7):

0x55a6dcbb8189 - foo

0x55a6dcbb8090 - .plt.sec

Doing additional investigation using objdump or gdb of the above source code example, it can be found that the entry address of foo function and the mystery target of .plt.sec from the Intel PIN is (after removing the relocation base address):

0000000000001189 <foo>:
   ...
 11ac:       e8 df fe ff ff          call   1090 <__isoc99_scanf@plt>

So instead of getting the output of .plt.sec, is it possible to somehow resolve this mysterious .plt.sec name into __isoc99_scanf? I would appreciate any suggestions.


问:
Is there a VBA to not only find if cell has data but transfer to if it does to another cell in different sheet?
I am creating an estimation calculator. I need to take certain data and transfer to specific cells so that when my sales team creates a quote, the estimate matches the current format used by accounting.

My current data is as follows

sheet name= Projects

on my Projects page I have

r7         s7              t7                  u7   v7    y7           z7
Date,      Item category , Description,        Qty, Unit, Item price , total price
12/6/2022, MISC,           MISC SALES DESCRIP, 2,   SET,   $15,$25
```
<p>on my Quote Page ( sheet6 is the page name in workbook) I need data to be displayed as</p>
<pre class="lang-txt prettyprint-override"><code>a16    b16                  g16            h16
Qty,   Description,         item price,    total price
2,     MISC SALES DESCRIP,  $15,$25
</code>```

The header of those columns shows where the data should be on the second page.

My problem

If the data in the first sheet is empty, then it needs to skip that and move to the next row with matching data and transfer it to the second sheet.

Some orders could have 1-2 row items, while others, 200 items. As it stands, I have an "If then" statement in the actual cell just so I can copy and paste the data to print it, vs. having it automatically placed and updated.

I currently have an "if then" statement in the second page. When I run my footer macro, I cannot get it to be on the last row -- as I need the data transposed, so I have to enter manually.

I've tried this just as a test to see if date was going to cycle and it did not:

```<code>    For Each cell In sheet6.Range("A16:A10000").Cells
        If IsEmpty(cell) = True Then cell.Value = projects.Range("u8").Cells: Exit For
    Next cell

Dim Last_Row As Long
Last_Row = Cells(Rows.Count, 1).End(xlUp).Row

With Sheet6.Shapes("FooterGrp2")
    .Left = Sheet6.Range("A16").Left
    .Top = Sheet6.Range("a" & Last_Row).Top
    .Width = Sheet6.Range("a:h").Width  '
    .Visible = msoCTrue
End With
Projects.PageSetup.PrintArea = "$A$16:$H$" & Last_Row + 2
Application.ScreenUpdating = True

</code>```

Body:
I am creating an estimation calculator. I need to take certain data and transfer to specific cells so that when my sales team creates a quote, the estimate matches the current format used by accounting.

My current data is as follows

sheet name= Projects

on my Projects page I have

r7         s7              t7                  u7   v7    y7           z7
Date,      Item category , Description,        Qty, Unit, Item price , total price
12/6/2022, MISC,           MISC SALES DESCRIP, 2,   SET,   $15,$25

on my Quote Page ( sheet6 is the page name in workbook) I need data to be displayed as

a16    b16                  g16            h16
Qty,   Description,         item price,    total price
2,     MISC SALES DESCRIP,  $15,$25

The header of those columns shows where the data should be on the second page.

My problem

If the data in the first sheet is empty, then it needs to skip that and move to the next row with matching data and transfer it to the second sheet.

Some orders could have 1-2 row items, while others, 200 items. As it stands, I have an "If then" statement in the actual cell just so I can copy and paste the data to print it, vs. having it automatically placed and updated.

I currently have an "if then" statement in the second page. When I run my footer macro, I cannot get it to be on the last row -- as I need the data transposed, so I have to enter manually.

I've tried this just as a test to see if date was going to cycle and it did not:

    For Each cell In sheet6.Range("A16:A10000").Cells
        If IsEmpty(cell) = True Then cell.Value = projects.Range("u8").Cells: Exit For
    Next cell

Dim Last_Row As Long
Last_Row = Cells(Rows.Count, 1).End(xlUp).Row

With Sheet6.Shapes("FooterGrp2")
    .Left = Sheet6.Range("A16").Left
    .Top = Sheet6.Range("a" & Last_Row).Top
    .Width = Sheet6.Range("a:h").Width  '
    .Visible = msoCTrue
End With
Projects.PageSetup.PrintArea = "$A$16:$H$" & Last_Row + 2
Application.ScreenUpdating = True


问:
Way to read non-CSV file (including strings and integers) separated with varied spaces
I'm trying to read everything from this text file into my heap in java.

```<code>
    Achernar       537 272
    Alcor          970  25
    Aldebaran      737 356
    Algol          900 325
    Almagest       990 235
    Alpha-Centauri 155  99
    Altair         450 650
    Antares        647 754
    Arcturus       964 579
    Belltrix       545 192
    Beta-Cassiopia 378 525
    Betelgeuse     412 377
    Canopus        218 150
    Capella        424   9
    Delta-Cygnus    42 472
    Deneb          218   8
    Epsilon-Ceti   271 471
    Epsilon-Cygnus  25 458
    Fomalhaut      437 856
    Gamma-Centauri 158 112
    Gamma-Cygnus    56 471
    Groombridge    996 904
    Hyperion       656 127
    Menkar         481 927
    Metis          570 460
    Microscopii    439 998
    Mizar           41 130
    Mu-Draconis    231 870
    Organon        685  58
    Pollux         565   9
    Procyon         74 227
    Regulus        373 106
    Rigel          210 208
    Siris          180 151
    Sol            175 145
    Theta-Persei   937 241
    Vega            33 975
    Vela           334 193
    Zeeman         335 194
    Zeta-Ptolemae  179  34
</code>```

The regex that I typically use for CSV files (",[ ]*") doesn't work, I've been trying to modify it a little but I'm not sure where to go with it.  Using the first line of the .txt as an example it should read Achernar as a String, 537 as a integer (x coordinate), and 272 as an integer (y coordinate).

I tried creating a String 'record', and splitting it into a String array 'tokens' with the using regex's like (""), (" "), and ("[ ]"), but when I try to read the the x coordinate after reading the string, I get an exception because the token array seems to be getting filled with spaces (instead of [Achernar, 537, 272] its something like [Achernar, , , , ... 537, 272].

I tried abandoning the token array and simply reading the inFile.hasNextLine() (which is what I'm using now) and there are no exceptions.. except it skips ever other entry in the text file because my parameter for the while loop is (inFile.hasNextLine()).  I understand why this doesn't work, though, because its not just checking the nextLine, it checking if it exists and skipping it entire if it is there.

^^ My current code using that technique

```<code>while (inFile.hasNextLine()) {
    entName = inFile.next();
    entX = inFile.nextInt();
    entY = inFile.nextInt();
    Astro temp = new Astro(entName, entX, entY);
    entDistance = temp.calculateDistance(x, y);
    heap.enqueue(new Astro(entName, entX, entY, entDistance));
}
</code>```

Body:
I'm trying to read everything from this text file into my heap in java.

    Achernar       537 272
    Alcor          970  25
    Aldebaran      737 356
    Algol          900 325
    Almagest       990 235
    Alpha-Centauri 155  99
    Altair         450 650
    Antares        647 754
    Arcturus       964 579
    Belltrix       545 192
    Beta-Cassiopia 378 525
    Betelgeuse     412 377
    Canopus        218 150
    Capella        424   9
    Delta-Cygnus    42 472
    Deneb          218   8
    Epsilon-Ceti   271 471
    Epsilon-Cygnus  25 458
    Fomalhaut      437 856
    Gamma-Centauri 158 112
    Gamma-Cygnus    56 471
    Groombridge    996 904
    Hyperion       656 127
    Menkar         481 927
    Metis          570 460
    Microscopii    439 998
    Mizar           41 130
    Mu-Draconis    231 870
    Organon        685  58
    Pollux         565   9
    Procyon         74 227
    Regulus        373 106
    Rigel          210 208
    Siris          180 151
    Sol            175 145
    Theta-Persei   937 241
    Vega            33 975
    Vela           334 193
    Zeeman         335 194
    Zeta-Ptolemae  179  34

The regex that I typically use for CSV files (",[ ]*") doesn't work, I've been trying to modify it a little but I'm not sure where to go with it.  Using the first line of the .txt as an example it should read Achernar as a String, 537 as a integer (x coordinate), and 272 as an integer (y coordinate).

I tried creating a String 'record', and splitting it into a String array 'tokens' with the using regex's like (""), (" "), and ("[ ]"), but when I try to read the the x coordinate after reading the string, I get an exception because the token array seems to be getting filled with spaces (instead of [Achernar, 537, 272] its something like [Achernar, , , , ... 537, 272].

I tried abandoning the token array and simply reading the inFile.hasNextLine() (which is what I'm using now) and there are no exceptions.. except it skips ever other entry in the text file because my parameter for the while loop is (inFile.hasNextLine()).  I understand why this doesn't work, though, because its not just checking the nextLine, it checking if it exists and skipping it entire if it is there.

^^ My current code using that technique

while (inFile.hasNextLine()) {
    entName = inFile.next();
    entX = inFile.nextInt();
    entY = inFile.nextInt();
    Astro temp = new Astro(entName, entX, entY);
    entDistance = temp.calculateDistance(x, y);
    heap.enqueue(new Astro(entName, entX, entY, entDistance));
}


问:
How does an auto refresh page extension works and how to recreate one with code?
I'm looking for a way to recreate the functionality of a refreshing page extension on a browser (e.g. Auto refresh plus in Chrome) by using javascript. The problem is that I have no ideia how to achieve that.
I must find a way to refresh the page every second or so, click on a link that appears on the page from time to time, add a sound effect for when it appears and send an e-mail notification every time it appears.

I'm trying to use a simple javascript snippet to run in the console in order to refresh the page:

```<code>win1 = window.open("https://www.myUrl.com/");
timer1 = setInterval(function(){win1.location.href="https://www.myUrl.com/"}, 1500);
</code>```

However, this implies running code from tab A on tab B which I found very challenging.
The code can't run on tab A alone because at the time it refreshes the page, it gets erased from the console.
I know it would have been so much easier to use an extension, but the platform I work for does not allowed any extensions.
I have basic HTML and javascript knowledge, but I find this would be a good project to learn more.
Also, if the solution involves other languages, I just need a direction to know where to look for and start this project.

Body:
I'm looking for a way to recreate the functionality of a refreshing page extension on a browser (e.g. Auto refresh plus in Chrome) by using javascript. The problem is that I have no ideia how to achieve that.
I must find a way to refresh the page every second or so, click on a link that appears on the page from time to time, add a sound effect for when it appears and send an e-mail notification every time it appears.

I'm trying to use a simple javascript snippet to run in the console in order to refresh the page:

win1 = window.open("https://www.myUrl.com/");
timer1 = setInterval(function(){win1.location.href="https://www.myUrl.com/"}, 1500);

However, this implies running code from tab A on tab B which I found very challenging.
The code can't run on tab A alone because at the time it refreshes the page, it gets erased from the console.
I know it would have been so much easier to use an extension, but the platform I work for does not allowed any extensions.
I have basic HTML and javascript knowledge, but I find this would be a good project to learn more.
Also, if the solution involves other languages, I just need a direction to know where to look for and start this project.


问:
Does TypeOrm automatically invalidate the cache?
I am working on a project which uses TypeOrm and I wanted to implement caching of database queries. Since TypeOrm supports caching directly by QueryBuilder.cache method, my code ended up looking something like this:

```<code>const items = this.itemsRepository
    .createQueryBuilder('item')
    .where('item.name = :name', { name })
    .cache(
        CacheKeyMaker.makeCacheKey('item', name), // generate cache key
        300000, // 5 minutes
    )
    .getMany();
</code>```

NOTE: I used ioredis as the cache driver

What I noticed then, after an insert or an update to the database, the cached keys were removed from the db (invalidated). Does TypeOrm cache automatically invalidate queries on each table after insert/update/delete? And if so, how "intelligent" is it? Does it only invalidate keys that were affected by the update? For example, if I query items with name="box" and then insert an item with a different name, will the cache still be invalidated (because the cache is actually still valid in this case).

I tried to manually test how TypeOrm cache invalidation works, but it seemed it's working inconsistently. I will be grateful for any knowledge, thanks in advance!

Body:
I am working on a project which uses TypeOrm and I wanted to implement caching of database queries. Since TypeOrm supports caching directly by QueryBuilder.cache method, my code ended up looking something like this:

const items = this.itemsRepository
    .createQueryBuilder('item')
    .where('item.name = :name', { name })
    .cache(
        CacheKeyMaker.makeCacheKey('item', name), // generate cache key
        300000, // 5 minutes
    )
    .getMany();

NOTE: I used ioredis as the cache driver

What I noticed then, after an insert or an update to the database, the cached keys were removed from the db (invalidated). Does TypeOrm cache automatically invalidate queries on each table after insert/update/delete? And if so, how "intelligent" is it? Does it only invalidate keys that were affected by the update? For example, if I query items with name="box" and then insert an item with a different name, will the cache still be invalidated (because the cache is actually still valid in this case).

I tried to manually test how TypeOrm cache invalidation works, but it seemed it's working inconsistently. I will be grateful for any knowledge, thanks in advance!


问:
why image.copy() return None
```<code>import numpy as np

def getSkewAngle(cvImage) -> float:
    # Prep image, copy, convert to gray scale, blur, and threshold
    newImage = cvImage.copy()
    gray = cv2.cvtColor(newImage, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (9, 9), 0)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    # Apply dilate to merge text into meaningful lines/paragraphs.
    # Use larger kernel on X axis to merge characters into single line, cancelling out any spaces.
    # But use smaller kernel on Y axis to separate between different blocks of text
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 5))
    dilate = cv2.dilate(thresh, kernel, iterations=2)

    # Find all contours
    contours, hierarchy = cv2.findContours(dilate, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key = cv2.contourArea, reverse = True)
    for c in contours:
        rect = cv2.boundingRect(c)
        x,y,w,h = rect
        cv2.rectangle(newImage,(x,y),(x+w,y+h),(0,255,0),2)

    # Find largest contour and surround in min area box
    largestContour = contours[0]
    print (len(contours))
    minAreaRect = cv2.minAreaRect(largestContour)
    cv2.imwrite("../img/boxes.jpg", newImage)
    # Determine the angle. Convert it to the value that was originally used to obtain skewed image
    angle = minAreaRect[-1]
    if angle < -45:
        angle = 90 + angle
    return -1.0 * angle
</code>```
```<code>def rotateImage(cvImage, angle: float):
    newImage = cvImage.copy()
    (h, w) = newImage.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    newImage = cv2.warpAffine(newImage, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    return newImage
</code>```
```<code>def deskew(cvImage):
    angle = getSkewAngle(cvImage)
    return rotateImage(cvImage, -1.0 * angle)
</code>```
```<code>new = cv2.imread("../img/incliné.png")
</code>```
```<code>fixed = deskew(new)  # error :'NoneType' object has no attribute 'copy'
</code>```

I tried to use np.copy(img) but it doesn't work
I tried to pass the path of image and use imread inside of the function but it does'nt work too
why cvImage.copy() return none and i had already used imread

Title: why image.copy() return None

Body:
import numpy as np

def getSkewAngle(cvImage) -> float:
    # Prep image, copy, convert to gray scale, blur, and threshold
    newImage = cvImage.copy()
    gray = cv2.cvtColor(newImage, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (9, 9), 0)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    # Apply dilate to merge text into meaningful lines/paragraphs.
    # Use larger kernel on X axis to merge characters into single line, cancelling out any spaces.
    # But use smaller kernel on Y axis to separate between different blocks of text
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 5))
    dilate = cv2.dilate(thresh, kernel, iterations=2)

    # Find all contours
    contours, hierarchy = cv2.findContours(dilate, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key = cv2.contourArea, reverse = True)
    for c in contours:
        rect = cv2.boundingRect(c)
        x,y,w,h = rect
        cv2.rectangle(newImage,(x,y),(x+w,y+h),(0,255,0),2)

    # Find largest contour and surround in min area box
    largestContour = contours[0]
    print (len(contours))
    minAreaRect = cv2.minAreaRect(largestContour)
    cv2.imwrite("../img/boxes.jpg", newImage)
    # Determine the angle. Convert it to the value that was originally used to obtain skewed image
    angle = minAreaRect[-1]
    if angle < -45:
        angle = 90 + angle
    return -1.0 * angle

def rotateImage(cvImage, angle: float):
    newImage = cvImage.copy()
    (h, w) = newImage.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    newImage = cv2.warpAffine(newImage, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    return newImage

def deskew(cvImage):
    angle = getSkewAngle(cvImage)
    return rotateImage(cvImage, -1.0 * angle)

new = cv2.imread("../img/incliné.png")

fixed = deskew(new)  # error :'NoneType' object has no attribute 'copy'

I tried to use np.copy(img) but it doesn't work
I tried to pass the path of image and use imread inside of the function but it does'nt work too
why cvImage.copy() return none and i had already used imread


问:
[JAVA]preventing specific duplicate elements from being added to a custom object arraylist
so lets say i have an class called customer with first and last name and username and password
i have another class called bankaccounts with account number and banlance;
and i have an arraylist of customers;
and i have a txt file that i need to read
and it contains the same customer sometimes

how do i make it so that the when its reading if the (first name,lastname,username)are the same
the program wii not add the customer to the list but instead will only add the account to the
existing customer in the list.

sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it

```<code>Bob, Mike, bobbmike, Ball!36Hi, 109001, Saving, 140.23, 0.05//good
Bob, Mike, bobbmike, Ball!36Hi, 109002, BasicChecking, 555.23//good
Mouse, Mickey, mickeymouse, MickCool890, ten, Saving, 89, 0.03//wrong numbber
Matt, Benjamin, jamimatt, Kit.24TT, 109201, InterestBearingChecking, 9000.00, 0.06//good
Keller, Helen, kel23hel, Poppins?89, 192911, Retirement, 11198.10//good
Mouse, Minnie, minniemouse, MinnCool19, 192922, Checking, 9000, 0.04//wrong type with interest
Keller, Helen, kel23hel, Poppins?89, 192912, InterestBearingChecking, 11198.10, 0.03//good
Tim, Mary, coolcats, Purr45??, 199122, BasicChecking, 201013.10//good
TheBuilder, Bob, bobbyNice18, 122101, Saving, 0.02//missing password, missing interest
</code>```
```<code>class Customer{
protected String firstName;
protected String lastName;
protected String username;
protected String password;
protected ArrayList<BasicAccount> accounts;

public void setLastName(String ln){this.lastName=ln;}
public String getLastName(){return lastName;}
public void setFirstName(String fn){this.firstName=fn;}
public String getFirstName(){return firstName;}
public void setUsername(String un){this.username=un;}
public String getUserName(){return username;}
public void setPassword(String pw){this.password=pw;}
public String getPassword(){return password;}

public Customer(){}

public Customer(String f,String l,String u,String p) throws Exception{
this.username=f;
this.lastName=l;
this.username=u;
this.password=p;
}

public void addAccount(BasicAccount a){
    this.accounts.add(a);

}

public void addAccount(String aType,float balance){
    BasicAccount a=new BasicAccount(aType,balance);

}

}
</code>```
```<code>class BasicAccount {
protected static int nextAvailableAccountNumber;
protected AccountType aType;
protected float balance;
protected int accountNum;

enum AccountType {BasicChecking, InterestBearingChecking, Saving, Retirement}

public BasicAccount(){};

public BasicAccount(String f,String l,String u,String p,int an,String type,float b){

}

public BasicAccount(Customer c,int a,String type,float b){

}
  public BasicAccount(int a,String type,float b){
this.accountNum=a;
this.aType=AccountType.valueOf(type);
this.balance=b;
nextAvailableAccountNumber=accountNum+1;
}

public BasicAccount(String f,String l, String u,String p,String type,float b){

}

public BasicAccount(Customer c,String type,float b){

}
  public BasicAccount(String type,float b){
this.accountNum=nextAvailableAccountNumber;
this.aType=AccountType.valueOf(type);
this.balance=b;
}

</code>```
```<code>public static void main(String[] args)throws IOException {
ArrayList<Customer>cc=new ArrayList<Customer>();
        Scanner k=new Scanner(System.in);
       out.println("please enter the filename");
       String filename=k.nextLine();
       File inFile=new File(filename);
       Scanner sc=new Scanner(inFile);

String error="";

ArrayList<String> errorLines=new ArrayList<String>();
while(sc.hasNext()){
    String line=sc.nextLine();
    try{

String []info=line.split(",");

if(info.length==7){
if(info[5].equals("BasicChecking")||info[5].equals("Retirement")){
Customer c=new Customer(info[0],info[1],info[2],info[3]);

BasicAccount act=new BasicAccount(c,Integer.parseInt(info[4]),info[5],Float.parseFloat(info[6]));

String [] user={c.firstName,c.lastName,c.username,c.password};

**for(Customer x:cc){

    if(x.contains(c.getFirstName())&&c.getLastName()%%c.getUserName){

   x.addAccount(act);

 }

else{
    c.addAccount(act);

cc.add(c);
}
}**//so if the customer object in the array list contains the same information from the
new Customer c it will only add the account to the x but if its not i will add to c and add
c to the arraylist but this doesn't work

}

else{

//error+="\n Wrong.";
//out.println(error);
}

}

}

catch(Exception e){
    error+="\n wrong";
errorLines.add(line);
out.println("wrong data");
    }
}
out.println(error);
if(errorLines.size()==0){}

else{
out.println(errorLines);
}

out.println(errorLines);

}
}

Main.java:277: error: cannot find symbol
    if(x.contains(c.getFirstName())&&c.getLastName()){
        ^
  symbol:   method contains(String)
  location: variable x of type Customer
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

</code>```

sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it

Body:
so lets say i have an class called customer with first and last name and username and password
i have another class called bankaccounts with account number and banlance;
and i have an arraylist of customers;
and i have a txt file that i need to read
and it contains the same customer sometimes

how do i make it so that the when its reading if the (first name,lastname,username)are the same
the program wii not add the customer to the list but instead will only add the account to the
existing customer in the list.

sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it

Bob, Mike, bobbmike, Ball!36Hi, 109001, Saving, 140.23, 0.05//good
Bob, Mike, bobbmike, Ball!36Hi, 109002, BasicChecking, 555.23//good
Mouse, Mickey, mickeymouse, MickCool890, ten, Saving, 89, 0.03//wrong numbber
Matt, Benjamin, jamimatt, Kit.24TT, 109201, InterestBearingChecking, 9000.00, 0.06//good
Keller, Helen, kel23hel, Poppins?89, 192911, Retirement, 11198.10//good
Mouse, Minnie, minniemouse, MinnCool19, 192922, Checking, 9000, 0.04//wrong type with interest
Keller, Helen, kel23hel, Poppins?89, 192912, InterestBearingChecking, 11198.10, 0.03//good
Tim, Mary, coolcats, Purr45??, 199122, BasicChecking, 201013.10//good
TheBuilder, Bob, bobbyNice18, 122101, Saving, 0.02//missing password, missing interest

class Customer{
protected String firstName;
protected String lastName;
protected String username;
protected String password;
protected ArrayList<BasicAccount> accounts;

public void setLastName(String ln){this.lastName=ln;}
public String getLastName(){return lastName;}
public void setFirstName(String fn){this.firstName=fn;}
public String getFirstName(){return firstName;}
public void setUsername(String un){this.username=un;}
public String getUserName(){return username;}
public void setPassword(String pw){this.password=pw;}
public String getPassword(){return password;}

public Customer(){}

public Customer(String f,String l,String u,String p) throws Exception{
this.username=f;
this.lastName=l;
this.username=u;
this.password=p;
}

public void addAccount(BasicAccount a){
    this.accounts.add(a);

}

public void addAccount(String aType,float balance){
    BasicAccount a=new BasicAccount(aType,balance);

}

}

class BasicAccount {
protected static int nextAvailableAccountNumber;
protected AccountType aType;
protected float balance;
protected int accountNum;

enum AccountType {BasicChecking, InterestBearingChecking, Saving, Retirement}

public BasicAccount(){};

public BasicAccount(String f,String l,String u,String p,int an,String type,float b){

}

public BasicAccount(Customer c,int a,String type,float b){

}
  public BasicAccount(int a,String type,float b){
this.accountNum=a;
this.aType=AccountType.valueOf(type);
this.balance=b;
nextAvailableAccountNumber=accountNum+1;
}

public BasicAccount(String f,String l, String u,String p,String type,float b){

}

public BasicAccount(Customer c,String type,float b){

}
  public BasicAccount(String type,float b){
this.accountNum=nextAvailableAccountNumber;
this.aType=AccountType.valueOf(type);
this.balance=b;
}

public static void main(String[] args)throws IOException {
ArrayList<Customer>cc=new ArrayList<Customer>();
        Scanner k=new Scanner(System.in);
       out.println("please enter the filename");
       String filename=k.nextLine();
       File inFile=new File(filename);
       Scanner sc=new Scanner(inFile);

String error="";

ArrayList<String> errorLines=new ArrayList<String>();
while(sc.hasNext()){
    String line=sc.nextLine();
    try{

String []info=line.split(",");

if(info.length==7){
if(info[5].equals("BasicChecking")||info[5].equals("Retirement")){
Customer c=new Customer(info[0],info[1],info[2],info[3]);

BasicAccount act=new BasicAccount(c,Integer.parseInt(info[4]),info[5],Float.parseFloat(info[6]));

String [] user={c.firstName,c.lastName,c.username,c.password};

**for(Customer x:cc){

    if(x.contains(c.getFirstName())&&c.getLastName()%%c.getUserName){

   x.addAccount(act);

 }

else{
    c.addAccount(act);

cc.add(c);
}
}**//so if the customer object in the array list contains the same information from the
new Customer c it will only add the account to the x but if its not i will add to c and add
c to the arraylist but this doesn't work

}

else{

//error+="\n Wrong.";
//out.println(error);
}

}

}

catch(Exception e){
    error+="\n wrong";
errorLines.add(line);
out.println("wrong data");
    }
}
out.println(error);
if(errorLines.size()==0){}

else{
out.println(errorLines);
}

out.println(errorLines);

}
}

Main.java:277: error: cannot find symbol
    if(x.contains(c.getFirstName())&&c.getLastName()){
        ^
  symbol:   method contains(String)
  location: variable x of type Customer
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it


问:
SCSS fix for PrimeNG `pFocusTrap` bug when parent of focusable element is hidden
I found a bug in PrimeNG pFocusTrap.
Basically when tabbing through focusable elements, focus will get stuck on an element whose ancestor is display:none. Here is my fix:

```<code>$displays: inline inline-block block grid table table-cell table-row flex inline-flex;
$tabbable: 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]';

@function d-size($size) {
    $ret: ();
    @each $n in $displays {
       $ret: append($ret,'.d-'+$size+'-'+$n,'comma');
    }
    @return $ret;
}

.d-none:not(#{d-size('sm')},#{d-size('md')},#{d-size('lg')},#{d-size('xl')}) *:is(#{$tabbable}),
.d-sm-none:not(#{d-size('md')},#{d-size('lg')},#{d-size('xl')}) *:is(#{$tabbable}),
.d-md-none:not(#{d-size('lg')},#{d-size('xl')}) *:is(#{$tabbable}),
.d-lg-none:not(#{d-size('xl')}) *:is(#{$tabbable}),
.d-xl-none *:is(#{$tabbable})
{
  display: none !important;
}
</code>```

Basically it applies display:none to any tabbable descendant of any elements that are using bootstraps d-xx-none utility.

My question is: I'm pretty new to SCSS, but is there any way to refactor and optimize the lines of code, and are there any bugs I may have overlooked?

Body:
I found a bug in PrimeNG pFocusTrap.
Basically when tabbing through focusable elements, focus will get stuck on an element whose ancestor is display:none. Here is my fix:

$displays: inline inline-block block grid table table-cell table-row flex inline-flex;
$tabbable: 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]';

@function d-size($size) {
    $ret: ();
    @each $n in $displays {
       $ret: append($ret,'.d-'+$size+'-'+$n,'comma');
    }
    @return $ret;
}

.d-none:not(#{d-size('sm')},#{d-size('md')},#{d-size('lg')},#{d-size('xl')}) *:is(#{$tabbable}),
.d-sm-none:not(#{d-size('md')},#{d-size('lg')},#{d-size('xl')}) *:is(#{$tabbable}),
.d-md-none:not(#{d-size('lg')},#{d-size('xl')}) *:is(#{$tabbable}),
.d-lg-none:not(#{d-size('xl')}) *:is(#{$tabbable}),
.d-xl-none *:is(#{$tabbable})
{
  display: none !important;
}

Basically it applies display:none to any tabbable descendant of any elements that are using bootstraps d-xx-none utility.

My question is: I'm pretty new to SCSS, but is there any way to refactor and optimize the lines of code, and are there any bugs I may have overlooked?


问:
Merge arrays of a nested struct after groupBy/aggregation
I have a schema like this:

```<code>root
 |-- first_name: string (nullable = true)
 |-- medical_group: struct (nullable = true)
 |    |-- address: struct (nullable = true)
 |    |    |-- phone_number: string (nullable = true)
 |    |    |-- city: string (nullable = true)
 |    |    |-- state: string (nullable = true)
 |    |    |-- address2: string (nullable = true)
 |    |    |-- zip: string (nullable = true)
 |    |    |-- secondary_phone_number: string (nullable = true)
 |    |    |-- address1: string (nullable = true)
 |    |-- offices: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- address: struct (nullable = true)
 |    |    |    |    |-- phone_number: string (nullable = true)
 |    |    |    |    |-- city: string (nullable = true)
 |    |    |    |    |-- state: string (nullable = true)
 |    |    |    |    |-- address2: string (nullable = true)
 |    |    |    |    |-- zip: string (nullable = true)
 |    |    |    |    |-- secondary_phone_number: string (nullable = true)
 |    |    |    |    |-- address1: string (nullable = true)
 |    |    |    |-- name: string (nullable = true)
 |    |-- unique_id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |-- unique_id: string (nullable = true)
 |-- last_name: string (nullable = true)
</code>```

And I'm trying to groupBy/aggregate the data by key1 and key2. The aggregation process is to remove duplicate rows in the DataFrame primarily, as well as aggregate the array of offices.

```<code>agg_list = [
    first("first_name").alias("first_name"),
    first("last_name").alias("last_name"),
    first("medical_group").alias("medical_group"),
    # Maybe this? collect_list("medical_group.offices").alias("mg.offices")
]

provider_structs_grouped = \
    provider_structs_structure \
        .groupBy(col('unique_id'), col('medical_group.unique_id')) \
        .agg(*agg_list)
</code>```

I thought I could create a temporary column that uses collect_list, update the nested struct's offices value, and then drop the temporary column, but I was struggling to update the nested struct's value.

Question: How can I aggregate/collect_list the offices, and update the nested offices array with that latest value? (Or perhaps there's a better way?)

Body:
I have a schema like this:

root
 |-- first_name: string (nullable = true)
 |-- medical_group: struct (nullable = true)
 |    |-- address: struct (nullable = true)
 |    |    |-- phone_number: string (nullable = true)
 |    |    |-- city: string (nullable = true)
 |    |    |-- state: string (nullable = true)
 |    |    |-- address2: string (nullable = true)
 |    |    |-- zip: string (nullable = true)
 |    |    |-- secondary_phone_number: string (nullable = true)
 |    |    |-- address1: string (nullable = true)
 |    |-- offices: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- address: struct (nullable = true)
 |    |    |    |    |-- phone_number: string (nullable = true)
 |    |    |    |    |-- city: string (nullable = true)
 |    |    |    |    |-- state: string (nullable = true)
 |    |    |    |    |-- address2: string (nullable = true)
 |    |    |    |    |-- zip: string (nullable = true)
 |    |    |    |    |-- secondary_phone_number: string (nullable = true)
 |    |    |    |    |-- address1: string (nullable = true)
 |    |    |    |-- name: string (nullable = true)
 |    |-- unique_id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |-- unique_id: string (nullable = true)
 |-- last_name: string (nullable = true)

And I'm trying to groupBy/aggregate the data by key1 and key2. The aggregation process is to remove duplicate rows in the DataFrame primarily, as well as aggregate the array of offices.

agg_list = [
    first("first_name").alias("first_name"),
    first("last_name").alias("last_name"),
    first("medical_group").alias("medical_group"),
    # Maybe this? collect_list("medical_group.offices").alias("mg.offices")
]

provider_structs_grouped = \
    provider_structs_structure \
        .groupBy(col('unique_id'), col('medical_group.unique_id')) \
        .agg(*agg_list)

I thought I could create a temporary column that uses collect_list, update the nested struct's offices value, and then drop the temporary column, but I was struggling to update the nested struct's value.

Question: How can I aggregate/collect_list the offices, and update the nested offices array with that latest value? (Or perhaps there's a better way?)


问:
IAM Policy self Managed MFA - How to allow only changes to their own MFA Device?
I am reading through these docs https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html and it states the following policy should be used to allow a user to manage their own MFA Devices:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowListActions",
            "Effect": "Allow",
            "Action": [
                "iam:ListUsers",
                "iam:ListVirtualMFADevices"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowIndividualUserToManageTheirOwnMFA",
            "Effect": "Allow",
            "Action": [
                "iam:CreateVirtualMFADevice",
                "iam:DeleteVirtualMFADevice",
                "iam:ListMFADevices",
                "iam:EnableMFADevice",
                "iam:ResyncMFADevice"
            ],
            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ]
        },
        {
            "Sid": "AllowIndividualUserToDeactivateOnlyTheirOwnMFAOnlyWhenUsingMFA",
            "Effect": "Allow",
            "Action": [
                "iam:DeactivateMFADevice"
            ],
            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ],
            "Condition": {
                "Bool": {
                    "aws:MultiFactorAuthPresent": "true"
                }
            }
        },
        {
            "Sid": "BlockMostAccessUnlessSignedInWithMFA",
            "Effect": "Deny",
            "NotAction": [
                "iam:CreateVirtualMFADevice",
                "iam:EnableMFADevice",
                "iam:ListMFADevices",
                "iam:ListUsers",
                "iam:ListVirtualMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "*",
            "Condition": {
                "BoolIfExists": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
        }
    ]
}
</code>```

We are using this policy at $dayjob and recently discovered that AWS IAM now allows you to change the name of your MFA device, and attach multiple MFA devices. A user recently added a new MFA device but named it something arbitrary, and as expected, this policy no longer works.

How would you then allow a user to only manage their own MFA devices even if they are arbitrarily named?

Would modifying

```<code>            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ]
</code>```

to something like

```<code>            "Resource": [
                "arn:aws:iam::*:mfa/*",
                "arn:aws:iam::*:user/${aws:username}"
            ]
</code>```

Allow the user to modify other IAM User's MFA devices? Or is there a way to add a Condition to solve for this scenario?

Body:
I am reading through these docs https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html and it states the following policy should be used to allow a user to manage their own MFA Devices:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowListActions",
            "Effect": "Allow",
            "Action": [
                "iam:ListUsers",
                "iam:ListVirtualMFADevices"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowIndividualUserToManageTheirOwnMFA",
            "Effect": "Allow",
            "Action": [
                "iam:CreateVirtualMFADevice",
                "iam:DeleteVirtualMFADevice",
                "iam:ListMFADevices",
                "iam:EnableMFADevice",
                "iam:ResyncMFADevice"
            ],
            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ]
        },
        {
            "Sid": "AllowIndividualUserToDeactivateOnlyTheirOwnMFAOnlyWhenUsingMFA",
            "Effect": "Allow",
            "Action": [
                "iam:DeactivateMFADevice"
            ],
            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ],
            "Condition": {
                "Bool": {
                    "aws:MultiFactorAuthPresent": "true"
                }
            }
        },
        {
            "Sid": "BlockMostAccessUnlessSignedInWithMFA",
            "Effect": "Deny",
            "NotAction": [
                "iam:CreateVirtualMFADevice",
                "iam:EnableMFADevice",
                "iam:ListMFADevices",
                "iam:ListUsers",
                "iam:ListVirtualMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": "*",
            "Condition": {
                "BoolIfExists": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
        }
    ]
}

We are using this policy at $dayjob and recently discovered that AWS IAM now allows you to change the name of your MFA device, and attach multiple MFA devices. A user recently added a new MFA device but named it something arbitrary, and as expected, this policy no longer works.

How would you then allow a user to only manage their own MFA devices even if they are arbitrarily named?

Would modifying

            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ]

to something like

            "Resource": [
                "arn:aws:iam::*:mfa/*",
                "arn:aws:iam::*:user/${aws:username}"
            ]

Allow the user to modify other IAM User's MFA devices? Or is there a way to add a Condition to solve for this scenario?


问:
FPU on STM32 Cortex-M4
This is going to be very easy for anybody who knows it, but I can't find the answer in any of the docs I have.   I'm trying to find the easiest way to load floating literals to the FPU.

I have done extensive development on ARM7, and lately Cortex-M4 and M7 STM32 CPU types, always using no OS, pure assembly.  Right now I am working on an M4 (STM32L4P5).    I am a newbie with the FPU, though, and trying to come up to speed fast.   I am using the GCC assembler, and have the "-mfpu=vfpv4" switch in my build file.

I can enable the FPU, and then load it with literals like so:

```<code>ldr           r0,=15
vmov          s0,r0
vcvt.f32.u32  s0,s0
</code>```

and then do math...all that works fine.

I can also load in more difficult floats like so:

```<code>vldr.f32    s1,zip
vldr.f32    s2,zap

zip:  .float  3.14159
zap:  .float  1.234e8
</code>```

And that works fine as well.  The assembler does the conversion to floating representation, so this is actually more efficient at runtime.

What I'm looking for now is (I'm going to feel stupid) the equivalent
of the common

```<code>ldr  r0,=15
</code>```

but directly loading the FPU registers.  For example, Zhu's book "Embedded Systems with ARM Cortex-M" says that I should be able to do

```<code>vldr.f32  s0,=3.14159
</code>```

but the gcc assembler won't take that.  how do I represent a decimal number in an inline literal like that?

Title: FPU on STM32 Cortex-M4

Body:
This is going to be very easy for anybody who knows it, but I can't find the answer in any of the docs I have.   I'm trying to find the easiest way to load floating literals to the FPU.

I have done extensive development on ARM7, and lately Cortex-M4 and M7 STM32 CPU types, always using no OS, pure assembly.  Right now I am working on an M4 (STM32L4P5).    I am a newbie with the FPU, though, and trying to come up to speed fast.   I am using the GCC assembler, and have the "-mfpu=vfpv4" switch in my build file.

I can enable the FPU, and then load it with literals like so:

ldr           r0,=15
vmov          s0,r0
vcvt.f32.u32  s0,s0

and then do math...all that works fine.

I can also load in more difficult floats like so:

vldr.f32    s1,zip
vldr.f32    s2,zap

zip:  .float  3.14159
zap:  .float  1.234e8

And that works fine as well.  The assembler does the conversion to floating representation, so this is actually more efficient at runtime.

What I'm looking for now is (I'm going to feel stupid) the equivalent
of the common

ldr  r0,=15

but directly loading the FPU registers.  For example, Zhu's book "Embedded Systems with ARM Cortex-M" says that I should be able to do

vldr.f32  s0,=3.14159

but the gcc assembler won't take that.  how do I represent a decimal number in an inline literal like that?


问:
socket.io cannot find module socket.io-parser
I've been working on a React App with a few others and it has been working great up until we added a .gitignore file and merged branches of the project which may have had different node packages installed. Anyway I'm trying to get all of the correct node packages install so I can get the app up and running again but I can't figure this one out.

When I run npm install in the working directory I get this error message.

node_modules/@types/socket.io/index.d.ts:20:68 - error TS2307: Cannot find module 'socket.io-parser' or its corresponding type declarations.

I have uninstalled and reinstalled socket.io and socket.io-parser with npm commands and that doesn't seem to help. What's worse is that I can look through my node packages and see that socket.io parser is clearly installed and is sitting there right next to socket.io yet socket.io doesn't seem to recognize it. In fact, I went back to previous versions of the app, and copied and pasted the package.json files and node_modules to the new version manually but npm install still gives me that error. in the socket.io/index.js files I see the following line has the error shown at the bottom: where 'socket.io-parser' is underlined in the line shown at the bottom below and the error message says: "Cannot find module 'socket.io-parser' or its corresponding type declarations.ts(2307)"

20 import { Encoder as ParserEncoder, Decoder as ParserDecoder } from 'socket.io-parser';


问:
BOA: Layer error: List.get: List is empty (index is 0). when trying to transform landsat 8 composite ToA to BoA in Google Earth Engine
I am trying to compute BoA from a Landsat 8 composite image. However, I am getting the following error:

BOA: Layer error: List.get: List is empty (index is 0). I would appreciate any suggestions.

Cheers,

https://code.earthengine.google.com/5ec5e2703da350014565b5a661fbbb6e

I am expecting to get BoA of a composite Landsat 8 image. I haven't been able to find a solution out there.

```<code>var Infra = {min: 0, max: 0.35, bands: ['B5', 'B4', 'B3']};
//////////////      Load landsat 8 FOR 2018    ///////////////////

var image2018 = ee.ImageCollection('LANDSAT/LC08/C02/T1')
.filterBounds(AOI)
.select(['B1','B2','B3','B4','B5','B6','B7','B8','B9','B10','B11']);

 // SimpleComposite

 var composite2018 =  ee.Algorithms.Landsat.simpleComposite({
   collection : image2018.filterDate('2016-06-01', '2018-11-30'),
   asFloat: true
 });
 Map.addLayer(composite2018.clip(AOI), Infra, '2018 composite');
print("image2018", image2018);

/// - Import the SIAC atmospheric correction module
var siac = require('users/marcyinfeng/utils:SIAC');

// - Apply SIAC and retrieve bottom of atmosphere (BOA) reflectance
//var L7_boa = siac.get_l7_sur(L7_col.first());
var L8_boa = siac.get_l8_sur(composite2018);
//var S2_boa = siac.get_sur(S2_col.first());

// - Check and visualization
var Color_comp_01 = {bands:"B4,B3,B2", min: 0.0, max: 0.2, gamma: 1};
//var Color_comp =    {bands:"B4,B3,B2", min:200, max:2000, gamma: 1};
//Map.addLayer(img, Color_comp, 'TOA');
Map.addLayer(L8_boa, Color_comp_01, 'BOA');
//Map.centerObject(L8_boa)
Map.centerObject(AOI)

</code>```

Body:
I am trying to compute BoA from a Landsat 8 composite image. However, I am getting the following error:

BOA: Layer error: List.get: List is empty (index is 0). I would appreciate any suggestions.

Cheers,

https://code.earthengine.google.com/5ec5e2703da350014565b5a661fbbb6e

I am expecting to get BoA of a composite Landsat 8 image. I haven't been able to find a solution out there.

var Infra = {min: 0, max: 0.35, bands: ['B5', 'B4', 'B3']};
//////////////      Load landsat 8 FOR 2018    ///////////////////

var image2018 = ee.ImageCollection('LANDSAT/LC08/C02/T1')
.filterBounds(AOI)
.select(['B1','B2','B3','B4','B5','B6','B7','B8','B9','B10','B11']);

 // SimpleComposite

 var composite2018 =  ee.Algorithms.Landsat.simpleComposite({
   collection : image2018.filterDate('2016-06-01', '2018-11-30'),
   asFloat: true
 });
 Map.addLayer(composite2018.clip(AOI), Infra, '2018 composite');
print("image2018", image2018);

/// - Import the SIAC atmospheric correction module
var siac = require('users/marcyinfeng/utils:SIAC');

// - Apply SIAC and retrieve bottom of atmosphere (BOA) reflectance
//var L7_boa = siac.get_l7_sur(L7_col.first());
var L8_boa = siac.get_l8_sur(composite2018);
//var S2_boa = siac.get_sur(S2_col.first());

// - Check and visualization
var Color_comp_01 = {bands:"B4,B3,B2", min: 0.0, max: 0.2, gamma: 1};
//var Color_comp =    {bands:"B4,B3,B2", min:200, max:2000, gamma: 1};
//Map.addLayer(img, Color_comp, 'TOA');
Map.addLayer(L8_boa, Color_comp_01, 'BOA');
//Map.centerObject(L8_boa)
Map.centerObject(AOI)


问:
How do I get my implementation of a NavigationServiceDelegate function to be called?
I'm building an iOS app with SwiftUI and am using Mapbox's NavigationViewController to provide turn-by-turn navigation instructions. I'd like to have custom code run when the visual instructions are updated in the navigation view, but my attempts at implementing the relevant delegate methods aren't getting called.

In Mapbox's online guide, it says it's possible to listen for changes to visual instructions when NavigationServiceDelegate.navigationService(_:didPassVisualInstructionPoint:routeProgress:) is called. So I created a MapboxNavigationService, assigned the coordinator as the service's delegate, and then added the service to the NavigationViewController via NavigationOptions. However, when I run the app and the Navigation View comes up complete with visual and audio instructions, nothing is printed and it seems that the delegate functions I implemented in the Coordinator are never run.

Can anyone help me figure out how to hook into the NavigationService callbacks?

Here's my UIViewControllerRepresentable implementation for reference:

```<code>struct NavView: UIViewControllerRepresentable {
    @ObservedObject var mapData: MapViewModel

    func makeUIViewController(context: Context) -> NavigationViewController {

        let indexedRouteResponse = IndexedRouteResponse(routeResponse: mapData.routeResponse!,routeIndex: 0)

        // Create a NavigationService and attach a delegate
        let navigationService = MapboxNavigationService(indexedRouteResponse: indexedRouteResponse, credentials: NavigationSettings.shared.directions.credentials)
        navigationService.delegate = context.coordinator

        let navOptions = NavigationOptions(navigationService: navigationService)

        let navViewController = NavigationViewController(for: indexedRouteResponse, navigationOptions: navOptions)

        return navViewController
    }

    func updateUIViewController(_ uiViewController: NavigationViewController, context: Context) {}

    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }

    class Coordinator: NSObject, NavigationServiceDelegate {
        func navigationService(_ service: NavigationService, didPassVisualInstructionPoint instruction: VisualInstructionBanner, routeProgress: RouteProgress) {
            print("Visual Instruction") // Not getting called
        }

        func navigationService(_ service: NavigationService, didPassSpokenInstructionPoint instruction: SpokenInstruction, routeProgress: RouteProgress) {
            print("Spoken Instruction") // Not getting called
        }
    }
}
</code>```

Body:
I'm building an iOS app with SwiftUI and am using Mapbox's NavigationViewController to provide turn-by-turn navigation instructions. I'd like to have custom code run when the visual instructions are updated in the navigation view, but my attempts at implementing the relevant delegate methods aren't getting called.

In Mapbox's online guide, it says it's possible to listen for changes to visual instructions when NavigationServiceDelegate.navigationService(_:didPassVisualInstructionPoint:routeProgress:) is called. So I created a MapboxNavigationService, assigned the coordinator as the service's delegate, and then added the service to the NavigationViewController via NavigationOptions. However, when I run the app and the Navigation View comes up complete with visual and audio instructions, nothing is printed and it seems that the delegate functions I implemented in the Coordinator are never run.

Can anyone help me figure out how to hook into the NavigationService callbacks?

Here's my UIViewControllerRepresentable implementation for reference:

struct NavView: UIViewControllerRepresentable {
    @ObservedObject var mapData: MapViewModel

    func makeUIViewController(context: Context) -> NavigationViewController {

        let indexedRouteResponse = IndexedRouteResponse(routeResponse: mapData.routeResponse!,routeIndex: 0)

        // Create a NavigationService and attach a delegate
        let navigationService = MapboxNavigationService(indexedRouteResponse: indexedRouteResponse, credentials: NavigationSettings.shared.directions.credentials)
        navigationService.delegate = context.coordinator

        let navOptions = NavigationOptions(navigationService: navigationService)

        let navViewController = NavigationViewController(for: indexedRouteResponse, navigationOptions: navOptions)

        return navViewController
    }

    func updateUIViewController(_ uiViewController: NavigationViewController, context: Context) {}

    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }

    class Coordinator: NSObject, NavigationServiceDelegate {
        func navigationService(_ service: NavigationService, didPassVisualInstructionPoint instruction: VisualInstructionBanner, routeProgress: RouteProgress) {
            print("Visual Instruction") // Not getting called
        }

        func navigationService(_ service: NavigationService, didPassSpokenInstructionPoint instruction: SpokenInstruction, routeProgress: RouteProgress) {
            print("Spoken Instruction") // Not getting called
        }
    }
}