text:
Q: Data acquisition of AWS IoT Aanalytics I would like to obtain the latest data by specifying Lambda's IoT Analytics dataset.
If you use getDatasetContent of IoTAnalytics of aws sdk, only the link for downloading the file will be returned.
Data itself can not be acquired.
I would like to know how to obtain information on the IoT Analytics data set from Lambda.

A: Hi and welcome to Stack Overflow!
If I understand your question correctly, you are asking how to get the data from an IoT Analytics Dataset using a Lambda function?
You are correct that get_dataset_content only returns the URI, but it is simple to then fetch the actual content, for example in Python it would look like this;
# Code Fragment to retrieve content from IoT Analytics Dataset

iota = boto3.client('iotanalytics')
response = iota.get_dataset_content(datasetName='my_data_set',versionId='$LATEST')
contentState = response['status']['state']

if (contentState == 'SUCCEEDED') :
    url = response['entries'][0]['dataURI']
    stream = urllib.request.urlopen(url)
    reader = csv.DictReader(codecs.iterdecode(stream, 'utf-8'))

    for record in reader:
        # Process the record as desired, you can refer to columns in the CSV
        # by using record['column_name'] using the DictReader iterator

Note that this code is specifically looking at the most recent results using the $LATEST version - you can also look for the $LATEST_SUCCEEDED version.
There's more documentation here for Boto - the AWS Python SDK, but you can use the same approach in all other sdk supported languages.
Hope that helps,
Roger


text:
Q: PIXI js, sprite not showing, no errors I have the following code:
var viewWidth, viewHeight, renderer, stage, loader;
var rendererOptions = {
    transparent: true
};

function init () {
    viewWidth = window.innerWidth;
    viewHeight = window.innerHeight;
    renderer = PIXI.autoDetectRenderer(viewWidth, viewHeight, rendererOptions);
    renderer.view.className = "rendererView";

    // add to DOM
    document.body.appendChild(renderer.view);

    // create stage
    stage = new PIXI.Container();
    stage.width = viewWidth;
    stage.height = viewHeight;
    stage.alpha = 0;

    // load images
    loader = PIXI.loader;

    loader.add("images/bg.jpg");
    loader.once("complete", onAssetsLoaded);
    loader.load();
}

function onAssetsLoaded () {
    console.log("assets loaded");

    createElements();
    update();
}

function createElements () {
    console.log("create elements");
    var bg = new PIXI.Sprite.fromImage("images/bg.jpg");

    bg.position.x = 200;
    bg.position.y = 200;

    stage.addChild(bg);
}

function update () {
    render();
    requestAnimationFrame(update);
}

function render () {
    renderer.render(stage);
}

But my sprite is not showing up. It's just a blank canvas. I've checked the network tab in chrome, it is being loaded. Logging the stage, it has one child; the sprite, which has a correct baseUrl and everything. But it's just blank. And i've put this on my webserver.
I've hit a wall. Does anyone have any idea what this might be? I'm using the latest version of Pixi, 3.0.
Thanks!

A: Solved it, it was my bad. I didn't realize I had set the alpha of the stage to 0...

A: I don't know much but I think you have to load image to texture and then load that to sprite.

A: Or maybe it's PIXI.loaders.Loader, not PIXI.loader

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ethernet adapter broken after VMWare deinstallation Unfortunately I cannot connect over LAN anymore after i deinstalled the VMWare Workstation Player.
The error just says "network cable unplugged". Which is obviously wrong.
What I've already did:

*

*Rebooting

*Updating the ethernet driver

*Removing the adapter with and without the driver

*Resetting all network settings

I'm pretty clueless at the moment.

A: Thanks for the downvotes ;)
I fixed it by booting into linux. It somehow re-initiated the ethernet port.


text:
Q: Laravel 9 - Constrain the data returned into index after search generated I have created a custom index blade which return orders.
When loaded the data are filtered with the status of the order. status_id is equal to 2.
if($user_role_id == 5){
                $orders->whereJsonContains('order_items.laboratory_id', ['1']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->whereNull('order_items.deleted_at');
            } else if($user_role_id == 6){
                $orders->whereJsonContains('order_items.laboratory_id', ['2']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->where('order_items.deleted_at', '=', NULL);
            } else if ...

The data are loaded and displayed correctly.

When I search a term inside the returned rows and columns,

the data are returned accordingly (means only the order having the search term into one or several columns are returned)

but also the order with a status_id different of 2. You can see in the above picture the left dropdown in black is in fact an order with a status_id equal to 3 (which mean order processed).
I have tried several things :
...
$orders  = $orders->whereIn('order_items.status_id', [2])->paginate(10);
...

$orders->where('order_items.status_id', [2]);

Would appreciate your expertise. Thanks.
Method
    /**
     * Display a listing of the orders filtered with status_id == 2
     *
     * @param  \App\Http\Requests  $request
     * @return \Illuminate\View\View
     */
    public function orderManagement(Request $request)
    {
        $staffs = $this->getStaffs();
        $laboratory_staffs = $this->getLaboratorystaffs();
        $status_orders = $this->getStatusorders();
        $user_role_id = $this->getUserRoleId();

        $term = $request->search_term;

        $orders = DB::table('order_items');
        $orders->leftJoin('order_status','order_items.status_id', '=', 'order_status.id');
        $orders->leftJoin('users AS users_a','order_items.orderer_id', '=', 'users_a.id');
        $orders->leftJoin('users AS users_b','order_items.customer_id', '=', 'users_b.id');
        $orders->leftJoin('users AS users_c','order_items.owner_id', '=', 'users_c.id');
        $orders->leftJoin('delivery_slots', 'order_items.delivery_slot_id', '=', 'delivery_slots.id');
        $orders->leftJoin('products', 'order_items.product_id', '=', 'products.id');
        $orders->leftJoin('product_categories', 'order_items.product_category_id', '=', 'product_categories.id');
        $orders->leftJoin('cake_servings','order_items.cake_serving_id', '=', 'cake_servings.id');
        $orders->leftJoin('tart_servings','order_items.tart_serving_id', '=', 'tart_servings.id');
        $orders->leftJoin('thin_tart_servings','order_items.thin_tart_serving_id', '=', 'thin_tart_servings.id');
        $orders->leftJoin('party_loaf_servings','order_items.party_loaf_serving_id', '=', 'party_loaf_servings.id');
        $orders->leftJoin('party_loaf_weights','order_items.party_loaf_weight_id', '=', 'party_loaf_weights.id');
        $orders->leftJoin('party_loaf_assortment_one','order_items.party_loaf_assortment_one_id', '=', 'party_loaf_assortment_one.id');
        $orders->leftJoin('party_loaf_assortment_two','order_items.party_loaf_assortment_two_id', '=', 'party_loaf_assortment_two.id');
        $orders->leftJoin('party_loaf_assortment_three','order_items.party_loaf_assortment_three_id', '=', 'party_loaf_assortment_three.id');
        $orders->leftJoin('party_loaf_assortment_four','order_items.party_loaf_assortment_four_id', '=', 'party_loaf_assortment_four.id');
        $orders->leftJoin('savoury_canapes_variants','order_items.savoury_canapes_variant_id', '=', 'savoury_canapes_variants.id');
        $orders->leftJoin('savoury_mini_croissants_variants','order_items.savoury_mini_croissants_variant_id', '=', 'savoury_mini_croissants_variants.id');
        $orders->leftJoin('savoury_mini_delices_variants','order_items.savoury_mini_delices_variant_id', '=', 'savoury_mini_delices_variants.id');
        $orders->leftJoin('savoury_mini_puffs_variants','order_items.savoury_mini_puffs_variant_id', '=', 'savoury_mini_puffs_variants.id');
        $orders->leftJoin('savoury_mini_ramequins_variants','order_items.savoury_mini_ramequins_variant_id', '=', 'savoury_mini_ramequins_variants.id');
        $orders->leftJoin('savoury_mini_vols_au_vent_variants','order_items.savoury_mini_vols_au_vent_variant_id', '=', 'savoury_mini_vols_au_vent_variants.id');
        $orders->leftJoin('savoury_petit_pain_bouchee_variants','order_items.savoury_petit_pain_bouchee_variant_id', '=', 'savoury_petit_pain_bouchee_variants.id');
        $orders->leftJoin('sweet_sweets','sweet_sweet_id', '=', 'sweet_sweets.id');
        $orders->leftJoin('ice_cream_small_pots_flavors','ice_cream_small_pots_flavor_id', '=', 'ice_cream_small_pots_flavors.id');
        $orders->leftJoin('ice_cream_pots_flavors','ice_cream_pots_flavor_id', '=', 'ice_cream_pots_flavors.id');
        $orders->leftJoin('ice_cream_frozen_fruits','ice_cream_frozen_fruit_id', '=', 'ice_cream_frozen_fruits.id');
        $orders->leftJoin('yul_log_christmas_servings','yul_log_christmas_serving_id', '=', 'yul_log_christmas_servings.id');
        $orders->leftJoin('yul_log_christmas_flavor','yul_log_christmas_flavor_id', '=', 'yul_log_christmas_flavor.id');
        $orders->leftJoin('yul_log_frozen_liters','yul_log_frozen_liter_id', '=', 'yul_log_frozen_liters.id');
        $orders->leftJoin('yul_log_frozen_flavor_one','yul_log_frozen_flavor_one_id', '=', 'yul_log_frozen_flavor_one.id');
        $orders->leftJoin('yul_log_frozen_flavor_two','yul_log_frozen_flavor_two_id', '=', 'yul_log_frozen_flavor_two.id');
        $orders->leftJoin('yul_log_frozen_flavor_three','yul_log_frozen_flavor_three_id', '=', 'yul_log_frozen_flavor_three.id');
        $orders->select(
            'order_items.id as id',
            'order_items.product_category_id as product_category_id',
            'product_categories.name as product_category_name',
            'order_items.order_id as order_id',
            'order_items.status_id as status_id',
            'order_status.status_order as status_order',
            'order_items.orderer_id as orderer_id',
            'order_items.customer_id as customer_id',
            'users_a.name as orderer_name',
            'users_b.name as customer_name',
            'users_b.mobile AS customer_mobile',
            'order_items.owner_id as owner_id',
            'users_c.name as owner_name',
            'order_items.delivery_date as delivery_date',
            'delivery_slots.delivery_slot as delivery_time',
            'products.id as product_id',
            'products.name as product_name',
            'order_items.quantity as quantity',
            'on_tray as on_tray',
            'cut_bread as cut_bread',
            'cake_servings.servings as cake_serving',
            'tart_servings.servings as tart_serving',
            'thin_tart_servings.servings as thin_tart_serving',
            'party_loaf_servings.servings as party_loaf_serving',
            'party_loaf_weights.weight as party_loaf_weight',
            'party_loaf_assortment_one.assortment as party_loaf_assortment_one',
            'party_loaf_assortment_two.assortment as party_loaf_assortment_two',
            'party_loaf_assortment_three.assortment as party_loaf_assortment_three',
            'party_loaf_assortment_four.assortment as party_loaf_assortment_four',
            'savoury_canapes_variants.variant as canape_variant',
            'savoury_mini_delices_variants.variant as mini_delice_variant',
            'savoury_mini_croissants_variants.variant as mini_croissant_variant',
            'savoury_mini_puffs_variants.variant as mini_puff_variant',
            'savoury_mini_ramequins_variants.variant as mini_ramequin_variant',
            'savoury_mini_vols_au_vent_variants.variant as mini_vol_au_vent_variant',
            'savoury_petit_pain_bouchee_variants.variant as petit_pain_bouchee_variant',
            'sweet_sweets.variant as sweet_variant',
            'ice_cream_small_pots_flavors.flavor as ice_cream_small_pot_flavor',
            'ice_cream_pots_flavors.flavor as ice_cream_pot_flavor',
            'ice_cream_frozen_fruits.fruit as ice_cream_frozen_fruit',
            'custom_laboratories as custom_laboratories',
            'custom_name as custom_name',
            'custom_servings as custom_servings',
            'custom_weights as custom_weight',
            'custom_size as custom_size',
            'yul_log_christmas_servings.servings as yul_log_christmas_serving',
            'yul_log_christmas_flavor.flavor as yul_log_christmas_flavor',
            'yul_log_frozen_liters.liter as yul_log_frozen_liter',
            'yul_log_frozen_flavor_one.flavor as yul_log_frozen_flavor_one',
            'yul_log_frozen_flavor_two.flavor as yul_log_frozen_flavor_two',
            'yul_log_frozen_flavor_three.flavor as yul_log_frozen_flavor_three',
            'inscription as inscription',
            'comment as comment',
            'order_items.deleted_at as deleted_at',
            );

            if($user_role_id == 5){
                $orders->whereJsonContains('order_items.laboratory_id', ['1']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->whereNull('order_items.deleted_at');
            } else if($user_role_id == 6){
                $orders->whereJsonContains('order_items.laboratory_id', ['2']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->where('order_items.deleted_at', '=', NULL);
            } else if($user_role_id == 7){
                $orders->whereJsonContains('order_items.laboratory_id', ['3']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->where('order_items.deleted_at', '=', NULL);
            } else if($user_role_id == 8){
                $orders->whereJsonContains('order_items.laboratory_id', ['4']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->where('order_items.deleted_at', '=', NULL);
            } else if($user_role_id == 9){
                $orders->whereJsonContains('order_items.laboratory_id', ['5']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->where('order_items.deleted_at', '=', NULL);
            } else if($user_role_id == 10){
                $orders->whereJsonContains('order_items.laboratory_id', ['6']);
                $orders->whereIn('order_items.status_id', [2]);
                $orders->where('order_items.deleted_at', '=', NULL);
            }

            if($request->search_term!="") {

                $orders->where('order_items.id', 'LIKE', "%" . $term . "%")
                        ->orWhere('order_items.order_id', 'LIKE', "%" . $term . "%")
                        ->orWhere('users_a.name', 'LIKE', "%" . $term . "%")
                        ->orWhere('users_b.name', 'LIKE', "%" . $term . "%")
                        ->orWhere('users_b.mobile', 'LIKE', "%" . $term . "%")
                        ->orWhere('order_items.delivery_date', 'LIKE', "%" . $term . "%")
                        ->orWhere('product_categories.name', 'LIKE', "%" . $term . "%")
                        ->orWhere('products.name', 'LIKE', "%" . $term . "%")
                        ->orWhere('custom_name', 'LIKE', "%" . $term . "%")
                        ->orWhere('inscription', 'LIKE', "%" . $term . "%")
                        ->orWhere('savoury_canapes_variants.variant', 'LIKE', "%" . $term . "%")
                        ->orWhere('savoury_mini_croissants_variants.variant', 'LIKE', "%" . $term . "%")
                        ->orWhere('savoury_mini_delices_variants.variant', 'LIKE', "%" . $term . "%")
                        ->orWhere('savoury_mini_puffs_variants.variant', 'LIKE', "%" . $term . "%")
                        ->orWhere('savoury_mini_ramequins_variants.variant', 'LIKE', "%" . $term . "%")
                        ->orWhere('savoury_mini_vols_au_vent_variants.variant', 'LIKE', "%" . $term . "%")
                        ->orWhere('savoury_petit_pain_bouchee_variants.variant', 'LIKE', "%" . $term . "%")
                        ->orWhere('ice_cream_small_pots_flavors.flavor', 'LIKE', "%" . $term . "%")
                        ->orWhere('ice_cream_pots_flavors.flavor', 'LIKE', "%" . $term . "%")
                        ->orWhere('ice_cream_frozen_fruits.fruit', 'LIKE', "%" . $term . "%")
                        ->orWhere('party_loaf_servings.servings', 'LIKE', "%" . $term . "%")
                        ->orWhere('party_loaf_assortment_one.assortment', 'LIKE', "%" . $term . "%")
                        ->orWhere('party_loaf_assortment_two.assortment', 'LIKE', "%" . $term . "%")
                        ->orWhere('party_loaf_assortment_three.assortment', 'LIKE', "%" . $term . "%")
                        ->orWhere('party_loaf_assortment_four.assortment', 'LIKE', "%" . $term . "%")
                        ->orWhere('custom_servings', 'LIKE', "%" . $term . "%")
                        ->orWhere('custom_weights', 'LIKE', "%" . $term . "%")
                        ->orWhere('custom_size', 'LIKE', "%" . $term . "%")
                        ->orWhere('yul_log_christmas_flavor.flavor', 'LIKE', "%" . $term . "%")
                        ->orWhere('yul_log_frozen_flavor_one.flavor', 'LIKE', "%" . $term . "%")
                        ->orWhere('yul_log_frozen_flavor_two.flavor', 'LIKE', "%" . $term . "%")
                        ->orWhere('yul_log_frozen_flavor_three.flavor', 'LIKE', "%" . $term . "%")
                        ->orWhere('inscription', 'LIKE', "%" . $term . "%")
                        ->orWhere('comment', 'LIKE', "%" . $term . "%");
            }

            $orders->where('order_items.deleted_at', '=', NULL);
            $orders->distinct();
            $orders->orderBy('order_items.delivery_date', 'asc');
            $orders  = $orders->whereIn('order_items.status_id', [2])->paginate(10);

        ## START CREATE THE VIEW
        // return view('orders.management', compact('laboratory_staffs', 'staffs','orders','status_orders', 'user_role_id'));
        return view('orders.management-second', compact('laboratory_staffs', 'staffs','orders','status_orders', 'user_role_id'));
        ## END CREATE THE VIEW

    }

A: Your query conditions are not organized correctly. Try the following:
if($request->search_term != "") {
    $orders->where(function ($query) use ($term) {
        $query->orWhere('order_items.id', 'LIKE', "%" . $term . "%")
            ->orWhere('order_items.order_id', 'LIKE', "%" . $term . "%")
            // ...
            ->orWhere('comment', 'LIKE', "%" . $term . "%");
    });
}


text:
Q: woocommerce function to get svg code product icon I have add a new field via admin panel in products product_icon

where I put an SVG icon code. I need to use this SVG plugin. I have put into woocommerce/includes/abstracts/abstract-wc-product.php new function.
public function get_icon( $context = 'view' ) {
    return $this->get_prop( 'icon', $context );
}

when I put it into a while loop where I have list products name, prices, etc new function get_icon() I have null. In SQL post meta meta key is ok "product_icon" for a correct product with the correct content (SVG code)
My listing Code:
<?php
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $product = wc_get_product( get_the_ID() );
        ?>

            <?php if ( 'grid' === $layout && 'grid-preset-3' === $gridPreset ) { ?>

            <?php } else { ?>

            <?php } ?>

                <?php echo wp_kses_post( $product->get_image( 'woocommerce_thumbnail' ) ); ?>

                <?php if ( 'grid' === $layout ) { ?>

                        <?php // woocommerce_template_loop_add_to_cart(); ?>

                <?php } ?>

                    <?php if ( 'grid' === $layout && 'grid-preset-3' === $gridPreset ) { ?>

                        <a class="producttitle" href="<?php echo esc_url( get_permalink() ); ?>"><?php echo get_the_title(); ?>

                    <?php } else { ?>

                        <a class="producttitlewhite" href="<?php echo esc_url( get_permalink() ); ?>"><?php echo get_the_title(); ?>

                    <?php } ?>

                    <?php if ( 'grid' === $layout && 'grid-preset-3' === $gridPreset ) { ?>

                        <?php if ( $showPrice ) { ?>

<?php echo $product->get_price_html(); ?>

Icon code<?php echo $product->get_icon(); ?>

<?php woocommerce_template_loop_add_to_cart(); ?>

                        <?php } ?>

                    <?php } else { ?>

                        <?php if ( $showPrice ) { ?>

<?php echo $product->get_price_html(); ?>

<?php woocommerce_template_loop_add_to_cart(); ?>

                        <?php } ?>

                    <?php } ?>

        <?php
    }
    wp_reset_postdata();
} else {
    ?>

<?php _e( 'No product found', 'essential-blocks' ); ?>

    <?php
}
?>

A: Well, you don't have to edit woocommerce/includes/abstracts/abstract-wc-product.php file to fetch the meta key and the get_prop function doesn't work that way that you're assuming.
You can simply use get_post_meta function to fetch your meta key value for the product.
so you just need to replace
<?php echo $product->get_icon(); ?>

with the below code:

<?php echo get_post_meta( $product->get_id(), 'product_icon', true ); ?>


text:
Q: Calculate sample size for Fisher Exact Test I'm researching the role of sender reputation in remediating Android vulnerabilities using large-scale notification campaign. There are 2 senders with different reputations and 1 as a control (no notification sent). I am measuring the effect of these notifications by the senders and finding out how many vulnerabilities were fixed when they were notified. I'm having a problem in the study design as I can't seem to figure out the sample size needed for a meaningful analysis. This is the contingency table so far.
          Fixed   Not fixed  Total
Sender1                        21
Sender2                        21
Control                        22

Total                          64

I know I have to do it pairwise and then use Multitest corrections (I'll be using Holm-Bonferrroni for this), but the question is whether the analysis will be meaningful or not? For that I have to calculate sample size needed. How to do that?
(The question might be very basic but I don't have a background in stats so pls help)

A: I will try to answer you question, please feel free to correct me if I understand you wrongly.
First, here is a sample size calculator for fishers exact test or use this package in R, and here an article. If you are interested in further explanation, I would suggest to google, fishers exact test is well described.
After this is said, to calculate sample size, you need prior knowledge. Sample size should NEVER be calculated based on the observations used for the actual analysis.
An alterative for using fishers exact test for calculating sample size is to use proportions.
Second you ask about correction for multiple testing. Unless you are looking at 1000 or more tests, I would never recommend correcting for multiple testing. Why? Because you simply increase type 2 errors when trying to decrease type 1 errors, and how can you make sure you do not want to perform a test later on the same data set? If you do so and are determined on correction you previous results are no longer valid but should be corrected for the new additional tests. Here is an article that comment on these problems.
I hope this may be of help


text:
Q: Javascript button pressed fade parent class out only one time works Hello so I did that when I click on 'decline' button it would fade out that 'td' and it works but it works only for the first one, I mean if there is more  which contains more 'decline' buttons it won't work ONLY WORKS ON FIRST BUTTON
code:
JAVASCRIPT
$(function () {
    $("#declinebutton").click(function () {
        $(this).closest('td').fadeOut();
    });
});

HTML:

        Username

        <button type="button" class="btn btn-danger" name="declinebutton" id="declinebutton">
             Decline request
        </button>

A: You have Just  to change declinebutton from and id to a class attribute and change the reference to it as well in you JS code, here is an example :
$(function () {
    $(".declinebutton").click(function () {
        $(this).closest('td').fadeOut();
    });
});

        Username

        <button type="button" class="btn btn-danger declinebutton" name="declinebutton">
             Decline request
        </button>

Note:
IDs should be unique, meaning one ID identify one and only one element whereas CLASS can identify more than one element.
So if you want to target a list of elements just give them the same class name and you are ready to go, hope this helps.


text:
Q: Mock a nested function with input arguments in Python My folder structure
main.py
    class Class1
        generate_columns()
        column_api()
utilities.py
    class Class2
        get_response()

I want to mock column_api() function in class Class1.
The function signature is as follows:
class Class1:
    def generate_columns():
        calls `get_response()` from `class Class2` and returns response

    def column_api(data=List[Dict]]):
        resp = self.generate_columns(data)
        for item in resp:
            if data["name"] == item["name"]:
                ret.append(item)
    return ret

I would like to mock column_api. Here's the test I have so far:
def test_column_api():
    testClass = Class1()
    mock_response = [{"id":"1", "name":"test1"}]
    load_data = [{"id":"1", "name":"test1"}, {"id":"2", "name":"test2"}]
    with patch("package.main.Class1.generate_columns") as api_mock:
        api_mock.return_value = mock_response

        result = testClass.column_api(load_data)
        assert len(result) == 1

It fails here with an AssertionError. The returned list is always empty no matter how much I try. But ideally, according to my function definition, the returned list should have one dictionary whose name matches with a name in the response object.
I am very new to Mock and patch concepts in Python. After reading through various posts on SO and the actual docs on Mock, I could come until this far. I think my api_mock is not being utilized by column_api function. I think that's where the problem is but I am not sure how to make column_api recognize api_mock. Any help on this is much appreciated! Hope my function definitions are clear here but I am happy to include any other information that I may have missed.
Thank you so much in advance. I have been breaking my head over this for quite sometime now. Hoping to find some answer here.

A: A good colleague of mine helped me with the solution and I am posting it down below. This solution worked for my purposes.
@pytest.fixture
def mocked_gen_col(monkeypatch):

    def mock_gen_technical(*args, **kwargs):
        return [
            {"name": "a"},
            {"name": "b"}
        ]
    monkeypatch.setattr(Class1, "generate_columns", mock_gen_technical)

def test_technical_column_api(mocked_gen_col):
    data = [{
        "id": "1",
        "name": "a"
    }]

    list = Class1().column_api(data=data)
    assert list[0]["name"] == "a"
    assert len(list) == 1


text:
Q: Inserting data into local database using parameters Hi all I have been stuck at this for two days. I am using Visual Studio 2013 and made a windows form project. Then using the following code I am trying to insert values but the "show Table data" option produces a table with null values. What have I done wrong?
        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.
 ConnectionStrings["WindowsFormsApplicationtodatabase.Properties.Settings.DatabasewebConnectionString"].ConnectionString);

        conn.Open();

        using (conn)
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO webtable (Id, url_name) VALUES (@id, @url)");
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@url", "nagia");
            cmd.Parameters.AddWithValue("@id", "9");

            cmd.ExecuteNonQuery();
        }

A: You can try this
 conn.Open();

 string strQuery = "INSERT INTO webtable (Id, url_name) VALUES (@id, @url)";
 SqlCommand cmd = new SqlCommand(strQuery, conn);
 cmd.Parameters.AddWithValue("@url", "nagia");
 cmd.Parameters.AddWithValue("@id", "9");
 cmd.Connection = conn;
 cmd.ExecuteNonQuery();
 conn.Close();

A: Try to Assign Data Types for the Parameters.
Refer this,
[SqlCommand Parameters Add vs. AddWithValue

A: You can try this code..
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["WindowsFormsApplicationtodatabase.Properties.Settings.DatabasewebConnectionString"].ConnectionString));
{

SqlCommand cmd = new SqlCommand("INSERT INTO webtable (Id, url_name) VALUES (@id, @url)",conn);

cmd.Parameters.AddWithValue("@url", "nagia");
cmd.Parameters.AddWithValue("@id", "9");
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

}


text:
Q: How to label encode a attribute in pandas dataframe? Example :
Assume an attribute Result
Result
| M |
| B |
| B |
| M |
Into
Result
| 0 |
| 1 |
| 1 |
| 0 |
To achieve this without using LabelEncoder or OneHotEncoding. Like Is there any possible way to do it with the python dictionary?

A: I would suggest creating a dictionary to map the values to new labels and use the map() method to label encode the attributes.
something like:
df['result'].map(mapping_dict)

A: Something like this will work,
df = pd.DataFrame(data=[{'result': 'M'}, {'result':'B'}, {'result':'B'}, {'result':'M'}])
# Sol 1
def changeValue(r):
    if r == 'M':
        return 0
    else:
        return 1

df.apply(lambda x: changeValue(x['result']), axis=1)
# Sol 2
# df['result'].map({'M': 0, 'B': 1})

A: try this:
f, _ = pd.factorize(df['Result'])
df['Result'] = f
print(df)
>>>

  Result
0   0
1   1
2   1
3   0


text:
Q: Ckeditor : How can i make few tags like h3 , h4 , h5 non editable in ckeditor Ckeditor : How can i make few tags like h3 , h4 , h5 non editable in ckeditor
open to js solution or css any will do

A: In config.js, use the following code to define which elements you want to allow in CKEditor (I removed h1) :
config.format_tags = 'p;h2;h3;h4;h5;h6;pre;address;div'

A: The protectedSource configuration setting is the setting of choice for that.

 {Array}  CKEDITOR.config.protectedSource
List of regular expressions to be executed over the input HTML, indicating code that must stay untouched.

I'm no expert on regular expressions but something like this should do the trick:
config.protectedSource.push(/[^<]*(
([^<]+)<\/h1>)/g);

you may have to play around with it a bit. Caveat: The regex in that form will catch only
...
 tags, not for example deviations like
...
.

A: You can add attribute contenteditable=false to the tag.
E.g.
ckeditor.insertHtml('
Not editable text
');


text:
Q: How enable compression for a JSON REST call in Suave? I want to know how return JSON for my REST calls compressed:
GET /orders HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate

But the docs only talk about returning files
let setJson it =
    it
    |>JsonUtils.toJson
    |> OK
    >=> setMimeType "application/json; charset=utf-8"

let doReq route request action =
    path route >=> setCORSHeaders >=> request (fun r -> action(r) |> setJson)

doReq "/orders" request (fun r -> queryOrders(r |> getTerm, Products.Name))

A: I believe this is configured in the MIME type maps by adding a new MIME type and passing true for the second parameter, like this:
let mimeTypes =
  defaultMimeTypesMap
    @@ (function | ".json" -> createMimeType "application/json" true | _ -> None)

let webConfig = { defaultConfig with mimeTypesMap = mimeTypes }

The configuration for MIME types and compression is documented on this page.


text:
Q: Error on unmarshaling with generated code (moxy): "A descriptor with default root element ... was not found in the project" I generated code using moxy for different xsd-Files:
http://www.forum-datenaustausch.ch/generalinvoiceresponse_400.xsd
and
http://www.forum-datenaustausch.ch/xmlstandards_generelle_rechnung_beispiele_antwort_4.3_20100901.zip
I generated jaxb-classes for both xsd (using moxy). Then i tried unmarshal xml-files (genrated by eclipse) with this code:
public void tempTest() throws JAXBException{
    JAXBContext jC = JAXBContext.newInstance(<package for corresponding type>.ResponseType.class);
    jC.createUnmarshaller().unmarshal(ResponseTest.class.getResourceAsStream("/responses/generalInvoiceResponse_400.xml"));
}

With xml-File of 4.3-type (2nd link) this works fine but with xml of 400-type (1st link) i get this error:
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element {http://www.forum-datenaustausch.ch/de}response was not found in the project]

It seems to be a problem with the name-space. The name space is different but i can not see a relevant difference in generated code or generated xml - the name space is consistent.
so what could cause this problem (where is the difference) and how to solve it?
small addition: i also tried to unmarshal xml marshaled with jaxb/moxy-code:
public void marshall() throws JAXBException, FileNotFoundException {
    JAXBContext jC = JAXBContext.newInstance(ResponseType.class);
    ObjectFactory of = new ObjectFactory();
    jC.createMarshaller().marshal( of.createResponse(of.createResponseType()),new FileOutputStream("simpleresponse.xml"));
}

this creates an very simple xml:
<?xml version="1.0" encoding="UTF-8"?>
<response xmlns="http://www.forum-datenaustausch.ch/de"/>

unmarshaling this yields the same error.

A: When creating a JAXBContext based on a model generated from an XML Schema you should always use the the newInstance method that takes the package name.  This will ensure that all the necessary bits are processed.
JAXBContext jC = JAXBContext.newInstance("ch.forum_datenaustausch.de");

When you use the JAXBContext.newInstance(Class...) method the JAXB implementation is assuming that you started from Jav classes.  Since the role of ObjectFactory can be played by any class annotated with @XmlRegistry the ObjectFactory class generated from the XML schema will be automatically picked up.  You could do the following, but I still recommend the above approach:
JAXBContext jC = JAXBContext.newInstance(ResponseType.class, ObjectFactory.class);

UPDATE

Thank you! but could you probably explain why it is working with one
  xsd and not with the other?

The schema where it "works" may have a global element with an anonymous type which causes an @XmlRootElement annotation to be generated meaning the ObjectFactory is not required.  The other may have a global element with a named complex type which causes an @XmlElementDecl annotation on an ObjectFactory class to be generated.

*

*http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html

A: I also got same error message over WebLogic 12 but problem was due to namespace prefix.
It got fixed after explicitly adding name space in @Xmlrootelement(name="namespace:root tag name")


text:
Q: What is Causing the Error: "Notice: Uninitialized string offset"? I have this PHP program from:  http://www.hithlonde.com/pi/#files The program is suppose to convert the numbers of pi into individual colors (One number per pixel)  and save it to an image file like this one: http://www.hithlonde.com/pi/Pi1024x768.gif
But when I try to run the PHP code it gives this runtime-error:
Notice: Uninitialized string offset: 44000 in C:\Users\User\Documents\NetBeansProjects\ColorDivisors\index.php on line 103

Notice: Uninitialized string offset: 44001 in C:\Users\User\Documents\NetBeansProjects\ColorDivisors\index.php on line 103

Notice: Uninitialized string offset: 44002 in C:\Users\User\Documents\NetBeansProjects\ColorDivisors\index.php on line 103

Notice: Uninitialized string offset: 44003 in C:\Users\User\Documents\NetBeansProjects\ColorDivisors\index.php on line 103

Notice: Uninitialized string offset: 44004 in C:\Users\User\Documents\NetBeansProjects\ColorDivisors\index.php on line 103

Here is the code.
    <?php
    //Title:
    //  Pi Graphical Visualization Script
    //Date:
    //  03.14.07
    //Author:
    //  Tim Habersack
    //Descript:
    //  Reads in the digits of pi, assigns a color to each number 0-9,
    //  then outputs to an image with one pixel representing a number.
    //Notes:
    //  (http://zenwerx.com/pi.php) is where I obtained the pi file,
    //  calculated to over 4 million decimal places.  The GD library
    //  in your php config must be enabled for this to function.
    //E-mail:
    //  tim@hithlonde.com
    //Copyright:
    //  Released under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License

    function NumToColor($ImagePassed, $NumPassed)
    {
        $the0 = imagecolorallocate($ImagePassed, 0xFF, 0xFF, 0xFF);
        $the1 = imagecolorallocate($ImagePassed, 0x00, 0xFF, 0xFF);
        $the2 = imagecolorallocate($ImagePassed, 0x00, 0x00, 0xFF);
        $the3 = imagecolorallocate($ImagePassed, 0xFF, 0x00, 0xFF);
        $the4 = imagecolorallocate($ImagePassed, 0x00, 0xFF, 0x00);
        $the5 = imagecolorallocate($ImagePassed, 0xFF, 0xA5, 0x00);
        $the6 = imagecolorallocate($ImagePassed, 0xFF, 0x00, 0x00);
        $the7 = imagecolorallocate($ImagePassed, 0xFF, 0xFF, 0x00);
        $the8 = imagecolorallocate($ImagePassed, 0x80, 0x80, 0x80);
        $the9 = imagecolorallocate($ImagePassed, 0x00, 0x00, 0x00);

        switch ($NumPassed)
        {
        case 0:
            return $the0;
            break;
        case 1:
            return $the1;
            break;
        case 2:
            return $the2;
            break;
        case 3:
            return $the3;
            break;
        case 4:
            return $the4;
            break;
        case 5:
            return $the5;
            break;
        case 6:
            return $the6;
            break;
        case 7:
            return $the7;
            break;
        case 8:
            return $the8;
            break;
        case 9:
            return $the9;
            break;
        }
    }

    //Set the size of the pi image
    $x = 200;
    $y = 200;

    $gd = imagecreatetruecolor($x, $y);

    //Connect the pi file to variable
    $theTestPi = file_get_contents("pi");

    $theGoodPi = "";

    $PiWalker = 0;

    //gets the # of digits needed, plus some extra for the \r dropped off, reads into var

    while ($PiWalker < $x * $y * 1.1)
    {
        if ($theTestPi[$PiWalker] == "\r")
        {
            $PiWalker++;
        }
        else
        {
            $theGoodPi = $theGoodPi . $theTestPi[$PiWalker];
        }
        $PiWalker++;
    }

    //$PiWalker = 0;

    //walks through the image, painting the pi characters pixel by pixel
    for ($theY = 0; $theY < $y; $theY++)
    {
        for ($theX = 0; $theX < $x; $theX++)
        {

/*This is line 103*/  imagesetpixel($gd, $theX, $theY, NumToColor($gd,$theGoodPi[$PiWalker]));

            $PiWalker++;
        }
    }

    header('Content-Type: image/png');
    imagepng($gd);

I can't figure out what exactly is giving this error.
I'm using xampp PHP Compiler version 1.8.3-4 (PHP version 5.5.11).

A: Looks like the issue is on line 95
This line should not be commented:
//$PiWalker = 0;

(change it to)
$PiWalker = 0;


text:
Q: Pass parent attribute in metaclass The metaclass is defined as below:
class MyMeta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        # uses attribute a,b,c,d
        a = namespace["a"]
        b = namespace["b"]
        c = namespace["c"]
        d = namespace["d"]
        ...
        return super().__new__(metacls, name, bases, namespace, **kwargs)

This metaclass uses attributes a, b, c, d.
Now classes can be created with this metaclass as:
class A(metaclass=MyMeta):
    a = "etc/dev"
    b = 2
    c = "c"
    d = "d"

class B(metaclass=MyMeta):
    a = "etc/dev/null"
    b = 2
    c = "c"
    d = "d"

The attribute a is variable for each class.
I want to extract the constant attributes in a base class to avoid duplication:
class BaseClass:
    b = 2
    c = "c"
    d = "d"

and create classes using the metaclass as:
class A(BaseClass, metaclass=MyMeta):
    a = "/etc/dev"

class B(BaseClass, metaclass=MyMeta):
    a = "/etc/dev/null"

The metaclass complains that it can not find attribute b from parent class.
test_mode = namespace["b"]
KeyError: 'b'

Is there a way to pass attributes from parent to a child metaclass ?
Constraint: Can not update the MyMeta metaclass as it's been borrowed/imported it from an existing library.

A: You can do it by making the metaclass __new__() method also check the namespaces of all the base classes of the class being defined. Here's one way of doing it. Note that it filters out attributes in the namespaces that have dunder identifiers.
Since you can't change the meta class you "borrowed" a custom one is derived from it. This revised version of my earlier answer also uses the collection.ChainMap class to make all the namespaces be considered without actually combining them all.
from collections import ChainMap
import re

class BorrowedMeta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        # uses attribute a,b,c,d
        a = namespace["a"]
        b = namespace["b"]
        c = namespace["c"]
        d = namespace["d"]
        ...
        return super().__new__(metacls, name, bases, namespace, **kwargs)

def is_dunder(name):
    """Determine if name is a Python dunder identifier."""
    return re.match(r'^__[^\d\W]\w*\Z__$', name, re.UNICODE)

class MyMeta(BorrowedMeta):
    def __new__(metacls, name, bases, namespace, **kwargs):
        chainmap = ChainMap(*[namespace] +
                             [{k: v for (k, v) in vars(base).items() if not(is_dunder(k))}
                                                    for base in bases])

        return super().__new__(metacls, name, bases, {**chainmap}, **kwargs)

class BaseClass:
    b = 2
    c = "c"
    d = "d"

class A(BaseClass, metaclass=MyMeta):
    a = "/etc/dev"

class B(BaseClass, metaclass=MyMeta):
    a = "/etc/dev/null"

from pprint import pprint
pprint(vars(A))
print()
pprint(vars(B))

Output:
mappingproxy({'__doc__': None,
              '__module__': '__main__',
              'a': '/etc/dev',
              'b': 2,
              'c': 'c',
              'd': 'd'})

mappingproxy({'__doc__': None,
              '__module__': '__main__',
              'a': '/etc/dev/null',
              'b': 2,
              'c': 'c',
              'd': 'd'})

A: No, you can't do what you want without changing the metaclass's behavior.
The problem is that the namespace argument that MyMeta.__new__ is looking in contains only the values defined in the class statement for the new class. It doesn't contain anything inherited, since the class and it's bases haven't been combined yet (that's what MyMeta.__new__ does when it calls super().__new__ at the bottom of its implementation, after it has done its thing with the a/b/c variables).


text:
Q: Click on an element in a row value by identifying another cell value within the same row I have to click on an element which is common across all the rows in a table. But the catch is ,I want to click on that element only for 1 particular row. The row i need can be anywhere in the table. So all i need is identify the row i need and then clicking on the element.
Added my code which i have already tried and it failed.
var ClickEdit = element
    .all(by.cssContainingText('.table-element-row'))
    .filter(function(rowElement){
        return rowElement.element(by.css("td h5")).getText().then(function(text){
            return text.trim() == "Company Created by Test Automation"
        });
    })
    .first()
    .element(by.name('action-menu-trigger')).click();

What i need is : Identify the row which has 'Created by Test Automation' and click on the element by name=action-menu-trigger within the same row.
The element by name=action-menu-trigger is present in all the rows of the table.

<app-user-profile-logo _ngcontent-c44="" class="ng-tns-c44-63" shape="circle" size="small" _nghost-c18="">

RS

</app-user-profile-logo>

Company
  Created by Test Automation

Robert

   Owner/Operator

Dubai

United Arab Emirates

<button _ngcontent-c44="" class="ng-tns-c44-63 mat-icon-button" aria-haspopup="true" mat-icon-button=""
  name="action-menu-trigger">

    <mat-icon _ngcontent-c44="" class="inv-icon-size--small mat-icon ng-tns-c44-63 mat-icon-no-color"
      role="img" svgicon="inv-ellipsis-h" aria-hidden="true">
      <svg width="100%" height="100%" viewBox="0 0 17 3" version="1.1" xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink" fit="" preserveAspectRatio="xMidYMid meet"
        focusable="false">

        <title>E1FE60C0-EF43-4EE7-AF32-E28F60D7C746@1,5x</title>
        <desc>Created with sketchtool.</desc>
        <defs></defs>
        <g id="UX-DESIGNER" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
          <g id="ui-03list_02--spec--product-type" transform="translate(-1493.000000, -589.000000)"
            fill="#333333">
            <g id="list/product-type-copy-2" transform="translate(255.000000, 547.000000)">
              <g id="Group-10" transform="translate(185.000000, 18.000000)">
                <g id="package/list">
                  <g id="ico/options" transform="translate(1053.000000, 24.000000)">
                    <g id="Group-4">
                      <circle id="Oval" cx="1.5" cy="1.5" r="1.5"></circle>
                      <circle id="Oval-Copy" cx="8.5" cy="1.5" r="1.5"></circle>
                      <circle id="Oval-Copy-2" cx="15.5" cy="1.5" r="1.5"></circle>
                    </g>
                  </g>
                </g>
              </g>
            </g>
          </g>
        </g>
      </svg>
    </mat-icon>

</button>
<mat-menu _ngcontent-c44="" class="ng-tns-c44-63 ng-tns-c9-93" xposition="before">
</mat-menu>

<app-user-profile-logo _ngcontent-c44="" class="ng-tns-c44-63" shape="circle" size="small" _nghost-c18="">

RS

</app-user-profile-logo>

Company
  Created by Test Automation

Robert

   Owner/Operator

Dubai

United Arab Emirates

<button _ngcontent-c44="" class="ng-tns-c44-63 mat-icon-button" aria-haspopup="true" mat-icon-button=""
  name="action-menu-trigger">

    <mat-icon _ngcontent-c44="" class="inv-icon-size--small mat-icon ng-tns-c44-63 mat-icon-no-color"
      role="img" svgicon="inv-ellipsis-h" aria-hidden="true">
      <svg width="100%" height="100%" viewBox="0 0 17 3" version="1.1" xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink" fit="" preserveAspectRatio="xMidYMid meet"
        focusable="false">

        <title>E1FE60C0-EF43-4EE7-AF32-E28F60D7C746@1,5x</title>
        <desc>Created with sketchtool.</desc>
        <defs></defs>
        <g id="UX-DESIGNER" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
          <g id="ui-03list_02--spec--product-type" transform="translate(-1493.000000, -589.000000)"
            fill="#333333">
            <g id="list/product-type-copy-2" transform="translate(255.000000, 547.000000)">
              <g id="Group-10" transform="translate(185.000000, 18.000000)">
                <g id="package/list">
                  <g id="ico/options" transform="translate(1053.000000, 24.000000)">
                    <g id="Group-4">
                      <circle id="Oval" cx="1.5" cy="1.5" r="1.5"></circle>
                      <circle id="Oval-Copy" cx="8.5" cy="1.5" r="1.5"></circle>
                      <circle id="Oval-Copy-2" cx="15.5" cy="1.5" r="1.5"></circle>
                    </g>
                  </g>
                </g>
              </g>
            </g>
          </g>
        </g>
      </svg>
    </mat-icon>

</button>
<mat-menu _ngcontent-c44="" class="ng-tns-c44-63 ng-tns-c9-93" xposition="before">
</mat-menu>

<button _ngcontent-c44="" class="ng-tns-c44-63 mat-icon-button" aria-haspopup="true" mat-icon-button="" name="action-menu-trigger"><mat-icon _ngcontent-c44="" class="inv-icon-size--small mat-icon ng-tns-c44-63 mat-icon-no-color" role="img" svgicon="inv-ellipsis-h" aria-hidden="true"><svg width="100%" height="100%" viewBox="0 0 17 3" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fit="" preserveAspectRatio="xMidYMid meet" focusable="false">

    <title>E1FE60C0-EF43-4EE7-AF32-E28F60D7C746@1,5x</title>
    <desc>Created with sketchtool.</desc>
    <defs></defs>
    <g id="UX-DESIGNER" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="ui-03list_02--spec--product-type" transform="translate(-1493.000000, -589.000000)" fill="#333333">
            <g id="list/product-type-copy-2" transform="translate(255.000000, 547.000000)">
                <g id="Group-10" transform="translate(185.000000, 18.000000)">
                    <g id="package/list">
                        <g id="ico/options" transform="translate(1053.000000, 24.000000)">
                            <g id="Group-4">
                                <circle id="Oval" cx="1.5" cy="1.5" r="1.5"></circle>
                                <circle id="Oval-Copy" cx="8.5" cy="1.5" r="1.5"></circle>
                                <circle id="Oval-Copy-2" cx="15.5" cy="1.5" r="1.5"></circle>
                            </g>
                        </g>
                    </g>
                </g>
            </g>
        </g>
    </g>
</svg></mat-icon>

</button>

A: If you can use XPath, to select the <button> element that is the descendant of the element containing "Created by Test Automation" text, use the following selector
//td[contains(., 'Created by Test Automation')]/following-sibling::td//button

A: You can pass the search text into by.cssContainingText() as following, then you no need to filter.
element(by.cssContainingText('tr.table-element-row', 'Company Created by Test Automation'))
.element(by.xpath('./..'))
.element(by.css('button[name="action-menu-trigger"]'))
.click()


text:
Q: Python - List not printing to outfile I'm trying to write a program for checking out/returning books at the library and I'm using temporary lists as storage for all the data in the patrons.txt and books.txt so I can edit it and then put it back in. The problem is that when I try to print the tempBookFile and tempPatronFile to outfile, the "file = outfile" part of following line
print(tempBookFile, file = outfile)

is highlighted in yellow and when I hover over it it says Expected type 'Optional[IO[str]] got 'TextIOWrapper[str]' instead". As a result, everything in the book list and patron list gets deleted, except for the name of the book which is stored in the patron file while it is checked out.
class Book:
    def __init__(self, title, author, genre, isbn):
        self.title = title
        self.author = author
        self.genre = genre
        self.isbn = isbn

    def printAll(self,outfile):
        print(self.title, "|", self.author, "|", self.genre, "|", self.isbn, file = outfile)

class Patron:
    def __init__(self, name, phone, books):
        self.name = name
        self.phone = phone
        self.books = books

    def printAll(self, outfile):
        print(self.name, "|", self.phone, "|", self.books, file = outfile)

def main():
    print("Welcome to JCK library!")
    menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

    while(menu != 6):
        if(menu == 1):
            outfile = open("books.txt", "w")
            title = input("Enter title: ")
            while(title != "done" and title != "Done"):

                author = input("Enter author: ")
                genre = input("Enter genre: ")
                isbn = input("Enter isbn: ")
                book = Book(title,author,genre,isbn)
                book.printAll(outfile)

                print("Book added: ", title)
                print("Author: ", author)
                print("Isbn: ", isbn, "\n")

                title = input("Enter title: ")
            outfile.close()
            menu = eval(input( "Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 2):
            outfile = open("patrons.txt", "w")
            name = input("Enter patron name: ")
            phone = input("Enter phone number: ")
            books = []

            patron = Patron(name,phone,books)
            patron.printAll(outfile)
            outfile.close()
            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 3):
            title = ""
            author = ""
            genre = ""
            isbn = ""
            name = ""
            phone = ""
            books = []
            outfile = open("patrons.txt", "r")
            patronName = input("Enter Patron Name: ")

            if (patronName in outfile.read()):
                print("Patron found.")

                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                        name = patronInfo[0]
                        phone = patronInfo[1]
                        books = patronInfo[2]

                #Creates a temporary list containing all of the contents of the patrons.txt file so that
                #the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                #Removes the line from the temporary list that contains information about the patron who is checking out
                #a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if(patronName in line):
                        tempPatronFile.pop(line)

                outfile.close()
                outfile = open("books.txt", "r")
                bookName = input("Enter Book Name: ")

                if bookName in outfile.read():
                    books.append(bookName)

                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                            title = bookInfo[0]
                            author = bookInfo[1]
                            genre = bookInfo[2]
                            isbn = bookInfo[3]

                    book = Book(title,author,genre,isbn)

                    #Creates a temporary list containing all of the contents of the books.txt file so that
                    #the list can be modified and then put back into the books.txt file
                    tempBookFile = outfile.readlines()

                    #Removes the line from the temporary list that contains information about the book so that
                    #the book can be re-added later after it has been returned.
                    for line in tempBookFile:
                        if(bookName in line):
                            tempBookFile.pop(line)

                    outfile.close()

                    outfile = open("books.txt", "w")
                    print(tempBookFile, file = outfile)
                    outfile.close()

                    outfile = open("patrons.txt", "w")
                    print(tempPatronFile, file = outfile)
                    patron = Patron(name,phone,books)
                    patron.printAll(outfile)
                    book.printAll(outfile)
                    outfile.close()

                    print("Book due in 2 weeks.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 4):
            outfile = open("patrons.txt", "r")
            patronName = input("Enter patron name: ")

            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                bookName = input("Enter book name: ")

                if(bookName in outfile.read()):
                    for line in outfile.readlines():
                        if(bookName in line):
                            bookInfo = line.split("|")
                        title = bookInfo[0]
                        author = bookInfo[1]
                        genre = bookInfo[2]
                        isbn = bookInfo[3]

                    book = Book(title, author, genre, isbn)

                # Creates a temporary list containing all of the contents of the patrons.txt file so that
                # the list can be modified and then put back into the patrons.txt file
                tempPatronFile = outfile.readlines()

                # Removes the line from the temporary list that contains information about the patron who is checking out
                # a book so that it can be re-added to the list after it is updated
                for line in tempPatronFile:
                    if (patronName in line):
                        tempPatronFile.pop(line)

                #Removes the information about the book which was stored in the patron file while it was checked out.
                #Upon being returned, the book will go back into the books.txt file
                for line in tempPatronFile:
                    if(bookName in line):
                        tempPatronFile.pop(line)

                outfile.close()

                outfile = open("books.txt", "r")
                tempBookFile = outfile.readlines()
                tempBookFile.append(book)###################################
                outfile.close()

                outfile = open("books.txt", "w")
                print(tempBookFile, file = outfile)
                outfile.close()

                outfile = open("patrons.txt", "w")
                for line in books:
                    if(bookName in line):
                        books.pop(line)
                patron = Patron(name,phone,books)
                print(tempPatronFile, file = outfile)
                patron.printAll(outfile)
                outfile.close()
                print("Book returned.")

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

        elif(menu == 5):
            outfile = open("patrons.txt", "r")
            patronName = input("Input patron's name: ")

            if(patronName in outfile.read()):
                for line in outfile.readlines():
                    if(patronName in line):
                        patronInfo = line.split("|")
                name = patronInfo[0]
                phone = patronInfo[1]
                books = patronInfo[2]

                print(patronName, "has the following book(s) checked out:\n", books)

            menu = eval(input("Main menu. Type 1 to enter books, 2  for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))

    print("Have a nice day!")

main()

A: The issue has to do with your old school file opening. You should avoid using open and close to manage your files and instead use a with statement. Most of the time if you are using resources that need to be cleaned up/managed you should use
with open("my_file.txt", "w") as output_file:
    # File based operations here

And then PyCharm will be happy. You can see a similar problem here: PyCharm - Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead
Also as someone commented (it's now deleted) make sure you are opening the file in the correct mode. "w" will erase everything in the file and let you write to it. "r" will only let you read from it. "a" will let you append to the file and might be what you want. If you look up the inputs to open you can get the full details. https://docs.python.org/3/library/functions.html#open


text:
Q: How to fetch last two year annual data in oracle There is table named sales_data which i used for my project.The table structure is below.

ID  Name    Year    Sales
1000    ABC 2016    50000
1000    ABC 2017    80000
1000    ABC 2015    90000
1000    ABC 2014    45000
1000    ABC 2013    30000
2000    PQR 2017    80000
2000    PQR 2015    90000
2000    PQR 2014    75000
2000    PQR 2013    60000
3000    XYZ 2015    123000
3000    XYZ 2013    56000
3000    XYZ 2012    45000
3000    XYZ 2011    30000

from this table. I want to fetch latest consecutive annual data. My result set is need to be like below

ID  Name    Year    Sales
1000    ABC 2017    80000
1000    ABC 2016    50000
2000    PQR 2017    80000
2000    PQR 2016    0
3000    XYZ 2015    123000
3000    XYZ 2014    0

because for PQR company lastest data is 2017 so it is 80000 but 2016 data is not present in this table so it's need to be 0.
Similar for XYZ company also.
Please help me on that. I am using Oracle 11g.

A: You can try this.
SELECT  t2.ID,t2.Name,t2.years,COALESCE(t1.Sales,0) Sales
FROM sales_data t1
RIGHT JOIN
(
  SELECT ID,Name,MAX(Year)   years
  FROM sales_data
  GROUP BY ID,Name
  UNION ALL
  SELECT ID,Name,MAX(Year) - 1  years
  FROM sales_data
  GROUP BY ID,Name
) t2 ON t1.ID = t2.ID AND t1.Name = t2.Name AND  t1.Year = t2.years
ORDER BY t2.ID,t2.years DESC

sqlfiddle: http://sqlfiddle.com/#!4/4fc37c/5

A: WITH Years AS
(
  SELECT ID,Name,MAX(Year) AS year
  FROM Table1
  GROUP BY ID,Name
  UNION ALL
  SELECT ID,Name,MAX(Year) - 1 AS year
  FROM Table1
  GROUP BY ID,Name
)
SELECT  y.ID,
        y.Name,
        y.year,
        COALESCE(t.Sales,0) AS Sales
FROM Years y
LEFT JOIN Table1 t
ON t.ID = y.ID
AND t.Name = y.Name
AND t.Year = y.year
ORDER BY y.ID,y.year DESC

Demo

http://sqlfiddle.com/#!4/c20fd/21

A: Yet another option:
SQL> with test (id, year, sales) as
  2    (select 1000, 2016, 50000 from dual union
  3     select 1000, 2017, 80000 from dual union
  4     select 1000, 2015, 90000 from dual union
  5     select 1000, 2014, 45000 from dual union
  6     --
  7     select 2000, 2017, 80000 from dual union
  8     select 2000, 2015, 90000 from dual union
  9     select 2000, 2014, 75000 from dual union
 10     --
 11     select 3000, 2015, 123000 from dual union
 12     select 3000, 2013, 56000 from dual union
 13     select 3000, 2012, 45000 from dual
 14    ),
 15  years as
 16    (select id, min_year + column_value - 1 year
 17     from (select id, min(year) min_year, max(year) max_year
 18           from test
 19           group by id
 20          ),
 21          table(cast(multiset(select level from dual
 22                              connect by level <= max_year - min_year + 1
 23                             ) as sys.odcinumberlist))
 24    ),
 25  ranking as
 26    (select y.id, y.year, nvl(t.sales, 0) sales,
 27       row_number() over (partition by y.id order by y.year desc) rn
 28     from years y left join test t on t.id = y.id and t.year = y.year
 29    )
 30  select r.id, r.year, r.sales
 31  from ranking r
 32  where r.rn <= 2
 33  order by r.id, r.year desc;

        ID       YEAR      SALES
---------- ---------- ----------
      1000       2017      80000
      1000       2016      50000
      2000       2017      80000
      2000       2016          0
      3000       2015     123000
      3000       2014          0

6 rows selected.

SQL>

A: Try this
SELECT sd1.ID,  sd1.name, sd2.year, COALESCE(sd3.sales,0)
FROM
(SELECT distinct ID, name from sales_data) as sd1 join
(SELECT distinct year from sales_data ) as sd2
Left join sales_data sd3
on sd1.ID = sd3.ID AND sd2.year = sd3.year


text:
Q: Change Value Displayed in v-slider and v-text-field based on a v-select option I have run into a quite interesting problem I cannot seem to wrap my head around.
I have a form that consists of multiple <v-slider>s and <v-text-field>s. for each attribute of an object there is a slider and text field using it as their v-model as follows:
<v-slider v-model='object1.value'></v-slider>
<v-text-field v-model='object1.value'></v-text-field>

The issue is these fields (as they are retrieved from the Database) come out in seconds which can be a burden on a user when entering values that could be more easily be represented as hours or minutes. I have a <v-select> that allows the user to select hours or minutes, however I cannot figure out how to change the value of the sliders and text fields to display the value as hours.
Example:

*

*value of the slider is 3600 (in seconds).

*User selects hours from the dropdown

*3600 should then be changed to 1
I have tried setting a watcher on the change in the dropdown, which consistently returns NaN when doing my math on the values supplied.
Does anyone have any ideas to solve this?
EDIT:
CodePen
EDIT 2:
So it seems a computed property may be what I am looking for, however I cannot for the life of me get it to work. I may just move these values bound to my inputs to other variables and reassign them on form submission.

A: You can use a computed property that scales the original value according to the selected time unit.
Based on your original pen, here is what you'd need to change:
In the select, add the number of seconds for the time unit as value - this is your conversion factor
<v-select
  :items=[
    {text: 'Seconds', value: 1},
    {text: 'Minutes', value: 60},
    {text: 'Hours', value: 3600}
  ]"
  v-model="conversionFactor"
/>

the computed property divides by the conversion factor on get and multiplies by the factor on write:
computed: {
  convertedValue: {
    get: function() {
      return this.exObj.value / this.conversionFactor
    },
    set: function(newValue) {
      this.exObj.value = newValue * this.conversionFactor
    }
  }
}

In addition, you might want to scale the slider maximum value based on the selected conversion as well:
<v-slider
  v-model="convertedValue" thumb-label
  :max='9999 / conversionFactor'
  :min='0'
/>

Here's a working pen: https://codepen.io/wwerner/pen/MXbyjL


text:
Q: Moment.min.js this.format is not a funtion I am trying to use a combodate in xeditable however, when I try to save moment.min.js says that this.format is not a function. This is coming from somewhere in moment.js so here is my code:
$('#start').editable({
  viewformat: 'DD-MM-YYYY',
  success: function(result, newValue){
    return $.ajax({
      url: '/Project/Edit',
      data: { id: '1', NewValue: newValue, type: 'StartDate' },
      success: function (result) {
        if (result.Success == 'Success') {
          notify('The Start Date was successfully updated.', 'success');
        } else {
          notify('The Start Date could not be updated at this time.', 'error');
        }
      }
    });
  }
}).on('hidden', function () {
  $(this).parent().next().children().removeClass('disabled');
});

Here is the line that is called in moment.js
toString: function () { return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")

This line in moment.js is called right after the editable success function is called.

A: I figured it out. I had to call the .format() method on newValue in the ajax call. That's how moment js was giving me that error. Here is the working code:
$('#start').editable({
  viewformat: 'DD-MM-YYYY',
  success: function(result, newValue){
    return $.ajax({
      url: '/Project/Edit',
      data: { id: '1', NewValue: newValue.format('MM/DD/YYYY'), type: 'StartDate' },
      success: function (result) {
        if (result.Success == 'Success') {
          notify('The Start Date was successfully updated.', 'success');
        } else {
          notify('The Start Date could not be updated at this time.', 'error');
        }
      }
    });
  }
}).on('hidden', function () {
  $(this).parent().next().children().removeClass('disabled');
});


text:
Q: AS3 ExternaInterface: Call a javascript function in a pop-up window invoked by Flash In Flash, I have invoked a pop-up window using
ExternalInterface.call("window.open","http://www.mypage.com,"win","height=640,width=480,toolbar=no,scrollbars=yes");

In the invoked pop-up, there is a javascript function I want to access. If the javascript were in the same page as the movie, I could use
ExternalInterface.call("jsFunction", "value")

Since it's not, how can I access the javascript functions in the pop-up window?

A: You will need to store a reference to the window that you opened to be able to access it. If you control the HTML/Javascript of the main main, you could insert something like this into the <script> block:
var popupref;

and window opening function:
function openWindow() {
    popupref = window.open(/*your params here*/)
}

and then in your ExternalInterface to open your window
ExternalInterface.call("openWindow");

and to call your popup window
ExternalInterface.call("popupref.myfunc");

I don't know off the top of my head, but you could potentially be able to make the ExternalInterface.call(...) by embedding the the whole popupref = window.open(...) call in it.
Be aware thought that the window that you opened has to come from the same domain and port otherwise the cross-domain browser security will not let you make the calls.


text:
Q: Javascript date differs based on month format While debugging my application I found weird thing:
new Date('2017-5-19')  -> Fri May 19 2017 00:00:00 GMT+0300 (FLE Summer Time)
new Date('2017-05-19') -> Fri May 19 2017 03:00:00 GMT+0300 (FLE Summer Time)

I set date from String, like '2017-5-19', but when there is zero before month number, date is different than without zero.
How can I achieve the same result by both 5 and 05 inputs?
p.s. I have to support strict mode

A: As indicated on MDN, using the Date constructor to parse dates is discouraged because of implementation differences.
However, if you really want to do so, the only solution is to ensure that the inputs you provide are consistent. This will ensure that (at least within a single environment) the outputs will be consistent.
To have both work like 2017-5-19:

function adjustDateString(str) {
    return str.split('-').map(Number).join('-');
}

console.log(new Date(adjustDateString('2017-5-19')))
console.log(new Date(adjustDateString('2017-05-19')))

To have both work like 2017-05-19:

function padTo2Digits(str) {
    return str.length >= 2 ? str : '0' + str;
}

function adjustDateString(str) {
    return str.split('-').map(padTo2Digits).join('-');
}

console.log(new Date(adjustDateString('2017-5-19')))
console.log(new Date(adjustDateString('2017-05-19')))

Edit: However, you're probably better off, as I pointed out above, not using the Date constructor on a string. Just split it into its values and pass those into the constructor:

function parseDate(str) {
  var parts = str.split('-').map(Number);

  return new Date(parts[0], parts[1], parts[2]);
}

console.log(parseDate('2017-5-19'));
console.log(parseDate('2017-05-19'));

Using array deconstructuring syntax (requires ES6+):

function parseDate(str) {
  let [year, month, day] = str.split('-').map(Number);

  return new Date(year, month, day);
}

console.log(parseDate('2017-5-19'));
console.log(parseDate('2017-05-19'));


text:
Q: Window Update Broke MVC Application I ran Windows Update yesterday and its introduced some problems when I'm trying to release a new version of my ASP.NET MVC 4 project.
The application compiles and runs okay locally, however when I push the version up to a test-site on my webserver it fell over with the error message:
System.Web.HttpCompileException: (0): error CS1705: Assembly 'App_Code, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

After some research I found that this is due to an update from 4.0.0.0 to 4.0.0.1.  I removed the System.Web.Mvc dll from my project and readded the dll that has the later version.  Again everything works locally but not on the web.  I then went through the web.config's and changed any mention of 4.0.0.0 to 4.0.0.1.  Likewise this continues to work internally but fails externally.  The error message is:

Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

I believe this has something to do with Elmah that I'm using for the error handling.
I tried to reinstall from Nuget as suggested here: Windows update caused MVC3 and MVC4 stop working but that hasn't worked and I'm getting the same error.
Added info:
The server hasn't yet been updated, I'm concerned that updating this might break the existing live version.

A: The error message is telling me that you have specified an incorrect version number for the MVC assembly in one of your config files.  Find it the config file with the incorrect version and change it to match whatever version you are using (you mentioned 4.0.0.1 above).  You need to check all the config files including

*

*The one in the project root

*The one in the Views folder

You could also do an assembly redirect in your config file to take care of this as well -- If its failing due to a third party lib this might be the most appropriate action to take.
Based on your feedback id suggest using a binding redirect.  Add this to your main web.config..
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.1" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

A: I had a similar problem where a MS update changed MVC.dll from 3.0.0.0 to 3.0.0.1.  I need to maintain various versions of my software so to ensure compatibility I had to copy the 3.0.0.0 dll to my project and reference it there before building the project.

A: After digging down some more,  I found the web.config inside the view folder is pointing to different version System.web.mvc . Once I changed to
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

from
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

change version of System.Web.MVC to 4.0.0.0 from 4.0.0.1
I was able to solve the issue.


text:
Q: What does "more a feature" mean? Does it mean "the same as..."?
"We think pure discount-rate moves of this nature — that lead to a joint selloff in high- and low-beta assets — are unlikely to be sustained in this environment where inflation is low and weakly pro-cyclical," Saroliya said. Sustained joint selloffs are more a feature of periods like 1974 and the early 1980s, when supply shocks triggered countercyclical inflation, he explained.
Source: http://www.marketwatch.com/story/is-janet-yellen-still-calling-the-tune-in-financial-markets-2017-07-10

A: When we say that something is more a feature of X we mean that it is more characteristic of X {than it is characteristic of Y}. In your sentence, Y corresponds to "this environment where..."
Sustained selloffs are more characteristic of periods like 1974 and the early 1908s than they are (characteristic) of this environment where inflation is low and weakly procyclical.
In the passage you quote, the Y comparand is implicit.

A rabbit won't eat bananas. That food is more a feature of simian
  diets.


text:
Q: Multiplying 3 NSDecimalNumber(s) simultaneously First of all, I'm using NSDecimalNumbers because I'm dealing with currency. I'm not having any trouble with the decimal numbers themselves, I would like to know if it's possible to multiply 3 NSDecimalNumber(s) at the same time.
In other words, if I was multiplying 3 integers I would simply:
int a = 2;
int b = 5;
int c = 7;

int x = a * b * c;

However, in order to multiply NSDecimalNumbers you're forced to use the decimalNumberByMultiplyingBy method.
Using this method, I have to do 2 calculations in order to multiply the 3 NSDecimalNumbers I'm dealing with, like so:
NSDecimalNumber *d1 = [NSDecimalNumber decimalNumberWithString:@"1.502"];
NSDecimalNumber *d2 = [NSDecimalNumber decimalNumberWithString:@"12.472"];
NSDecimalNumber *d3 = [NSDecimalNumber decimalNumberWithString:@"0.765"];

//Calculation
NSDecimalNumber *initialValue = [d1 decimalNumberByMultiplyingBy:d2];
NSDecimalNumber *finalValue = [initialValue decimalNumberByMultiplyingBy:d3];

//Formatting
NSString *output = [NSString stringWithFormat:@"%@", finalValue];
NSDecimalNumber *n = [NSDecimalNumber decimalNumberWithString:output];

//r is my NSNumberFormatter, which I've configured elsewhere
NSString *s = [r stringFromNumber:n];

NSLog(@"%@",s);

Is there a way to multiply all 3 NSDecimalNumbers at the same time instead of this clunky way around it?

A: No is the answer.  Multiplication is a binary operation.  Even
int x = a * b * c;

actually involves two separate multiplications.  It looks less clunky because of the infix notation.
You can do
result = [[d1 decimalNumberByMultiplyingBy: d2] decimalNumberByMultiplyingBy: d3];

which is the equivalent to the first statement.

A: Don't have a Mac nearby, but I think you can do it like that:
NSDecimalNumber *d1 = [NSDecimalNumber decimalNumberWithString:@"1.502"];
NSDecimalNumber *d2 = [NSDecimalNumber decimalNumberWithString:@"12.472"];
NSDecimalNumber *d3 = [NSDecimalNumber decimalNumberWithString:@"0.765"];

//Calculation
NSDecimalNumber *finalValue = [[d1 decimalNumberByMultiplyingBy:d2] decimalNumberByMultiplyingBy:d3];

A: Just write a helper method that encapsulates the NSDecimalNumber multiplication methods and takes 3 NSDecimalNumber arguments and returns a NSDecimalNumber;


text:
Q: Firebase AppCheck token always null I'm having this issue since one week on a Xamarin Android application.
I get the token with this method:
public async void GetToken()
{
 var AppCheckToken =  await AppCheck.GetToken(false);

            if (AppCheckToken is AppCheckTokenResult Tok)
            {
                string r;
                r = Tok.Token;
                Preferences.Set("AppCheckToken", r);
            }
}

that always return this string eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ== on both debug and physical (production) mode. I also tried to make internal tests in Play Console and then download the app from there, but result is always the same.
Here's how I initialize AppCheck:
        auth = FirebaseAuth.GetInstance(app);
        PlayIntegrityAppCheckProviderFactory f = new PlayIntegrityAppCheckProviderFactory();
        f.Create(app);
        AppCheck = FirebaseAppCheck.GetInstance(app);
        AppCheck.InstallAppCheckProviderFactory(f);
        AppCheck.SetTokenAutoRefreshEnabled(true);

I noticed also that AppCheckToken variable declared in GetToken() method is always null and returns this FirebaseException:

--- End of managed Firebase.FirebaseException stack trace --- com.google.firebase.FirebaseException: null at
com.google.firebase.appcheck.internal.DefaultFirebaseAppCheck.lambda$getToken$1(DefaultFirebaseAppCheck.java:205)
at
com.google.firebase.appcheck.internal.DefaultFirebaseAppCheck$$ExternalSyntheticLambda1.then(Unknown
Source:0) at
com.google.android.gms.tasks.zze.run(com.google.android.gms:play-services-tasks@@18.0.2:1)
at android.os.Handler.handleCallback(Handler.java:942) at
android.os.Handler.dispatchMessage(Handler.java:99) at
android.os.Looper.loopOnce(Looper.java:201) at
android.os.Looper.loop(Looper.java:288) at
android.app.ActivityThread.main(ActivityThread.java:7892) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) Caused
by: java.lang.NumberFormatException: null at
java.lang.Long.parseLong(Long.java:699) at
java.lang.Long.parseLong(Long.java:861) at
com.google.firebase.appcheck.playintegrity.internal.PlayIntegrityAppCheckProvider.lambda$getPlayIntegrityAttestation$4$com-google-firebase-appcheck-playintegrity-internal-PlayIntegrityAppCheckProvider(PlayIntegrityAppCheckProvider.java:105) at
com.google.firebase.appcheck.playintegrity.internal.PlayIntegrityAppCheckProvider$$ExternalSyntheticLambda1.then(Unknown
Source:4) at
com.google.android.gms.tasks.zzo.run(com.google.android.gms:play-services-tasks@@18.0.2:1)
... 8 more

I tried also to generate a debug token from Firebase Console to use in the app in debug mode but when I make the call to Firebase Storage (that is already enforced) it keeps saying "AppCheck Token is invalid".
UPDATE:
I've tried also this approach: FirebaseAppCheck AppCheck = FirebaseAppCheck.Instance; AppCheck.InstallAppCheckProviderFactory(PlayIntegrityProviderFactory.Instance);
and for just one time FirebaseException was saying something like "PlayStore is not uptodate in your device". So I've updated PlayStore and now it throws the same error described above. I've tried to get the token with an AddOnSuccessListener(this) but result is the same.
Also I have to tell that var AppCheckToken declared before the if statement becomes always an object of class DefaultFirebaseAppCheckTokenResult.
I don't know what else to do...
IMHO there's a problem with declaration of objects (that are nulls), but since there aren't documents on how to use AppCheck on C# I'm screwed.


text:
Q: Spreadsheet UI - User prompted to open or save userAppPanel from docs.google.com My UI works for me (I'm the spreadsheet owner and script creator).  However, when I share the spreadsheet with other users, the UI does not display fully and they are prompted to open or save the userAppPanel from docs.google.com.
I've complete cut down my script to the following, still not luck:
function showDialog() {
    // Create the UI application
    var uiApp = UiApp.createApplication();

    // Provide the Popup with a title
    uiApp.setTitle('Parameter Collection Dialog');

    // Create an user instruction label
    var lblInstructions = uiApp.createLabel()
      .setText('Select a type of Person and Country');

    // Add the panel to the application
    uiApp.add(lblInstructions);

    // Show the application in the spreadsheet
    var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
    spreadSheet.show(uiApp);
}

The UI works when the the script is run from the script editor for every user that tries - however, when I hook it up to an "on open spreadsheet" trigger, the script only works for me - and no-one else.
I'm so close to nailing my requirement and this is a very frustrating last hurdle.
Many thanks
Update:  Please see my comment for a solution i.e. use onOpen function rather than a manual onOpen trigger.

A: I've attempted to recreate the problem and was able to do so easily. This appears to be a bug. I suggest you open an issue in the Issue Tracker and update this thread with the bug number.

A: Thanks for confirming Srik. However, I have worked out a solution:
I was hooking up the showDialog function to the On Open trigger, manually through the script editor. but, if you change the showDialog() function name to onOpen(), then you don't have to hook up the function to the event manually as onOpen is a built in event, and it now works for all users (providing they are shared users, and logged in).
I will open an issue too, as I believe it should work both ways.
Hope my solution helps others too :)

A: Unfortunately the workaround with renaming the function onOpen is not always applicable, for instance when you need the function to run under the identity of someone (yourself for example). If you rename it onOpen(), it will run under no identity. I cannot do that because I need to authenticate into a database.
This seems to confirm that the problem is linked to the identity of the person triggering the script.
have you posted an issue ? Could you please share the link to it ?


text:
Q: Prove the following determinant formula i need to prove the following

$$ \begin{bmatrix}
1+ x_1y_1 & x_1y_2 & \cdots & x_1y_n \\
x_2y_1 & 1+ x_2y_2 & \cdots & x_2y_n \\
\vdots & \vdots & \ddots & \vdots \\
x_ny_1 & x_ny_2 & \cdots & 1+x_ny_n \\
\end{bmatrix} = 1 + \sum_{i=1}^n{x_iy_i}
$$

can anyone point me the first move?

A: Your matrix can be written as $I+xy^T$ where $I$ is the identity matrix and $x=(x_1,\dots,x_n)^T, y=(y_1,\dots,y_n)^T$.
Then apply here.

A: The matrix
$$
A=
\begin{bmatrix}
x_1y_1 & x_1y_2 & \cdots & x_1y_n \\
x_2y_1 & x_2y_2 & \cdots & x_2y_n \\
\vdots & \vdots & \ddots & \vdots \\
x_ny_1 & x_ny_2 & \cdots & x_ny_n \\
\end{bmatrix}
$$
can be written as
$$
A=\begin{bmatrix}x_1\\x_2\\\vdots\\x_n\end{bmatrix}
\begin{bmatrix}y_1 & y_2 & \dots & y_n\end{bmatrix}
$$
so it has rank $1$. It also has the eigenvalue $\lambda=x_1y_1+\dots+x_ny_n$, so its characteristic polynomial is
$$
p_A(X)=(0-X)^{n-1}(\lambda-X)
$$
The determinant of $A+I$ is thus
$$
p_A(-1)=\lambda+1=1+\sum_{1\le i\le n}x_iy_i.
$$

A: In this answer, it is shown that if $A$ is an $n\times m$ matrix and $B$ is an $m\times n$ matrix, then
$$
\lambda^m\det(\lambda I_n-AB)=\lambda^n\det(\lambda I_m-BA)
$$
Setting $\lambda=-1$ gives
$$
\det(I_n+AB)=\det(I_m+BA)
$$
Setting $A=\left[\begin{array}{c}x_1\\x_2\\\vdots\\x_n\end{array}\right]$ and $B=\left[\begin{array}{c}y_1&y_2&\dots&y_n\end{array}\right]$ gives your result.

A: Hint: Just use induction, and use cofactor expansion along last row, along with elementary row operations


text:
Q: ToolTip on ListView SubItem is not shown I am unable to show tooltips on ListView subitems. Involved implementation is:
ListView sqlView = new ListView() { Dock = DockStyle.Fill, View = View.Details, MultiSelect = true, FullRowSelect = true, HeaderStyle = ColumnHeaderStyle.Nonclickable, GridLines = true };
...
sqlView.ShowItemToolTips = true;
sqlView.MouseMove += sqlView_MouseMove;
...
// filled in foreach, don't worry it's correct here ;)
item.SubItems[columnIndex].Text = "✔";
item.SubItems[columnIndex].Tag = ("via: '" + sqlEntry.Login + "'");

Mouse event handler method:
void sqlView_MouseMove(object sender, MouseEventArgs e)
{
    ListView sqlView = ((ListView)sender);

    ListViewItem item = sqlView.GetItemAt(e.X, e.Y);
    ListViewHitTestInfo info = sqlView.HitTest(e.X, e.Y);

    if (item != null && info.SubItem != null && info.SubItem.Tag != null)
    {
        ToolTip tt = new ToolTip();
        //tt.ShowAlways = true; - no effect
        //tt.Active = true;     - no effect

        tt.SetToolTip(sqlView, (String)info.SubItem.Tag);
    }
}

Events are firing. Subitems Tags are filled properly. No Tooltip shown. Why?
Thx for help.

A: Don't create a new ToolTip() each time through. Just create one and reuse it.


text:
Q: Flask and jsonify: Escaping characters I have a flask view which returns some JSON formatted data:
def myview():
    entities = get_my_entities()
    return jsonify({'entities': entities})

entities if a list of dictionaries; in each dictionary there is a value like http://example.com/get/<user_id>/12345678 where <user_id> is a placeholder where the user should insert an indentifier that that have been given (and which should not appear in the JSON result).
The problem is, the <user_id> gets escaped and appears as %3Cuser_id%3E. Is there a way to stop the characters getting escaped?

A: Thanks to Martijn. I'm using url_for to build the URLs, and its doing the escaping.


text:
Q: Printing prime number between a range. Sieve of Eratosthenes I've got all the numbers appended into list1 from x to y (inclusive). I now only need the list to contain only prime numbers from x to y inclusive
def primes(x , y):
    list1 = []
    for i in range(m, n + 1):
            list1.append(i)
    for elements in list1:
            if elements % 2 == 0:
                    pos = list1.index(elements)
                    list1.pop(pos)
    return list1

I've got all the numbers appended into list1 from x to y (inclusive) and also got rid of the even numbers but i cant seem to get rid of the other numbers that arent prime. I now only need the list to contain only prime numbers from x to y inclusive
For example x = 7, y = 23
list1 = [7, 11, 13, 17, 19, 23]
Thanks in advance

A: Here's a few tips: You don't need to generate the whole list of integer between x and y, and then remove the non-prime one. One faster approach is to generate all the prime numbers smaller than y and then remove those who are smaller than x. That way you can use the previously computed prime numbers to efficiently check if a number is a prime or not.
So let's start at the beginning. 2 is the only even prime number. So you can start from 2 and iterates over the odd number till y. A number will be prime if it is not divisible by any previous prime number.
For each number between 0 and y, you start with the assumption that it is a prime number. You check if it is divisible by the previous primes. If it is a multiple of any prime number then you can stop (break) since you know it is not a prime number. If it was not a multiple of any previous prime, then you add it to the list of prime numbers.
Finally once you have your list of prime numbers between 0 and y, you remove the elements smaller than x.
Which gives in Python:
def primes(x , y):
    l = [2] # list of prime numbers
    for n in range(3,y+1,2): # iterations over odd numbers
        isprime = True
        for e in l:
            if n % e == 0:
                isprime = False
                break
        if(isprime):
            l.append(n)

    return [e for e in l if e >= x]

print(primes(7,23))
# [7, 11, 13, 17, 19, 23]


text:
Q: Impicit conversion warning I am doing this simple operation with a string in VB.NET
I have a string of information called segmentInfo looking like this:
XRT0034:3:89:23
So I am just trying to get a number out of it:
Dim rowNum As Integer = segmentInfo.split(":")(1)

And I am getting actually 2 warnings. Both warning are given on the same line of code.
Warning - Implicit conversion from 'String' to 'Integer'
Warning - Implicit conversion from 'String' to 'Char'

Maybe I could understand the first one, about the string to integer...but the second one?? I do not understand.
Anyway, can anybody tell me what I am doing wrong and how to fix it?

A: The Split method takes a Char (array) as a parameter, not a string. Hence:
.... segmentInfo.split(":"c)(1)

Secondly, you need to parse the resulting string to an integer:
Dim rowNum As Integer = Integer.Parse(segmentInfo.split(":"c)(1))

Do this only when you know that the string is a number. Otherwise, use TryParse.

A: No such overload method String.Split which take one parameter of type String
From MSDN String.Split Method
You can change to
Dim rowNum As Integer = segmentInfo.split(":"c)(1)

":"c - c is character of type Char Type Characters (Visual Basic)
For converting String to Integer use Int32.TryParse or Int32.Parse method to convert string to integer
Dim rowNum As Int32 = Int32.Parse(segmentInfo.split(":"c)(1))
'Exception will be thrown if string value not convertible to Integer type

Or
Dim rowNum As Int32
If Int32.TryParse(segmentInfo.split(":"c)(1), rowNum) = True Then
    'Use succesfully converted integer value
Else
    'Show message about invalid text
End If

A: You must parse it to integer form
Dim rowNum As Integer = Convert.ToInt32(segmentInfo.split(":")(1))

A: Dim rowNum As Integer = Integer.Parse(segmentInfo.split(":"c)(1))


text:
Q: Preciso declarar a Versão do SVG na tag? Estou com uma dúvida sobre a necessidade de declarar a versão do SVG na tag <svg>
Sei que o SVG começou com a versão 1.0, 1.1, 1.2 e agora está na versão 2.0. Alguns SVG vejo com a declaração da versão e outros sem, porém os dois são renderizados normalmente pelo Browser. Também sei que existem várias mudanças entre a versão 1.2 e 2.0.
Ai ficou a dúvida, uma vez que eu não declaro a versão do SVG como o navegador vai saber qual versão estou usado? Existe realmente a necessidade de declarar o version já que têm coisas bem diferentes entre uma versão e outra?
Exemplo com version="1.1" declarada.

<svg version="1.1" x="0px" y="0px" width="612px" height="502.174px" viewBox="0 65.326 612 502.174" >
    <ellipse class="ground" cx="183.5" cy="187.5" rx="159" ry="80"/>
</svg>

Exemplo sem version declarada

<svg viewBox="0 0 30 10">
  <circle id="myCircle" cx="5" cy="5" r="4"/>
</svg>

A: Não existe.
Conforme documentação na MDN, o atributo version é puramente informativo, sem nenhuma influência em como os elementos serão processados ou renderizados.
Tanto que a partir da versão 2.0 o atributo está obsoleto.