text:
Q: PHP Curl Как вытянуть значения? Всем привет! В общем нужно вытянуть значение из
             (div class="yt-lockup yt-lockup-tile yt-lockup-video clearfix"
             data-context-item-id="Aj0F3D_XDm0" data-visibility-
             tracking="CEEQ3DAYAyITCMTl0sOg-tICFUfMHQodzD4EnCj0JEDtnNz-w7vBngI=")
Нужно вытянуть значение data-context-item-id.
Помогите добрые люди) Вот что пробовал....
 $ch = curl_init();

 curl_setopt($ch, CURLOPT_URL,$url);//инициализация cURL

 curl_setopt($ch,CURLOPT_TIMEOUT, 60);//максимальное время для работы функций cURL
 curl_setopt($ch,CURLOPT_VERBOSE,true);
 curl_setopt($ch,CURLOPT_ENCODING, "");//все кодировки

 curl_setopt($ch,CURLOPT_HEADER,true);//включение заголовков в вывод
 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//не проверять SSL сертификат
 curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//не проверять HOST SSL
 curl_setopt($ch,CURLOPT_COOKIEJAR, 'youtube.txt');//сохранить куки в файл

 curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);//следования любому заголовку
 curl_setopt($ch,CURLOPT_MAXREDIRS,30);//максимальное количество принимаемых редиректов

 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true );

 $a = curl_exec($ch);
  //отслеживание ошибок
  if($a === FALSE){
  echo "cURL Error: " .curl_error($ch);
   }

   $html = new simple_html_dom();
   $html->load($a,true,false);
   $links = array();
   $imgs = array();
   foreach($html->find("div.yt-lockup yt-lockup-tile yt-lockup-video clearfix ")as $s){
   $links[] = $s->data-context-item-id;
}

A: Во первых лучше использовать какую нибудь готовую либу типа guzzle чтобы не мучаться с curl (хотя она тоже использует его внутри)
Во вторых проще (ну мне по крайней мере) регуляркой типа
preg_match('/div class="yt-lockup yt-lockup-tile yt-lockup-video clearfix"\s+data-context-item-id="(?<value>[^"]+)/s', $content, $matches);
$value = $matches['value'];


text:
Q: Add ("House Number") field for the orders address datas in Magento 2.2.6 I hope someone can help me :)
I would like to add a ("House Number") field for shipping and billing informations in Magento 2.
I have successfully created the field, but when I submit a test order, this field will appear blank in the confirmation and not be saved anywhere.
I've been searching for a lot on this topic, but I did not find any answer yet.
I built the ("House Number") module with an online module generator, called Magento 2 module creator and code generator.
I've attached the previous code in an attachment.
It would be great if someone could help me with that.
However, if someone assumes this issue as a job, please send a message.
\app\code\Magemod\view\frontend\web\js\model\shipping-save-processor\default.js
 define([
'ko',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/resource-url-manager',
'mage/storage',
'Magento_Checkout/js/model/payment-service',
'Magento_Checkout/js/model/payment/method-converter',
'Magento_Checkout/js/model/error-processor',
'Magento_Checkout/js/model/full-screen-loader',
'Magento_Checkout/js/action/select-billing-address',
'Magento_Checkout/js/model/shipping-save-processor/payload-extender'
], function (
ko,
quote,
resourceUrlManager,
storage,
paymentService,
methodConverter,
errorProcessor,
fullScreenLoader,
selectBillingAddressAction,
payloadExtender
) {
'use strict';

return {
    /**
     * @return {jQuery.Deferred}
     */
    saveShippingInformation: function () {
        var payload;

        //console.log(quote.shippingAddress());

        if (!quote.billingAddress()) {
            selectBillingAddressAction(quote.shippingAddress());
        }

        var haz ;
        require(['jquery', 'jquery/ui'], function($){
          jQuery(document).ready( function() {
            haz= $('[name="haz"]').val();

          });
        });
        payload = {
                addressInformation: {
                    'shipping_address': quote.shippingAddress(),
                    'billing_address': quote.billingAddress(),
                'shipping_method_code': quote.shippingMethod()['method_code'],
                'shipping_carrier_code': quote.shippingMethod()['carrier_code'],
                   'extension_attributes':{
                        haz: haz
                    }
                }
            };
        payloadExtender(payload);

        fullScreenLoader.startLoader();

        return storage.post(
            resourceUrlManager.getUrlForSetShippingInformation(quote),
            JSON.stringify(payload)
        ).done(
            function (response) {
                quote.setTotals(response.totals);
                paymentService.setPaymentMethods(methodConverter(response['payment_methods']));
                fullScreenLoader.stopLoader();
            }
        ).fail(
            function (response) {
                errorProcessor.process(response);
                fullScreenLoader.stopLoader();
            }
        );
    }
};
});

\app\code\Magemod\view\frontend\requirejs-config.js
var config = {
"map": {
    "*": {
        'Magento_Checkout/js/model/shipping-save-processor/default': 'Magemod_Haz/js/model/shipping-save-processor/default'
    }
}
};

\app\code\Magemod\Setup\InstallData.php
<?php
namespace Magemod\Haz\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
class InstallData implements InstallDataInterface
{

private $customerSetupFactory;

/**
 * Constructor
 *
 * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
 */
public function __construct(
    CustomerSetupFactory $customerSetupFactory
) {
    $this->customerSetupFactory = $customerSetupFactory;
}

/**
 * {@inheritdoc}
 */
public function install(
    ModuleDataSetupInterface $setup,
    ModuleContextInterface $context
) {
    $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

    $customerSetup->addAttribute(\Magento\Customer\Model\Indexer\Address\AttributeProvider::ENTITY, 'haz', [
        'label' => 'Haz',
        'input' => 'text',
        'type' => 'varchar',
        'source' => '',
        'required' => true,
        'position' => 333,
        'visible' => true,
        'system' => false,
        'is_used_in_grid' => false,
        'is_visible_in_grid' => false,
        'is_filterable_in_grid' => false,
        'is_searchable_in_grid' => false,
        'backend' => ''
    ]);

    $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'haz')
    ->addData(['used_in_forms' => [
            'adminhtml_customer_address',
            'customer_address_edit',
            'customer_register_address'
        ]
    ]);
    $attribute->save();
}
}

\app\code\Magemod\Plugin\Checkout\Model\Checkout\LayoutProcessor.php
<?php
namespace Magemod\Haz\Plugin\Checkout\Model\Checkout;
class LayoutProcessor
{
/**
 * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
 * @param array $jsLayout
 * @return array
 */
public function afterProcess(
    \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
    array  $jsLayout
) {
    $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
    ['shippingAddress']['children']['shipping-address-fieldset']['children']['haz'] = [
        'component' => 'Magento_Ui/js/form/element/abstract',
        'config' => [
            'customScope' => 'shippingAddress',
            'template' => 'ui/form/field',
            'elementTmpl' => 'ui/form/element/input',
            'options' => [],
            'id' => 'haz'
        ],
        'dataScope' => 'shippingAddress.haz',
        'label' => 'Opt-In to our news letter',
        'provider' => 'checkoutProvider',
        'visible' => true,
        'validation' => [],
        'sortOrder' => 250,
        'id' => 'haz',
        'value'=>'haz'
    ];

    return $jsLayout;
}
}
?>

\app\code\Magemod\Model\Checkout\ShippingInformationManagementPlugin.php
<?php
namespace Magemod\Haz\Model\Checkout;
class ShippingInformationManagementPlugin
{

protected $quoteRepository;
protected $logger;

public function __construct(
    \Psr\Log\LoggerInterface $logger,
    \Magento\Quote\Model\QuoteRepository $quoteRepository
) {
    $this->_logger = $logger;
    $this->quoteRepository = $quoteRepository;
}

/**
 * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
 * @param $cartId
 * @param \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
 */
public function beforeSaveAddressInformation(
    \Magento\Checkout\Model\ShippingInformationManagement $subject,
    $cartId,
    \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
) {
    $extAttributes = $addressInformation->getExtensionAttributes();
    $haz = $extAttributes->getHaz();
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************$haz');
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,$haz);
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************$haz');
    $postData = file_get_contents("php://input");//Get all param
    $postData = (array)json_decode($postData);//Decode all json param
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************$postData');
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($postData,true));
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************/$postData');

    $this->_logger->log(\Psr\Log\LogLevel::DEBUG,'***********************');
    //$this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($extAttributes->Debug(),true));
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($addressInformation->Debug(),true));

    $quote = $this->quoteRepository->getActive($cartId);
    $quote->setHaz('165');
    $postData = file_get_contents("php://input");//Get all param
    $postData = (array)json_decode($postData);//Decode all json param
    $this->_logger->log(\Psr\Log\LogLevel::DEBUG, print_r($postData,true));
}
}

\app\code\Magemod\etc\frontend\di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="haz" type="Magemod\Haz\Plugin\Checkout\Model\Checkout\LayoutProcessor" sortOrder="100"/>
    </type>
</config>

\app\code\Magemod\etc\di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Checkout\Model\ShippingInformationManagement">
    <plugin name="save-in-quote" type="Magemod\Haz\Model\Checkout\ShippingInformationManagementPlugin" sortOrder="10"/>
</type>
</config>

\app\code\Magemod\etc\extension_attributes.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
<extension_attributes for="Magento\Checkout\Api\Data\ShippingInformationInterface">
    <attribute code="haz" type="string"/>
</extension_attributes>
</config>

\app\code\Magemod\registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magemod_Haz',
    __DIR__
);

\app\code\Magemod\composer.json
{
"name": "magemod/module-haz",
"description": "",
"type": "magento2-module",
"license": "proprietary",
"authors": [
    {
        "email": "info@mage2gen.com",
        "name": "Mage2Gen"
    }
],
"minimum-stability": "dev",
"require": {},
"autoload": {
    "psr-4": {
        "Magemod\\Haz\\": ""
    },
    "files": [
        "registration.php"
    ]
   }
}

\app\code\Magemod\etc\module.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magemod_Haz" setup_version="1.0.0">
    <sequence>
        <module name="Magento_Customer"/>
    </sequence>
</module>
</config>

A: Try adding the fieldset.xml file to your etc directory with the following content:
<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
       <scope id="global">
          <fieldset id="sales_convert_quote_address">
            <field name="haz">
               <aspect name="to_order" />
            </field>
         </fieldset>
      </scope>
</config>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change target filename in nuget package when packing via msbuild pack target? I have a csproj file containing entry like
<None Include="library.txt" Pack="true" PackagePath="content" />

The file is correctly included in the nuget package as /content/library.txt.
Is there a way how to change the file name itself (the package path is always just directory). I.E. what I'm after is
/content/readme.md in nuget without changing the source file name or extension.
This is possible in vanilla nuget (for reference
How do I change target filename in NuGet Package?)

A:
This is possible in vanilla nuget

That is not true according to the linked post, if you look at the note at the bottom.

The File extension in src and target must match or the specified target will be treated like a directory.

The same behavior also applies to csproj. As long as the file extension of your included file matches the output file it works. Using the following line would include the library.txt file as readme.txt in the package.
<None Include="library.txt" Pack="true" PackagePath="/content/readme.txt" />

However, if you would use a different file extension, e.g. PackagePath="/content/readme.md", then the path in the package would be /content/readme.md/library.txt. See this comment on an issue on GitHub from Jon Skeet. This issue still persists in Visual Studio 2019, too.
The easiest workaround is to rename the file to your target file name, obviously. Of course you can copy the file on build and pack it manually or employ MSBuild magic, but I do not think you can do this with csproj as of now.


text:
Q: WildFly returns 404 error while same Maven project works fine on TomEE I am trying to make Hello World web application using Eclipse and Java-ee 8, but i can not access .xhtml file, getting 404 error.
It is Maven project.
Before i deploy and run on server, which is WildFly 21.0.2, i do Maven -> Update and Run as -> Maven -> Clean verify.
The server is starting OK, because i can access it at localhost.
Page i am trying to access is index.xhtml, which is in webapp folder next to WEB-INF folder.
There is a similiar question: Error 404 - Not Found Wildfly, but restarting Eclipse did not help.
Page is accessible when i deploy to Apache TomEE 8.0.5 web profile.
When i deploy my java-ee-8 application to WildFly 21.0.2 server (also tried 19.1.0) i can not access xhtml page. I get 404 error code. When i deploy to Apache TomEE 8.0.5 web profile, page is accessible. Both servers are compatible with java-ee-8 and started successfully. No errors in console nor logs.
No configuration were done to the servers, i just added them to Eclipse and started. Same project was deployed. Does anyone know where could be the problem? I want to deploy my app to WildFly, not TomEE.
TomEE starting log, also with accessing the page: https://textuploader.com/185ql
WildFly starting log (nothing in console when trying to access the page): https://textuploader.com/185qc
project structure:

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>vis</groupId>
    <artifactId>eshop-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">
    <display-name>eshop-web</display-name>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
</web-app>

index.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Hello World</title>

Hello World

project facets:

Url i am trying to access is this: http://localhost:8080/eshop-web/index.xhtml
Also tried: http://localhost:8080/index.xhtml, http://localhost:8080/webapp/index.xhtml, but still the page can not be found. I think it might be project configuration bug.

A:
URL I am trying to access is this: http://localhost:8080/eshop-web/index.xhtml

The context path is wrong.
In case of WildFly, the actually used context path is logged with key WFLYUT0021.
The following line is found in your WildFly startup log when searching for this key:

23:00:04,727 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 81) WFLYUT0021: Registered web context: '/javaee-test-0.0.1-SNAPSHOT' for server 'default-server'

So, adjust the URL accordingly: http://localhost:8080/javaee-test-0.0.1-SNAPSHOT/index.xhtml


text:
Q: If $Z$ is a complex number such that $ |Z|\ge 2 $ the the range of values of $\ |Z+\frac{1}2|\ $ is? If Z is a complex number such that $ |Z|\ge 2 $ the the range of values of $\ |Z+1/2|\ $ is ?
My try
I tried using the triangle inequality according to which ||Z| +|1/2||  $\ge$  |Z+ 1/2| this implies  5/2 $\ge$ |Z+1/2|
then |Z-(-1/2)| $\ge$ |Z| -|1/2| then |Z+1/2| $\ge$ 3/2 then |Z+ 1/2 | $\in$ [3/2,5/2]
but the answer given is |Z+ 1/2 | $\in$ (1,2)
If there is some mistake please point out or confirm that the method is right and the answer given may be wrong . Thanks in advance .

A: We cannot establish an upper bound on $|Z+1/2|$ because we have no upper bound on $|Z|$. You write $$|Z+1/2|\leq ||Z|+|1/2||=|Z|+1/2.$$ We know that $|Z|\geq 2$, but this doesn't really help us. All we know is that $|Z|+1/2\geq 5/2$, but the inequality is going the wrong way to use in the chain above. So we cannot bound $|Z+1/2|$ above. For instance, $Z$ could equal $10^n$ for any value of $n$.


text:
Q: Baudrate with RS485 communication in PC I am a newbie to serial programming. I need to develop an application where a device send serial data at 250Kbps which needs to be captured through a PC. I know that the conventional RS232 COM ports have a baud rate restriction to 115Kbaud.
Can I use a RS485 to USB converter and achieve this communication?
And an additional questions if any of you guys are familiar with this topic.
When I used C# for acquiring the serial data, with a conventional COM port (or even with a RS232 to USB converter) the system generated exception when I initialized the baud rate register with a value higher than 115Kbaud.
Please let me know what do need to solve my high baud rate application.

A: even though this is an old post, here is an answer with all the technical details:
The baud rates available and usable for a Windows PC RS232 / RS485 application depend on:

*

*The baud rate range the RS232/RS485 chipset and its Windows device driver permits. For older/consumer devices, this is many times only include standard baud rates up to 115200 baud (see e.g. this information from NI). In the original post I assume the problem was indeed that such a "basic" RS232 device was used and its COM port driver itself didn't accept a setting setting higher than 115200 bit. Note also the difference between the baud rate the driver accepts (which can be pretty much everything), and the actual transmission rate on the RS232 side. See the FTDI chipset knowledgebase on achievable baud rates.

*The actual limits of the electrical design of the RS232/RS485 interface. The known suppliers (MOXA, Lantronix, Digi Edgeport, VSCOM, to name a few) have special products designed for industrial applications and high baud rates up to MBit range. Also FTDI itself offers complete cable sets for different baud rate rates.

*The electrical characteristics of your cable / connection. This includes cable length, cable shield, and for differential voltage transmissions like RS485 also proper termination with termination resistors (see e.g. this TI application note on RS485). For 250KBit I'd certainly recommend proper termination with 120 ohms termination resistors on both ends.
Finally - before starting an own programming project, I suggest to always check the COM port connection with an existing software tool. Any freeware like RealTerm or YAT, or our Docklight evaluation should be able to do this.


text:
Q: Hook/Overlay a DirectX game? Can anyone tell me how to hook/overlay a DirectX game in C#?
I've tried getting a fullscreen C# window to overlap a game, however it wont.
After researching a little, I found out that I need to hook the game and then display the C# window.
Can anyone explain how I would do this?
Would I be able to display a C# form over a DirectX game?

A: (disclosure: I work for this company)
You can try our Deviare API, it has functionality to hook COM objects from C#.
It's a set of COM objects that can be used from any programming language (supporting COM). An article with source code showing how to capture video and add an overlay is available: instrumenting Direct3D applications to capture video and calculate FPS
COM Spy Console and Direct Sound Capture are two examples that implements a console to hook COM objects like DirectX.
Hope it helps.

A: Since you don't have direct DirectX Access from C# this may be tricky.
From my limited understanding of the concept:
DirectX Hooks consist of attaching to a DirectX Context and manipulating it, this may/may not require messing with another program's memory, something that's best suited to C/C++
I may be wrong though, however this is an advanced topic and my gut tells me you may have issues under .NET

A: You can try my example on hooking the Direct3D 9 API using C#. This utilizes EasyHook an open source .NET assembly that allows you to install hooks from managed code into unmanaged functions.
SlimDX is also used - this is an open source managed wrapper around the Direct3D libraries.
The tricky part of the hooking is determining the addresses of a COM objects' virtual functions. This is done in the above example using a small C++ helper DLL that finds the addresses from the VTable. [Update: there is a comment posted that show's how to get the function pointers from the VTable in C# also - given a IntPtr to the com object]
The example hooks the EndScene method of an IDirect3DDevice9, which is also where you would want to draw any overlays. As to displaying a form in the overlay I'm not so sure that will be so easy - I mean you can render the image easily enough, but you will have to capture inputs and manually respond/pass-thru the events to the form in question appropriately. Good luck!


text:
Q: What is the Scala syntax for summing a List of objects? For example
case class Blah(security: String, price: Double)
val myList = List(Blah("a", 2.0), Blah("b", 4.0))
val sum = myList.sum(_.price) // does not work

What is the syntax for obtaining the sum?

A: Try this:
val sum = myList.map(_.price).sum

Or alternately:
val sum = myList.foldLeft(0.0)(_ + _.price)

You appear to be trying to use this method:
def sum [B >: A] (implicit num: Numeric[B]): B

and the compiler can't figure out how the function you're providing is an instance of Numeric, because it isn't.

A: As an alternative to missingfaktor's Scalaz example, if you really want to sum a list of objects (as opposed to mapping each of them to a number and then summing those numbers), scalaz supports this as well.
This depends on the class in question having an instance of Monoid defined for it (which in practice means that it must have a Zero and a Semigroup defined).  The monoid can be considered a weaker generalisation of core scala's Numeric trait specifically for summing; after all, if you can define a zero element and a way to add/combine two elements, then you have everything you need to get the sum of multiple objects.
Scalaz' logic is exactly the same as the way you'd sum integers manually - list.foldLeft(0) { _ + _ } - except that the Zero provides the initial zero element, and the Semigroup provides the implementation of + (called append).
It might look something like this:
import scalaz._
import Scalaz._

// Define Monoid for Blah
object Blah {
  implicit def zero4Blah: Zero[Blah] = zero(Blah("", 0))
  implicit def semigroup4Blah: Semigroup[Blah] = semigroup { (a, b) =>
    // Decide how to combine security names - just append them here
    Blah(a.security + b.security, a.price + b.price)
  }
}

// Now later in your class
val myList = List(Blah("a", 2.0), Blah("b", 4.0))
val mySum = myList.asMA.sum

In this case mySum will actually be an instance of Blah equal to Blah("ab", 6.0), rather than just being a Double.
OK, for this particular example you don't really gain that much because getting a "sum" of the security names isn't very useful.  But for other classes (e.g. if you had a quantity as well as a price, or multiple relevant properties) this can be very useful.  Fundamentally it's great that if you can define some way of adding two instances of your class together, you can tell scalaz about it (by defining a Semigroup); and if you can define a zero element too, you can use that definition to easily sum collections of your class.

A: Scalaz has this method under a name foldMap. The signature is:
def M[A].foldMap[B](f: A => B)(implicit f: Foldable[M], m: Monoid[B]): B

Usage:
scala> case class Blah(security: String, price: Double)
defined class Blah

scala> val myList = List(Blah("a", 2.0), Blah("b", 4.0))
myList: List[Blah] = List(Blah(a,2.0), Blah(b,4.0))

scala> myList.foldMap(_.price)
res11: Double = 6.0

B here doesn't have to be a numeric type. It can be any monoid. Example:
scala> myList.foldMap(_.security)
res12: String = ab


text:
Q: Why is email not returned with api connector when SSO with azure b2c? I have an user flow with an API connector. I'm using the "before sending the token" api connector to retrieve the user's role in my database and then sending it back in the token as extension_Role.
Everything works fine when I'm doing the normal flow, which for me is:

*

*Sign-up

*Disconnect

*Sign-in

This works fine because in the sign-up I manually enter the email and in the sign-in I also manually enter the email. In both those cases, I have the email claim received by my C# backend api connector.
Where it gets tricky is when I'm going to another website, using the same user flow, but with SSO activated. This means that it won't trigger me to enter my credentials again, but it will try to log me in in the background. When it's doing that, I still have my C# backend called, but this time there is not email. This is the received JSON:
{
    "step":"PreTokenIssuance",
    "client_id":"HIDDEN FOR SECURITY",
    "ui_locales":"en-US",
    "objectId":"HIDDEN FOR SECURITY",
    "surname":"HIDDEN FOR SECURITY",
    "displayName":"HIDDEN FOR SECURITY",
    "givenName":"HIDDEN FOR SECURITY"
}

I was wondering why I don't have the email.
There are the application claims and user claims on my user flow:

If there is no real solution to this issue, one would be to create a new custom field named "AutomaticEmail" and to fill ou this field with the user email on sign-up. This will work, but I think that this is a dumb solution since there's already a field email for this purpose and if the user change email for whatever reason, there will be a lot of issues.

A: •   It is because when you are logging into another website, it is an untrusted domain and even though the claims in the backend C# json file are hidden after authenticating through SSO, the claims output in the token received are encrypted while the email claim attribute is omitted while other claim attributes are still present in the token received even though being hidden/encrypted.
•   So, the email claim attribute might be returned null in the json file as its value in the column might be missing or unknown. So, when an element is null, either the key-value pair regarding the email attribute is omitted and returns a value that corresponds to the Azure AD B2C claim data type. Thus, since the email claim attribute is a string type, it returns empty string as "" just as the email attribute is unseen in the authentication token received.
•   Also, add the below claim to the custom policy output claims so that you will be able to get email as an attribute in response token as may be your custom policy might allow you to signup/sign in through multiple attribute claim types and you might not be getting email claim when using other claim types other than email.
    <!-- This was already here -->
   <OutputClaim ClaimTypeReferenceId="email" />
   <!-- Added claim -->
   <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress"
    PartnerClaimType="email" />

Please find the link below which explains the API connectors to extend and customize the user-signup flows as well as the handling of null values returned: -
https://learn.microsoft.com/en-us/azure/active-directory-b2c/api-connectors-overview?pivots=b2c-custom-policy
https://learn.microsoft.com/en-us/answers/questions/406952/email-claim-sometimes-missing-in-b2c-tokens.html


text:
Q: Does variation of parameters always work? I want to solve the differential equation $y'-2y=e^x$.
I solved the homogenous differential equation and I got that $y_0(x)=e^{2x}\cdot c$, where $c$ is a real constant.
Now I want to apply variation of parameters. So, $y_p=c(x)\cdot e^{2x}$ and $y'_p=c'(x)\cdot e^{2x}+2\cdot c(x)e^{2x}$ and if I plug it into my equation I get that $c'(x)\cdot e^{2x}=e^x$, so $c'(x)=e^{-x}$ and $c(x)=-e^{-x}$. But this doesn't verify my equation. What did I do wrong?

A: The particular solution is not $c(x)$ but $y_p = e^{2x}c(x) = -e^{x}$, which verifies the equation.

A: The simple solution of the linear ODE $$y'-2y=e^x \implies y=e^{2x}\int e^{-2x} e^x dx+C e^{2x} \implies y(x)=-e^{x}+Ce^{2x}$$
The solution of homogeneous part is $y=P e^{2x}$. Let us vary $P$ as $P(x)$  and put in $y'-2y=e^{x}$ to get $$P'=e^{-x} \implies P(x)=-e^{-x} +D \implies y(x)=-e^{x}+De^{2x}.$$
The same as above.


text:
Q: Passing an async function to a confirmation modal in React I have a few action buttons in a table in react. Buttons are for disabling and enabling users in the firebase database.
I have the firebase logic in a component called Users.jsx everything works fine; however, I want to add a confirmation modal before the async function is called.
my handler function for disabling a user, for example,  in Users.jsx is this
  // Disable user
  const handleDisableUser = async uid => {
    try {
      const disableUser = httpsCallable(functions, 'disableUser');
      await disableUser({ uid });
      const userRef = doc(db, 'users', uid);
      await updateDoc(userRef, {
        isDisabled: true,
      });
    } catch (error) {
      console.error(error);
    }
  };

Currently the button in the table triggering the function is:
<IconButton
 disabled={user.data.isDisabled}
 color='error'
 onClick={() => handleDisableUser(user.id)}
 >
 <PersonOffIcon />
</IconButton>

However, I want this function to be triggered in a modal when the user clicks "I confirm" button.
I tried creating a state for the confirmation modal like this:
 const [isConfirmationOpen, setIsConfirmationOpen] = useState(false);
 const [confirmationText, setConfirmationText] = useState(null);
 const [confirmationAction, setConfirmationAction] = useState(null);

Then created a wrapper function to open the modal and passed handleDisableUser to the state:
  const handleDisableUserWrapper = uid => {
    setConfirmationText('Are you sure you want to disable this user?');
    setConfirmationAction(() => handleDisableUser(uid));
    setIsConfirmationOpen(true);
  };

However, when adding this state in the modal it's still null!
 <Button variant='contained' onClick={confirmationAction}>

There must be a way to do this. What am I doing wrong?

A: The problem is in
setConfirmationAction(() => handleDisableUser(uid));

Passing function as argument to state setter method has different meaning. You are supposed to use it like
setState((previous) => doSomethingOn(previous))

Where doSomethingOn returns a modified version of previous
Instead of attempting to save callback function () => handleDisableUser(uid), you can maintain uid on a state.
const [confirmingUid, setConfirmingUid] = useState(null)
On confirmation modal, You can call handleDisableUser(confirmingUid)


text:
Q: Mysql - avoid duplicate values I have this query:
SELECT track,data FROM tracks WHERE id != ? ORDER BY RAND() LIMIT %d,%d"

and this are my values:
(always twelve values:)
1,2,3,4,5,6,7,8,9,10,1,2
Now I have two "double" values, 1 and 2.
How can I avoid that my ORDER BY RAND() is getting 2x the 1 or the 2?
Is this even possible?
EDIT:
Is DISTINCT working, when I select more than two columns and just the "track" is the same and "data" always something else?
On a quick check, DISTINC gave 2x -> 1 or 2.

A: Just add DISTINCT:
SELECT DISTINCT track FROM ...

EDIT:
If you want to select two columns and display only one row per value in the first column, you'll have to aggregate values. For example by displaying the biggest value of data :
SELECT track, MAX(data) FROM tracks WHERE id != ?
GROUP BY track
ORDER BY RAND() LIMIT %d,%d


text:
Q: Python Error Handling while base decoding I tried to do the following :
I have read a code in base64 via QR Code and then I converted it.
If I get an error while I do the convert, I will write a error variable to 1 and then continue without exiting the program.
I don't find a solution for me. Did anyone has an idea how I can handle it?
I tried it with the Python Try Command but I didn't get it working or I have done something wrong.
here is a snip of my code:
        secure = base64.b64decode(secure_base).decode("utf-8", "ignore")
        number = base64.b64decode(number_base).decode("utf-8", "ignore")
        start = int(base64.b64decode(start_base).decode("utf-8", "ignore"))
        end = int(base64.b64decode(end_base).decode("utf-8", "ignore"))

thanks a lot.

A: You can use the try and Except in python in the following manner.
try:
    """some intelligent program here, which some times may FOOBAR"""
except Exception as e:
    error_recieved = e
    """Do whatever you want here incase of an error"""

Remember that the program in try skips to except just after the  line in which the error/exception occured.


text:
Q: Can not read files while reading from local storage I have a method which read files from a particular folder from my phone. I want to share those files via Gmail or other services. It works most of the time but sometime few files are not attached. I have tried so many ways but did not solve this issue yet. I will appreciate if anyone can help me out. Thanks in advance.
Here is the code sample.
try {
        File root = Environment.getExternalStorageDirectory();
        File directory = new File(root.getAbsolutePath() + "/logs");
        File[] files = directory.listFiles();
        attachments.clear();
        if (files != null && files.length > 0) {
            Log.e("Report:", "-------------for loop start--------");
            for (File value : files) {
                Log.e("Report:", value.getName());
                Uri uri = FileProvider.getUriForFile(getContext(), "bd.com.cmed.pksf.provider", value);
                attachments.add(uri);
            }
            Log.e("Report:", "-------------for loop end--------");
        }
    } catch (Exception e) {
        Log.e("Report:", e.getMessage());
    }

Here is the code that I added in AndroidManifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

   <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="bd.com.cmed.pksf.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

Path provider file
    <paths>
     <external-path name="external_files" path="."/>
    </paths>

Here is the log that I have got.
    E/Report:: -------------for loop start--------
E/Report:: member_add.json
E/Report:: referral_add.json
E/Report:: -------------for loop end--------
E/Report:: -------------for loop start--------
E/Report:: member_add.json
E/Report:: referral_add.json
E/Report:: -------------for loop end--------
E/Report:: -------------for loop start--------
E/Report:: referral_add.json
E/Report:: -------------for loop end--------
E/Report:: -------------for loop start--------
E/Report:: referral_add.json
E/Report:: -------------for loop end--------
E/Report:: -------------for loop start--------
E/Report:: member_add.json
E/Report:: referral_add.json
E/Report:: -------------for loop end--------


text:
Q: C formatted string - How to add leading zeros to string value using sprintf? I want to add zeroes at the starting of a string. I am using format specifier.
My input string is hello
I want output as 000hello.
I know how to do this for integer.
int main()
{
    int i=232;
    char str[21];
    sprintf(str,"%08d",i);

    printf("%s",str);

    return 0;
}

OUTPUT will be -- 00000232

If I do the same for string.
 int main()
    {
        char i[]="hello";
        char str[21];
        sprintf(str,"%08s",i);

        printf("%s",str);

        return 0;
    }

OUTPUT will be -    hello (with 3 leading space)

Why it is giving space in case of string and zero in case of integer?

A:
How to add leading zeros to string value using sprintf?

Use "%0*d%s" to prepend zeros.
"%0*d" --> 0 min width of zeros, * derived width from the argument list, d print an int.
An exception is needed when the string needs no zeros up front.
void PrependZeros(char *dest, const char *src, unsigned width) {
  size_t len = strlen(src);
  if (len >= width) strcpy(dest, src);
  else sprintf(dest, "%0*d%s", (int) (width - len), 0, src);
}

Yet I do not think sprintf() is the right tool for the job and would code as below.
// prepend "0" as needed resulting in a string of _minimal_ width.
void PrependZeros(char *dest, const char *src, unsigned minimal_width) {
  size_t len = strlen(src);
  size_t zeros = (len > minimal_width) ? 0 : minimal_width - len;
  memset(dest, '0', zeros);
  strcpy(dest + zeros, src);
}

void testw(const char *src, unsigned width) {
  char dest[100];
  PrependZeros(dest, src, width);
  printf("%u <%s>\n", width, dest);
}

int main() {
  for (unsigned w = 0; w < 10; w++)
    testw("Hello", w);
  for (unsigned w = 0; w < 2; w++)
    testw("", w);
}

Output
0 <Hello>
1 <Hello>
2 <Hello>
3 <Hello>
4 <Hello>
5 <Hello>
6 <0Hello>
7 <00Hello>
8 <000Hello>
9 <0000Hello>
0 <>
1 <0>

A: void left_fill_zeros(char* dest, const char* str, int length)
{
    sprintf(dest, "%.*d%s", (int)(length-strlen(str)), 0, str);
}

int main(void)
{
    char output[256];
    left_fill_zeros(output, "Hello", 10);
    puts(output);

    // Total length will be 10 chars
    // Output will be: "00000Hello"
    return 0;
}


text:
Q: multiple layered split view like sparrow app a question similar to this was asked before and there are tonnes of open source examples for a single layered split view.. but I was wondering if there was one similar to the sparrow email client app, where you can drag/hide multiple views..

A: You can check this and this
Both contains functionality which you are looking for and available on github.

A: check out http://www.cocoacontrols.com.
There are plenty of out-of-the box ready implementations for this kind of cunktionality.
Searches:
for "Stack": 1
for "Panel": 2
for "Slide": 3
for "Side": 4


text:
Q: process Builder java cannot run some of the python code in java. How to solve? I am using java to create ProcessBuilder to run python.
Both of the two py can be run sucessfully in the python program. (the two py have no issue with the code)
input.py:
print 'hello'
number=[3,5,2,0,6]
print number
number.sort()
print number
number.append(0)
print number
print number.count(0)
print number.index(5)

TESTopenBaseOnt.py:
from rdflib import URIRef, Graph, Namespace
from rdflib.plugins.parsers.notation3 import N3Parser
from rdflib.namespace import RDF, OWL, RDFS
from rdflib import URIRef, BNode, Literal
from rdflib import Namespace
from rdflib.namespace import RDF, FOAF, RDFS
from rdflib import Graph

gUpdate = Graph()
print ".> Step....1"
gUpdate.parse("BBCOntology.rdf" )
print ".> Step....2"
print gUpdate.serialize(format='xml')
print ".>  Finished......."
#

AS you can see the picture.
The code works for python:input.py
However, it does not work for python:TESTopenBaseOnt.py
It might be because java cannot run the parse function in python. as the result shows that, the program stoped at step1.
public static void main(String [] args) throws IOException
    {

        try

        {
        ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C:Desktop//searchTestJava//input.py");

//      ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C:Desktop//searchTestJava//TESTopenBaseOnt.py");

        Process p = pb.start();
        BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));

        System.out.println(".........start   process.........");
        String line = "";
        while ((line = bfr.readLine()) != null){
            System.out.println("Python Output: " + line);
        }

        System.out.println("........end   process.......");

        }catch(Exception e){System.out.println(e);}

    }

So how to solve the problem that the python cannot run in the java

A: Your script runs, but it does not reach "Step 2", so
gUpdate.parse("BBCOntology.rdf" )

will be the source of the problem. Possibly it is because the file BBCOntology.rdf is not in the current working directory of the Python process. Or it could be that the Python process does not have permission to open that file.
It might be worth reading the error stream from the Python process and printing that out in Java. Use p.getErrorStream() in the same manner that you use p.getInputStream().
Or, easier, add an exception handler to your Python code that catches and prints exception messages to standard out:
import traceback

try:
    gUpdate = Graph()
    print ".> Step....1"
    gUpdate.parse("BBCOntology.rdf" )
    print ".> Step....2"
    print gUpdate.serialize(format='xml')
    print ".>  Finished......."
except Exception as exc:
    traceback.print_exc()
    raise exc

Your Java process should then print the message, which might be informative.

A: gUpdate = Graph()
print ".> Step....1"
gUpdate.parse("D:\\Desktop\\searchTestJava\\BBCOntology.rdf" )
print ".> Step....2"

The BBCOntology.rdf is  in the current working directory of the Python process. So the program can work in python even if I wrote as (gUpdate.parse("BBCOntology.rdf" )).
However, java does not know the directory BBCOntology.rdf is same as the TESTopenBaseOnt.py.
Once I add the gUpdate.parse("D:\Desktop\searchTestJava\BBCOntology.rdf" ) , Java can work.


text:
Q: Difference in the characteristic impedance of a low frequency signal In one of my PCB design, for a RS 485 signal termination resistor of 120 ohm is there. But the differential characteristics impedance of the signal is taken as 100 ohm instead of 120 and the signal travelling down the trace is of low frequency.
Does this impedance mismatch/change affects the low frequency signal particularly at the destination with reflections or some other SI issues?

A: If we put in a voltage pulse Vi into a line having characteristic impedance Z0 that is terminated with impedance ZL the reflected voltage is...
$$V_R=V_I\frac{Z_L-Z_0}{Z_L+Z_0}$$
For a 100 ohm line terminated with 120 ohms the reflected voltage is...
$$V_R=V_I\frac{120-100}{120+100} = \frac{1}{11} V_i$$
This means that there will be a reflection of about 9.1% of the input signal.
I believe the RS485 spec says that the transmitter needs to output at least 1.5V and the receiver needs to detect any signals of at least 200mV.  In a typical case a 9.1% reflection is not going to cause problems on RS485.
For such a small reflection to actually cause problems, the signal would have to be very attenuated by the time it reached the receiver.  This could happen for example if the wires were very long (like thousands of meters).
SLOW SIGNALS
If the RS485 physical layer is used with UARTs on both ends, and the baud rate is slow we might also consider whether the signal settles before the bits are sampled.
Propagation speed in a 100 ohm cable might be like 0.6 C (so like 0.18 m/ns).
If we had (for example) a 100 m cable the signal would take like 555ns to travel the length of the cable.
For 9% reflection the signal would be settled to within 99% of its final value if it bounced back and forth to the receiver twice.  From the time the receiver first saw the signal it would need to make one more round-trip of 1.11us to be 99% settled.
Note that I am just picking 99% percent settled because it is an easy case involving one round trip of reflections, which allows me to demonstrate the calculation.
If the UART samples the bits at the middle of the bit-time, then we would probably be OK if the round trip was less than 1/2 bit-time (let's say 1/4 bit-time to be safe and account for oscillator mismatch).
In that case we would want the bit-time to be at least 1.11us * 4 = 4.44us.
So, in the example case of 100m of cable, baud rates below 225kbps would likely be completely settled (like to within 1% of final value) before the receiver sampled the bit.
You can do the same calculation with your own cable length to find the limiting baud rate for your application.

A: If you can afford to have a delay between sending messages on the line I would do that. As it will ensure that previous messages will have enough time to dissipate. The time needed for the signal to dissipate is depending on the length of the line so experimentation might be needed, but a bit of code can be written that tests reliability of the line with an increasing delay and you stop increasing when the message transmission is reliable.
Most lines typically range from 100Ω to 150Ω for twisted-pair cables. As long as you have resistors on both ends of the line you should be fine.
For additional reading look at this page as it explains how to deal with the reflection coefficient optimally.


text:
Q: how to input default value into hidden input I have this database with the following data:
        data 1: text1
        data 2: text2
        .
        .
        .
        data 14: text 14
I was trying to input this data into a "select" column. So I had done this:
<script>
function dropdownlistchange(dropDown) {
    var selectedValue = dropDown.options[dropDown.selectedIndex].value;
    document.getElementById("category").value = selectedValue;
}
</script>

and the display is:
<?php
$con= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($con,"adminsys") or die ("no database");
$query = "SELECT * FROM productmodelcategory";
$results = mysqli_query($con, $query)or die("Connection could not be established");
echo "<select class='categoryoption' name='categorylist' id='categorylist' onChange='dropdownlistchange(this);'>";
while ($row = mysqli_fetch_assoc($results))
{
echo "<option value='".$row['Category']."'selected='selected'>".$row['Category']."</option>";
}
echo "</select>";
?>

and my display output is:
<input name="category" type="hidden" id="category" value="" required="required"/>

The problem that I having is I am attaching this coding in a submit form, and when I try to not selecting any value due to leave it as default value, and when i submit form, the value displaying "Column 'Category' cannot be null". Anyone can help me solve this problem? I not sure changing the "onchange" method into what method.

A: Your category input will hold some value when user actually select something from dropdown. If user didn't select anything in this case category input will not hold any value.
Do one thing assign value attribute to your category input like below
<input name="category" type="hidden" id="category" required="required" value="0"/>

Else, you can set 1st row value as default as follow
<?php
$con= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($con,"adminsys") or die ("no database");
$query = "SELECT * FROM productmodelcategory";
$results = mysqli_query($con, $query)or die("Connection could not be established");
echo "<select class='categoryoption' name='categorylist' id='categorylist' onChange='dropdownlistchange(this);'>";
$i = 0;
$default_value =0;
while ($row = mysqli_fetch_assoc($results))
{
    if($i == 0){
        $default_value = $row['Category'];
        $i = 1;
    }
    echo "<option value='".$row['Category']."'selected='selected'>".$row['Category']."</option>";
}
echo "</select>";
?>
<input name="category" type="hidden" id="category" required="required" value="<?php echo $default_value;?>"/>


text:
Q: ConversionService bean vs regular converter bean for convert Object I want to convert Entity to another object for response (ex: ActionEntity to ActionResponse).
In Spring we can create a bean like this:
@Component
public class EntityToResponseConverter implements Converter<ActionEntity,
ActionResponse>{
    @Override
    public RequestResponse convert(ActionEntity entity) {
        ActionResponse response = new ActionResponse();
        response.setId(entity.getId());
        response.setOrigId(entity.getOrigId());
        return response;
    }
}

And then I autowire a ConversionService to use.
Another way I can create new bean like this:
@Component
public class EntityToResponseConverter {

    public ActionResponse convert(ActionEntity entity) {
        ActionResponse response = new ActionResponse();
        response.setId(entity.getId());
        response.setOrigId(entity.getOrigId());
        return response;
    }
}

And then I autowire this bean to use.
When we should implement Converter instead of create a regular bean?

A: Converter is an interface which you can used for automatically converting:
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new YourCustomConverter());
    }
}

When converters registered, Spring will automatically convert request data for your controller if the data type match.


text:
Q: Html.DisplayFor adds text in quotes? If I add some code like this:

    @Html.DisplayFor(x => x.SomeTextField)

...it is rendered like so...

    "
    SomeTextFieldsValue
    "

This is strange as it isn't using a tag as I would have expected... say, a label tag.
What is this use of double quotes in the html. Is it shorthand for a tag?
It's hard to find an answer by googling.

I ASKED THIS QUESTION A MOMENT AGO AND IT QUICKLY GOT MARKED AS PREVIOUSLY ANSWERED BY THIS THREAD (by Richard Everett, Reniuz, Soner Gönül):
What is the @Html.DisplayFor syntax for?
Please read my question before doing the same again and you will see IT IS NOT the same question at all?

A: The default display template used by DisplayFor for a string doesn't add double quotes in the generated HTML.
So I see two possibilities:

*

*Value of SomeTextField contains those double quotes

*You have in your project a custom DisplayTemplate for the type of SomeTextField (I assume string) that adds them

A: It's actually a chrome thing. Chrome is just showing where text exists.

A: I think you need LabelFor instead of DisplayFor. DisplayFor displaying template based on type you want to render.


text:
Q: How to dynamically add attributes to mulitple div with same class name using jquery? I have a "div" written in my html code like this

and this is created dynamically when page renders so how many div with this same class name is going to be created is not fixed but using my code i can get the total no of div presented at a time after page load.
i stored that value in a variable "counter".
so for example at some time if their are 5 div with "mydata" class name then counter have 5 value
but now i want to add id attribute(Start from 1 upto counter value)   to each div.
ex: first div is look like this

second one is like this

 and so on.
so please tell me how can add this id attr to my div(as discribed other )using jquery ?
-Thanks

A: No need for the counter.
However you can't use only a number for the id attribute. It must start with a letter.

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
  followed by any number of letters, digits ([0-9]), hyphens ("-"),
  underscores ("_"), colons (":"), and periods (".").

ID and NAME tokens

Here is the jQuery code:
$('.mydata').each(function(i){
    $(this).attr('id', 'id_'+(i+1));
});

The IDs will be:

...

A: $('.mydata').each(function(index, element) {
    $(element).attr('id', 'id_' + (index + 1));
});

A: var i  = 1 ;

$('.mydata').each(function(){

$(this).attr('id',i);

i++;

});

A: Also,
$('.mydata').attr('id', function (i, oldValue) {
    return 'id_' + i;
});

Nice and simple :)


text:
Q: Mac OS Nativescript Sidekick UI flickering My host OS is Windows 10 and I have installed Mac OS Mojave on it it with using Vmware. My pc's GPU is Intel HD 4600. It is on board. Screen resolution is 1366 x 768px and it is LCD. I have mounted darwin.iso for installing wmvare tools. Mac OS is working good. But nativescript sidekicks UI is flickering as loop. Other app UI have not any problem. I have tried it on High Sierra too but result is same
EDIT
You can make a script this command open -a NativeScript\ Sidekick --args --disable-gpu as with link instructions

A: You try to run Sidekick in a Terminal by using this command.
open -a NativeScript\ Sidekick --args --disable-gpu


text:
Q: Why is my HttpClient.SendAsync being cancelled? I'm using a wrapper class I've made for HttpClient.  When I call SendAsync it throws an exception stating "A Task was cancelled".
I don't understand why this is happening, I'm not passing it a cancellation token and I'm using Await to wait for the result before returning.  Can anyone help please?
EDIT 1:  I've read there is an issue with HttpClient and Using in .NET 4.0 if not coded properly.  http://forums.asp.net/t/1863442.aspx?HttpClient+Error+A+Task+was+canceled+ .  However, I'm using .NET 4.5 and the Await keyword, so I shouldn't be having this problem.  Also when I mouse-over the HttpClient object during a breakpoint when the exception is throw it doesn't indicate the object is disposed.
Code snippet from HttpClientWrapper Class where the exception is occurring;
Try
  Return Await Client.SendAsync(Message, HttpCompletionOption.ResponseHeadersRead)
Catch ex As Exception
  If DebugMode Then Output(OutputBufferKey, Method.ToString & " " & Url & " " & ex.Message, OutputType.Error)
End Try

Custom HttpClientWrapper Class;
Public Class HttpClientWrapper
  Implements IDisposable

  Protected Handler As New HttpClientHandler
  Protected Client As HttpClient = Nothing

  Public Property OutputBufferKey As String = Nothing
  Public Property CancellationToken As CancellationToken? = Nothing

  Public Sub New(Optional Proxy As WebProxy = Nothing, Optional Cookies As CookieContainer = Nothing, Optional UserAgent As String = Nothing, _
                 Optional OutputBufferKey As String = Nothing, Optional CancellationToken As CancellationToken? = Nothing)
    Me.OutputBufferKey = OutputBufferKey
    Me.CancellationToken = CancellationToken

    If UserAgent Is Nothing Then UserAgent = RandomString(UserAgents)

    SetCookies(Cookies)
    SetProxy(Proxy)

    Handler.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
    Client = New HttpClient(Handler, True)

    Client.Timeout = New TimeSpan(DefaultTimeout)
    Client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate")
    Client.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5")
    Client.DefaultRequestHeaders.Add("DNT", "1")
    Client.DefaultRequestHeaders.Add("User-Agent", UserAgent)
  End Sub

  Public Sub New(User As User, Optional OutputBufferKey As String = Nothing, Optional CancellationToken As CancellationToken? = Nothing)
    Me.New(User.GetProxy, User.Cookies, User.UserAgent, OutputBufferKey, CancellationToken)
  End Sub

  Public Sub New(User As User, Task As Task)
    Me.New(User.GetProxy, User.Cookies, User.UserAgent, Task.OutputBufferKey, Task.CancellationToken.Token)
  End Sub

  Public Sub SetTimeout(Value As Integer)
    Client.Timeout = New TimeSpan(Value)
  End Sub

  Private Sub SetCookies(Cookies As CookieContainer)
    If Cookies Is Nothing Then
      Handler.UseCookies = False
    Else
      Handler.UseCookies = True
      Handler.CookieContainer = Cookies
    End If
  End Sub

  Private Sub SetProxy(Proxy As WebProxy)
    If Proxy Is Nothing Then
      Handler.UseProxy = False
    Else
      Handler.UseProxy = True
      Handler.Proxy = Proxy
    End If
  End Sub

  Public Async Function WebRequestByteAsync(Url As String, Optional RequestMethod As RequestMethod = RequestMethod.GET, Optional Content As Object = Nothing, _
                                              Optional ContentType As ContentType = ContentType.Default, Optional Accept As String = DefaultAcceptString, _
                                              Optional AdditionalHeaders As NameValueCollection = Nothing, Optional Referer As String = Nothing, Optional NoCache As Boolean = False) _
                                   As Tasks.Task(Of Byte())
    Using Response As HttpResponseMessage = Await WebRequestAsync(Url, RequestMethod, Content, ContentType, Accept, AdditionalHeaders, Referer, NoCache)
      If Response IsNot Nothing Then
        If Response.StatusCode = HttpStatusCode.OK Then
          Return Await GetResponseByteAsync(Response)
        Else
          Output(OutputBufferKey, Url & " did not return OK (200)", OutputType.Error)
        End If
      End If
      Return Nothing
    End Using
  End Function

  Public Async Function WebRequestStringAsync(Url As String, Optional RequestMethod As RequestMethod = RequestMethod.GET, Optional Content As Object = Nothing, _
                                              Optional ContentType As ContentType = ContentType.Default, Optional Accept As String = DefaultAcceptString, _
                                              Optional AdditionalHeaders As NameValueCollection = Nothing, Optional Referer As String = Nothing, Optional NoCache As Boolean = False) _
                                   As Tasks.Task(Of String)
    Using Response As HttpResponseMessage = Await WebRequestAsync(Url, RequestMethod, Content, ContentType, Accept, AdditionalHeaders, Referer, NoCache)
      If Response IsNot Nothing Then
        If Response.StatusCode = HttpStatusCode.OK Then
          Return Await GetResponseStringAsync(Response)
        Else
          Output(OutputBufferKey, Url & " did not return OK (200)", OutputType.Error)
        End If
      End If
      Return Nothing
    End Using
  End Function

  Public Async Function WebRequestAsync(Url As String, Optional RequestMethod As RequestMethod = RequestMethod.GET, Optional Content As Object = Nothing, _
                                              Optional ContentType As ContentType = ContentType.Default, Optional Accept As String = DefaultAcceptString, _
                                              Optional AdditionalHeaders As NameValueCollection = Nothing, Optional Referer As String = Nothing, Optional NoCache As Boolean = False, _
                                              Optional CanBeCancelled As Boolean = True) _
                                   As Tasks.Task(Of HttpResponseMessage)

    Dim Method As HttpMethod = Nothing
    Select Case RequestMethod
      Case Variables.RequestMethod.DELETE : Method = HttpMethod.Delete
      Case Variables.RequestMethod.GET : Method = HttpMethod.Get
      Case Variables.RequestMethod.OPTIONS : Method = HttpMethod.Options
      Case Variables.RequestMethod.POST : Method = HttpMethod.Post
      Case Variables.RequestMethod.PUT : Method = HttpMethod.Put
    End Select

    'prepare message
    Dim Message As New HttpRequestMessage(Method, Url)
    Message.Headers.ExpectContinue = False
    Message.Headers.TryAddWithoutValidation("Accept", Accept)
    If Referer IsNot Nothing Then Message.Headers.Add("Referer", Referer)
    If NoCache Then
      Message.Headers.Add("Pragma", "no-cache")
      Message.Headers.Add("Cache-Control", "no-cache")
    End If
    If AdditionalHeaders IsNot Nothing Then
      For Each Key In AdditionalHeaders.AllKeys
        Message.Headers.TryAddWithoutValidation(Key, AdditionalHeaders(Key))
      Next
    End If

    'set content
    If Content IsNot Nothing Then
      Dim ContentTypeString As String = GetEnumDescription(ContentType)

      Dim ContentBytes As Byte() = Nothing
      If TypeOf Content Is String Then
        ContentBytes = Encoding.UTF8.GetBytes(CType(Content, String))
      ElseIf TypeOf Content Is Byte() Then
        ContentBytes = CType(Content, Byte())
      ElseIf TypeOf Content Is MultiPartPostData Then
        Dim MultiPartPostData As MultiPartPostData = CType(Content, MultiPartPostData)
        ContentBytes = MultiPartPostData.Bytes
        ContentTypeString += "; boundary=" & MultiPartPostData.Boundary
      End If

      Dim ByteArrayContent As New ByteArrayContent(ContentBytes)
      ByteArrayContent.Headers.Add("Content-Type", ContentTypeString)
      Message.Content = ByteArrayContent
    End If

    'get response
    Output(OutputBufferKey, RequestMethod.ToString & " " & Url, OutputType.Debug)

    Try
      Return Await Client.SendAsync(Message, HttpCompletionOption.ResponseHeadersRead)
    Catch ex As Exception
      If DebugMode Then Output(OutputBufferKey, Method.ToString & " " & Url & " " & ex.Message, OutputType.Error)
    End Try

    Return Nothing
  End Function

  Public Async Function GetResponseByteAsync(Response As HttpResponseMessage) As Tasks.Task(Of Byte())
    If Response Is Nothing Then
      If DebugMode Then Output(OutputBufferKey, "Unable read content from response message: Is nothing", OutputType.Error)
    Else
      Try
        Return Await Response.Content.ReadAsByteArrayAsync
      Catch ex As Exception
        If DebugMode Then Output(OutputBufferKey, "Unable read content from " & Response.RequestMessage.RequestUri.ToString & ": " & ex.Message, OutputType.Error)
      End Try
    End If

    Return Nothing
  End Function

  Public Async Function GetResponseStringAsync(Response As HttpResponseMessage) As Tasks.Task(Of String)
    If Response Is Nothing Then
      If DebugMode Then Output(OutputBufferKey, "Unable read content from response message: Is nothing", OutputType.Error)
    Else
      Try
        Return Await Response.Content.ReadAsStringAsync
      Catch ex As Exception
        If DebugMode Then Output(OutputBufferKey, "Unable read content from " & Response.RequestMessage.RequestUri.ToString & ": " & ex.Message, OutputType.Error)
      End Try
    End If

    Return Nothing
  End Function

#Region "IDisposable Support"
  Private disposedValue As Boolean ' To detect redundant calls

  ' IDisposable
  Protected Overridable Sub Dispose(disposing As Boolean)
    If Not Me.disposedValue Then
      If disposing Then
        If Client IsNot Nothing Then Client.Dispose()
      End If

    End If
    Me.disposedValue = True
  End Sub

  ' This code added by Visual Basic to correctly implement the disposable pattern.
  Public Sub Dispose() Implements IDisposable.Dispose
    ' Do not change this code.  Put cleanup code in Dispose(disposing As Boolean) above.
    Dispose(True)
    GC.SuppressFinalize(Me)
  End Sub
#End Region

End Class

Main code;
Module Main

  Dim ProxyUrl As String = "proxies.txt"

  Sub main()
    DebugMode = True
    OutputToConsole = True

    Dim Proxies As New ProxyList(ProxyUrl)

    Try
      Run(Proxies).GetAwaiter.GetResult()
    Catch ex As Exception
      MsgBox(ex.Message)
    End Try

    Console.ReadLine()

  End Sub

  Public Async Function Run(Proxies As ProxyList) As Tasks.Task

    Dim Proxy As WebProxy = Await Proxies.GetProxy

    Using Client As New HttpClientWrapper(Proxy)

      Dim Response As String = Await Client.WebRequestStringAsync("http://www.google.com")
      If Response IsNot Nothing Then Console.WriteLine(Response)

    End Using

  End Function

End Module

A: HTTPClient says task has been cancelled when timeout is reached: are you sure you have large enought timeout/the web service responds in a timely fashion?

A: I had the same issue.
I was configuring the HttpClientFactory like this:
services.AddHttpClient(string.Empty, c =>
            {
               c.Timeout = TimeSpan.FromSeconds(15);
            })
        .ConfigurePrimaryHttpMessageHandler((c) => new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
            });

Then calling
var response = await client.SendAsync(request);

It turns out changing the automatic decompression to GZip only fixed the issue:
AutomaticDecompression = DecompressionMethods.GZip

Really odd.


text:
Q: Single Linked List print in order of for loop I'm Trying to print out the linked list in the order I created each node in the linked list. For example it should print out "0 1 2 3 4" but my code is wrong and doesn't print out anything. I think the problem lies somewhere in my for loop.
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};

int main(void)
{
    struct node *head = NULL;
    struct node *tail = NULL;
    struct node *current;
    current = head;
    int i;
    for(i = 0; i <= 9; i++)
    {
        current = (struct node*)malloc(sizeof(struct node));
        current-> data = i;
        current-> next = tail;
        tail = current;
        current = current->next;
    }

    current = head;
    while(current)
    {
        printf("i: %d\n", current-> data);
        current = current->next;
    }
}

A: You appeared to be getting tripped up by the pointer arithmetic when building your list.  Try this instead:
int main(void)
{
    struct node *head = NULL;
    struct node *tail = NULL;
    struct node *current;
    int i;
    for (i=0; i <= 9; i++)
    {
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp-> data = i;
        temp-> next = NULL;
        if (head == NULL)            // empty list: assign the head
        {
            head = temp;
            tail = temp;
            current = head;
        }
        else                         // non-empty list: add new node
        {
            current-> next = temp;
            tail = temp;
            current = current->next;
        }
    }

    // reset to head of list and print out all data
    current = head;

    while (current)
    {
        printf("i: %d\n", current-> data);
        current = current->next;
    }
}


text:
Q: How can i compare two arrays that have different sizes? I have to compare the elements of an array from a file to that of a given array in order to replace them with values from a third array that correspond with the second array.
I tried looping through both arrays and comparing them but since they are not the same size it does not work.
int decrypt(char *letters,char *array1,char *array2,int count)
{
    int i,j;
    for(i=0;i<count;i++)
    {
        for(j=0;j<28;j++)
        {
            if(*(letters+i)== *(array1+j))
            {
                *(letters+i)= *(array2+j);
            }
        }
    }

    printf("The decrypted message is: %s\n",letters);
}

A: You must break; from the inner loop after a match was found, otherwise the letter might be replaced again. Suppose the decoding arrays are
char array1[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ .";
char array2[] = " .QWERTYUIOPASDFGHJKLZXCVBNM";

When the letter 'C' is decoded it will become 'Q', but if you don't break out of the inner loop, the 'Q' will again be decoded to 'G'. I suggest
int decrypt(char *letters, char *array1, char *array2, int count)
{
    int i, j;
    for(i = 0; i < count; i++)
    {
        for(j = 0; j < 28; j++)
        {
            if(letters[i] == array1[j])
            {
                letters[i] = array2[j];
                break;                      // added here
            }
        }
    }
    printf("The decrypted message is: %s\n", letters);
}

Note that if the input message contains lower-case letters, they should be detected, converted to upper-case, decoded, and converted back to lower-case.


text:
Q: Android Clickable Banner Notification What would be a good way of creating a banner that appears over an activity and/or fragment that shows only for 2-3 seconds then disappears. I also want it to disappear when simply clicked on. I want it to hold an image.
It seems like it could be done via a heads-up notification correct? I would just create a custom notification lay out and make it so it doesn't do anything when clicked on so it just disappears from my current view.
Would that be the right approach?

A: if i understand the requirements correctly, You simply want a little view that will show up and float over everything else on the screen.
In ur main activity u can include a layout   as the last element in the file i.e. at the bottom since layout files are parsed from top to bottom so the element that is at the bottom is actually on top of everything when the view is rendered. its almost like an overlay. Assuming that ur main activity is the one that handles all the fragments in the application and is always running.
Optionally u can include that layout in every layout file that needs a view like that to show up and just show it when needed almost like the snack bar at the bottom of the screen.
If u would like it to slide in like a heads-up notification then u can always add a translateAnimation to the view when it u want to show it and it will look like a popup notification. What u do in the clicklisteners is not controlled by the view that u have build.
I would also recommend creating a custom view that way u can have listeners that fragments or activities can implement in order to create custom actions for the notifications depending on the data that is part of the notification.
As for making it disappear have a timer job running that will make it disappear after 2-3 seconds.
Let me know if u would like any clarification since I am unsure if it makes sense since I have not provided any examples.

A: You should use the headsup notification for your use-case as it aligns perfectly for what you want.


text:
Q: How do I use LESS variables in my local package? I made a local package to handle the browser implementation of our app.
Package.onUse(function(api) {
    api.versionsFrom('1.2.1');
    api.use('angular');
    api.use('twbs:bootstrap', 'web.browser');

    //.... some lines skipped

    api.addFiles([
        'styles/variables.less',
        'styles/forms.less'
    ], 'web.browser');
});

In variables.less I have one variable declaration: @gray-light: #E6E6E6;, and in forms.less I have a style declaration that uses the variable. However when I try and compile the app I get the following error:
While processing files with less (for target web.browser):
packages/app-name-browser/styles/forms.less:6:22: variable @gray-light is undefined
I don't have the problem when I include the declaration in the same file, so I'm assuming the problem is that variables.less is being loaded after forms.less. Any way I can remedy this?

A: You can do something like:
Package.onUse(function(api) {
    api.versionsFrom('1.2.1');
    api.use('angular');
    api.use('twbs:bootstrap', 'web.browser');

    //.... some lines skipped

    api.addFiles([
        'styles/variables.less',
        'styles/forms.less'
    ], 'client', {isImport: true});
});

And then in you main .less file you can import these files by
@import '{your-package:name}/styles/variables.less';
@import '{your-package:name}/styles/forms.less';


text:
Q: Ruby Twitter gem followers method repeating 20 times rather than displaying first 20 followers so im using the ruby twitter gem and api in conjunction with omniauth, to log into twitter via a simple rails app, and return the first 20 followers of a user. The main piece of code to do this is a method in a lib file stating:
def followers
    client.followers.take(20)
end

For some reason, the app works perfectly locally, but after being deployed to heroku, it displays my first follower, 20 times repeated, as opposed to the first 20 followers. Any help would be appreciated. Here is my code:
I have a basic twitter api app in rails, which works perfectally locally, however when I pushed to Heroku it doesn't work and upon checking the logs there is an error saying uninitialized constant WelcomeController::TwitterApi. I can not find out how to rectify this. Many thanks.
lib/twitter_api.rb
class TwitterApi
  def initialize(user)
    @user = user
  end

  def our_public_tweets
    client.user_timeline(user, count: 1, exclude_replies: true, include_rts: false)
  end

  def followers
    client.followers.take(20)
  end

  private

  attr_reader :user

  def client
    @client ||= Twitter::REST::Client.new do |config|
      config.consumer_key = Rails.application.secrets.twitter_api_key
      config.consumer_secret = Rails.application.secrets.twitter_api_secret
      config.access_token = user.token
      config.access_token_secret = user.secret
    end
  end
end

application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  # to enable the current_user variable to be used in the view file
  helper_method :current_user

end

welcome_controller.rb
class WelcomeController < ApplicationController

require 'twitter_api'

  def index
    @twitter_api = TwitterApi.new(current_user)
  end
end

views/welcome/index.html.erb

OMNIAUTH AND TWITTER API

  <% if current_user %>

Signed in as <%= current_user.name %>

      <%= image_tag current_user.profile_image, class: "profile_image" %>

<%= link_to "Sign out", signout_path, id: "sign_out" %>

Latest tweet from <%= current_user.name %>:

      <% @twitter_api.our_public_tweets.each do |tweet| %>
        <% cache('our_public_tweets', expires_in: 6.hours) do %>
          <%= parsed_tweet(tweet) %>
        <% end %>
      <% end %>

First 20 followers for <%= current_user.name %>:

      <% @twitter_api.followers.each do |follower| %>
        <% cache('followers', expires_in: 6.hours) do %>

<%= follower.name %>

        <% end %>
      <% end %>

  <% else %>

    <%= link_to "/auth/twitter", id: "link_button" do %>

    <% end %>

Click the twitter icon to sign in and view followers

  <% end %>

models/user.rb
class User < ApplicationRecord
  def self.from_omniauth(auth_hash)
    #Look up the user or create them using keys in the auth hash
    user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create
    user.update(
      name: auth_hash.info.name,
      profile_image: auth_hash.info.image,
      twitter_user_name: auth_hash.info.nickname,
      token: auth_hash.credentials.token,
      secret: auth_hash.credentials.secret
    )
    user
  end

  # token and secret is what came back from omniauth and this was saved to the user database.
end

application_helper.rb
module ApplicationHelper

  def parsed_tweet(tweet)
    _parsed_tweet = tweet.text.dup

    tweet.urls.each do |entity|
      html_link = link_to(entity.display_url.to_s, entity.expanded_url.to_s, target: 'blank')
      _parsed_tweet.sub!(entity.url.to_s, html_link)
    end

    tweet.media.each do |entity|
      html_link = link_to(entity.display_url.to_s, entity.expanded_url.to_s, target: 'blank')
      _parsed_tweet.sub!(entity.url.to_s, html_link)
    end

    _parsed_tweet.html_safe
  end
end

A: There is your problem, incorrect caching.
    <% cache('followers', expires_in: 6.hours) do %>

<%= follower.name %>

    <% end %>

When cache is empty, you don't find anything by key "followers". You take first follower and cache it with that key. And by the time you display the second follower, there is a usable cache entry already, so you use the cache, not second follower's data.
Same problem with your other blocks. I think you meant to cache entire loops, not individual elements.

For some reason, the app works perfectly locally

Because locally you have :null cache_store, I think.


text:
Q: WPF menu and header images I need to have an image instead of text in my menu header. I have written a code but its not showing up the image.
Following is my xaml part for it.
<Menu Height="50" Width="50" VerticalAlignment="Top" IsMainMenu="True">
            <MenuItem Height="50" Width="50">
                <MenuItem.Header>
                    <Image HorizontalAlignment="Left" Height="50" VerticalAlignment="Top" Width="50" Source="Images/pulsesi_icon_black.PNG"/>
                </MenuItem.Header>

            </MenuItem>

        </Menu>

Help me out of it, I don't need an Icon.

A: you can use Menuitem.Icon for image in header.
 <MenuItem >
   <MenuItem.Icon>
     <Image Width="20" Height="20" Source="/Resources/Images/Key.jpg" />
   </MenuItem.Icon>
 </MenuItem>


text:
Q: how to use getter and setter for Encapsulation I have a confusion in how do getter and setter provide encapsulation. I mean what is the difference between assigning value to a variable directly and assigning them through getter and setter. Also lets say we have two class A & B. While using getter and setter to set values from class B we have to make an object of class A in class B, so how are the variables encapsulated when we already know in which class they are defined.

A: You encapsulate the variables declaring them private so other classes can't access them without a getter or setter method. For example:
private int num; //variable to-be defined from constructor
public int getNum(){
 return num;
}

Other objects can't access the private num variable from this object without using the getNum() method.
If you want to change the encapsulated variable:
public void changeNum(int n){
 num = n;
}

The num variable is changed without breaking the java syntax.

A: With setters we can apply extra validation on the specified value which won't be possible when you assign the value directly to the property. A example could be to check whether the value is not null for example:
public void setVariable(Object value) {
    if (value == null) {
        throw new IllegalArgumentException();
    } else {
        ...
    }
}

Other possibilities you get with setters is that you can apply extra computations. If you would for example have a BankAccount instance and you change the interest the setter could initiate recalculation of the interest that has to be paid to the user.
A possibility you get by applying a getter is that you can return default value in case the value is not set yet.
Another appliance of the getter and setters is restricting the access to the variable. We could for example make the getter public while the setter is protected. This means that everybody can read the property but only classes that extend the other class, or are in the same package can set the value.
Regarding your second question. I don't fully understand the question. Could you elaborate a bit more on that one.

A: Getters are public and setters are private (usually). This means that any objects can read our class's variables, but only our class's objects can change their value. This provides encapsulation in the sense "it doesn't give other objects more access than they need". This is logical because say our class is a car and our object is Ferrari. The new variable is Horsepower of the Ferrari, say. Only Ferrari makers can change the value of the horsepower that Ferrari gives. Others can only read, and not change.
Answering your second question, when an object of A is made, you will need to initialize all (or at least some) variables of A. This is analogous to, in the above analogy, creating a new Ferrari car. Once you create the Ferrari, you will obviously have to know all of its variables. Also, here class B is assumed to be a " safe" class, say Main. B cannot be Mercedes or Audi. (This is something the programmer needs to take care of, again by using public/private encapsulation to the Ferrari class) Mercedes or Audi classes will not have the permissions to create a Ferrari car. Only "Main" and "Ferrari" will have that.


text:
Q: Solving the equation of damped oscillator I'm asked to prove that any solution of the equation $$\ddot\Phi+\Gamma\dot\Phi+\omega_0^2\Phi=0;\qquad \omega_0>\frac\Gamma 2$$ is $$\Phi=A_0e^{-\frac{\Gamma}{2} t}e^{i(\omega t-\beta)};\qquad \omega^2\equiv\omega_0 ^2-\left(\frac{\Gamma}2\right)^2$$
maybe show is simple, but I would get the process of obtaining the solution, many thanks in advance.

A: Let $x=(\Phi, \dot{\Phi})^T$. Then the equation becomes
$\dot{x}(t) =  A x(t)$, where $A= \begin{bmatrix} 0 & 1 \\ -\omega_0^2 & -\Gamma \end{bmatrix} $ which has the solution $x(t) = e^{At} x_0$.
The eigenvalues of $A$ are given by solutions to $\lambda(\lambda+\Gamma) + \omega_0^2 = 0$, which are
$\lambda = {1 \over 2} (-\Gamma \pm \sqrt{\Gamma^2-4 \omega_0^2}) ={1 \over 2} (-\Gamma \pm i\sqrt{4 \omega_0^2-\Gamma^2}) =-{ 1\over 2} \Gamma \pm i \sqrt{\omega_0^2-({\Gamma \over 2})^2} = -{ 1\over 2} \Gamma \pm i \omega$.
Since the eigenvalues are distinct, $A$ is diagonalisable and can be written as
$A= V \begin{bmatrix} -{ 1\over 2} \Gamma + i \omega & 0 \\ 0 & -{ 1\over 2} \Gamma - i \omega  \end{bmatrix} V^{-1}$, and so $e^{At} = V \begin{bmatrix} e^{(-{ 1\over 2} \Gamma + i \omega)t} & 0 \\ 0 & e^{(-{ 1\over 2} \Gamma - i \omega)t}  \end{bmatrix} V^{-1}$.
Hence the general solution is given by
$\Phi(t) = c_+ e^{(-{ 1\over 2} \Gamma + i \omega)t} + c_- e^{(-{ 1\over 2} \Gamma - i \omega)t}$ for some constants $c_+,c_-$.


text:
Q: Rewrite url query string to path I have a URL like this:
/user/registration/?user_group_id=Buyers
I would transform it in:
/user/registration/buyers/
I tryed many ways but they didn't worked, mod rewrite is enblaed and worked for other instructions.
in my htaccess:
RewriteEngine On
RewriteBase /

#without www
#RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
#RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

#with www
RewriteCond %{HTTP_HOST} ^(?!www\.)(.+)
RewriteRule ^(.*) http://www.%1/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* ./index.php

RewriteRule ^user/registration/([^/]*)$ /user/registration/?user_group_id=$1 [L]

<Files *.ini>
    order deny,allow
    deny from all
</Files>

thank you

A: Use this:
RewriteEngine On
RewriteRule ^user/registration/([^/]*)$ /user/registration/?user_group_id=$1 [L]

It will give you the path: /user/registration/buyers/


text:
Q: Subset based on one value in multiple columns I have a dataset with weekly number of lucky days for some of those weekly values  i have values greater than 7 which must be a mistake.
Therefore what I want to do is to delete rows which have a value greater than 7 in one of the multiple columns. Those columns are column 21 to 68.  What I have tried so far is this:
new_df <- subset(df, 21:68 <= 7)

This leaves me with an completely empty new_df.
I know there is a option that goes like this:
new_df <- subset(df, b != 7 & d != 7)

But I feel like there must be a more elegant way than to name every single column which I want to refer to. Do I need to use square brackets or sth. like that?
There is no Error message when computing the above mentioned command.
The referred values are numerical.
Can someone help?


text:
Q: xcode8 project crash by xcode9 reason: 'Sigh. Contentview size is zero running on ios11
    2017-10-26 14:42:50.817301+0800 thememaker[32585:4041966] [MC] Loaded MobileCoreServices.framework
2017-10-26 14:42:50.822148+0800 thememaker[32585:4041966] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-10-26 14:42:51.295291+0800 thememaker[32585:4041966] * Assertion failure in -[_UINavigationBarVisualProviderModernIOS _contentViewFittingHeight], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3694.4.18/_UINavigationBarVisualProviderModernIOS.m:544
2017-10-26 14:42:51.297238+0800 thememaker[32585:4041966] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Sigh. Contentview size is zero.'
*** First throw call stack:
(0x185e93d38 0x1853a8528 0x185e93c0c 0x186822c24 0x18fdf79cc 0x18fbf3518 0x18fdf9efc 0x18f5ae8f4 0x18f632ca4 0x18f632bac 0x18f333dfc 0x18f333c44 0x18f331de0 0x18f2a38a4 0x18f2a37d4 0x100b0b5ac 0x100b08f58 0x100b08c40 0x18f82a8bc 0x18f9d3588 0x18f9d32c0 0x18f5abd8c 0x18f9d3588 0x18f9d32c0 0x18fbf1774 0x18f9d3588 0x18f9d32c0 0x18f609ae4 0x18f82a8bc 0x18f9d3588 0x18f9d32c0 0x18f82a560 0x18f82ad00 0x18f9d3588 0x18f9d3700 0x18f9d32c0 0x18f8298a0 0x18fba67f0 0x18f50c8dc 0x18f312cdc 0x18f50b5c0 0x18f799454 0x18fa691f0 0x18f7990b8 0x18f799928 0x18ff026e8 0x18ff0258c 0x18fc7e9c0 0x18fe13fc8 0x18fc7e870 0x18fa68850 0x18f509e28 0x18f90d6ec 0x188535768 0x18853e070 0x1026f945c 0x102705b74 0x188569a04 0x1885696a8 0x188569c44 0x185e3c358 0x185e3c2d8 0x185e3bb60 0x185e39738 0x185d5a2d8 0x187bebf84 0x18f307880 0x100b5dccc 0x18587e56c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

running ios10 it's worked fine.
but running on ios11 crashed:(

when I start app crashed and not execute didFinishLaunchingWithOptions
Any help on this ? thanks.


text:
Q: Android adding custom Interpolator to Animation prevents the animation from getting cancel I have extended the Animation class to show circle being drawn as animation here is my Animation class
public class CircleAnimation extends Animation {

    private Circle circle;

    private float oldAngle;
    private float newAngle;

    public CircleAnimation(Circle circle, int newAngle) {
        this.oldAngle = circle.getAngle();
        this.newAngle = newAngle;
        this.circle = circle;
        setInterpolator(new ReverseInterpolator());
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation transformation) {
        float angle = oldAngle + ((newAngle - oldAngle) * interpolatedTime);
        circle.setAngle(angle);
        circle.requestLayout();
    }
}

Everything works as expected and now I wanted to reverse the animation i.e start from a full circle to half circle and finally to empty.
The easiest way I found was to use a custom Interpolator as described here in the stackoverflow answer and I implemented the same.
public class ReverseInterpolator implements Interpolator {
    @Override
    public float getInterpolation(float paramFloat) {
        return Math.abs(paramFloat - 1f);
    }
}

I have two button to start and stop the animation
    public void stop(View v) {
        if (circle != null) {
            circle.getAnimation().cancel();
        }
    }

    public void start(View v) {
        CircleAnimation animation = new CircleAnimation(circle, 360);
        animation.setDuration(10000);
        circle.startAnimation(animation);
    }

The problem is if I use the setInterpolator(new ReverseInterpolator()); in my animation to reverse the circle being drawn the start and stop works only once and if I try starting it again the animation does not work but if I remove the ReverseInterpolator from my animation to draw circle the start and stop works any number of time, Can someone explain why is this happening?


text:
Q: Problem of existence of unused function in each screen when using SharedViewModel I have a question before I plan to use SharedViewModel.
SharedViewModel allows two screens to share(pass) data while using one ViewModel.
Assume that there are two fragments, A and B, using a SharedViewModel and having a List type of LiveData.
Fragment A can add and delete items from the List through the ViewModel. using add() and delete().
In fragment B, there is save() that saves this List to DB.
By the way, although List data is shared through SharedViewModel, save() is not needed at all in A, and in B, there is no need for add() and delete() at all, and it is unused code.
Isn't this a problem at all?


text:
Q: What's the maximum number of datarun bytes in an MFT record? As the number of fragments in a file increases, you can watch the number of bytes used in the MFT record grow.  As expected, it grows in increments of 8 until it fills every last byte of the 1024 byte base record, before splitting into a second record.  At first blush, you might expect the answer to be "1024 - headerlength."
However, as that second record grows, it doesn't use every byte of that record.  Instead, it tops out at 1016, leaving 8 bytes of the record unused when it splits into a 3rd record (see below).  If I continue splitting the runs, the third record will also split, again at 1016 instead of 1024.
NTFS is usually highly efficient in handling MFT records, which makes this behavior highly suspect.  It smells like a bug, although I suppose there could be some obscure reason it's necessary.
But then I started experimenting with 4k MFT records (format /L).  And both the base records and the extension records always use the full 4096 bytes.
So now it really looks like a bug.  Although I'm not sure if the bug is that 1k records top out at 1016, or that 4k records don't top out at 4088.  Either there's a good reason to reserve those final bytes or there isn't, right?
In addition to wasting a precious resource, it makes computing 'available' space on MFT records really complicated.  Is the formula really "assume records will grow to the MFT record size, unless it's an extension record, then subtract 8, unless it's a 4k record, then don't do the subtraction?"  Or does this behavior imply there's some other criteria here?  Is there a trick?
FWIW, here's the 1016 byte record right before the split (as seen in a disk editor).  You can see the end of attributes marker (FFFFFFFF 82794711) followed by 8 empty bytes.  The trailing 02 00 is the Updatebytes used by MFT records.  After the next split, the size of this record drops in half.
    Offset    |  00 01 02 03 04 05 06 07   08 09 0A 0B 0C 0D 0E 0F |      ASCII
------------------------------------------------------------------------------------------------
  00C8788400  |  46 49 4C 45 30 00 03 00   E2 2F 31 C5 11 00 00 00 | FILE0..../1.....
  00C8788410  |  2F 00 00 00 38 00 01 00   F8 03 00 00 00 04 00 00 | /...8...........
  00C8788420  |  51 31 00 00 00 00 8F 00   01 00 00 00 21 1E 02 00 | Q1..........!...
  00C8788430  |  02 00 11 01 00 00 00 00   80 00 00 00 B8 03 00 00 | ................
  00C8788440  |  01 00 00 00 00 00 00 00   00 00 00 00 00 00 00 00 | ................
  00C8788450  |  3E 08 00 00 00 00 00 00   40 00 00 00 00 00 00 00 | >.......@.......
  00C8788460  |  00 F0 83 00 00 00 00 00   62 EB 83 00 00 00 00 00 | ........b.......
  00C8788470  |  62 EB 83 00 00 00 00 00   41 01 80 F0 9E 03 11 01 | b.......A.......
  00C8788480  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788490  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C87884A0  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C87884B0  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C87884C0  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C87884D0  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C87884E0  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C87884F0  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788500  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C8788510  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788520  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788530  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C8788540  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788550  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788560  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C8788570  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788580  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788590  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C87885A0  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C87885B0  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C87885C0  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C87885D0  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C87885E0  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C87885F0  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 02 00 | ................
  00C8788600  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788610  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788620  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C8788630  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788640  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788650  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C8788660  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788670  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788680  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C8788690  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C87886A0  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C87886B0  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C87886C0  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C87886D0  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C87886E0  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C87886F0  |  FF 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788700  |  11 01 FF 11 01 FF 31 01   32 A1 FE 11 01 FF 21 01 | ......1.2.....!.
  00C8788710  |  3A FE 11 01 FF 21 01 C3   F8 11 01 FF 21 01 BD FB | :....!......!...
  00C8788720  |  11 01 FF 11 01 FF 21 01   52 FD 11 01 FF 11 01 FF | ......!.R.......
  00C8788730  |  11 01 FF 21 01 A5 A9 11   01 FF 21 01 A2 EF 11 01 | ...!......!.....
  00C8788740  |  FA 11 01 F9 11 01 FF 11   01 FF 11 01 FF 11 01 FD | ................
  00C8788750  |  11 01 FF 11 01 FB 11 01   FF 11 01 F2 11 01 FB 11 | ................
  00C8788760  |  01 FC 11 01 FD 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C8788770  |  FD 11 01 FF 11 01 FF 11   01 FF 11 01 FF 11 01 FF | ................
  00C8788780  |  11 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C8788790  |  01 FF 11 01 FF 11 01 FF   11 01 FF 21 01 F4 FE 21 | ...........!...!
  00C87887A0  |  01 01 FF 11 01 FF 11 01   FF 11 01 FF 11 01 FF 11 | ................
  00C87887B0  |  01 FF 11 01 FF 11 01 FF   21 01 FD FE 11 01 FF 11 | ........!.......
  00C87887C0  |  01 FF 11 01 FF 11 01 FF   11 01 FF 11 01 FF 11 01 | ................
  00C87887D0  |  FF 11 01 85 11 01 FF 11   01 FB 11 01 FF 11 01 FF | ................
  00C87887E0  |  11 01 FF 11 01 FB 42 1F   07 3A 3D C5 01 00 00 00 | ......B..:=.....
  00C87887F0  |  FF FF FF FF 82 79 47 11   00 00 00 00 00 00 02 00 | .....yG.........


text:
Q: retrieve ._id of sub-document in array I am trying to get the objectid of the newly created member, by doing this:
let member = await account.members.push(body);
let acct = await account.save();
console.log(member); //result is an integer
let team_member_id = acct.members[member].id;

I get an error: Cannot read property 'id' of undefined
What is the correct way to do this?

A: This was the solution:
let member = account.members.create(body);
account.members.push(member);
const acct = await account.save();

let team_member_id = member.id;

Insert and return ID of sub-document in MongoDB document sub-document array