text:
Q: Magento 2: Graphql Custom collection data returns null
I'm creating Graphql for my custom module, but after
setting an endpoint and writing a query for it, does not return
any data.

Below are the files I have created for Graphql,

MyVendor/RMAModule/etc/schema.graphqls

type Query {
    RmaResolver (
        emailId: String @doc(description: "Email Address")
    ): RmaResolver @resolver(class:"MyVendor\\RMAModule\\Model\\Resolver\\RmaResolver") @doc(description:"Custom Module Datapassing")
}

type RmaResolver {
    rmaData: [RmaRecord] @doc(description: "RMA records")
}

type RmaRecord {
    entity_id : Int @doc(description: "Entity Id")
    order_id : Int @doc(description: "Order Id")
    customer_id : Int @doc(description: "Customer Id")
    customer_name : String @doc(description: "Customer Name")
    customer_email : String @doc(description: "Customer Email")
    delivery_status : String @doc(description: "Delivery Status")
    additional_info : String @doc(description: "Additional Info")
    rma_status : String @doc(description: "RMA Status")
    created_on : String @doc(description: "Created on")
}

MyVendor/RMAModule/Model/Resolver/RmaResolver.php

    <?php
namespace MyVendor\RMAModule\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;
use MyVendor\RMAModule\Model\RmaFactory;

class RmaResolver implements ResolverInterface
{
    /**
     * @var ValueFactory
     */
    private $valueFactory;

    /**
     * @var RmaFactory
     */
    protected $rmaFactory;

    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepository;

    /**
     * @var AccountManagementInterface
     */
    protected $customerAccountManagement;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

     /**
     * @param ValueFactory $valueFactory
     * @param RmaFactory $rmaFactory
     * @param CustomerRepositoryInterface $customerRepository
     * @param AccountManagementInterface $customerAccountManagement
     * @param StoreManagerInterface $storeManager
     * @param array
     */
    public function __construct(
        ValueFactory $valueFactory,
        RmaFactory $rmaFactory,
        CustomerRepositoryInterface $customerRepository,
        AccountManagementInterface $customerAccountManagement,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->valueFactory = $valueFactory;
        $this->rmaFactory = $rmaFactory;
        $this->customerRepository = $customerRepository;
        $this->customerAccountManagement = $customerAccountManagement;
        $this->storeManager = $storeManager;
    }

     /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null)
    {
        try{
            $emailId = $this->getEmailId($args);
            $rmaData = $this->getRmaData($emailId);

            $result = function () use ($rmaData) {
                return !empty($rmaData) ? $rmaData : [];
            };
            return $this->valueFactory->create($result);
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        } catch (LocalizedException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        }
    }

     /**
     * @param array $args
     * @return int
     * @throws GraphQlInputException
     */
    public function getEmailId(array $args): int
    {
        if (!isset($args['emailId'])) {
            throw new GraphQlInputException(__('EmailId should be specified'));
        }

        return (int)$args['emailId'];
    }

    /**
     * @return array
     * @throws GraphQlNoSuchEntityException
     */
    public function getRmaData(string $emailId): array
    {
        $emailNotExist = $this->emailExistOrNot($emailId);

        if($emailNotExist){
            // Guest User
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                ->addFieldToFilter("customer_email", $emailId)
                ->addFieldToFilter('customer_id', null);
        }else{
            // Customer
            $customerData = $this->customerRepository->get($emailId);
            $customerId = (int)$customerData->getId();
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                            ->addFieldToFilter("customer_id", $customerId);
        }

        $output['rmaData'] = [];
        foreach ($rmaCollection as $rmaItem) {
            // $output['rmaData'][] = [
            //     'entity_id' => $rmaItem['entity_id'],
            //     'order_id' => $rmaItem['order_id'],
            //     'customer_id' => $rmaItem['customer_id'],
            //     'customer_name' => $rmaItem['customer_name'],
            //     'customer_email' => $rmaItem['customer_email'],
            //     'delivery_status' => $rmaItem['delivery_status'],
            //     'additional_info' => $rmaItem['additional_info'],
            //     'rma_status' => $rmaItem['rma_status'],
            //     'created_on' => $rmaItem['created_on']
            // ];
            $rmaId = $rmaItem->getId();
            $output['rmaData'][$rmaId]['entity_id'] = $rmaItem['entity_id'];
            $output['rmaData'][$rmaId]['order_id'] = $rmaItem['order_id'];
            $output['rmaData'][$rmaId]['customer_id'] = $rmaItem['customer_id'];
            $output['rmaData'][$rmaId]['customer_name'] = $rmaItem['customer_name'];
            $output['rmaData'][$rmaId]['customer_email'] = $rmaItem['customer_email'];
            $output['rmaData'][$rmaId]['delivery_status'] = $rmaItem['delivery_status'];
            $output['rmaData'][$rmaId]['additional_info'] = $rmaItem['additional_info'];
            $output['rmaData'][$rmaId]['rma_status'] = $rmaItem['rma_status'];
            $output['rmaData'][$rmaId]['created_on'] = $rmaItem['created_on'];
        }
        return $output;

    }

    /**
     * Returns Email Id exist or not
     *
     * @return bool
     */
    public function emailExistOrNot($emailId): bool
    {
        $websiteId = (int)$this->storeManager->getWebsite()->getId();
        $isEmailNotExists = $this->customerAccountManagement->isEmailAvailable($emailId, $websiteId);
        return $isEmailNotExists;
    }
}

I have set an endpoint as http://127.0.0.1/magento243/graphql and the query is,
{
  RmaResolver(emailId: "abc@example.com") {
    rmaData{
      entity_id
      order_id
      customer_id
      customer_name
      customer_email
      delivery_status
      additional_info
      rma_status
      created_on
    }
  }
}

But the result is blank array,
{
  "data": {
    "RmaResolver": {
      "rmaData": []
    }
  }
}

I have also created an API for getting data and with the API I'm getting records. FYI defined email-id is a customer and has rma records.
Please let me know if anyone has a solution.

A:
Update below files and run magetno 2 upgrade and cache clean command

MyVendor/RMAModule/etc/schema.graphqls
type Query {
    RmaResolver (
        emailId: String @doc(description: "Email Address")
    ): [RmaRecord] @resolver(class:"MyVendor\\RMAModule\\Model\\Resolver\\RmaResolver") @doc(description:"Custom Module Datapassing")
}

type RmaRecord {
    entity_id : Int @doc(description: "Entity Id")
    order_id : Int @doc(description: "Order Id")
    customer_id : Int @doc(description: "Customer Id")
    customer_name : String @doc(description: "Customer Name")
    customer_email : String @doc(description: "Customer Email")
    delivery_status : String @doc(description: "Delivery Status")
    additional_info : String @doc(description: "Additional Info")
    rma_status : String @doc(description: "RMA Status")
    created_on : String @doc(description: "Created on")
}

MyVendor/RMAModule/Model/Resolver/RmaResolver.php
<?php

namespace MyVendor\RMAModule\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;
use MyVendor\RMAModule\Model\RmaFactory;

class RmaResolver implements ResolverInterface
{
    /**
     * @var ValueFactory
     */
    private $valueFactory;

    /**
     * @var RmaFactory
     */
    protected $rmaFactory;

    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepository;

    /**
     * @var AccountManagementInterface
     */
    protected $customerAccountManagement;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

     /**
     * @param ValueFactory $valueFactory
     * @param RmaFactory $rmaFactory
     * @param CustomerRepositoryInterface $customerRepository
     * @param AccountManagementInterface $customerAccountManagement
     * @param StoreManagerInterface $storeManager
     * @param array
     */
    public function __construct(
        ValueFactory $valueFactory,
        RmaFactory $rmaFactory,
        CustomerRepositoryInterface $customerRepository,
        AccountManagementInterface $customerAccountManagement,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->valueFactory = $valueFactory;
        $this->rmaFactory = $rmaFactory;
        $this->customerRepository = $customerRepository;
        $this->customerAccountManagement = $customerAccountManagement;
        $this->storeManager = $storeManager;
    }

     /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null)
    {
        try{
            return $this->getRmaData($args);
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        } catch (LocalizedException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()));
        }
        return [];
    }

     /**
     * @param array $args
     * @return int
     * @throws GraphQlInputException
     */
    public function getEmailId(array $args): int
    {
        if (!isset($args['emailId'])) {
            throw new GraphQlInputException(__('EmailId should be specified'));
        }
        return (int)$args['emailId'];
    }

    /**
     * @return array
     * @throws GraphQlNoSuchEntityException
     */
    public function getRmaData(string $emailId): array
    {
        $emailNotExist = $this->emailExistOrNot($emailId);

        if($emailNotExist){
            // Guest User
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                ->addFieldToFilter("customer_email", $emailId)
                ->addFieldToFilter('customer_id', null);
        }else{
            // Customer
            $customerData = $this->customerRepository->get($emailId);
            $customerId = (int)$customerData->getId();
            $rmaCollection = $this->rmaFactory->create()->getCollection()
                            ->addFieldToFilter("customer_id", $customerId);
        }

        $output = [];
        foreach ($rmaCollection as $rmaItem) {
            // $output['rmaData'][] = [
            //     'entity_id' => $rmaItem['entity_id'],
            //     'order_id' => $rmaItem['order_id'],
            //     'customer_id' => $rmaItem['customer_id'],
            //     'customer_name' => $rmaItem['customer_name'],
            //     'customer_email' => $rmaItem['customer_email'],
            //     'delivery_status' => $rmaItem['delivery_status'],
            //     'additional_info' => $rmaItem['additional_info'],
            //     'rma_status' => $rmaItem['rma_status'],
            //     'created_on' => $rmaItem['created_on']
            // ];
            $rmaId = $rmaItem->getId();
            $output[$rmaId]['entity_id'] = $rmaItem['entity_id'];
            $output[$rmaId]['order_id'] = $rmaItem['order_id'];
            $output[$rmaId]['customer_id'] = $rmaItem['customer_id'];
            $output[$rmaId]['customer_name'] = $rmaItem['customer_name'];
            $output[$rmaId]['customer_email'] = $rmaItem['customer_email'];
            $output[$rmaId]['delivery_status'] = $rmaItem['delivery_status'];
            $output[$rmaId]['additional_info'] = $rmaItem['additional_info'];
            $output[$rmaId]['rma_status'] = $rmaItem['rma_status'];
            $output[$rmaId]['created_on'] = $rmaItem['created_on'];
        }
        return $output;
    }

    /**
     * Returns Email Id exist or not
     *
     * @return bool
     */
    public function emailExistOrNot($emailId): bool
    {
        $websiteId = (int)$this->storeManager->getWebsite()->getId();
        $isEmailNotExists = $this->customerAccountManagement->isEmailAvailable($emailId, $websiteId);
        return $isEmailNotExists;
    }
}

Query is:
query RmaResolver {
    RmaResolver(emailId: "abc@example.com"){
        entity_id
        order_id
        customer_id
        customer_name
        customer_email
        delivery_status
        additional_info
        rma_status
        created_on
    }
}

[Update]
Check Below For Your Reference, It might help you.
app/code/VendoreName/ModuleName/etc/schema.graphqls
type Query {
    getbytype (
        type: Int @doc(description: "get Banner by type")
    ): [getbyytype] @resolver(class: "VendoreName\\ModuleName\\Model\\Resolver\\BannerType") @doc(description: "The query returns the banner belong to type id")
}

type getbyytype @doc(description: "all Attributes to show in Product Details Page") {
    banner_id : Int  @doc(description: "Banner Id")
    title : String  @doc(description: "Title")
    status : Int  @doc(description: "Status")
    image : String  @doc(description: "If image then show")
    banner_title : String  @doc(description: "Banner title")
    color_picker : String  @doc(description: "Colore Picker title")
    color_picker_bg: String  @doc(description: "Background Colore Picker title")
    banner_content : String  @doc(description: "Banner Content")
    banner_type : Int  @doc(description: "Banner Type")
    button_show : Int  @doc(description: "Button Show status")
    button_txt : String  @doc(description: "Button text")
    button_color : String  @doc(description: "Button colore")
    display_position : Int  @doc(description: "Display Position ")
    position : Int  @doc(description: "Position")
}

app/code/VendoreName/ModuleName/Model/Resolver/BannerType.php
<?php

namespace VendoreName\ModuleName\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

class BannerType implements ResolverInterface
{
    private $bannertypeDataProvider;

    /**
     * @param DataProvider\BannerType $bannertypeDataProvider
     */
    public function __construct(
        \VendoreName\ModuleName\Model\Resolver\DataProvider\BannerType $bannertypeDataProvider
    ) {
        $this->bannertypeDataProvider = $bannertypeDataProvider;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        //by Type
        $type = $this->getType($args);
        $bannerData = $this->bannertypeDataProvider->getByType($type);
        return $bannerData;
    }

    private function getType(array $args)
    {
        if (!isset($args['type'])) {
            throw new GraphQlInputException(__('"Type should be specified'));
        }
        return $args['type'];
    }
}

app/code/VendoreName/ModuleName/Model/Resolver/DataProvider/BannerType.php
<?php

namespace VendoreName\ModuleName\Model\Resolver\DataProvider;

class BannerType extends \Magento\Framework\View\Element\Template
{
    protected $_bannerTypeData;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \VendoreName\ModuleName\Model\BannerFactory $bannerTypeData,
        array $data = []
    ) {
        $this->_bannerTypeData = $bannerTypeData;
        parent::__construct($context, $data);
    }

    /**
     * @params int $id
     * this function return all the word of the day by id
     **/
    public function getByType($type)
    {
        $atr_data = $this->_bannerTypeData->create()->getCollection();
        $atr_data->addFieldToFilter('display_position', $type);
        $attributes_data = [];
        $x = 0;
        foreach ($atr_data as $attribute) {
            $attributes_data[$x]['banner_id'] = $attribute->getId();
            $attributes_data[$x]['title'] = $attribute->getTitle();
            $attributes_data[$x]['status'] = $attribute->getStatus();
            $attributes_data[$x]['image'] = $attribute->getImage();
            $attributes_data[$x]['banner_title'] = $attribute->getBannerTitle();
            $attributes_data[$x]['color_picker'] = $attribute->getColorPicker();
            $attributes_data[$x]['color_picker_bg'] = $attribute->getColorPickerBg();
            $attributes_data[$x]['banner_content'] = $attribute->getBannerContent();
            $attributes_data[$x]['button_show'] = $attribute->getButtonShow();
            $attributes_data[$x]['button_txt'] = $attribute->getButtonTxt();
            $attributes_data[$x]['button_color'] = $attribute->getButtonColor();
            $attributes_data[$x]['banner_type'] = $attribute->getBannerType();
            $attributes_data[$x]['display_position'] = $attribute->getDisplayPosition();
            $attributes_data[$x]['position'] = $attribute->getPosition();
            $x++;
        }
        return $attributes_data;
    }
}

Query is:
query getbytype {
  getbytype(type: 2) {
    banner_id
    title
    status
    image
    banner_title
    color_picker
    color_picker_bg
    banner_content
    banner_type
    button_show
    button_txt
    button_color
    display_position
    position
  }
}

Note: Must be run upgrade and cache clean command.

Please try with static data and you can use echo and print_r() and
check into the network tab to inspect (F12) to see data and log
MyVendor/RMAModule/Model/Resolver/RmaResolver.php

Before changes
/**
 * @param array $args
 * @return int
 * @throws GraphQlInputException
 */
public function getEmailId(array $args): int
{
    if (!isset($args['emailId'])) {
        throw new GraphQlInputException(__('EmailId should be specified'));
    }
    return (int)$args['emailId'];
}

After Changes which is working
/**
     * @param array $args
     * @return string
     * @throws GraphQlInputException
     */
    public function getEmailId(array $args): string
    {
        if (!isset($args['emailId'])) {
            throw new GraphQlInputException(__('EmailId should be specified'));
        }

        return (string)$args['emailId'];
    }


text:
Q: NoSuchSessionException in selenium on git I have selenium script running on Firefox browser. This script execute well on local system but when we push the code on GIT and execute pipeline then it break after executing some steps by throwing below exception:
org.openqa.selenium.NoSuchSessionException: Tried to run command without establishing a connection
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'XXXXXXXXXXXXX', ip: '1XXXXXX', os.name: 'Linux', os.arch: 'amd64', os.version: 'XXXXX-aws', java.version: '1.8.0_242'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 75.0,   javascriptEnabled: true, moz:accessibilityChecks: false, moz:buildID: 20200403170909,  moz:geckodriverVersion: 0.26.0, moz:headless: false, moz:processID: 64, moz:profile: /tmp/rust_mozprofilerzeT93, moz:shutdownTimeout: 60000, moz:useNonSpecCompliantPointerOrigin: false, moz:webdriverClick: true, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX,   platformVersion: 00000aws, rotatable: false, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webdriver.remote.sessionid: 7061f603-50d8-48c7-bfc0-e75...}
Session ID: 7061f603-50d8-48c7-bfc0-e7540fd5c115

YML File have this code to get Firefox driver:
services:
    - selenium/standalone-Firefox

Same thing happens with chrome. What i observed when system did not find the element, and went to take the  screen shot  script throws this error. And this is intermittent, some time works well.
Please help if have face such type of issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Twilio Rest API / Node Js call status no working I'm creating a tool that can automatically call someone when I click a button.
So far, I've tested three solutions: The first one was using the rest API call, the second one was using node js SDK that is available in the Twilio console using the function & assets feature, and the last one was using Twilio Studio feature.
All of them are not giving me the satisfaction of creating something that can be used in production.
The main problem is the call status given to the StatusCallback url parameter.
For example:

*

*if you set a timeout value by default or something higher than the duration of the ringing time, it will send you a completed status. The timeout value needs to be smaller than the maximum number of ringtone that your carrier set by default if you want to receive a no-answered status.

*If your phone is on "airplane mode" and you make a call to it using Twilio, the statusCallback will be sent to the URL as "completed".

*If you make the same phone call and imagine that the user rejects the call by clicking on the red phone instead of the green phone, the statusCallback will send you a completed status.
So it's been a week since I've coded a NodeJS solution using Twilio Functions, making POST requests using Postman, and also creating a flow to test it using Twilio Studio. Every time that I've tried those three solutions, with the three same scenarios described above, I've never been able to obtain a real valuable/informative status that can help me to resend the call until someone answers or, based on the status, send an SMS to the person to inform him that we have tried to call him and that he either was not available or rejected the call.
Has one of you already tested that and maybe succeeded in having anything else than a "completed" status? That is no use in case you need to handle those cases.
Thank you for your help.


text:
Q: IllegalArgumentException: Path must be absolute: ../DATA_WAREHOUSE/0_RAW/ASADI/raw_t_xd_diag_log_manually_car raw_t_xd_diag_log_manually_car = spark.read.format('parquet').load("../DATA_WAREHOUSE/0_RAW/ASADI/raw_t_xd_diag_log_manually_car").withColumn("vin", fn.concat(['whc_cd', 'lit','vehicle_id']))
I am getting an error while running this code in Azure Databricks.

A: The error is correct - you need to provide a full path or URI, like, /mnt/my-data/..., or abfss://container@storage...../path or something like that. But you're specifying the relative path that isn't resolvable because there is no notion of the current directory.


text:
Q: How to get response from scrapy.Request without callback? I want to send a request and wait for a response from the server in order to perform action-dependent actions. I write the following
resp = yield scrapy.Request(*kwargs)

and got None in resp. In documentation I find that need to use call_back function, but this function call after processing next commands. How to wait response from server?

A: I found the inline_requests module which has inline_requests decorator.
It solved my problem.

A: This isn't really how scrapy should be used, as waiting for a response is the same as using a callback. If you need to keep processing previous responses in conjunction with the new one, you can always pass and keep passing the response on the meta argument.
Now, to make this sometimes more readable you can also use scrapy-inline-requests which makes exactly the same as explained before under the hood, as it doesn't stop scrapy but makes the following request in order (same as doing a request after another with callbacks).
If using scrapy-inline-requests please be careful on making the methods to only be generators and also sending new requests or items when a new inline request is being processed.

A: it's not an answer to this question, but is alternative how to get response object and parse it using xpath. Here I use requests, bs4 and lxml libraries.
import requests
from bs4 import BeautifulSoup
from lxml import etree

url = 'your_url'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
dom = etree.HTML(str(soup))
target_data = dom.xpath("//div......target path......")


text:
Q: Inequality involving Harmonic mean Let $a, b \ge 0 $ and $x,y > 1$ Show $\frac{1}{1/x+1/y}(a+b) \le \max(ax,by)$
If $a = b = 0$ then this is clear so assume not both are zero.
This seems to be related to the harmonic mean but I am not quite getting it.
$\frac{1}{1/x+1/y}(a+b)  = \frac{xy}{x+y}(a+b) = \frac{1}{2}H(x,y)(a+b)$
Where $H(x,y) = \frac{2xy}{x+y}$ : the harmonic mean of $x,y$
And, $\max(ax,by) = \frac{1}{2}[ax+by+\mid ax - by \mid ] = A(ax,by) + \frac{1}{2}\mid ax - by \mid$
Where $A(ax,by) = \frac{ax+by}{2}$ : the arithmetic mean of $ax,by$
This is where I get stuck.
EDIT: I am closer but not quite:
$\displaystyle \frac{a+b}{x+y} = \frac{a}{x+y}+\frac{b}{x+y} \le \frac{a}{y} + \frac{b}{x} \implies xy\frac{a+b}{x+y} \le xy(\frac{a}{y} + \frac{b}{x} ) = ax + by \le 2\max(ax,by) $

A: In fact, the conditions for $x,y,a,b$ can be loosened:
For all $x,y > 0$ and $a,b \in \mathbb{R}$, we have
$$\frac{1}{1/x+1/y}(a+b)=\dfrac{y\cdot ax+x\cdot by}{x+y} \le \dfrac{y\cdot \max(ax,by)+x\cdot \max(ax,by)}{x+y} =\max(ax,by).$$

A: Cauchy Schwarz says for $a,b\in\mathbb{R}$ and $x,y\gt0$,
$$
(a+b)^2\le\left(a^2x+b^2y\right)\left(\frac1x+\frac1y\right)
$$
which gives, for $a+b\ge0$,
$$
\begin{align}
\frac1{\frac1x+\frac1y}(a+b)
&\le\frac{a(ax)+b(by)}{a+b}\\
&\le\max(ax,by)
\end{align}
$$


text:
Q: How to change the project name property in the subproject list in Gradle after initialisation? I would like to know if it was possible to modify the project name property in the subprojects list in Gradle, after the build?
I'll try to explain myself a little bit better. In Gradle, you specify the name of your projects in a settings file that is included during initialization.
However, for some reasaon I need to change to order in which the projects are processed at "runtime".
ex : println $subprojects will show [project : 'a', project : 'b', project : 'c']
I have already done the sorting in a different list but it would be a bit cleaner and more maintainable if I could modify the program in order for the subprojects list to match my sorted list.


text:
Q: ajax onkeyup event 501 from rapid input On the Javascript side of things I registered an event listener to a text <input> for the onkeyup event.
Each time the event is triggered, a function is invoked that creates an xmlhttprequest object that passes the input's value as an url encoded POST variable to the request.
The request page is an aspx script which accepts the post variable, does some processing on it, and adds the processed input as a parameter to a MS SQL query.  The result set produced from executing the query is placed into a dataset which is converted to XML and then transformed via an XSLT into XHTML that is then inserted into the page that made the ajax call via the innerHTML injection method.
If you've followed me so far, the result is a full-text search on an MS SQL DB that produces results for each key release.  It is also worth mentioning that I am using MS SQL 2005 and IIS6.0.
The system seems to work great, except for one test-case.  That is when someone just pounds input as fast as they possibly can the server eventually returns 501 internal server errors for each request.  After a few minutes, it seems to "fix" itself and operate normally again.  I was unable to gleam any useful information from IIS about these internal errors.
Now this is mere speculation, but my first assumptions were that either there were too many open simultaneous requests that had not yet finished, or that there were too many requests being made in a short period.
My initial thought was to create a queue of these xmlhttprequests and only open one at a time.
However, rather than the queue I tried this:
Each onkeyup:

*

*Call abort on the last xmlhttprequest that was generated by onkeyup

*Create a new xmlhttprequest for this onkeyup
This procedure appears to eliminate the problem.
What I was unable to do was determine the root cause of this issue: is it a server limitation? or is it a browser limitation?  Is there some other way to solve this problem without needing this abort procedure?
I can post code if necessary, but the code is very lengthy and many technologies are at use in this project so I'm not sure if it would really help anyone answer this question.

A: You may want to look at debouncing.
http://ajaxian.com/archives/debounce-your-javascript-functions


text:
Q: How is `auto a(b);` parsed in C++? I came across a curious line of code of the form:
// Given the following definitions:
class B;
B b;

// Line of interest:
auto a(b);

I thought it must be a typo, but after some experimentation found out that it works, and seems to always call the copy constructor of the type of b (even if you have other classes that can also have a matching constructor, and even if you additionally delete the copy constructor for the type of b).
I don't know the technical name of such a statement, so I'm not sure how to search for it in cppreference or StackOverflow.  How does the compiler parse this type of statement in general, and where is it documented?
--
Re: duplicate marking.  I don't see how they've addressed this construct.  I already know auto uses template type deduction, that doesn't clarify anything in this case.

A:
How is auto a(b); parsed in C++?

Depends on what b is. If b is a type, then this is a declaration of function with name a with deduced return type and a single argument of type b.
If b is not a type, then this defines a variable by the name a whose type is deduced from the initialiser.

where is it documented?

The authoritative documentation is the standard document. The standard sections [dcl.type.auto], [dcl.ambig.res], [dcl.fct], [dcl.init] should be relevant.
There are also websites that offer the documentation in (arguably) more approachable manner.
This should also be covered by recent (as in, anything since 2011) introductory C++ books.

and even if you additionally delete the copy constructor for the type of b

I doubt this. Create a mcve.


text:
Q: Why does TYPO3 Composer Helper (typo3/full) installs TYPO3 Core 8.7? I want to install TYPO3 9 with all core extensions, so I can snap the needed extensions for my project.
I used https://get.typo3.org/misc/composer/helper to install TYPO3 9 with all core-exensions.
I clicked on typo3/full and got
composer require typo3/cms-about typo3/cms-adminpanel typo3/cms-backend typo3/cms-belog typo3/cms-beuser typo3/cms-core typo3/cms-extbase typo3/cms-extensionmanager typo3/cms-feedit typo3/cms-felogin typo3/cms-filelist typo3/cms-filemetadata typo3/cms-fluid typo3/cms-fluid-styled-content typo3/cms-form typo3/cms-frontend typo3/cms-impexp typo3/cms-indexed-search typo3/cms-info typo3/cms-install typo3/cms-linkvalidator typo3/cms-lowlevel typo3/cms-opendocs typo3/cms-recordlist typo3/cms-recycler typo3/cms-redirects typo3/cms-reports typo3/cms-rsaauth typo3/cms-rte-ckeditor typo3/cms-scheduler typo3/cms-seo typo3/cms-setup typo3/cms-sys-action typo3/cms-sys-note typo3/cms-t3editor typo3/cms-taskcenter typo3/cms-tstemplate typo3/cms-viewpage typo3/cms-workspaces

But in my console I got the following error by typo3/cms-core 8.7 … don't understand why
$ composer require typo3/cms-about typo3/cms-adminpanel typo3/cms-backend typo3/cms-belog typo3/cms-beuser typo3/cms-core typo3/cms-extbase typo3/cms-extensionmanager typo3/cms-feedit typo3/cms-felogin typo3/cms-filelist typo3/cms-filemetadata typo3/cms-fluid typo3/cms-fluid-styled-content typo3/cms-form typo3/cms-frontend typo3/cms-impexp typo3/cms-indexed-search typo3/cms-info typo3/cms-install typo3/cms-linkvalidator typo3/cms-lowlevel typo3/cms-opendocs typo3/cms-recordlist typo3/cms-recycler typo3/cms-redirects typo3/cms-reports typo3/cms-rsaauth typo3/cms-rte-ckeditor typo3/cms-scheduler typo3/cms-seo typo3/cms-setup typo3/cms-sys-action typo3/cms-sys-note typo3/cms-t3editor typo3/cms-taskcenter typo3/cms-tstemplate typo3/cms-viewpage typo3/cms-workspaces

Using version ^9.5 for typo3/cms-about
Using version ^9.5 for typo3/cms-adminpanel
Using version ^9.5 for typo3/cms-backend
Using version ^9.5 for typo3/cms-belog
Using version ^9.5 for typo3/cms-beuser
Using version ^8.7 for typo3/cms-core
Using version ^9.5 for typo3/cms-extbase
Using version ^9.5 for typo3/cms-extensionmanager
Using version ^9.5 for typo3/cms-feedit
Using version ^9.5 for typo3/cms-felogin
Using version ^9.5 for typo3/cms-filelist
Using version ^9.5 for typo3/cms-filemetadata
Using version ^9.5 for typo3/cms-fluid
Using version ^9.5 for typo3/cms-fluid-styled-content
Using version ^9.5 for typo3/cms-form
Using version ^9.5 for typo3/cms-frontend
Using version ^9.5 for typo3/cms-impexp
Using version ^9.5 for typo3/cms-indexed-search
Using version ^9.5 for typo3/cms-info
Using version ^9.5 for typo3/cms-install
Using version ^9.5 for typo3/cms-linkvalidator
Using version ^9.5 for typo3/cms-lowlevel
Using version ^9.5 for typo3/cms-opendocs
Using version ^9.5 for typo3/cms-recordlist
Using version ^9.5 for typo3/cms-recycler
Using version ^9.5 for typo3/cms-redirects
Using version ^9.5 for typo3/cms-reports
Using version ^9.5 for typo3/cms-rsaauth
Using version ^9.5 for typo3/cms-rte-ckeditor
Using version ^9.5 for typo3/cms-scheduler
Using version ^9.5 for typo3/cms-seo
Using version ^9.5 for typo3/cms-setup
Using version ^9.5 for typo3/cms-sys-action
Using version ^9.5 for typo3/cms-sys-note
Using version ^9.5 for typo3/cms-t3editor
Using version ^9.5 for typo3/cms-taskcenter
Using version ^9.5 for typo3/cms-tstemplate
Using version ^9.5 for typo3/cms-viewpage
Using version ^9.5 for typo3/cms-workspaces
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - typo3/cms-about v9.5.5 requires typo3/cms-core 9.5.5 -> satisfiable by typo3/cms-core[v9.5.5] but these conflict with your requirements or minimum-stability.
    - typo3/cms-about v9.5.4 requires typo3/cms-core 9.5.4 -> satisfiable by typo3/cms-core[v9.5.4] but these conflict with your requirements or minimum-stability.
    - typo3/cms-about v9.5.3 requires typo3/cms-core 9.5.3 -> satisfiable by typo3/cms-core[v9.5.3] but these conflict with your requirements or minimum-stability.
    - typo3/cms-about v9.5.2 requires typo3/cms-core 9.5.2 -> satisfiable by typo3/cms-core[v9.5.2] but these conflict with your requirements or minimum-stability.
    - typo3/cms-about v9.5.1 requires typo3/cms-core 9.5.1 -> satisfiable by typo3/cms-core[v9.5.1] but these conflict with your requirements or minimum-stability.
    - typo3/cms-about v9.5.0 requires typo3/cms-core 9.5.0 -> satisfiable by typo3/cms-core[v9.5.0] but these conflict with your requirements or minimum-stability.
    - Installation request for typo3/cms-about ^9.5 -> satisfiable by typo3/cms-about[v9.5.0, v9.5.1, v9.5.2, v9.5.3, v9.5.4, v9.5.5].

Installation failed, deleting ./composer.json.

TYPO3 installs the typo3/cms-core version 8.7, but I don't know why. Does someone know whats wrong here?
I think the requirement of one extension is false?

A: It was my mistake.
I tried to install TYPO3 9.5 with PHP 7.1 only on my local machine. After I started a ddev with PHP 7.2 everything works like expected.
I hope that helps others who get the same issue.

A: Did you choose the right TYPO3 version?
You will get other packages and configuration options if you select a corresponding version here in advance.
Currently you can choose between the following versions:

*

*Any Version

*TYPO3 10.2

*TYPO3 9.5 LTS

*TYPO3 8.7 LTS


text:
Q: Post Form data to Update MySQL get 500 Server Error I am trying to put together a form that is populated from data in a MySQL. Then I want to allow the visitor to change information in that form and by pressing a button, update the database with the new information. This is going to be used by only about 700 people or less to update their member information and access to the form will be through an email that the member gets, so it doesn't have to be a bullet proof system.
I am giving the member a link that displays their member information (that part works) It is just when I attempt to send them to the last page that would do the update is where I get the 500 Server Error. Here is some of my code from the form for them to update. It populates the fields from the database and allows the member to edit the field :
<form name="update" action="submitupdate.php" method="POST" />

    <input type="hidden" name="id" value="<?=$record['id']?>"

Business Name:
<input type="text" size="55" name="business_name" value="<?=$record['business_name']?>" >

Here is my submitupdate.php (That I get the 500 Server error on):
$con = mysql_connect("lxxxxx", "xxxxxx", "xxxxx");
mysql_select_db("xxxxxx", $con);
if(!$con){
die("Can not connect " . mysql_error());
}

$id = $_POST['id'];
$business_name = $_POST['business_name'];
$phone = $_POST['phone'];
$fax = $_POST['fax'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$website = $_POST['website'];
$contact = $_POST['contact'];
$email = $_POST['email'];

if(isset($_POST['update'])) {
$UpdateQuery = "UPDATE members SET business_name='$_POST[business_name]', phone='$_POST[phone]', fax='$_POST[fax]', address1='$_POST[address1]', address2='$_POST[address2]', city='$_POST[city]', state='$_POST[state]', zip='$_POST[zip]', website='$_POST[website]', contact='$_POST[contact]',  email='$_POST[email]', update_flag='$_POST[update_flag]',  WHERE id='$id'";
mysql_query($UpdateQuery, $con);

$retval = mysql_query($UpdateQuery, $con);

if ($retval )
{
$sql = "SELECT * FROM members WHERE id = $id";
$my_Data = mysql_query($sql,$con);

while($record = mysql_fetch_array($my_Data)) {
?>

Then I just want to display the updated record

Business Name:
<input type="text" size="55" name="business_name" value="<?=$record['business_name']?>" >

Phone:
<input type="text" size="55" name="phone" value="<?=$record['phone']?>" >


text:
Q: Regex number and hyphen I'm trying to match number with regular expression like:
34-7878-3523-4233

with this:
^[0-9][0-9-]*-[0-9-]*[0-9]$

But the expression also allow
34--34--------88
So how can I allow only one hyphen between the number?

A: That's because, you have included the hyphen in the allowed characters in your character class. You should have it outside.
You can try something like this: -
^([0-9]+-)*[0-9]+$

Now this will match 0 or more repetition of some digits followed by a hyphen. Then one or more digits at the end.

A: Use the normal*(special normal*)* pattern:
^[0-9]+(-[0-9]+)+$

where normal is [0-9] and special is -

A: Your regex:
See it in action: Regexr.com
^[0-9]+(-[0-9]+)+$

Matches:
1-2
1-2-3

Doesn't match:
1
1-
1-2-
1-2----3
1---3


text:
Q: Can't get arrays to work in PHP So I'm having a problem with my code here:
$answerString = $_GET['answers'];

$questionsString = $_GET['questions'];

$question = array();

$answer = explode(',', $answerString);

$question = explode(',', $questionsString);

$score = 0;

for($index = 0; $index <= 9; $index++)
{
    $query = "SELECT * FROM questions WHERE id = '$question[$index]'";
    $result = mysql_query($query);
    $rows = mysql_fetch_array($result, MYSQL_ASSOC);

    $cans = $rows['answer'];
    $test = array($cans);
    $ans = array();
    foreach ($test as $correct){
    $ans[] = $correct;
    }
    print_r($ans);

            if($answer[$index] == $rows['answer'])
    {
        $score++;
    }

}

What I want to do with it, is to store each $cans into an array having elements and such, but this code will output all data into element 0 and so I can't call them all to use in a variable.
Array ( [0] => C ) Array ( [0] => C ) Array ( [0] => D ) Array ( [0] => A ) Array ( [0] => B ) Array ( [0] => B ) Array ( [0] => A ) Array ( [0] => C ) Array ( [0] => B ) Array ( [0] => D )

then if I replaced these codes
$cans = $rows['answer'];
$test = array($cans);
$ans = array();
foreach ($test as $correct){
$ans[] = $correct;

into this
echo $rows['answer'];

Then it will just simply print all the data like this: BCACABDDCB
If there is a way to get all the printed output at once then I can just use str_split to split them.
I really can't find an answer about this. Thanks in advance guys.

A: You're going about this the wrong way. Firstly, you don't even have a definite relationship between question/answer and ID. You should fix this.
FYI, you can make arrays in a GET/POST by using the item[key]=value syntax:
?answers[1]=B&answers[2]=C&answers[3]=A

And so on.
As for your PHP... Stop using mysql_* functions. They're horrid things to use nowadays (and personally, I'd fail any student who used them in one of my classes).
<?php

// PDO object
$db = new PDO("mysql:localhost;dbname=database", $username, $password);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

// vars from HTTP
$answers = $_REQUEST['answers'];

// default vars
$score = 0;
$sql = "SELECT * FROM questions WHERE id = :id limit 1";

// here, we prepare the query above.
$query = $db->prepare($query);

foreach ($answers as $id => $answer) {

    $query->execute(array(":id" => $id));

    // make sure you have mysqlnd installed or anything
    // involving php and mysql is a nightmare anyway.
    $row = $query->fetch();
    $expected = $row["answer"];

    if ($answer === $expected)
        $score++;
}

You can simplify this further, probably. Read up on prepared statements.


text:
Q: Talend Json API with parameter and Iterations I am trying to populate missing historical exchange rates. I have the missing value that I am pulling from the query and iterating and using the JSON API with the date parameter. However, it seems to be failing. I have attached the image below.
Here is the paramter for the Json API. I have removed the accesskey key for privacy purposes:
"https://apilayer.net/api/historical?access_key=cdfsdfsdf&Date="+((Date)globalMap.get("row9.d"))+"&currencies=CAD&source=GBP&format=1"

What am I doing wrong?

A: You are converting a Date to a String without using SimpleDateFormat. The usual output format is yyyy-mm-dd according to the docs. This could work with your API or it could not. Depends. This means that the API call might use the wrong date format.
So, two steps are indicated:
Visibility
Add a tJavaRow directly before your GBPToCAD to inspect the values  (don't forget to generate the code in tJavaRow first!) and add something like the following:
System.out.println("https://apilayer.net/api/historical?access_key=cdfsdfsdf&Date="+((Date) globalMap.get("row9.d"))+"&currencies=CAD&source=GBP&format=1")

to check what the request actually looks like.
Transformation
Then I suppose you have to add SimpleDateFormat. It could look like this:
"https://apilayer.net/api/historical?access_key=cdfsdfsdf&Date=" +
new SimpleDateFormat("yyyy_MM_dd").format((Date) globalMap.get("row9.d")) +
"&currencies=CAD&source=GBP&format=1"

Again, check the output in the tJavaRow component first and adjust the format to whatever format your API expects.
If everything is set, your call should work just fine.


text:
Q: Firebase does not save data in database Good morning, could someone tell me what are the ports that realtime database usese? I believe it is not the same as FCM or am I mistaken?
The port 80 and 443 are released, but when I go to send something to the database it does not send if I change to a network where everything is released it sends someone would have any idea what it can be?

A: If someone wants to release the firebase in the firewall, you have to apply a rule to the following ips:
74.125.0.0/16
35.192.0.0/12

A: The Firebase Realtime Database communicates between the client and server over HTTPS, which uses port 443.
When available it uses Web Sockets for the communications, but those too go over port 443.


text:
Q: Стили скачут при перезагрузке страницы с участием localStorage, как исправить? У меня такая проблема.
HTML:
<input class="checkbox" id="checkbox" type="checkbox">

CSS:
black{background:#000}

Jquery:
$(function () {

    if (localStorage.chkbox && localStorage.chkbox != '') {
        $('#checkbox').attr('checked', 'checked');
  $('body').addClass('black')
    } else {
        $('#checkbox').removeAttr('checked');
  $('body').removeClass('black')
    }

    $('#checkbox').click(function () {

        if ($('#checkbox').is(':checked')) {
            localStorage.chkbox = $('#checkbox').val();
    $('body').addClass('black')
        } else {
            localStorage.chkbox = '';
    $('body').removeClass('black')
        }
    });
});

Ссылка, чтобы посмотреть: https://jsfiddle.net/r4yo9Leb/1/
Скрипт выполняет свои задачи, но при перезагрузке страницы, идёт заметная смена стилей. Как это можно исправить? И вообще возможно ли такое?

A: $(function () {
  // ...
});

Это в jQuery значит «Выполнить код после полной загрузки DOM».
Должно стать лучше, если вынести смену класса body из этой функции и разместить такой скрипт где-то вначале body.
let isChecked = localStorage.chkbox;

if (isChecked) {
  $("body").addClass("black");
} else {
  $("body").removeClass("black");
}

$(function() {
  let $cb = $("#checkbox");

  if (isChecked) {
    $cb.attr("checked", "checked");
  } else {
    $cb.removeAttr("checked");
  }

  $cb.on("click", function() {

    if ($cb.is(":checked")) {
      localStorage.chkbox = $cb.val();
      $("body").addClass("black");
    } else {
      localStorage.chkbox = "";
      $("body").removeClass("black");
    }

  });
});


text:
Q: how to add an onclick event to a primefaces growl? I've got a problem to add any kind of event to a growl element. My goal is to close the growl by right-clicking on it.
I tried different solutions and my growl looks like this:
<h:form id="loginForm" class="col-md-2 col-md-offset-5 loginForm">
<p:growl id="growl" showDetail="false" life="3000" sticky="true" >
...Login Stuff ...
<p:commandButton id="loginButton" value="Login" update="growl js" styleClass="fullWidth loginElement"
    actionListener="#{loginBean.loginShiro}" ajax="true"
    oncomplete="handleLoginRequest(xhr, status, args)" />
</h:form>

at first I tried something like this at the end in my javascript code:
$( '#growl').onClick(function() {
    alert('Test!!!')
});

I swapped the "#growl" to ".ui-growl", ".ui-growl-item" and ".ui-growl-item-container", but with no effort.
Then I thought maybe the growl element is not rendered when javascript is rendered, and i tried to put my javacode directly in the form and update it with the commandbutton as well. So this part was directly in the form:
<h:panelGroup id="js">
    <script type="text/javascript">
        $('#growl').onClick(function() {
         alert('Test!?')
        });
    </script>
</h:panelGroup>

... didn't worked as well.
just adding a onclick="..." property wasnt working and i couldn't add a  element becouse a growl is just a message and its missing an interface.
I'm out of ideas, do you guys have any suggestions?
I dont want a button to close it, and i achieved to close it with a left-click with help of this answer:
https://stackoverflow.com/a/15711724/3297005
but thats still not exactly what i wanted.
The best solution would be this:
    $('#grow').mousedown(function(event) {...}
couse i dont know any other way to check if the button pressed, was a right-mouse button.
I hope someone has an idea.
thanks guys

Edit:
Thanks for your suggestions.
After your comments I tried to use:
    $("#loginForm\:growl_container").ready(...)
and this works. So i think its the right path to my element.
But:
$("#loginForm\\:growl_container").click() and
$("#loginForm\\:growl_container").mousedown()

are still not working :'-(
I tried to update them in my panel element too, but also without success.
I tried the click events with other elements inside my form, and its working.
I think there must be something special with this p:growl or h:message elements.

A: Since p:growl is inside the h:form you can't access the p:growl only by its ID.
Attach the Form Id while accessing it.
And one more thing is Primefaces seems to attach the text _container to the end of your  p:growl Id.
So if you have
<p:growl id="myGrowl">...</p:growl>
then the Id would be:myGrowl_container
Example:
$("#loginForm\\:growl_container")

And also try using click() when using Jquery like one of the Question comments suggest.


text:
Q: Wordpress custom loop showing duplicate content I'm setting up a custom loop in my custom_functions.php. The basic idea of the loop is this
 function category() {
   if (is_category(3557)) {
      News Category content
   }
   else{
      Main categories content
   }
 }

This works fine for all the main categories, but on the news page I'm showing the news content followed by the main site content.

A: I realized what was wrong - I'm working with the Thesis theme, and the example I found on how to start a custom loop had
else
  thesis_loop::category();

at the end. However, once I added actual content to override the default loop, I just needed to add brackets for the else statement, so it became
else {
   Main category content
}


text:
Q: Fill ListView dynamically with tabcontrol I have five tabs. Each tab has its own table. I want to fill all the tabs with one function. That function fires on SelectedIndexChanged
How can I select the table in the current tab? I need it to fill all the tables dynamically.
I have tried this with LINQ:
Controls.OfType<ListView>()
    .FirstOrDefault(c => c.TabIndex == tabControl.SelectedIndex);

But ofcourse this does not work.
Help is appreciated.

A: Instead of a form Controls, use TabControl.SelectedTab Controls like this
var listView = tabControl.SelectedTab.Controls.OfType<ListView>().FirstOrDefault();

A: Handle the Selected event of your TabControl and recursively search for your ListView. This works even if it is nested in another control e.g. a GroupBox
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
    ListView listView = this.FindListView(e.TabPage.Controls);
}

private ListView FindListView(Control.ControlCollection controls)
{
    ListView result = null;
    foreach (Control control in controls)
    {
        result = control as ListView;
        if (result == null)
        {
            result = FindListView(control.Controls);
        }
        if (result != null)
        {
            break;
        }
    }
    return result;
}


text:
Q: unable to run Jupyter notebook after Pip3 install Getting error msg in terminal
Jupyter: command not found

after pip3 install.
I did some reading and it seems to have to do with the path pip installed in being different to my working directory?
The jupyter is installed in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
and my default path seems to be
export   echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin

I tried to move my path to where jupyter is installed by running :PATH="$HOME/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/bin:$PATH"
But it still didn't work

A: Assuming that you are using Linux (based on echo $PATH), you should be able to get working with the following: venv docs
1: Verify python3.7
which python3.7
/usr/local/bin/python3.7

2: Install venv (look up how for your distribution)
3: Navigate to your project
(mkdir JupyterTest)
cd JupyterTest

4: Create a virtual environment
python3.7 -m venv venv

5: Activate the virtual environment
source venv/bin/activate

6: Ensure it took
python --version #(Should output python 3.7.x)
Python 3.7.0

7: install jupyter
pip install jupyter

8: Run a notebook
jupyter-notebook

I've tested the above on my Linux Mint machine, and I have several versions of Python installed in parallel.

A: this one liner worked for me:
export PATH=$PATH:/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/bin


text:
Q: QAxWidget steals focus from client application Calling a functions that changes the GUI of an QAxWidget makes the caller loose focus.
How can I avoid this?

A: Certain actions make Windows transfer the active window state to another window / application.
When you trigger one of them your ActiveX application becomes active and therefore you loose focus in your client application.
To avoid this use can write a scope guard that resets the focus to your client after Windows has wrongly transferred the active state:
class AxFocusScopeGuard
{
public:
    AxFocusScopeGuard(QWidget* parentWidget)
        : m_focusedWidget(parentWidget->focusWidget())
    { }

    ~AxFocusScopeGuard()
    {
        QCoreApplication::processEvents();
        if(m_focusedWidget)
            m_focusedWidget->setFocus();
    }

private:
    QWidget* m_focusedWidget = nullptr;
};

void ActiveXCallHandler::updateGuiActiveX()
{
    AxFocusScopeGuard guard(m_parentWidget);
    axWidget->dynamicCall("updateYourGui()");
}


text:
Q: Promote Jenkins build by copying archived file to shared folder That seems a very intuitive step to do but I have a issue with that.We have a build that contains some archived files. Let's say, we would like to promote it and copy the artifact saved in this build to some shared storage location. So we are using a promote plugin that is exactly what we need but there is NO option to use a "parent" job archived files. I tried to use "copy artifact from another project" but I cannot pass a build number of a "parent" build.
What do I miss?
P.S. We cannot use "Publish Over" plugin since it expose all Jenkins users our shared folders and enables all users to copy files there.

A: I'm not sure i understood right when you say

I tried to use "copy artifact from another project" but I cannot pass a build number of a "parent" build."

But possibly it could help, with these variables you can retrieve information from the parent job:
Retrieve build number or artifacts of downstream build in Jenkins
Moreover, you can try this one too: https://wiki.jenkins.io/display/JENKINS/Copy+Artifact+Plugin
It permit you to finger print artefact and than copy them, i used in the past and it works pretty good!
Hope it helps

A: Here I found a lead to my solution:  Jenkins: Use Archived Artifact in Promoted Build
Within the "Copy Artifact Plugin":
Project name: "my parent job name" (somehow, ${PROMOTED_JOB_NAME} refuses to work)
Which build: Specific build
Build number: ${PROMOTED_NUMBER}
Artifact to copy: empty
Artifact not to copy: empty
Target directory: \\my_shared_folder\


text:
Q: CSS transparancy question I have got ot the following css to make my table cell's background transparent
background-color:black;
filter: alpha(opacity = 20);

the problem is, this transparency also makes the text transparent. How can i make it only target the background. or how can i over ride it when in my <span>. I've tired setting the occupicy to 100 in my <span>s for text but it doesnt override it. the text still comes out transparent
EDIT: I'm using IE6

A: You want to use rgba color which lets you set the alpha transparency of the color:
background-color: rgba(0,0,0,0.2); /* == black 20% opacity */

Read about rgba here: http://css-tricks.com/rgba-browser-support/
You can use filter for IE, code for all browsers would be:
  background-color: #000000;
  background-color: rgba(0, 0, 0, 0.2); /* FF3+, Saf3+, Opera 10.10+, Chrome, IE9 */
            filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#33000000',EndColorStr='#33000000'); /* IE6–IE9 */


text:
Q: Saving Multiple Image Path url in Database at once My multiple image upload code works fine. But while inserting the image path url in the database only one image path is saved. How can i save all the image path url's at once.
Here is my GetPictureData()
public string GetPictureData()
{
    string retFileName = "";
    try
    {
        if (((FileUpload1.PostedFile != null)))
        {
            if ((FileUpload1.PostedFile.ContentType.ToUpper().Contains("IMAGE")))
            {
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        //Stream inStream = hpf.InputStream;
                        //byte[] fileData = new byte[hpf.ContentLength];
                        //inStream.Read(fileData, 0, hpf.ContentLength);

                        String sTimeStamp = GetTimeStamp();
                        string iFileName = System.IO.Path.GetFileName(hpf.FileName);
                        string newFileName = iFileName.Replace(" ", "_");
                        string OutFile = Server.MapPath(ConfigurationManager.AppSettings["LocalImageDirectory"]) + "\\" + sTimeStamp + "_" + newFileName;
                        hpf.SaveAs(OutFile);
                        OutFile = ConfigurationManager.AppSettings["LocalImageDirectory"] + "\\" + sTimeStamp + "_" + newFileName;
                        retFileName = OutFile;
                    }
                }
            }
        }
    }
    catch(Exception ex)
    {
        string msg = ex.Message;
        Response.Write(msg);
    }

    return retFileName;

}

and here is my UploadButton code
    protected void btnUpload_Click(object sender, EventArgs e)
{
    if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
    {

        string filepath = GetPictureData();

            if (filepath != "")
            {
                string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
                                    " update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
                Database db = DatabaseFactory.CreateDatabase();
                DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
                db.ExecuteNonQuery(cmd);
                LoadImages();
            }

    }
}

Thanks

A: You error lies in the fact that the GetPictureData loops over a collection of files, but only the last file is returned to the button event where you call the save to database code. Of course, only the last file will be saved in the database.
The workaround is to create a standalone method to save in the database where you pass the filename and the localAuctionID. You call this method inside the GetPictureData (renamed more correctly to SavePictureData) internal loop for each file to be saved
As a pseudocode (not tested)
private void SaveToDb(int localAutID, string filepath)
{
     string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) " +
        "values(@auID, @file, 0); " +
        " update auctionstep1 set ListingStatus = 'Photographed' " +
        "where auctionid = @auID and (listingstatus <> 'Created' " +
        "AND listingstatus <> 'Saved');";
        Database db = DatabaseFactory.CreateDatabase();
        DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
        DbParameter p1 = cmd.CreateParameter()
                         {ParameterName="@auID", DbType=DbType.Int32, Value=localAutID};
        DbParameter p2 = cmd.CreateParameter()
                         {ParameterName="@file", DbType=DbType.AnsiString, Value=filepath};
        db.ExecuteNonQuery(cmd);
}

And if SavePictureData call it inside the for loop
for (int i = 0; i < hfc.Count; i++)
{
    .....
    retFileName = OutFile;
    SaveToDb(Convert.ToInt32(Session["localauctionid"]), retFileName);
}

A: if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
    {
    string filepath = GetPictureData();

        if (filepath != "")
        {
            string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
                                " update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
            db.ExecuteNonQuery(cmd);
            LoadImages();
        }

A: The person only clicks the upload button once - hence only one image being saved.
Personally I would evaluate the way you have coded this. I would move the code you use to save the image to the db into a stand alone method and call it when the image upload is complete in GetPictureData()


text:
Q: What is the type of pointer to pointer? This may be a little odd, but I can't find a reasonable answer to what is the type of pointer to pointer, like for example char**?
Keeping in mind that pointer is not a type.

A:
Keeping in mid that pointer is not a type.

Well, pointer is a type in the sense that it is a category of types. But indeed, the word pointer does not specify any specific type. Likewise, pointer to pointer is not a type. Pointer to pointer to char on the other hand is a type.
Consider following proposition, which is true: "(Pointer to type) is a type". Notice how the proposition is recursive. Because "Pointer to type is" a "type", you can substitute "type" with "Pointer to type" and end up with following proposition which is also true: "(Pointer to (Pointer to type)) is a type".
So, as I said, char** is a type. It is in the category of pointer types. An object of type char** points to an object of type char* which is also a pointer type. char* points to an object of type char which is not a pointer type.

A: You can think of the computer RAM as of the large warehouse with a lot of boxes. When you define a new variable and set its value, like this:
char c = 'A';

you create a new box placed somewhere in the memory (say, at the address 0x12345678). Its length equals length of char datatype (1 byte) and its value is set to 'A'.
After that you can create a new variable which is a pointer to c:
char* pointer_to_c = &c;

Here you create a new box placed somewhere else in the memory (say, at the address 0x1234567C). Its length equals length of char* datatype (4 bytes on 32-bit system) and its value is set to the addess of c (0x12345678).
After that you can create a new variable which is a pointer to pointer_to_c:
char** pointer_to__pointer_to_c = &pointer_to_c;

Here you create a new box placed somewhere else in the memory (say, at the address 0x12345680). Its length equals length of char** datatype (4 bytes on 32-bit system) and its value is set to the addess of pointer_to_c (0x1234567C).
You can view the address stored in pointer variable in debug watches window or print it to console or file, like this:
cout << std::hex << pointer_to_c << endl;

So, pointer to a pointer is a variable which stores address of place in the memory where the pointer is stored.
Hope it will help


text:
Q: WARNING: Unexpected type for now playing key kMRMediaRemoteNowPlayingInfoDuration I'm seeing the following error in my console.
WARNING: Unexpected type for now playing key kMRMediaRemoteNowPlayingInfoDuration (is CFType, should be CFNumber). Removing from now playing info dictionary.

Does anyone know what I am doing wrong?
if let duration = player.currentItem?.asset.duration {
   nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration
}

A: I have faced the same problem and fixed it Find the below solution: you have forgotten to mention".seconds"
if let currentItem = player.currentItem {
     let duration = currentItem.asset.duration
      nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration.seconds

}

Reference: https://developer.apple.com/documentation/avfoundation/media_playback_and_selection/creating_a_basic_video_player_ios_and_tvos/controlling_background_audio


text:
Q: Javascript to get amount from radio button with input title I'm a bit stuck here as I could find many sample codes here getting the value from radio input with id or value.
How do I get it from a title as below using only pure javascript and then output to total ?

    Home address - £4.99 <input type="radio" name="deliveryType" value="home" title="4.99" checked = "checked" />  |
    Collect from warehouse - no charge <input type="radio" name="deliveryType" value="trade" title="0" />

Total cost

    Total <input type="text" name="total" id="total" size="10" readonly="readonly" />

JS:
var checkedRadioButtons = document.querySelectorAll('input[type="radio"]:checked');

A: you can use getAttribute function
var checkedRadioButtons = document.querySelectorAll('input[type="radio"]:checked');

var total = 0;
for ( var i = 0 ;  i < checkedRadioButtons.length ; i++ ) {
    total += Number( checkedRadioButtons[i].getAttribute('title') );
}

console.log( total );

A: Use getAttribute to get the title attribute value.

var checkedRadioButtons = document.querySelector('[name="deliveryType"]:checked');

document.getElementById("total").value = checkedRadioButtons.getAttribute("title");

Home address - £4.99
    <input type="radio" name="deliveryType" value="home" title="4.99" checked="checked" />  |   Collect from warehouse - no charge
    <input type="radio" name="deliveryType" value="trade" title="0" />

Total cost

Total
    <input type="text" name="total" id="total" size="10" readonly="readonly" />

Demo : http://jsfiddle.net/kishoresahas/z75d0q3L


text:
Q: Why regularexpressionvalidator is being ignored? I have implemented a regex using regularexpressionvalidator but it doesn't work.
It's like that it's ignoring the validator. Why ?
  <div class="form-group">
                            <label class="control-label">
                                New Password
                                 <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtnewPassword"
                                     ErrorMessage="*" Display="Dynamic" ForeColor="red" ValidationGroup="acc"></asp:RequiredFieldValidator>
                                <asp:RegularExpressionValidator ID="regexValNewPassword" runat="server" Display="Dynamic" ForeColor="red" ValidationGroup="acc"
                                    ControlToValidate="txtnewPassword"
                                    EnableClientScript="False"
                                    ErrorMessage="***"
                                    ValidationExpression="^[1-9]+[0-9]*$" Visible="True">
                                    *
                                </asp:RegularExpressionValidator>

                            </label>
                            <asp:TextBox runat="server" ID="txtnewPassword" TextMode="Password" CssClass="form-control passwords"></asp:TextBox>

                        </div>

Update:
See.. I want my regex to throw an error when I only input a string of digits e.g. 123455. It should only accept mixed chars string e.g. 12ac3b12 or aac2211@11

A: You can use this regex that will not match if the input is only digits. It will only match if the input has at least one digit and one alphabet, as per your current requirements. Here minimum password length is 2 and you can make it any length by specifying number here {N,} You can further tweak the regex in case you have similar other requirements regarding character set or let me know and I can further update the regex.
^(?=.*[A-Za-z])(?=.*\d).{2,}$

Demo,
https://regex101.com/r/Fv7cw7/1

A: Your regex ^[1-9]+[0-9]*$ matches only digits and should start with 1-9.
To check if there is at least a character and a digit you could use a positive lookahead.
^(?=.*[A-Za-z@])(?=.*\d)[@a-zA-Z\d]+$
Regex demo
Explanation

*

*^ Start of the string

*(?=.*[A-Za-z@]) Positive lookahead to assert 1 character from the character class

*(?=.*\d) Positive lookahead to assert 1 digit

*[@a-zA-Z\d]+ Match 1+ times what is allowed in the character class. You can add to the character class what you would allow to match.

*$ End of the string

Due to the 2 positive lookaheads, the minimum length is 2 characters. If you want to match a minimum length like for example 8, you can add a quantifier like {8} to the character class instead of a +.


text:
Q: How do I create a PSP emulator? I know that I need to know at least C and Assembly. In your own opinion what else does one need to know apart from knowing how to program in C and Assembly efficiently? Are there any books you can suggest to get me started? I also read that you need to know about the hardware architecture of the platform you are emulating. Would you also recommend the books listed here?

A: For experts only
You would have to know all the inner workings and hardware details of PSP, which are business secrets of Sony and therefore not published. The way most emulators are made is reverse engineering, a process in which the device itself is disassembled and its inner workings are studied. That includes analyzing the chips thoroughly, reading the contents of ROM chips and sometimes even deciphering encrypted data. Full analysis usually requires specialized equipment and years of engineering experience.


text:
Q: How to target tree elements using external commands in nightwatch.js? I am looking for advice on how best to structure all the moving parts to get my nightwatch.js tests setup correctly using custom commands. I want to abstract out a command to load a dropdown menu, by putting it outside the page object, but it only works when I move the elements out of the tree section. How do I include the tree elements in the abstraction below - stuck atm. Thanks,
So my tests looks like this -
'xyz': function (client) {
    var page = client.page.myPage();

    page
        .setDropDownButtonValue(page, '@createBtn', 'New Folder')
        .api.useCss()
        .waitForElementVisible('[placeholder="New Folder Name"]', 3000)
        .setValue('[placeholder="New Folder Name"]', 'Whatever');
}

and my custom command - setDropDownButtonValue - looks like this
exports.command = function (scope, button, value) {

var xpathMatch = '//*[text()="' + value + '"]';

scope
    .waitForElementVisible(button, 5000)
    .click(button)
    .waitForElementVisible('@dropdownMenu', 5000)
    .api.useXpath();

return scope.
     waitForElementVisible(xpathMatch, 5000)
     .click(xpathMatch);

};
And myPage object looks like this -
'use strict';

module.exports = {
sections: {
    tree: {
        selector: '.drive-tree-container'
        elements: {
            createBtn: { selector: '[data-bind*="_onCreateActionClick"]' },
            dropdownMenu: { selector: '[data-bind*="element: menuDOM"].dropdown-menu.create-menu' }
        }
    }
},

elements: {
    tree: { selector: '.drive-tree-container' }
}

};
The above unit test only works when I remove the tree section -
'use strict';

module.exports = {
elements: {
    createBtn: { selector: '[data-bind*="_onCreateActionClick"]' },
    dropdownMenu: { selector: '[data-bind*="element: menuDOM"].dropdown-menu.create-menu' }
}

};


text:
Q: Only show child pages of a specific page ID in an ACF Relationship Select Box I'm building a music lesson company. I have a main 'Team' page with a bunch of child pages for each music tutor, this has some ACF stuff on it. On the site there's also a 'Lessons' page, which is a single page that features all the instruments that each open a modal box to show a bit of information when clicked on, part of that info includes these details:

*

*Which tutors teach that specific instrument

*The tutor/s name

*The tutor/s photograph

*A link to the tutor/s child page

Using ACF I've set up an initial relationship select box to get everything started, and the client can go to the lessons page and select which tutors teach which instrument, this is great but to reduce the chances of human error I'd only like my client to be able to select from child pages found under the 'Team' page.
The ACF documentation does offer some help, but this is to only select the child parents of the specific page you're currently editing - found here
I've tried editing the function to look like this so it only displays child pages from a specific page ID (in this case it's 11).
function my_relationship_query( $args, $field, $post_id ) {

// only show children of the current post being edited
$args = array(
'post_parent' => 11,
'post_type'   => 'any',
'numberposts' => 10,
'post_status' => 'any'
);
$children = get_children( $args );

// return
return $args;

}

// filter for every field
add_filter('acf/fields/relationship/query', 'my_relationship_query', 10, 3);

But it isn't doing what I want it to, haha. I'm wracking my brains. My PHP experience is still in its adolescence, so any help or advice on where I'm going wrong would be fab. Thanks!

A: It looks like you are returning the $args rather than the $children. Try something like this:
function my_relationship_query( $args, $field, $post_id ) {

    $args = array(
        'post_parent' => $post_id, // updated to use the current $post_id
        'post_type'   => 'any',
        'numberposts' => 10,
        'post_status' => 'any'
    );

    $children = get_children( $args );

    // return
    return $children; // updated to return $children

}

// filter for every field
add_filter('acf/fields/relationship/query', 'my_relationship_query', 10, 3);


text:
Q: failed to run unmanaged cpp unit test for managed code I have the following C# code(sample.dll).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample
 {
     public class Worker
     {
  /// <summary>
  /// Callback method signature to send array of values.
  /// </summary>
  /// <param name="values">The values.</param>
  public delegate void FloatValuesReady(float[] values);

  /// <summary>
  /// Occurs when [float values are ready].
  /// </summary>
  public event FloatValuesReady ReadFloatValues;

  /// <summary>
  /// Sums the specified i.
  /// </summary>
  /// <param name="i">The i.</param>
  /// <param name="j">The j.</param>
  /// <returns></returns>
  public int Sum(int i, int j)
  {
     return i + j;
  }

  /// <summary>
  /// Gets the Student object.
  /// </summary>
  /// <returns></returns>
  public ManagedStudent GetStudent()
  {
     Console.WriteLine("Enter a Name:");
     string text = Console.ReadLine();
     if (text != string.Empty)
     {
        return new ManagedStudent { Name = text };
     }
     return new ManagedStudent { Name = "NoName" };
  }

  /// <summary>
  /// Read some float values from Console and give it back to the caller using ReadFloatValues callback.
  /// So Caller should add event handler to ReadFloatValues event.
  /// </summary>
  public void GetSomeFloatValues()
  {
     List<float> values = new List<float>();
     Console.WriteLine("Enter 4 valid float values for the Native App");
     while (values.Count < 4)
     {
        string valueText = Console.ReadLine();
        float value;
        if(float.TryParse(valueText, out value))
        {
           values.Add(value);
        }
     }
     if (this.ReadFloatValues != null)
     {
        this.ReadFloatValues(values.ToArray());
     }
  }
  }
  /// <summary>
  /// A Managed Class
  /// </summary>
 public class ManagedStudent
 {
    public string Name { get; set; }
 }
}

I have created C++ wrapper for the above sample.dll to acess the managed code in unmanaged code(wrapper.dll). Below is the code for SampleWrapper.h,SampleWrapper.cpp,NativeInterface.h.
/*Sample Wrapper.h*/
using namespace System;
using namespace Sample;
namespace Wrapper
{
  public ref class SampleWrapper
  {
  /* Private Constructor to achieve signle ton*/
    SampleWrapper(void)
    {
        workerObj = gcnew Worker();
     workerObj->ReadFloatValues += gcnew Worker::FloatValuesReady(this, &Wrapper::SampleWrapper::FloatArrayReadyMethod);
    }
public:
    Worker ^ workerObj;
  /* Static reference to single ton instace.
     In order to use applications built in C.*/
    static SampleWrapper ^ Instance = gcnew SampleWrapper();
  void FloatArrayReadyMethod(array<float> ^ values);
    };
  }

  /*NativeInterface.cpp/*
 #ifdef __cplusplus
 extern "C"
{
   #endif
/* Un managed type definition of student equalent to the Managed*/
 typedef struct
 {
  char* name;
 }UnManagedStudent;

   /* A simple interface using the premitive types. Accepts 2 paramters      and retun*/
  __declspec(dllexport) int SumFromCSharp(int i, int j);

  /* An interface to get the Student Information in a Structure.
  This function calls the C# class method and gets the managed Student Object
  and converts to unmanged student*/
__declspec(dllexport) UnManagedStudent GetStudent();

   /* Function pointer to a native function to achieve call back*/
   typedef void (*GetFloatArrayCallback) (float values[], int length);

     /* An interface that makes call to C# to read some float values.
  The C# worker respond back in event call back.
  In order to pass the information back to the native app
  it should give the callback pointer*/
  __declspec(dllexport) void   GetFloatArrayFromCSharp(GetFloatArrayCallback cb);

  #ifdef __cplusplus
      }
      #endif

/*sampleWrapper.cpp*/

#include "SampleWrapper.h"
#include "NativeInterface.h"
using namespace Sample;

   namespace Wrapper
    {
    #ifdef __cplusplus
    extern "C"
    {
     #endif
  void copyManagedStringToCharPointer(char target[], System::String ^  inputString)
    {
    int maxSize = inputString->Length;
    if ( maxSize > 0)
   {
     for (int index = 0; index < maxSize; ++index )
     {
        target[index] = (char)inputString->default[index];
     }
     target[maxSize] = '\0';
  }
  }

  void copyManagedFloatToUnfloatArray(float target[], array<float> ^ values)
  {
  int maxSize = values->Length;
  if ( maxSize > 0)
  {
     for (int index = 0; index < maxSize; index++ )
     {
        target[index] = (float)values[index];
     }
  }
   }

 __declspec(dllexport) int SumFromCSharp(int i, int j)
  {
    Worker ^ worker = SampleWrapper::Instance->workerObj;
    return worker->Sum(i,j);
   }

  __declspec(dllexport) UnManagedStudent GetStudent()
    {
    Worker ^ worker = SampleWrapper::Instance->workerObj;
    ManagedStudent ^ studentObj = worker->GetStudent();
  String ^ mName = studentObj->Name;
  UnManagedStudent studentStruct;
  studentStruct.name = new char[mName->Length];
  copyManagedStringToCharPointer(studentStruct.name,mName);
  return studentStruct;
  }

    GetFloatArrayCallback floatArrayCallback;
  __declspec(dllexport) void GetFloatArrayFromCSharp(GetFloatArrayCallback cb)
  {
   floatArrayCallback = cb;
  Worker ^ worker = SampleWrapper::Instance->workerObj;
  worker->GetSomeFloatValues();
  }

  void SampleWrapper::FloatArrayReadyMethod(array<float> ^ values)
  {
  float *nativeValues = new float[values->Length];
  copyManagedFloatToUnfloatArray(nativeValues, values);
  floatArrayCallback(nativeValues, values->Length);
  }

  #ifdef __cplusplus
   }
 #endif
   }

then created small application which will access managed code through unamanaged code like below(native.dll).
 #include "DemoNativeDll.h"
  #include "NativeInterface.h"

 using namespace nsNativeDll;

CDemoNativeDll::CDemoNativeDll(void)

{
   }
   CDemoNativeDll::~CDemoNativeDll(void)
   {
  }

   int CDemoNativeDll::GetSum(int value1, int value2)
  {
  return SumFromCSharp(value1,value2);
  }

Then i have created unit case for Native.dll as below
#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\NativeDll\DemoNativeDll.h"
#include "..\Wrapper\NativeInterface.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace nsNativeDll;

namespace UnitTest1
{
   TEST_CLASS(UnitTest1)
  {
   public:

    TEST_METHOD(TestMethod1)
    {
        CDemoNativeDll* obj = new CDemoNativeDll();
        int sum = obj->GetSum(10,15);

        Assert::AreEqual(sum,15);
        // TODO: Your test code here
     }

  };
   }

I am getting the EEFileLoadException exception. How to reslove this exception. I am using Visual Studio 2012 cppunit.

A:   __declspec(dllexport) void   GetFloatArrayFromCSharp(GetFloatArrayCallback cb);

Using __declspec(dllexport) is a simple way to expose managed code to native code.  But it is too simple, there is no reasonable way to detect any mishap in the managed code.  Which likes throwing exceptions when anything goes wrong.  All you can see is an "it didn't work" exception without any way to find out anything about the managed exception.  No exception message, no access to the Holy Stack Trace.
You are getting a preview of how hard it is going to be to support your customer.  Who will call you and tell you "it did not work".  Nothing you can do to help unless you can get a debugger running on his machine.  That tends to be hard to come by.
Well, you have one on yours, you can at least use it to diagnose the unit test failure.  Project + Properties, Debugging, change the Debugger Type setting from "Auto" to "Mixed".  That enables the managed debugging engine, you can now look at the exception details.  Usually a bog-standard one, "File not found" is a very common mishap.  Especially since the CLR has no good reason to look for the managed assembly in the directory where it is stored right now, configuring the primary appdomain is something else you can't do.  You probably have to put it in the GAC or move the cppunit test runner so it is in the same directory as your DLLs.  Fuslogvw.exe is a good utility to diagnose assembly resolution problems, it shows you where the CLR looked for the assembly and what config it uses.
But feel free to put this unit test result into the "major fail" category.  Consider getting ahead with COM interop or CLR hosting, they both give you an HRESULT error code and support IErrorInfo to obtain the exception message.


text:
Q: Java Reflection with Annotation Class not working I'm pretty experienced with Java, however a novice to using Reflection and Annotation classes, which I'm trying to learn for fun. To get some practice, I made an Identifiable class which is designed to add several helpful methods to any class it inherits.
Here is the full class:
abstract class Identifiable<T, K extends Comparable<K>> implements Comparable<Identifiable<T, K>> {

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Identifier { }

    private static Method getMethodAnnotatedWith(final Class<?> type) {
        return Arrays.stream(type.getDeclaredMethods())
                .filter(m -> m.isAnnotationPresent(Identifier.class))
                .findFirst()
                .orElse(null);
    }

    private K id;

    @SuppressWarnings("unchecked")
    public Identifiable(Class<T> clazz) {
        var m = getMethodAnnotatedWith(clazz);
        if (m == null) throw new IllegalArgumentException(
            clazz.toString() + " does not have a method annotated by @Identifier"
        );

        try {
            id = (K) m.invoke(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int compareTo(@NotNull Identifiable<T, K> i) {
        return id.compareTo(i.id);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Identifiable<?, ?> that = (Identifiable<?, ?>) o;
        return id == that.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

And here is how I am trying to design it to work:
class Foo extends Identifiable<Foo, Integer> {
    private final int i;

    Foo(int i) {
        super(Foo.class);
        this.i = i;
    }

    @Identifier
    int getI() {
        return i;
    }
}

However, id is always 0 for some reason, so I'm not sure if it's a problem with my Identifier annotation class or the way I'm using reflection. I'm pretty sure it's the latter since while debugging, I found that it is able to access the method with the annotation. Any help would be appreciated, thanks!

A: Don't call the annotated method during construction.
If the identifier value is immutable (final), just pass the value to the super constructor.
public Identifiable(K id) {
    this.id = id;
}

Foo(int i) {
    super(i);
    this.i = i;
}

If the identifier value is mutable, you need to change the logic to invoke the method when you need the value, not cache the value during construction.
abstract class Identifiable<T, K extends Comparable<K>> implements Comparable<Identifiable<T, K>> {

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Identifier {/**/}

    private Method idGetter;

    protected Identifiable(Class<T> type) {
        this.idGetter = Arrays.stream(type.getDeclaredMethods())
                .filter(m -> m.isAnnotationPresent(Identifier.class))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException(type.getName() + " does not have a method annotated by @Identifier"));
    }

    @SuppressWarnings("unchecked")
    private final K getIdentifiableKey() {
        try {
            return (K) this.idGetter.invoke(this);
        } catch (IllegalAccessException e) {
            throw new IllegalAccessError(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int compareTo(Identifiable<T, K> that) {
        return this.getIdentifiableKey().compareTo(that.getIdentifiableKey());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Identifiable<?, ?> that = (Identifiable<?, ?>) o;
        return this.getIdentifiableKey().equals(that.getIdentifiableKey()); // Call equals(), don't use ==
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.getIdentifiableKey());
    }
}

Alternatively, use a functional interface and supply it with a method reference.
abstract class Identifiable<T extends Identifiable<T, K>, K extends Comparable<K>> implements Comparable<Identifiable<T, K>> {

    private Function<T, K> idGetter;

    protected Identifiable(Function<T, K> idGetter) {
        this.idGetter = Objects.requireNonNull(idGetter);
    }

    @Override
    @SuppressWarnings("unchecked")
    public int compareTo(Identifiable<T, K> that) {
        return this.idGetter.apply((T) this).compareTo(that.idGetter.apply((T) that));
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Identifiable<T, K> that = (Identifiable<T, K>) o;
        return this.idGetter.apply((T) this).equals(that.idGetter.apply((T) that));
    }

    @Override
    @SuppressWarnings("unchecked")
    public int hashCode() {
        return Objects.hash(this.idGetter.apply((T) this));
    }
}

class Foo extends Identifiable<Foo, Integer> {
    private final int i;

    Foo(int i) {
        super(Foo::getI);
        this.i = i;
    }

    int getI() {
        return i;
    }
}


text:
Q: Concerned about security due to strange tech happenings at home I've done a little research into this but have not discovered a definitive answer that satisfies my mind with, what I would consider to be a sound reason. Can anyone shed some light on what has happened here when I conducted a Tracert search recently please?
tracert findings with inconsistencies
The reasons for my trace search and investigation were also prompted by my discovering of an unknown drive on my laptop, (which I created a homepage shortcut to so I could investigate at a more appropriate time), but once I returned to check it out I discovered the following...
mysterious Z, here then gone??
Any thoughts on what is happening and what actions I should take would be much appreciated. kind regards Juice 1: https://i.stack.imgur.com/6VzTX.png 2: https://i.stack.imgur.com/D1xiQ.jpg
Is it normal for the Z drive to be visible but not accessible and then for it to change or move itself? After all, I purchased this laptop with Win10 already installed and I have made no changes to the OS at all. Strangely, if I try to update a driver I get a notification telling me to see my IT administrator for permission....

A: Tracert screenshot is normal. Question has been asked many times before.
1 2 3 4. The devices in between don't respond to those ICMP requests hence "request timed out".
Mysterious Z:\ drive is not very mysterious https://windowsreport.com/windows-10-z-drive/
That new drive labeled (Z: ) is the restore partition which is added to give you the option of restoring back to your previous version of windows. It is nothing to worry about, and should not be deleted.
Is your laptop in airplane mode??


text:
Q: ActionBarActivity and ActionBar.TabListener is deprecated inside Android Tab Fragment ( Eclipse ApI 22 ) I am implementing the ActionBar.TabListener in My Tab Fragment .
I updated the API 22, After updating it showing ActionBar.TabListener and ActionBarActivity  is deprecated.
Like this i have used in my code
public class Tabview_Landing extends ActionBarActivity  implements ActionBar.TabListener
{
}

Link help me to solve this.

A: ActionBarActivity was replaced by AppCompatActivity.
Action bar tabs can be replaced by:

*

*TabLayout from the Android Design Support Library, with or without a ViewPager; or

*a ViewPager and your favorite other tab solution for it, whether that be PagerTabStrip or any number of third-party tab implementations; or

*FragmentTabHost


text:
Q: Inline-block doesn't work on one element I have four links on my web page's footer. I've set hover style with white background color to the text links and also "display: inline-block;". When I hover on those links, they  looks like this:

Inline-block doesn't always work on the Facebook link, that means that it depends on the screen size. And I can't figure out why it behaves like this. I'm using Bootstrap for my work.
This is the HTML for those 2 links:

Jansuki Shop

            Müürivahe 17

            Tallinn

8 Delfiini Facebookis

And this is the CSS:
#addr p, #fb p
{
    margin: 0;
    padding: 0;
    display: inline-block;
}

#addr p:hover, #fb p:hover
{
    background-color: rgb(255,255,255);
    color: rgb(157,52,46);
    text-decoration: none;
}

I've tried to inspect it and I see that the Facebook p tag has a wider padding or container (I don't know how to call this) than the p tag that belongs to address part. I know I'm not supposed to post my project's link here, but if there's someone who could help me, I'd be very happy. Thank you in advance.

A: Have you tried to set width and height for your inline-blocks?


text:
Q: Should i be using My own MVVM implementation? Hi there i've been into MvvM and modular design the last few days, i find it really nice design principle that be scaled and maintained really well.
But here is the thing, i see there are multiple platforms like Prism that make the whole process automated, they have their own templates, their own observable objects, they provide nice logging information and a lot more things that i dont mention like wrapper for ICommands , messaging and so on.
Now i see those platforms do things more complicated than i need them to, like breaking down the ui into modules and so on.
I was thinking if its worth to just make my own stuff and just live independent of them,  considering that i still havent moved into massive projects should i just use my own Homemade Bootstrapping, observable objects/lists etc   ?
What are some features that i might miss in the future by not using tested platforms like Prism?

A: You can do things just fine with the standard IObservable stuff, a framework isn't required.
However, Its probably not worthwhile writing your own framework if you find you want one.
Using the existing popular ones will be good for your CV and they have already done the hard work for you.
Concentrate on making your product and use all the building blocks you can to get it done faster/cheaper/better

A: You tagged question with C# - so .NET already have some MVVM parts implemented
 - ObservableCollection<T>
 - BindingList<T> (for Winforms applications)
 - Databinding in WPF and Wiforms
For building application with MVVM pattern you need to implement only ICommand interface and maybe create own base class for viewmodels which implements INotifyPropertyChanged.
In case projects doesn't have tight time constraints - suggest to not using frameworks. MVVM pattern is not framework and doesn't require any framework to be used.
By writing own implementation you will learn and understand better needs of MVVM pattern, understand why some frameworks was made and how they work, which will help you later efficiently using any MVVM related framework.
Frameworks should be used in cases when you have known problem and have possible solution, and you find framework which provide required solution in more effective(cost/time) way from project's point of view.


text:
Q: String variable returns empty despite being assigned a value I have a UserForm, what I do is open a workbook from a dialogbox then create a new workbook based on a template. I want to assign both files' names + extension (.xlsm) to a string which I'll use in a copy method.
I'm a beginner with VBA everything is the userform's code:
Public Sub Btn1_Click()
Dim FileName1 As String
Dim FileToOpen As Variant
Dim OpenBook As Workbook
    FileToOpen = Application.GetOpenFilename(Title:="Choose file to poen", FileFilter:="Excel Files (*.xlsm*),*xls*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        TextBox1.Value = FileToOpen
    End If
FileName1 = OpenBook.Name
End Sub

Public Sub Btn2_Click()
Dim FileName2 As String
Dim wb As Workbook
Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)

If choice1 = True Then
    Set wb = Workbooks.Add("path to file template 1")
ElseIf choice2 = True Then
    Set wb = Workbooks.Add("path to file template 2")
End If

With fPth
  .InitialFileName = Filename & ".xlsm"
  .Title = "Please choose a name for your new file"
  .InitialView = msoFileDialogViewList
  If .Show <> 0 Then
    wb.SaveAs Filename:=.SelectedItems(1), FileFormat:=xlOpenXMLWorkbookMacroEnabled
  End If
End With
FileName2 = wb.Name
End Sub

All I'm trying to do is use FileName1 and FileName2 in my copy method which I'll assign to a button as well and will run once both files are open.
If I add a MsgBox to show either variable directly after assigning values to them, they do return the file's name. When I use the MsgBox in a random button I added for testing purposes, they simply return empty. All my methods are set as public.

A: Option Explicit
Public FileName1 As String
Public FileName2 As String

At the start of my module solves the issue.