text:
Q: PDO Invalid Boolean Parameter I am trying to update my table using the following:
$stmt = $db->prepare("
    UPDATE Business SET
        Business.Name = ?,
        Business.Phone = ?,
        Business.Fax = ?,
        Business.Address = ?,
        Business.City = ?,
        Business.StateId = ?,
        Business.Zip = ?,
        Business.Referral = ?,
        Business.IsRemindedWeekly = ?,
        Business.DeletedOn = ?
    WHERE
        Business.BusinessId = ?");

// Execute the query
$stmt->execute(array(
    $_POST["Name"],
    $_POST["Phone"],
    $_POST["Fax"],
    $_POST["Address"],
    $_POST["City"],
    $_POST["StateId"],
    $_POST["Zip"],
    $_POST["Referral"],
    $_POST["IsRemindedWeekly"],
    ($_POST["DeletedOn"] && $_POST["DeletedOn"] != "0000-00-00" ? $_POST["DeletedOn"] : null),
    $_POST["BusinessId"]
));

And my schema looks like this:
CREATE TABLE `business` (
  `BusinessId` int(11) NOT NULL,
  `Name` varchar(255) NOT NULL,
  `Phone` char(10) DEFAULT NULL,
  `Fax` char(10) DEFAULT NULL,
  `Address` varchar(255) DEFAULT NULL,
  `City` varchar(64) DEFAULT NULL,
  `StateId` int(11) DEFAULT NULL,
  `Zip` char(5) DEFAULT NULL,
  `Signature` blob DEFAULT NULL,
  `Referral` varchar(255) DEFAULT NULL,
  `IsRemindedWeekly` bit(1) NOT NULL DEFAULT b'0',
  `DeletedOn` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

However, the IsRemindedWeekly column is always being set to 1 regardless of the value sent to the request. When inspecting the network tab the payload appears to be sending a String value of "1", but even if I change my parameterized value to:
($_POST["IsRemindedWeekly"] == "1" ? 1 : 0)

(notice the non-type comparison operator) but regardless, the value in my database is still 1 after update operation. Am I missing something?
UPDATE
I am a little upset that the thread was closed because I'm still having difficulties. I've decided to use bindValue but it still isn't working. I've tried:
// Passing a 1 or 0 with PARAM_INT always returns false
$stmt->bindValue(":isRemindedWeekly", ($_POST["IsRemindedWeekly"] == "1" ? 1 : 0), PDO::PARAM_INT);

// Passing a 1 or 0 with PARAM_BOOL always returns false
$stmt->bindValue(":isRemindedWeekly", ($_POST["IsRemindedWeekly"] == "1" ? 1 : 0), PDO::PARAM_BOOL);

// Passing a true or false with PARAM_INT always returns false
$stmt->bindValue(":isRemindedWeekly", $_POST["IsRemindedWeekly"], PDO::PARAM_INT);

// Passing a true or false with a PARAM_BOOL always returns true
$stmt->bindValue(":isRemindedWeekly", $_POST["IsRemindedWeekly"], PDO::PARAM_BOOL);

A: When it expects PDO::PARAM_BOOL, you probably should provide it with boolean:
$_POST["IsRemindedWeekly"] == "1" // this evaluates to boolean

While it is generally easier to change the column to TINYINT and use 0 and 1, because you'd have define the data-type for bindValue() as int $data_type = PDO::PARAM_BOOL. This might be a matter of taste, because there is nothing wrong with either approach - but casting to boolean on read is less effort, than on write.

What you get from the $_POST will always be of data-type string.
eg. for int you'd have to type-cast: (int) $_POST["IsRemindedWeekly"].
And you were missing the the type-cast to boolean, as I've suggested it above:
$stmt->bindValue(":isRemindedWeekly", $_POST["IsRemindedWeekly"] == "1", PDO::PARAM_BOOL);

Also see the PHP manual for Type Juggling, which is quite essential.


text:
Q: Create new PDF from template with PHP I have a docx document file set up with formating and layout, which I saved as a PDF file.
I want to use this pdf file as a template for creating new pdf files pre-filled with user data.
I have seen FPDF, FPDI, tcPDF, domPDF, Zend PDF, http://koivi.com/fill-pdf-form-fields/ (Justin Koivisto), a few convertion tools like HTML2PDF and a few command line tools mentioned here on stackoverflow. With the exception of FPDI, none of them offer an example using a PDF template to either search-and-replace custom tags with actual data (usually from a database) or add data without specifying a bunch of values like x, y, postion, font, font-formating etc.
Creating a PDF from scratch seems like too much work.
I have not yet considered using a HTML2PDF converter as the results appear to vary greatly, and then there is the issue with styling. Some tools allow CSS, but often with limits like no float support.
Are there no easy way of using a template like there is for Excel with PHPExcel ?
My need is:

*

*Free

*Load and use a template

*Search-and-replace custom tags

*Add data (text, image, font, formating etc)

*Custom header and footer

*Must work with shared hosting

*Allow download, save/store to server and attach to email (preferable without having to save it first) of final generated PDF

A: use TCPDF you can create the PDF template using HTML tags principles it is fast to create, easy to use, easy to integrate I used it for generating detailed invoices of a law office(multiple pages with different format), the production envelope of a jewellery workshop (included photo), stock notes and invoices.
TCPD examples

A: try FPDI it support editing an existing template and making changes in that template file
usage is pretty stratight forward :
<?php
require_once('fpdf.php');
require_once('fpdi.php');

$pdf = new FPDI();

$pagecount = $pdf->setSourceFile('TestDoc.pdf');
$tplidx = $pdf->importPage(1, '/MediaBox');

$pdf->addPage();
$pdf->useTemplate($tplidx, 10, 10, 90);

$pdf->Output('newpdf.pdf', 'D');

Also refer to links below:
Is there a solution for pdf template in PHP?
Writing/Drawing over a PDF template document in PHP

A: http://www.livedocx.com/
LiveDocx is a template-based document creation platform.
http://www.phplivedocx.org/articles/getting-started-with-phplivedocx/

A: Instead of doing this with PHP, you could use Word or OpenOffice Mail Merge feature to create the template and import the data into the tags.  Then you can "print" but export as a pdf instead of actually printing.  This might be a faster solution provided you don't need to update the template regularly.  I did this for about 150 products and it took less than 30 minutes including creating the template and uploading the pdfs.  Just an after-thought, hope this helps somebody else!

A: I really recommend MPDF :

*

*it is based on FPDF and HTML2FPDF, so you can use some of their functions or add others

*it has tons of cool features (create any kind of barcodes, locale support, watermarks, and many more)

*it has an extremely well made documentation

*it has a community forum

*it has examples!

*it has an easy learning curve

The only bad thing is that it is a little heavy-weight, but you can remove things that you dont need.

A: The problem with trying to use a PDF as a "template" is that PDF is a typeset document format. Eg. it is a fixed layout and you shouldn't really mess with the layout too much.
It would be much simpler, if you want to do more with this, to use something like XSL-FO to generate your documents from an XML "template". All you need do is generate the XML with the right fields in place and the XSL-FO renderer can then create the PDF for you.
The best (only?) free XSL-FO renderer is Apache FOP.

A: You can skip all the pain of defining template over existing PDF with https://github.com/applicius/dhek/releases . It creates a JSON mapping area over PDF page/coordinates, so that you can fill it with PDF API you prefer.

A: I was needing that for a project so I've created a fast tool for that. You can check it and feel free to contribute  here

A: If your server has OpenOffice installed you can use soffice in headless mode to convert RTF-Files (Rich Text Format) to PDF.

*

*Create RTF with template brackets inside Text like "Dear, {{{name}}}, how are you?"

*Open the file and load the content with $content=file_get_contents('path_to_file');

*Replace the text as you wish: $content=str_replace('{{{name}}}', 'Bruce Wanye', $content);

*Save the content to a new file: file_put_contents('path_to_file2', $content);

*Now convert to PDF: excec("soffice --headless --convert-to pdf 'path_to_file2' --outdir 'target_directory'");

A: Here is some example how to create multiple pages with one PDF template and content  as HTML.  Based on MPDF library.
$mpdf = new mPDF('utf-8', $format_size, 0, '', $margin_left, $margin_right, $margin_top, $margin_bottom, 0, 0, $orientation);

if ( $bg_template ) {
    // is a PDF template file
    $mpdf->SetImportUse();
    $pagecount = $mpdf->SetSourceFile( $bg_template );
    $tplIdx = $mpdf->ImportPage( $pagecount );
}

foreach ( $html as $one_letter_text ) {
    $mpdf->addPage();

    if ( $bg_template ) {
        $mpdf->useTemplate( $tplIdx, 0, 0);
    }

    $mpdf->WriteHTML( $one_letter_text );
}
$title = 'my-letter.pdf';

$pdf_path = $this->created_pdf_upload_dir.'/'.$title;
$mpdf->Output( $pdf_path, 'F');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Arithmetic sequences I am learning about arithmetic progressions and I came across the question: "Prove that there is no infinite arithmetic sequence whose terms are all prime numbers."
I can see that there is no constant difference between all the prime numbers and hence an arithmetic sequence consisting only of prime numbers can't exist. However, I am unsure about how to prove this mathematically.

A: Let us suppose this arithmetic sequence exists. Then, let the first term be p, and the common difference is d. Then, the (p+1)th term is p+pd, but it is a multiple of p, so it is composite. But, we assumed all terms are prime. Therefore, no arithmetic sequence has all terms as primes.

A: Here's another proof. Suppose otherwise, and take an arithmetic progression with only primes. Let its first term be $n$, and its common difference be $d$. Take a prime $p>d$. There exists an integer $a$ such that $$p\mid da+n,$$ namely, $n$ times the modular inverse of $-d$. Therefore, $$d(p+a)+n$$ will be a multiple of $p$ bigger than $p$ in the progression, and we're done.


text:
Q: Routing between 2 routers on home network I have a home network with 2 routers,
A Main router (192.168.1.xxx), and the mesh (Tenda) router (192.168.2.xxx), which its main node is in the 192.168.1 network (192.168.1.14).
The problem is that the main router (192.168.1.1) can't find the 192.168.2 network (and I can't add static route to it).
I tried different approach, I added static routing on windows (to my machine on 192.168.1.15 which is directly connected to the main router).
I see using wireshark that the it tries to find a machine on the 192.168.2 network using the main Tenda node (192.168.1.14), but strangely, this Tenda node can't find a route.
The Tenda router (the main node is in the 192.168.1) failed to find a computer which is on the 192.168.2 network.
The other side works, I can ping from a computer on the 192.168.2 network to a computer on the 192.168.1 network.
Any help will be appreciated.
Thanks,
Eli


text:
Q: Virtualbox static IP to windows VM on ubuntu host I am trying to setup a windows VM on Ubuntu host using Virtual box. Since I would be running a SQL server database on the windows VM I am trying to setup a static IP on that VM. In order to do that I followed the instruction available here.
Below are my Virtualbox Network configurations for host-only adapter:

Here is my Network configuration for windows VM:

and lastly here is my configuration for the windows network adapter where I have assinged the static IP

When I run ifconfig, this is what I get for vboxnet1 adapter on my ubuntu host
vboxnet1  Link encap:Ethernet  HWaddr 0a:00:27:00:00:01
inet addr:192.168.57.1  Bcast:192.168.57.255  Mask:255.255.255.0
inet6 addr: fe80::800:27ff:fe00:1/64 Scope:Link
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:90 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B)  TX bytes:15853 (15.8 KB)

Even after this when I ping the assigned static IP I am not getting any response:
> ping 192.168.57.103
PING 192.168.57.103 (192.168.57.103) 56(84) bytes of data.
^C
--- 192.168.57.103 ping statistics ---
942 packets transmitted, 0 received, 100% packet loss, time 946463ms

Please let me know if I am missing anything? Let me know if you need any other information that would be helpful for debugging this issue.
* Edited with solution *
As per @cslotty's response below the problem was that the ICMP echo port was blocked in windows firewall. enabling that port fixed the issue.

A: Try to change the subnet mask to 255.255.255.255! You're not configuring that Windows VM to use a whole subnet, but only one address, right?
http://www.howtogeek.com/howto/19249/how-to-assign-a-static-ip-address-in-xp-vista-or-windows-7/
After all settings are correct, the Windows firewall could be the blocking issue.


text:
Q: pandoc returning "Cannot decode byte '\xf9'" I'm downloading a webpage from within R using xml2, and then using pandoc to convert it to pdf.
My R code
library(xml2)
download_html("https://thehustle.co/apple-christmas-present", "test.html")

cmd line
pandoc test.html -o converted.pdf

This fails with the error
pandoc: Cannot decode byte '\xf9': Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream

I'm not sure whats going on here. If the webpage is not in utf-8 (and that is the root error), is there someway to convert it to?

A: There are two things you could try:

*

*Use pandoc directly: don't use a different tool, but let pandoc handle the download.
pandoc https://thehustle.co/apple-christmas-present -f html -o converted.pdf

*Use iconv to ensure that the input is really UTF-8 encoded:
iconv -t utf-8 test.html | pandoc -f html -o converted.pdf

If neither works then it's likely to be a problem with the website.


text:
Q: Vue routes doesn't work i can not use vue routes get's the following error( npm 3.10.10, webpack 3.8.1). How to solve this

Failed to compile.
./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/quotes.vue
  Module not found: Error: Can't resolve './components/quote.vue' in
  'D:\vue\vue-laravel\src\components' @
  ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/quotes.vue
  11:0-43 @ ./src/components/quotes.vue @ ./src/main.js @ multi
  (webpack)-dev-server/client?http://localhost:8080
  webpack/hot/dev-server ./src/main.js

I use webpack-simple
main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import NewQuote from './components/new-quote.vue'
import Quotes from './components/quotes.vue'

Vue.use(VueRouter)

const routes = [
  {path: '', component: Quotes},
  {path: '/new-quote', component: NewQuote}
]

const router = new VueRouter({
    mode:'history',
    routes // short for `routes: routes`
})

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

Quotes.vue
<template>

    <button class="btn btn-primary" v-on:click="onGetQuotes">Get Quotes</button>

    <app-quote v-for="quote in quotes" v-bind:qt="quote"></app-quote>

</template>

Quote.vue
<template>

Simple Quotes

       {{ qt.content }}

         <input type="text">
         Save
         Cancel

         Edit
         Delete

</template>

new-quote.vue
<template>

Simple Quotes

         <form v-on:submit.prevent="createQuote">

              Content:
              <input type="text" class="form-control" v-model="quoteContent">

            <button type="submit" class="btn btn-default">Create New Quote</button>
         </form>

</template>

App.vue
<template>

    <router-view></router-view>

</template>

A: I have used { import Quote from './components/quote.vue } instead of { import Quote from './quote.vue }. Now works fine

A: Its './components/Quote.vue' with a capital Q


text:
Q: Getting individual array elements from the data returned by a chainlink external adapter In the job I'm adding for my external adapter, I'm looking to get results for the first 3 elements in the Results array one at a time.(see the data returned from my external adapter below)
So I'm adding "position" to my chainlink request in the consumer contract and wanting to use that in the jsonparse like below, rather than pass it to the external adapter. However, I get this error JSONParse task error: $(decode_cbor.position) is not a valid array index
parse        [type=jsonparse path="data,MRData,RaceTable,Races,0,Results,$(decode_cbor.position),number" data="$(fetch)"]```

in my consumer contract
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("position", "1");

The data returned from the external adapter looks like this.
{
    "MRData": {
        "xmlns": "http://ergast.com/mrd/1.4",
        "series": "f1",
        "url": "http://ergast.com/api/f1/current/last/results.json",
        "limit": "30",
        "offset": "0",
        "total": "20",

        "RaceTable": {
            "season": "2021",
            "round": "17",

          "Races": [{
                "season": "2021",
                "round": "17",
                "url": "http://en.wikipedia.org/wiki/2021_United_States_Grand_Prix",
                "raceName": "United States Grand Prix",
                "Circuit": {
                    "circuitId": "americas",
                    "url": "http://en.wikipedia.org/wiki/Circuit_of_the_Americas",
                    "circuitName": "Circuit of the Americas",
                    "Location": {
                        "lat": "30.1328",
                        "long": "-97.6411",
                        "locality": "Austin",
                        "country": "USA"
                    }
                },
                "date": "2021-10-24",
                "time": "19:00:00Z",

                "Results": [{
                    "number": "33",
                    "position": "1",
                    "positionText": "1",
                    "points": "25",
                    "Driver": {
                        "driverId": "max_verstappen",
                        "permanentNumber": "33",
                        "code": "VER",
                        "url": "http://en.wikipedia.org/wiki/Max_Verstappen",
                        "givenName": "Max",
                        "familyName": "Verstappen",
                        "dateOfBirth": "1997-09-30",
                        "nationality": "Dutch"
                    },.....

The full results can be found here. http://ergast.com/api/f1/current/last/results.json
Should I be able to do something like this? Is there a better way to go about this? Should I edit the adapter instead?
schemaVersion = 1
name = "f1latestresults2"
contractAddress = "0x765aCc258f3a7b2D8d103D1A9310fc51b07D5425"
maxTaskDuration = "0s"
observationSource = """
    decode_log   [type=ethabidecodelog
                  abi="OracleRequest(bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data)"
                  data="$(jobRun.logData)"
                  topics="$(jobRun.logTopics)"]

    decode_cbor  [type=cborparse data="$(decode_log.data)"]

    fetch        [type=bridge name="raceresults" requestData="{\\"id\\":$(jobSpec.externalJobID),\\"data\\":{\\"position\\":\\"0\\"}}"]

    parse        [type=jsonparse path="data,MRData,RaceTable,Races,0,Results,$(decode_cbor.position),number" data="$(fetch)"]

    encode_data  [type=ethabiencode abi="(uint256 value)" data="{ \\"value\\": $(parse) }"]
    encode_tx    [type=ethabiencode
                  abi="fulfillOracleRequest(bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data)"
                  data="{\\"requestId\\": $(decode_log.requestId), \\"payment\\": $(decode_log.payment), \\"callbackAddress\\": $(decode_log.callbackAddr), \\"callbackFunctionId\\": $(decode_log.callbackFunctionId), \\"expiration\\": $(decode_log.cancelExpiration), \\"data\\": $(encode_data)}"
                 ]
    submit_tx    [type=ethtx to="0x765aCc258f3a7b2D8d103D1A9310fc51b07D5425" data="$(encode_tx)"]

    decode_log -> decode_cbor -> fetch -> parse -> encode_data -> encode_tx -> submit_tx
"""
externalJobID = "cfa059b4-a31d-4c30-99e4-3a2fd4c57739"

A: The syntax you are using looks correct to me, so I'm not 100% sure if the TOML jobs can support having a parameter like that within a string yet?
If the rest of the JSON path is static, suggest just having it as a built up string in your consuming contract, and just sending it as a full string in the request, then using that in your TOML spec, similar to the example in the docs
req.add("path", "data,MRData,RaceTable,Races,0,Results,0");

Then in your TOML job spec:
parse        [type=jsonparse path="$(decode_cbor.path)" data="$(fetch)"]


text:
Q: How can I inject qualifier bean in UT? I'm trying to write UT for the below class. CircuitBreakerRegistry class has two qualifiers in the same application.
@Configuration
@RefreshScope
@Log4j2
public class ApplicationConfig {
    @Bean("daoCollection")
    public Map<String, CacheDao> daoCollection(@Autowired DataProviderConfig dataProviderConfig,
                   @Value("#{systemEnvironment['DB_USERNAME'] ?: 'bob'}") String cacheUserName,
                   @Value("#{systemEnvironment['DB_PASSWORD'] ?: 'abc123'}") String cachePassword,
                   @Qualifier("couchbaseClientCircuitBreaker") @Autowired CircuitBreakerRegistry circuitBreakerRegistry
    )
{
    log.info("Creating daoCollection Configuration bean.");
}

Here is my respective UT,
@WebFluxTest
@ContextConfiguration(classes = ApplicationConfig.class)
@ImportAutoConfiguration(value = RefreshAutoConfiguration.class)
class ApplicationConfigTest {
    @Autowired
    ApplicationContext applicationContext;

    @Test
    void daoCollectionTest() {
        assertNotNull(applicationContext.getBean("daoCollection"));
    }
}

I'm getting below exception,
java.lang.IllegalStateException: Failed to load ApplicationContext

...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'daoCollection' defined in com.company.team.dataprovider.config.ApplicationConfig: Unsatisfied dependency expressed through method 'daoCollection' parameter 3; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value="couchbaseClientCircuitBreaker"), @org.springframework.beans.factory.annotation.Autowired(required=true)}

Now I'm looking for a solution to inject the qualifier before all the UT cases I will be going to write for my application.


text:
Q: Redeclaring a class on update I am having a small problem when it comes to redeclaring a class. I made an update function that calls to a remote server, gets the files/classes, and updates it on the current server. The problem is I have to use a class the has been declared already because the new class contains features that have been updated.
I've been trying to unset the class but that does not work and I don't see a way of removing the require_once() of the file and then re including.
So is there a way where I can redeclare a class and have it run locally and not on the global scope?

A: You can use the runkit extension: runkit-import


text:
Q: How can i multiple table combining with Laravel? For example ;
 $hall_templates = HallTemplate::where('hall_id' , $id)->orderBy('order' , 'ASC')->get();

Output:
 [{"id":16,"hall_id":3,"template_name":"Magazin Outlet","order":1,"width":12,"height":12},
  {"id":17,"hall_id":3,"template_name":"Merinos K\u00fclt\u00fcr Merkezi","order":2,"width":22,"height":12}]

For example second table info as below;
$armchair_number_count = HallTemplateArmChair::where('template_id' , 16)->get();

Output:
[{"id":1,"template_id":16,"armchair_no":"a1"},
 {"id":2,"template_id":16,"armchair_no":null}]

how can i combine these two tables.
I want to do output:
array({"id":16,"hall_id":3,"template_name":"Magazin Outlet","order":1,"width":12,"height":12, "armchair_number_count",2},
{"id":17,"hall_id":3,"template_name":"Merinos K\u00fclt\u00fcr Merkezi","order":2,"width":22,"height":12, "armchair_number_count",0);

Thank you for your help.

A: Use the withCount() method:
HallTemplate::withCount('armchairNumber')->where('hall_id' , $id)->orderBy('order' , 'ASC')->get();

This method will count chairs and will add armchair_number_count property to each HallTemplate object.
To make it work, define the relationship in the HallTemplate model:
public function armchairNumber()
{
    return $this->hasMany(HallTemplateArmChair::class, 'template_id');
}


text:
Q: Add form fields to Checkout -> Payment&Review step is there any tutorial, documentation or hints how to add a custom form to the Payment&Review step for my custom offline payment module in Magento2 checkout process and how to connect it to the database? I have seen some tutorials that describe how to add fields to the shipping address (e.g. https://sohelrana09.wordpress.com/2015/11/28/how-to-add-custom-field-to-shipping-address-form-in-magento-2-onepage-checkout/) but that is no option for me because the solution should work even for products without shipping. Any ideas?
Thanks a lot

A: In this page of the docs you can find how to add a custom form.
That tutorial you linked can you also use to add fields to other parts of the shipping step btw. It doesn't have to be in the shipping address form.

A: <?php

       namespace Codilar\Field\Model\Plugin\Checkout;
        class LayoutProcessor2
{
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {
        $configuration = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'];
        foreach ($configuration as $paymentGroup => $groupConfig) {
            if (isset($groupConfig['component']) AND $groupConfig['component'] === 'Magento_Checkout/js/view/billing-address') {

                $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                ['payment']['children']['payments-list']['children'][$paymentGroup]['children']['form-fields']['children']['company_tax_id'] = [
                    'component' => 'Magento_Ui/js/form/element/abstract',
                    'config' => [
                        'customScope' => 'billingAddress.custom_attributes',
                        'template' => 'ui/form/field',
                        'elementTmpl' => 'ui/form/element/input',
                        'options' => [],
                        'id' => 'custom-field'
                    ],
                    'dataScope' => 'billingAddress.custom_attributes.custom_field',
                    'label' => 'Custom Field',
                    'provider' => 'checkoutProvider',
                    'visible' => true,
                    'validation' => [],
                    'sortOrder' => 250,
                    'id' => 'custom-field'
                ];
            }
        }
        return $jsLayout;
    }
}

<?php
namespace Codilar\Field\Model\Plugin\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']['custom_field'] = [
            'component' => 'Magento_Ui/js/form/element/abstract',
            'config' => [
                'customScope' => 'shippingAddress.custom_attributes',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/input',
                'options' => [],
                'id' => 'custom-field'
            ],
            'dataScope' => 'shippingAddress.custom_attributes.custom_field',
            'label' => 'Custom Field',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => [],
            'sortOrder' => 250,
            'id' => 'custom-field'
        ];
        return $jsLayout;
    }
}


text:
Q: Generative-Discriminative pairs: Naive Bayes and Logistic Regression I'm trying to understand the something written in this paper.
At the bottom of page 7:

This means that if the naive Bayes model  $$ p(y,\mathbf{x}) = p(y) \prod_k p(x_k|y) $$ is trained to
  maximize the conditional likelihood, we recover the same classifier as
  from logistic regression. Conversely, if the logistic regression model
  $$p(y|\mathbf{x}) = \frac{1}{Z(\mathbf{x})} exp\left\{\sum_k \lambda_k f_k(y,\mathbf{x}) \right\} $$ is interpreted generatively, as in  $$p(y,\mathbf{x}) = \frac{exp\left\{\sum_k \lambda_k f_k(y,\mathbf{x}) \right\}}{\sum_{y', \mathbf{x}'}exp\left\{\sum_k \lambda_k f_k(y',\mathbf{x}') \right\}}$$ and is trained to
  maximize the joint likelihood p(y, x), then we recover the same
  classifier as from naive Bayes.

I'm having trouble seeing why this is.The next page goes on to say

...consider the family of naive Bayes distributions. This is a family
  of joint distributions whose conditionals all take the "logistic
  regression form". But there are many other joint models, some with
  complex dependencies among $\mathbf{x}$, whose conditional
  distributions also have the logistic regression form.

Aren't these statements contradictory? The conditioned-Bayes distributions are a subset of the logistic-regression-form distributions, so isn't it possible that maximizing over the latter yields a distribution not contained in the former?

A: The $f_k(y,{\bf x})$ introduced at the top of page 5 are of a very special form that, crucially, is linear in ${\bf x}$ and so (dropping the $k$ subscript for a moment) can be written $f(y,{\bf x}) = \alpha_1^{(y)}x_1 + \ldots + \alpha_K^{(y)}x_K$ .  Exponentiating, that's just $\prod_k g(x_k|y)$, i.e. of Naïve-Bayes form.  Your second equation is the paper's (1.7), which is just the more transparent (1.6) in disguise.
You are quite right that if $f_k(y,{\bf x})$ were not of this special form then the mapping to NB would not be guaranteed.


text:
Q: Dart: type 'Null' is not a subtype of type 'Future' in Mockito The code below used to work before null safety, but now I get "type 'Null' is not a subtype of type 'Future<String?>'" and I have absolutely no idea why and what to do. Please help, this should be really easy (except for me), because you just have to copy the code and run it as test to get the exception:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockMethodChannel extends Mock implements MethodChannel {}

void main() {

  group('all', () {

      test('test', () async {
        final mockMethodChannel = MockMethodChannel();
        when(mockMethodChannel
            .invokeMethod<String>("GET com.eight/preference-management/preferences"))
            .thenAnswer((_) async => "test");
      });
  });
}

A: If you are using Flutter with null safety, then the way to create a mock class is different, you need to use @GenerateMocks annotation now.
Please read documentation on null safety.

A: if you want a simple way just do like this
   class WorkerAPI {
         late ApiHelper _helper;

          WorkerAPI() {
            _helper = GetIt.I<ApiHelper>();
          }

          Future<Result<List<WorkerModel>>> getWorkers() async {
            return await _helper.get(
                url: urls.workers,
                onSuccess: (response) {
                  Iterable listJson = json.decode(response.body);
                  List<WorkerModel> list =
                      listJson.map((e) => WorkerModel.fromJson(e)).toList();
                  return list;
                });
          }

     // override your method in mock with Non-nullable return type

      class WorkerApiMock extends Mock implements WorkerAPI {
          @override
          Future<Result<List<WorkerModel>>> getWorkers() {
             return super.noSuchMethod(Invocation.method(#getWorkers,null),
             returnValue:Future.value(Result.success(List.filled(0,WorkerModel()))));
        }

    }

if you want check this => https://github.com/dart-lang/mockito/blob/master/test/manual_mocks_test.dart

A: Your signature for MethodChannel.invokeMethod function says it returns a Future<String?> but since the MockMethodChannel doesnot have any implementation for invokeMethod() , it will return null; dart's null safety gets angry because you lied. For a quick fix, the invokeMethod can have a return type of Future<String?>?. When you do so, you are saying null safety shouldn't bother even if the returned value is null.
However this is not a permanent solution I just want you to understand the problem.
you could add build_runner in your dev_dependencies: in pubspec.yaml
dart pub add build_runner --dev
and modify your code to
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
//modified
import 'package:mockito/annotations.dart';
import 'generated file.dart';

class MockMethodChannel extends Mock implements MethodChannel {}

//modified
@GenerateMocks([MockMethodChannel])
void main() {

  group('all', () {

      test('test', () async {
        final mockMethodChannel = MockMockMethodChannel();
        when(mockMethodChannel
            .invokeMethod<String>("GET com.eight/preference-management/preferences"))
            .thenAnswer((_) async => "test");
      });
  });
}

and run
flutter pub run  build_runner build --delete-conflicting-outputs for build runner to build the stub files for you


text:
Q: How to communicate a Rust and a Ruby process using a Unix socket pair I am trying to communicate a Rust process with a child Ruby process using a Unix socket pair. I have tried the same using only Ruby and it works, but I can't seem to get it to work with Rust.
I have tried passing the "rust_socket" file descriptor to the Ruby script, passing the "ruby_socket" file descriptor to Ruby and different combinations of reading / writing to the socket. I feel like I should be passing the "ruby_socket" file descriptor, but when I do that I get a bad file descriptor error.
// The rust side of things
use std::process::Command;
use std::os::unix::net::UnixStream;
use std::os::unix::io::IntoRawFd;
use std::io::{Read, Write};

fn main() {
    let (rust_socket, mut ruby_socket) = match UnixStream::pair() {
        Ok((rust_socket, ruby_socket)) => (rust_socket, ruby_socket),
        Err(e) => {
            println!("Failed to open socket pair: {:?}", e);
            return;
        }
    };

    let _output = Command::new("ruby")
        .args(&["/home/station/workspace/rust_server/src/client.rb", &rust_socket.into_raw_fd().to_string()])
        .spawn()
        .expect("Failed to start ruby process");

    let mut response = String::new();
    ruby_socket.read_to_string(&mut response).unwrap();
}

# The ruby side of things
require "socket"

begin
  socket = UNIXSocket.for_fd(ARGV.shift.to_i)
  socket.send("Hello world!\n", 0)
ensure
  socket&.close
end

I expected to be able to read the "Hello world!" string from Rust, but it does not work.

A: The problem seems to be that Rust sets all file descriptors to be closed when a child is created by setting the FD_CLOEXEC flag. The only way to get around this seems to be using libc to call fcntl.
Here's some code that seems to work, but I don't know Rust, so use at your own risk. Another issue you will have is you need to close the parent side of rust_socket after spawing the child, otherwise read_to_string will block forever waiting for the stream to be closed. You can do this with drop, but you will also need to use AsRawFd rather than IntoRawFd:
use std::process::Command;
use std::os::unix::net::UnixStream;
use std::os::unix::io::AsRawFd;
use std::io::Read;

extern crate libc;

fn main() {
    // Create the socket pair.
    let (rust_socket, mut ruby_socket) = UnixStream::pair().unwrap();

    // Unset FD_CLOEXEC on the socket to be passed to the child.
    let fd = rust_socket.as_raw_fd();
    unsafe {
        let flags = libc::fcntl(fd, libc::F_GETFD);
        libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC);
    }

    // Spawn the child
    let _output = Command::new("ruby")
        .args(&["client.rb", &fd.to_string()])
        .spawn();

    // After spawning, close the parents side of rust_socket.
    // If we use IntoRawFd, rust_socket would have been moved by this point
    // so we need AsRawFD instead.
    drop(rust_socket);

    let mut response = String::new();
    ruby_socket.read_to_string(&mut response).unwrap();

    println!("Ruby said '{}'", response);
}


text:
Q: iPhone, AVAudioPlayer and multiplesounds im new developer and making  my firt iPhone app ,and i want to make button to on/off multiplesounds , example when i press button for multiple sounds after when i play sounds it plays all sound at same time and if its off can play only one sounds, what code is to make ON/OFF multiple sounds play?
sorry for my bad english, Tanks!

A: Sania,
In order to play multiple sounds at once, Apple recommends using the .caf format which is hardware decoded.  Also, you basically just create a new AVAudioPlayer object for each sound file instead of re-using the same object in the case where you only want one sound to play at a time.
I won't go into much of the code since there is already a LOT out there if you just search for it... but here are some helpful links to get you started:
http://developer.apple.com/iphone/library/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html
http://www.mobileorchard.com/easy-audio-playback-with-avaudioplayer/
// a function I use to play multiple sounds at once
- (void)playOnce:(NSString *)aSound {

// Gets the file system path to the sound to play.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];

// Converts the sound's file path to an NSURL object
NSURL *soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = soundURL;
[soundURL release];

AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error:nil];
self.theAudio = newAudio; // automatically retain audio and dealloc old file if new file is loaded

[newAudio release]; // release the audio safely

// buffers data and primes to play
[theAudio prepareToPlay];

// set it up and play
[theAudio setNumberOfLoops:0];
[theAudio setVolume: volumeLevel];
[theAudio setDelegate: self];
[theAudio play];

}


text:
Q: Multipart form submits and sends email but file upload fails with jQuery check I have a simple HTML form that can be filled out and the information emailed via the POST method. I recently added a file upload to the form - If i do no checks with Javascript/jQuery then it submits fine and the file uploads no problem. However if I use jQuery validation the form responds with the success message and I receive the email, all the information is there but the file upload fails.
Form:
<form class="smtcheck" style="font-family: Arial;" action="https://myurl.co.uk/emails/smt.php" method="post" enctype="multipart/form-data">

<select style="font-family: Arial;" name="title">
    <option style="font-family: Arial;" selected="selected" disabled="disabled" value="">Title</option>
    <option style="font-family: Arial;" value="Mr">Mr</option>
    <option style="font-family: Arial;" value="Miss">Miss</option>
    <option style="font-family: Arial;" value="Mrs">Mrs</option>
    <option style="font-family: Arial;" value="Ms">Ms</option>
    <option style="font-family: Arial;" value="Sir">Sir</option>
    <option style="font-family: Arial;" value="Dr">Dr</option>
    <option style="font-family: Arial;" value="Mx">Mx</option>
    </select><input class="wipe" style="font-family: Arial;" type="text" name="name" placeholder="Full Name*" required="">

    <input class="wipe" style="font-family: Arial;" type="text" name="email" placeholder="Email Address*" required="">
    <input class="wipe" style="font-family: Arial;" type="text" name="phone" value="Phone Number*" required="">
    <input class="wipe" style="font-family: Arial;" type="text" name="make" value="Make*" required="">
    <input class="wipe" style="font-family: Arial;" type="text" name="model" value="Model">
    <input class="wipe" style="font-family: Arial;" type="text" name="age" value="Age">
    <input class="wipe" style="font-family: Arial;" type="text" name="serial" value="Serial No">
    <input type="file" name="imgup" id="imgup">
    <input class="right" style="font-family: Arial;" type="submit" value="SEND"></form>

jQuery:
jQuery(document).ready(function(){

    $(document).on("click","span.close",function(){$(this).parent().slideUp(300)})

    $('.smtcheck').submit(function(e){

        e.preventDefault();

        var error = false;

        var name = $("input[name='name']").val();

        var email = $("input[name='email']").val();

        var phone = $("input[name='phone']").val();

        var make = $("input[name='make']").val();

        if(name.length == 0){

        var error = true;

        var name = $("input[name='name']").addClass("error");
        alert("Please ensure you have filled out your name.");

        }else{

        var error = false;
        $("input[name='name']").removeClass("error");

        }

        if(make.length == 0){

        var error = true;

        var make = $("input[name='make']").addClass("error");
        alert("Please ensure you have filled out your trailer make.");

        }else{

        var error = false;
        $("input[name='make']").removeClass("error");

        }

        if(phone.length == 0){

        var error = true;

        var phone = $("input[name='phone']").addClass("error");
        alert("Please ensure you have filled out your phone number.");

        }else{

        var error = false;
        $("input[name='phone']").removeClass("error");

        }

        if(email.length == 0 || email.indexOf('@') == '-1'){

        var error = true;

        var email = $("input[name='email']").addClass("error");
        alert("Please ensure you have filled out your email.");

        }else{

        var error = false;
        $("input[name='email']").removeClass("error");

        }

        if(error == false){

        $.post("https://myurl.co.uk/emails/smt.php", $(".smtcheck").serialize(),function(result){

        if (result) {

                           $("input[type=submit]").remove();

                           $('.formresponse').show();

                            }else{

                            alert("Please ensure you have filled out all the required fields and try again.");

                        }

                        return false;
                    });

                }

    });

});

I've never tried doing an AJAX submit of a multipart form so unsure why the file fails to upload with the jQuery validation?

A:

var frm = $(document.formname);
var jdata = JSON.stringify(frm.serializeArray());

This will serialize all the input values except file inputs.if you want to do this, do form submit with ajax like,

$(document).on("submit", "form#formname", function (event) {
        event.preventDefault();
        if ($("#formname").validationEngine('validate')) {
            $('.loader').show();
            $.ajax({
                url: $(this).attr("action"),
                type: $(this).attr("method"),
                dataType: "JSON",
                data: new FormData(this),
                processData: false,
                contentType: false,
                success: function (result) {
                },
                error: function (xhr, desc, err) {
                }
            });
        }
    });

You can show any success of error messages in ajax success/error if needed


text:
Q: TypeScript not finding definitions I have the following file structure:
+ src
|  test.ts
|  z_module.d.ts
tsconfig.json

test.ts
// does nothing?
/// <reference path="./z_module.d.ts" />
// can't now write:
var a: zzrm.zzrmObject;

// have to use:
import * as zzrm from 'zzrm';
var a: zzrm.zzrmObject;

z_module.d.ts
declare module "zzrm" {
  export interface zzrmObject {id: string}
}

I have tried to reduce the problem but may well have reduced it incorrectly.  The problem originally came from trying to use sequelize-auto-ts.  Downloading the repo, upgrading the sequelize.d.ts and opening in Visual Studio Code (version 0.10.6) immediately highlights this line with the error "Cannot find namespace 'sequelize'."
var Sequelize:sequelize.SequelizeStatic = require('sequelize');
              ^^^^^^^^^

Even though sequelize.d.ts is successfully reference at the top of the file with: /// <reference path="../../typings/sequelize/sequelize.d.ts" />

A: The above "reduced" example works if the zzrm module is declared without the quotation marks:
declare module zzrm {
  export interface zzrmObject {id: string}
}

When I updated the sequelize.d.ts I failed to note that the module declaration had changed from
declare module sequelize { ... }

to
declare module "sequelize" { ... }

This is referred to in the TypeScript docs under "Ambient External Modules" but I haven't quite yet figured out how these parts all fit together and why they require you to also add import * as zzrm from 'z_module';


text:
Q: Custom Event Handler I have a function that I'm using while(true) to repeatedly scan memory addresses of an application to detect change. I sleep the thread 1 second between iterations and this helps performance. However, is there a way to create a custom event handler to do away with the loops?

A: Have you looked into using a Timer with an Interval of 1000 (milliseconds)?
This also gives you a clean way out of your polling by simply destroying the timer, instead of having to check some condition and breaking out of your while loop.


text:
Q: Entity Framework using foreign key as only primary key in one to many I am using Entity Framework code first to design the database.
I have 2 models with One to Many relationship. One "Foo" can have many "FooData" as follows -
public class Foo {
  [Key]
  public string serialNumber{get; set;}
  public int someNumber {get; set;}
  public string someName {get; set;}
  // Many more properties
  // Navigation Collection
  public virtual ICollection<FooData> FooDatas{get; set;}
}

public class FooData{
  [Key]
  [ForeignKey("foo")]
  public string SerialNum {get; set;}
  public DateTime SomeTime {get; set;}
  public byte[] SomeData {get; set;}
  // Navigation property
  public virtual Foo foo {get; set;}
}

When I try to add a controller for "Foo" in MVC, using "Foo" as a scaffolding model, it gives me this error - "Multiplicity is not valid in Role. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be 1".
I would appreciate some help here.
Thank you

A: Because of how you have it defined the same key is used in both so it is a 1-to-1 relationship. If you want a real  one to many you will need to add/create another field and set them up as a composite key on the FooData table/entity.
public class Foo {
    [Key]
    public string serialNumber{get; set;}
    public virtual ICollection<FooData> FooDatas{get; set;}
}

public class FooData {
  [Key, Column(Order = 0),ForeignKey("foo")]
  public string SerialNum {get; set;}
  [Key,Column(Order=1)]
  public int DataId {get;set;}
  public virtual Foo foo {get; set;}
}


text:
Q: What does a prime (apostrophe) mean before a predicate? I found this statement in a paper by John McCarthy:
$$
\forall x.ostrich\ x \supset  species\ x ={}^\prime{}ostrich
$$
I can't figure out what the prime indicates.

A: It seems to me that it is used as an "operator" for nominalization, in place of the standard $\lambda$ operator.
See :

*

*Nino Cocchiarella, Conceptual Realism and the Nexus of Predication : Lecture Five (Rome, 2004), page 14 :

Consider, for example, the predicate phrase "is famous", which can be symbolized as a $\lambda$-abstract $[\lambda xFamous(x)]$ as well as simply by $Famous( )$. The $\lambda$-abstract is preferable as a way of representing the infinitive "to be famous", which is one form of nominalization:

to be famous $\to$ to be an $x$ such that $x$ is famous $\to$ $[\lambda xFamous(x)]$.

The $\lambda$-abstract  $[\lambda xFamous(x)]$ acts as a term, and thus can fill the argument-place of a predicate (like : $x = t$).

A: An apostrophe before the name of a predicate has no standard meaning. I believe McCarthy is just using it as a systematic way for assigning symbolic identifiers to classes, so that he can economise on axioms. I.e., if instead of saying $ostrich(x)$ you say $species(x) = 452$ and instead of saying $penguin(x)$ you say $species(x) = 453$, then you avoid the possibility of having an $x$ that satisfies $ostrich(x) \land penguin(x)$. $'ostrich$ and $'penguin$ are McCarthy's convention for naming the symbolic identifiers, rather than using specific identifiers like $452$ and $453$.


text:
Q: C# How to do WebBrowserDocumentComplete in a foreach loop I thought this might be simple but i guess it's not, i have like 100 websites i need to load into a browser. I've loaded them into a List but my foreach happens before the website loads.  Does anybody have a way to make each of these load and actually process WebBrowserDocumentComplete before loading the next one? queue doesn't work.
foreach(string oneWebsite in ALLWebSites)
{
webBrowser1.Navigate(oneWebsite);
webBrowser1.DocumentCompleted += new     WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
//do work
}

A: An AutoResetEvent should work
http://msdn.microsoft.com/en-us/library/system.threading.waithandle.waitone(v=vs.71).aspx
static AutoResetEvent autoEvent = new AutoResetEvent(false);

webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
foreach(string oneWebsite in ALLWebSites)
{
webBrowser1.Navigate(oneWebsite);
autoEvent.WaitOne(new TimeSpan(0, 1, 0), false))
}

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//do work
autoEvent.Set();
}

A: At the end of the DocumentCOmplete handler have the browser navigate to the next site in the list.

A: Something like this should work:
var websiteIndex = 0;
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

private void ProcessWebsite()
{
    if (websiteIndex < ALLWebSites.Count)
    {
        webBrowser1.Navigate(ALLWebSites[websiteIndex]);
        websiteIndex++;
    }
}

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    //do work

    // when work is done, process next one
    ProcessWebsite();
}


text:
Q: Shotwell, eog, and the Desktop background can't handle some JPGs everybody else can Take a look at this picture. (In order to reproduce the problem, open this page and click "Download.")

It appears OK in the browser. I can open it with GIMP. But if I open the directory where it's in with the file Manager (stock Gnome in Ubuntu 22.04) it can't display the thumbnail. If I set it as a desktop background I get a black screen. If I open it with the image viewer (eog) I get this:

Clearly, there's some bug in the desktop environment's image handling. Faulty library?


text:
Q: How to remove TSR(Terminate-Stay-Resident) program from memory I have a very basic TSR code. What it does is, when I type "D" key, it will print "E" on the screen, nothing else. What I want to do is: when i press "ESC" button I want to remove my TSR and return to original BIOS routine.
org 100h

equ 060h

EOI            equ 020h
Master_8259    equ 020h

main:
    call _inst_09

_inst_09:
    cli
    xor     ax, ax
    mov     es, ax
    mov     bx, [es:09h*4]
    mov     [stari_int09_off], bx
    mov     bx, [es:09h*4+2]
    mov     [stari_int09_seg], bx

    mov     dx, tastatura
    mov     [es:09h*4], dx
    mov     ax, cs
    mov     [es:09h*4+2], ax
    sti

    mov ax,3100h
    mov dx,500
    int 21h
    ret

tastatura:
    push    ax
    in      al, KBD             ; Ucitati scan_code iz I/O registra tastature
    mov    [kbdata], al
    cmp byte[kbdata],20h
    je .lup
    mov     al, EOI             ; Kod za End Of Interrupt (EOI)
    out     Master_8259, al     ; Poslati EOI na Master PIC (dozvola novih prekida)
    pop     ax
    iret
.lup:
    mov al,45h
    mov ah,0eh
    int 10h
    mov     al, EOI
    out     Master_8259, al
    pop     ax
    iret

stari_int09_seg: dw 0
stari_int09_off: dw 0

kbdata:     db 0

%include "ekran.asm"

I know that i need to uninstall my modified interupt but my program became iresponsive after i did so.
This would be the unnistaling procedure
_uninst_09:
cli
xor     ax, ax
mov     es, ax
mov     ax, [stari_int09_seg]
mov     [es:09h*4+2], ax
mov     dx, [stari_int09_off]
mov     [es:09h*4], dx
sti
ret

The trick is I don't know where to put it. I tried checking if ESC is pressed and then jump to this procedure but it seems it is not working.

A: Restore all hooked interrupt vectors to their original values, close all files (if any), free all dynamic memory allocated from DOS (if any), then free the program area itself. Depending on whether the TSR is a COM file or an EXE file, its starting address would be different. For COM files, the program memory starts at the file beginning; for EXE files, it's slightly more tricky. Then return from the interrupt handler as usual, it won't be invoked ever again.
To free DOS memory, use interrupt 21h, function 49h.
EDIT: your problem is with your interrupt handler. It doesn't process the keyboard input right, thus breaking the keyboard for the foreground process.
In the handler, call the original one first thing (with respect to the fact that it's an interrupt handler):
tastatura:
    push es
    push ax
    mov ax, [stari_int09_seg]
    mov es, ax
    mov ax, [stari_int09_off]
    pushf
    call es:ax

Then use int 16 to read the keyboard input.


text:
Q: Android google plus sign in error when login onemore I have login google plus, but when i login success, and in the new activity, i logout,after i login again,it is not success login.
Log:ClearcutLoggerApiImpl: disconnect managed GoogleApiClient
It is code:
GoogleSingleton:
public class GoogleSingleton {
    private ILogInGoogleListener mListener = null;

    public void setLogInGooglePlusListener(final ILogInGoogleListener listener) {
        this.mListener = listener;
    }

    public interface ILogInGoogleListener {
        void logInGooglePlusSuccess(String name,
                                    String email,
                                    String pid);
    }

    private static GoogleSingleton googleSingleton;
    private final GoogleApiClient mGoogleApiClient;
    private ConnectionResult mConnectionResult;
    public static final int RC_SIGN_IN = 321;
    private Activity activity;

    private GoogleSingleton(final Activity activity) {
        this.activity = activity;
        mGoogleApiClient = new GoogleApiClient.Builder(activity)
                                   .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                                       @Override
                                       public void onConnected(final Bundle bundle) {
                                           try {
                                               if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                                                   System.out.println(">>>> Log in xong");
                                                   Person currentPerson = Plus.PeopleApi
                                                                                .getCurrentPerson(mGoogleApiClient);
                                                   String personName =
                                                           currentPerson.getDisplayName();
                                                   String email =
                                                           Plus.AccountApi.getAccountName(mGoogleApiClient);
                                                   String id = currentPerson.getId();
                                                   if (mListener != null) {
                                                       mListener.logInGooglePlusSuccess(personName,
                                                                                email,
                                                                                id);
                                                   }

                                               }
                                           } catch (Exception e) {
                                               e.printStackTrace();
                                           }
                                           // Update the UI after signin
                                       }

                                       @Override
                                       public void onConnectionSuspended(final int i) {
                                           mGoogleApiClient.connect();
                                           System.out.println(">>>> chua log in");
                                       }
                                   })
                                   .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                                       @Override
                                       public void onConnectionFailed(final ConnectionResult result) {
                                           if (!result.hasResolution()) {
                                               GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
                                                                                activity,
                                                                                0)
                                                                     .show();
                                           }
                                           mConnectionResult = result;
                                       }
                                   })
                                   .addApi(Plus.API)
                                   .addScope(Plus.SCOPE_PLUS_LOGIN)
                                   .build();
    }

    public static GoogleSingleton getInstance(Activity activity) {
        if (googleSingleton == null) {
            googleSingleton = new GoogleSingleton(activity);
        }
        return googleSingleton;
    }

    public void connectGoogle() {
        mGoogleApiClient.connect();
    }

    public void disConnectGoogle() {
        mGoogleApiClient.disconnect();
    }

    public boolean isConnecting() {
        return mGoogleApiClient.isConnecting();
    }

    public boolean isConnected() {
        return mGoogleApiClient.isConnected();
    }

    public void login() {
        System.out.println(">>>>>> check login Singleton");
        if (!mGoogleApiClient.isConnecting()) {
            if (mConnectionResult != null && mConnectionResult.hasResolution()) {
                System.out.println(">>>>>> check login Singleton Try:" + mGoogleApiClient.isConnected() + "__" + mConnectionResult.hasResolution());

                try {
                    mConnectionResult.startResolutionForResult(activity,
                                                               RC_SIGN_IN);
                    System.out.println(">>>>>> abce");

                } catch (IntentSender.SendIntentException e) {
                    mGoogleApiClient.connect();
                }
            }
        } else {
            System.out.println(">>>>>> check login Singleton:" + mGoogleApiClient.isConnected() + "__" + mConnectionResult.hasResolution());
        }
    }

    public void logOut() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
            //set text button google plus.
        }
    }
}

Activity 1:
LogIn:
 /**
 * init google plus.
 * - init api client.
 * - fill data when success.
 * - set text when login success.
 */
private void initGooglePlus() {
    GoogleSingleton.getInstance(this)
                   .connectGoogle();
    GoogleSingleton.getInstance(this)
                   .setLogInGooglePlusListener(new GoogleSingleton.ILogInGoogleListener() {
                       @Override
                       public void logInGooglePlusSuccess(final String name,
                                                          final String email,
                                                          final String pid) {
                           System.out.println(">>>>> check name:"+name);
                           logInGooglePlus(name,
                                           email,
                                           pid);
                       }
                   });
}

  /**
 * - Sign in google.
 * - check null button,and check have sign in.
 * - when logout,set data model user local empty.
 * - if have sign in, click sign out,reverse.
 *
 * @param view
 *         This is button google.
 */
@OnClick(R.id.btnDangNhapGoogle)
protected void setOnDangNhapClicked(View view) {
    //sign in and sign out google.
    if (btnDangNhapGooglePlus != null) {
        //log out
        if (btnDangNhapGooglePlus.getText()
                                 .equals(getResources().getString(R.string.text_log_out))) {
            if (GoogleSingleton.getInstance(this)
                               .isConnected()) {
                //Log out.
                GoogleSingleton.getInstance(this)
                               .logOut();
                //set text button google plus.
                btnDangNhapGooglePlus.setText(getResources().getString(R.string.text_dang_nhap_bang_google_plus));
                //set null user model.
                LocalStorage.getShareInstance(SignInActivity.this)
                            .saveUserModel(new UserModel());
            }
        }//log in
        else {
            if (!GoogleSingleton.getInstance(this)
                                .isConnecting()) {
                GoogleSingleton.getInstance(this)
                               .login();

            }
        }
    }

}

/**
 * - activity result of facebook, google plus.
 * - when logout from account activity, logout all social, and set local data user empty.
 *
 * @param requestCode
 *         This is request.
 * @param resultCode
 *         This is result.
 * @param data
 *         This is data.
 */
@Override
protected void onActivityResult(final int requestCode,
                                final int resultCode,
                                final Intent data) {
    super.onActivityResult(requestCode,
                           resultCode,
                           data);
    mCallbackManager.onActivityResult(requestCode,
                                      resultCode,
                                      data);
    System.out.println(">>>>>> connect requecode"+requestCode);
    if (requestCode == GoogleSingleton.RC_SIGN_IN) {
        System.out.println(">>>>>> connect RC_SIGN_IN");
        if (!GoogleSingleton.getInstance(this)
                            .isConnecting()) {
            System.out.println(">>>>>> connect vvvvv");
            mIsCheckLoginGoogle = true;
            GoogleSingleton.getInstance(this)
                           .connectGoogle();
        }
    }
    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_LOGOUT_ALL) {
        System.out.println(">>>>>> check result logout code");
        logOutFaceBookAndGooglePlusResult();
        //set null user model.
        LocalStorage.getShareInstance(SignInActivity.this)
                    .saveUserModel(new UserModel());
    }
}

/**
 * - check facebook and google plus.
 * - logout facebook and google plus.
 * - set text google plus.
 */
private void logOutFaceBookAndGooglePlusResult() {
    if (GoogleSingleton.getInstance(this)
                       .isConnected()) {
        GoogleSingleton.getInstance(this)
                       .logOut();
        //set text button google plus.
        btnDangNhapGooglePlus.setText(getResources().getString(R.string.text_dang_nhap_bang_google_plus));
    }
    //log out facebook.
    if (AccessToken.getCurrentAccessToken() != null) {
        LoginManager.getInstance()
                    .logOut();
    }
}

Activity 2:
 //init google connect.
    GoogleSingleton.getInstance(this).connectGoogle();
//logout google.
        GoogleSingleton.getInstance(this).logOut();


text:
Q: 3-Way SQL Join Returning Bad Data I'm attempting to use the following sql to retrieve the total amount received, and the total amount sold from 3 tables:
select ITEMS.ITEM_NO, SUM(RECEIVINGS.QTY_RECVD), SUM(SALES.QTY_SOLD)
from ITEMS
left join RECEIVINGS
on ITEMS.ITEM_NO = RECEVINGS.ITEM_NO
left join SALES
on ITEMS.ITEM_NO = SALES.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'
GROUP BY ITEMS.ITEM_NO

The query above returns data that is several orders of magnitude greater than the actual values.  However, if I break it into two queries:
select ITEMS.ITEM_NO, SUM(RECEIVINGS.QTY_RECVD)
from ITEMS
left join RECEIVINGS
on ITEMS.ITEM_NO = RECEVINGS.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'
GROUP BY ITEMS.ITEM_NO

select ITEMS.ITEM_NO, SUM(SALES.QTY_SOLD)
from ITEMS
left join SALES
on ITEMS.ITEM_NO = SALES.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'
GROUP BY ITEMS.ITEM_NO

it works perfectly.  What gives?  Is there any reason the first query that joins all three tables won't work, yet two separate queries will?

A: If either receivings or sales has more than one row (and especially if both have more than one row) then the values will each get multiplied by the number of rows in the other. One way to solve this issue is to calculate the totals separately then join:
select ITEMS.ITEM_NO, COALESCE(R.SUM_RECEIVINGS,0), COALESCE(S.SUM_SALES,0)
from ITEMS
left join (SELECT RECEIVINGS.ITEM_NO, SUM(RECEIVINGS.QTY_RECVD) as SUM_RECEIVINGS
    FROM RECEIVINGS
    GROUP BY RECEIVINGS.ITEM_NO) as R ON ITEMS.ITEM_NO = R.ITEM_NO
left join (SELECT SALES.ITEM_NO, SUM(SALES.QTY_RECVD) as SUM_SALES
    FROM SALES
    GROUP BY SALES.ITEM_NO) as S ON ITEMS.ITEM_NO = S.ITEM_NO
WHERE ITEMS.ITEM_NO = '12345'


text:
Q: Use PowerShell to Copy Files to a Shared Drive I have a script powershell, script сopies database backup files to a network drive.
The script copies only 1 file from 2.
I want to copy all files from local disk D to a network drive, and archive files.
How can I fix this script?
$TimeStamp = get-date -f dd_MM_yyyy

$Destination = "M:\networkdrive\folder\BACKUP_10.200.153.55\DATA_" + $TimeStamp

New-Item -ItemType directory -Path $Destination -Force

Copy-Item -Path D:\MSSQL\BACKUP\*.* -Destination $Destination -Force

Remove-Item D:\MSSQL\BACKUP\*.*

A: This will send your backup folder, zipped, to the network store.
#requires -Version 5

$Destination = "M:\networkdrive\folder\BACKUP_10.200.153.55\DATA_$(Get-Date -f dd_MM_yyyy).zip"

Compress-Archive -Path D:\MSSQL\BACKUP\* -DestinationPath $Destination -CompressionLevel Optimal -Force -ErrorAction Stop

Get-ChildItem D:\MSSQL\BACKUP -Recurse -Force | Remove-Item -Force

A: You are going to have to do a loop to find all the files and copy each one. I suggest doing something like:
$TimeStamp = get-date -f dd_MM_yyyy
$Destination = "M:\networkdrive\folder\BACKUP_10.200.153.55\DATA_" + $TimeStamp
New-Item -ItemType directory -Path $Destination -Force

gci "D:\MSSQL\BACKUP" -recurse | %{ #loops through al files in that folder and subfolders
    #gets path to file
    $file = $_.Fullname

    #copies file
    Copy-Item -Path $file -Destination $Destination -Force

    #removes file from original location
    Remove-Item $file
}


text:
Q: Save two clients data to a variable? I have two clients who will be connecting to my server. I have the following code that sets up the server, and then clients would run the command
telnet localhost 3000 on their terminals. Now this part works
var http = require('http');
var net = require('net')
var listOfClients = []
var server = net.createServer(function(socket) {
  socket.write("Welcome to ROCK PAPER SCISSORS choose from the following \n")
  socket.write("[1] Rock \n")
  socket.write("[2] Paper \n")
  socket.write("[3] Scissors \n")
  listOfClients.push(socket)
  server.getConnections(function(error, count) {
    if (count == 2) {

      let p1 = listOfClients[0].on('data', function(data) {
        return data;

      });

      let p2 = listOfClients[1].on('data', function(data) {
        return data;

      });

      console.log(p1)
      console.log(p2)
    }
  });
});

then the clients choose 1 or 2 or 3 for rock/paper/scissors I want to save what they used in a variable , but the method
let p1 = listOfClients[0].on('data', function(data) {
  return data;
});

doesn't save the data into a variable and returns a lot of stuff that I don't understand. Any ideas on how to do this? I have the sockets in the list just need them save the clients input to a variable.

A: NodeJS works using events.
According to the documentations:

Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be called.

In your code, the listOfClients[0].on('data'... snippet of code, is actually creating a listener for the event 'data'.
In essence, you're telling the code to: Hey, can you keep listening to those and do something when it happens?
In your code, you're telling it to 'do something when the client[0] send some data'.
So when you write:
const variableName = something.on('someEvent', function(data) {});

The variable variableName is in reality, receiving the result of the event listener and using a callback as second argument.
Let's write a quick function that has one argument as a callback:
function myFunction(data, callback) {
    callback("This is where you're trying to return the value");

    return 'this is the event listener return';
}

const myVar = myFunction('Anything you please', function(callbackResult) {
    console.log(`This is the callback: ${callbackResult}`);
});

console.log(`This is the var value: ${myVar}`);

Running the above code will output:
node v10.15.2 linux/amd64

This is the callback: This is where you're trying to return the value
This is the var value: this is the event listener return

One solution to your problem, is just assigning the data to a variable outside the event listener, like so:
const storeHere = [];

function myFunction(data, callback) {
    callback("This is where you're trying to return the value");

  return data;
}

const myVar = myFunction('Anything you please', function(callbackResult) {
    storeHere.push(callbackResult); // Store somewhere outside
});

console.log(`This is the externalVar value: ${storeHere}`);
console.log(`This is the var value: ${myVar}`);


text:
Q: Magento2 : Having issue with product add to cart jmeter I am using Magento2.2.5 and using benchmark_2015.jmx, Facing issue when test for logged in customer and adding product to cart, Cart shows empty.
It's default magento benchmark_2015 script, stored in the installation folder at setup/performance-toolkit/benchmark_2015.jmx
Request where form key is extracted : http://prntscr.com/mty0su
Login request : http://prntscr.com/mty19u
Add to cart request : http://prntscr.com/mty00o
Let me know if you need more details
https://image.prntscr.com/image/2QJvTGhnS_6ROx0aM7-goA.png
https://image.prntscr.com/image/Hv3aM1XIRp6Y_VmJjub5QA.png
https://image.prntscr.com/image/Yz6glTNgTpONPv0LWChj2A.png


text:
Q: How to make nested loop faster to find instr in vba Problem Description: Loop through excel max rows(approx. 10000000) to find instr. After finding instr, taking the values and copy the values to different sheet. Every time find the match which is instr, copy the value only the matches and paste it to different sheet.
Problem: I am using nested loop and my loop is running slow, so for 10 millions rows its taking around 19:37 mins. I timed it. So first question is there different ways of doing it or how do i make it faster instead of 20 mins, is it possible to compare 20 millions( each sheet 10 million rows, 10 million strings) strings within 1 min or two. Here is my current code
  Sub zym()
   Dim x As Long, lastrow As Long, lastrowx As Long, i As Long, ii As Long
   Dim ws As Worksheet, ws2 As Worksheet, b As String
   Dim j As Long

   Set ws = Worksheets("Sheet1")
   Set ws2 = Worksheets("Sheet2")
   Set ws3 = Worksheets("Sheet3")
   j = 1
      T1 = GetTickCount

  lastrow = ws.UsedRange.Rows.Count + 1
  lastrowx = ws2.UsedRange.Rows.Count + 1

   ReDim sheet1array(1 To lastrow)
   ReDim sheet2array(1 To lastrowx)

    For i = LBound(sheet1array) To UBound(sheet1array)
        b = "-" & ws.Range("A" & i) & "-"
      For ii = LBound(sheet2array) To UBound(sheet2array)
        If InStr(1, ws2.Range("A" & ii), b) > 0 Then
        ws3.Range("A" & j) = ws2.Range("A" & ii)
        j = j + 1
        End If

       Next ii
     Next i
    Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
    Debug.Print "Array Count = " & Format(ii, "#,###")

End Sub

A: I would use the Power Query Add-In for this. It has a Text.Contains function that is roughly similar to VB's InStr. I had a go at this particular challenge and got it working. You can download and use my demo file from my OneDrive:
http://1drv.ms/1AzPAZp
It's the file: Power Query demo - Searching for a list of strings among another list of strings.xlsx.
As described on the ReadMe sheet, I didn't have to write many functions - it was mostly built by clicking around the UI.
My design is to cross-join the Search and Target tables (the equivalent of your Sheet1 and Sheet2 I think) to get every possibly combination, then apply the Text.Contains function and filter on the result.
A key design objective is speed - it runs in about 1 second for the current semi-random test data:
19 Search Strings (currently single words)
78780 Target Strings (currently lines from War and Peace)
(so around 1.5 million combinations)
9268 Output matches.
So non-trivial scale, but nowhere near your requirements. Hopefully that will scale up to your needs - I'm keen to hear how it goes.
Note that the Target_Strings query could be replaced with one querying data directly from a database or website - Power Query is not limited to Excel as a datasource.

A: Reading from and writing to cells on a sheet slows down any macro. The following code copies cell values into arrays and loops through these. Output is copied in chunks from a result array into the target sheet.
On my notebook the original code took 56 sec, this code 3.7 sec:
Sub zym2()
    Dim lastrow As Long, i As Long, j As Long, start As Long
    Dim ws As Worksheet, ws2 As Worksheet, ws3 As Worksheet
    Dim b As String
    Dim T1 As Long
    Dim arr1, arr2, arr3, c

    Set ws = Worksheets("sh1")
    Set ws2 = Worksheets("sh2")
    Set ws3 = Worksheets("sh3")
    ws3.Columns(1).Clear
    T1 = Timer

    arr1 = Intersect(ws.Columns(1), ws.UsedRange)
    lastrow = UBound(arr1)
    arr2 = ws2.UsedRange
    ReDim arr3(1 To lastrow / 10, 2)   ' initial length is arbitrary

    j = 0
    start = 1
    For i = 1 To lastrow
        b = "-" & arr1(i, 1) & "-"
        For Each c In arr2
            If InStr(1, c, b) > 0 Then
                If j = UBound(arr3) Then
                    ws3.Range(Cells(start, 1), Cells(start - 1 + j, 1)) = arr3
                    start = start + j
                    j = 0
                End If
                j = j + 1
                arr3(j, 1) = c
            End If
        Next c
    Next i
    If j > 0 Then
        ws3.Range(Cells(start, 1), Cells(start - 1 + j, 1)) = arr3
    End If
    Debug.Print "Array Time = " & Format(Timer - T1, "##.0")
    Debug.Print "Array Count = " & Format(start - 1 + j, "#,###")
End Sub

A: Although I have already offered an answer I want to propose a totally different algorithm here in order to improve the performance by another order of magnitude.
When the "big list" on sheet1 is scanned and matches in sheet2 are searched, the information about a successful search is thrown away after one pass. Sheet1 will contain repetitions of a search value, and when scanning sheet2 we can make use of it's frequency.
The means to finding unique search values and their frequencies is a dictionary object. To use it in VBA one has to add a reference to "Microsoft Scripting" in the VBA editor.
The second assumption is that the output list does not need to preserve the input order (because it will be sorted anyway). The following code will produce an output list in sheet3 with search values in the order in which they occur in the big list but with all repetitions in one block. Statements for timing have been commented out as an external class definition is needed for this.
Sub zym_dict()
' http://superuser.com/questions/976906/how-to-make-nested-loop-faster-to-find-instr-in-vba
' by E/S/P 2015-09-25
' 2nd improvement: use a dictionary object to count unique search items and loop over these
' speed 1:13 vs. array version; 1:186 vs. original (cell) version

    Dim numvalues As Long, i As Long, j As Long, nextresult As Long
    Dim numcompared As Long, numresults As Long
    Dim cnt As Long
    Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
    Dim searchterm As String
    Dim values, arr2, results, c, v
    Dim uniq As New Scripting.Dictionary

    ' Dim mStopWatch As New clsStopWatch

    Set ws1 = Worksheets("sheet1")
    Set ws2 = Worksheets("sheet2")
    Set ws3 = Worksheets("sheet3")

    ' mStopWatch.StartWatch

    values = Intersect(ws1.Columns(1), ws1.UsedRange)
    arr2 = Intersect(ws2.Range("A:B"), ws2.UsedRange)
    numcompared = UBound(arr2, 1)

    ' collect unique values and their frequencies
    For i = 1 To UBound(values, 1)
        uniq(values(i, 1)) = uniq(values(i, 1)) + 1
    Next i

    numresults = 0
    ' 2nd index is repeat count
    For j = 1 To numcompared
        arr2(j, 2) = 0
    Next j

    For Each v In uniq
        searchterm = "-" & v & "-"
        cnt = uniq.Item(v)
        For j = 1 To numcompared
            If InStr(1, arr2(j, 1), searchterm) > 0 Then
                ' copy this value multiple times into result array
                arr2(j, 2) = arr2(j, 2) + cnt ' repeat count
                numresults = numresults + cnt
            End If
        Next j
    Next

    ' generate output list
    ReDim results(1 To numresults, 1 To 2)
    ws3.Columns(1).Clear
    nextresult = 0
    For i = 1 To numcompared
        v = arr2(i, 1)
        cnt = arr2(i, 2)  ' may be 0!
        For j = 1 To cnt
            results(nextresult + j, 1) = v
        Next j
        nextresult = nextresult + cnt
    Next i

    ' copy values to sheet
    ws3.Range(Cells(1, 1), Cells(nextresult, 2)) = results

    ' Debug.Print "runtime = " & Format(mStopWatch.StopWatch, "#0.00 ms")
    Debug.Print Format(nextresult, "#,### resulting lines")
End Sub

Compared to the OP's code the speed improvement is 1:186. A 20 minute run would then only take a couple of seconds.


text:
Q: Can I create a Comparator object from a lambda expression without explicit variable? I am not yet familiar with lambda expression in Java.
Can
//create a comparator object using a Lambda expression
Comparator<Double> compareDouble = (d1, d2) -> d1.compareTo(d2);

//Sort the Collection in this case 'testList' in reverse order
Collections.sort(testList, Collections.reverseOrder(compareDouble));

be written without explicitly create a variable compareDouble?
I tried the following, but why does it not work?
//Sort the Collection in this case 'testList' in reverse order
Collections.sort(testList, Collections.reverseOrder(new Comparator<Double> ((d1, d2) -> d1.compareTo(d2))));

Thanks.

A: First, your immediate error: You forgot to place parentheses around your casting type.  Try:
Collections.sort(testList, Collections.reverseOrder( (Comparator<Double>) ((d1, d2) -> d1.compareTo(d2))));

Edit: The above error was when the question didn't have new so it looked like a cast.
Also, Java's type inference will work without explicitly casting your lambda expression to the necessary functional type.  Try:
Collections.sort(testList, Collections.reverseOrder( (d1, d2) -> d1.compareTo(d2) ));

When the comparison operation already exists as in this case, you can make it even simpler with a method reference:
Collections.sort(testList, Collections.reverseOrder(Double::compare));

A: Double already implements Comparable, so you can use the zero-arg reverseOrder() overload:
testList.sort(Collections.reverseOrder());

Or you can reverse your custom comparator:
testList.sort((d1, d2) -> d2.compareTo(d1));

A: I'd go with something like:
Collections.sort(testList, Comparator.comparingDouble(Type::getDoubleValue).reversed());

Where Type is the name of your class and getDoubleValue is the double value being used as the sort key.
Another shorter alternative.
testList.sort(Comparator.comparingDouble(Type::getDoubleValue).reversed());

edit
I think I've misinterpreted your current problem. Nevertheless, altering your current solution to:
Collections.sort(testList, Collections.reverseOrder((e, a) -> e.compareTo(a)));

Would suffice.
It's just a matter of taking the behavior you've assigned to the variable compareDouble and directly pass it into the reverseOrder method.


text:
Q: API Call returning Gibberish I'm building a recipe app with Next.js and JS and using RapidAPI for the api. I used the JS axios snippet for the api but when it tries to fetch, it shows the data as gibberish.
{data: '\x03�\x04\x00�̦���r��/椥f�b���\nfY\v�ݜX(«ձoi�<\x16X�KX�\x1A~3�&Ԁ��\x7F�…�����\rg�Y\x19��[\x15{<;R\x7F�܄E�_r��M�i�\x05��M��\x11��{X\r�e�7\x00\x03', status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…}, …}
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
data
:
"\u0003�\u0004\u0000�̦���r��/椥f�b���\nfY\u000b�ݜX(«ձoi�<\u0016X�KX�\u001a~3�&Ԁ���D\u0019��/L���\n��_\u0018� :\rH҄:��\f\u0011�R�\t�0��A�\b�Z�%v:e�X�S�}��_ϟ̽�!��� �\u000e��\u0010�P{�̃���{�!�����\u0018�\u000e\u000b�\"�Ag�Y\u001bg�\u001c/�:����qF4¬f�\u001biҁư��lPZ�Ţ(-α�\u0016EI�{�f�pF�\u0011-�\u0015��I.\u0015Ɛ�f�@�B>oI��\u001c�x\u0014��\u0012�j+�I?��\u0014q�\u0005��[��u�^�i�1b~{q�xvx��CT�D�'�Q�k�z���\u0011p\u0003��e\u0005��N�\u0003�r̷.p��&�{���Q��;GF�s�-�?��\u001c���*\b�'\u0016������ꈽ��c������\rg�Y\u0019��[\u0015{<;R�܄E�_r��M�i�\u0005��M��\u0011��{X\r�e�7\u0000\u0003"
headers
:
AxiosHeaders {content-length: '928', content-type: 'application/json; charset=utf-8', date: 'Tue, 10 Jan 2023 00:14:52 GMT', etag: '"6fu9sm4bm6fx"', vary: 'Accept-Encoding'}
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
:
200
statusText
:
"OK"
[[Prototype]]
:
Object

Below is the call for the api. I don't know if it has something to do with my key or what. Any help would be greatly appreciated.
export default async function handler(req, res) {
   const options = {
      url: 'https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/complexSearch',
      params: {
         query: req.query.keyword,
         diet: req.query.diet,
         intolerances: req.query.intolerances,
         excludeIngredients: req.query.exclude,
         number: '20',
         offset: '0',
      },
      headers: {
         'X-RapidAPI-Host':
            'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com',
         'X-RapidAPI-Key': process.env.NEXT_PUBLIC_RAPIDAPI_KEY,
      },
   };

   try {
      let response = await axios(options);
      res.status(200).json(response.data);
   } catch (error) {
      console.error(error.response);
   }
}


text:
Q: Errors while I am trying to create replication to my postgres database I am trying to create "replication" for my database. I watched many tutorials and documentations.
Finally, I followed this tutorial in this video.
The problem is when I add the recovery data in recovery.conf I surprised that the whole cluster does work and its failed to start with :
sudo systemctl stop postgresql@12-test Where "test" is the backup cluster.
Then I tried many solutions but it was zero result. Next I removed data in the "test" cluster and I redo the steps for pg_basebackup without adding any thing to recovery.conf file and its started correctly and synchronized with the existing data in main cluster at the backup moment.
Note : Its not synchronized with any data have been inserted recently after pg_basebackup.
So, The problem is : Why when Adding data to recovery.conf file its failed to start and Absolutely I need to add data to make the replication works fine?
Or If you can provide me with a suitable tutorial or documentation to this replication.
Note 2 : I am trying to replication on the same PC then I'll move to it on cloud or on another PC.
Here is datasheet I followed with the video :
Sheet

A: Discovered it. The file recovery.conf that is no longer used in postgresql 12.
I have followed other documents and solved my problem.
Now I have two synchronized devices.


text:
Q: Enum trick in C++/CLI In native C++ we could use enum trick in class definition:
namespace EFoo
{
  enum { a = 10; };
}

class Foo
{
   // Declare an array of 10 integers.
   int m_Arr[EFoo::a];
};

However, with managed enum in C++/CLI,
public enum class EFoo
{
  a = 10,
};

EFoo::a couldn't be converted implicitly to int,
so the enum trick wouldn't be allowed.
Is there any workaround?
Thanks.

A: If you are just trying to achieve the 'enum hack', you should not have to do that in any recent compiler, as they will support static const member declarations.
class Foo
{
private:
    static const int ARRAY_SIZE = 10;
    int m_arr[ARRAY_SIZE];
};

Otherwise, doing an int cast like Jonathan Wood answered would work to change from a managed enum to an int.

A: Try:
arr[(int)EFoo.a];

A: If you dont need the enacpsulation, why not declare it as an "enum" instead of the "enum class"? You can then use it without the cast, and also, without the classname .


text:
Q: Javascript: get window.location everything but host? i have like
http://www.mydomain.com/hello/you
with top.location.host, i can get "http://www.mydomain.com"
with window.location.href i can get "http://www.mydomain.com/hello/you"
is there a chance to get just "/hello/you" ???

A: location.pathname

pathname will only return the path. If you want the querystring and optionally hash, you would need to combine the search and hash properties as well. Consider this url:
http://www.example.com/path/to/glory?key=value&world=cup#part/of/page

location.pathname => "/path/to/glory"
location.search   => "?key=value&world=cup"
location.hash     => "#part/of/page"

If you want the entire thing,
/path/to/glory?key=value&world=cup#part/of/page

then just concatenate all these:
location.pathname + location.search + location.hash

Always wanted to use with somewhere. This looks like the perfect opportunity :)
with(location) {
    pathname + search + hash;
}

A: Another approach would be excluding the protocol and host from the entire href using substring.
window.location.href.substring(
    (window.location.protocol+'//'+window.location.host).length
)

If your url is http://google.com/test?whatever=1#hello it will return /test?whatever=1#hello.


text:
Q: trying to see the bi bi-x while hover. what am i doing wrong? I set the bi bi-x display to none; what i need to change/add in html/css?

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

          Card link

          Another link

css-
   .card-body:hover + .hide{
    display: block;
  }


text:
Q: Running Things in Parallel with SAS Enterprise Guide Good afternoon, Stack Overflow gods and goddesses. I have a question about running code in SAS Enterprise Guide 7.1 in parallel.
Currently, I have 5 small PROC SQLs running in a project. The code runs fine, but it executes in series (IE: One at a time) and even though I have each piece broken out in an individual section, I can't seem to get all 5 to run at once. For example, take the code below:
PROC SQL;
    connect to Oracle (user = "&Oracle_ID." password = "&Oracle_PW." path = "&Oracle_Path.");
    Create table place.base_balance_data as select * from connection to Oracle (
        Select
            DEBR.Acct_Ref_Id
            ,case when DEBR.Acct_Typ_Cd = '2' and DEBR.Settle_Dt_Bal_Amt > 0
                then sum(settle_dt_bal_amt)
                else sum(0)
                end as Typ_2_Settle_Dt_Bal_Amt
            ,case when DEBR.Acct_Typ_Cd = '5' and DEBR.Settle_Dt_Bal_Amt > 0
                then sum(settle_dt_bal_amt)
                else sum(0)
                end as Typ_5_Settle_Dt_Bal_Amt
            ,case when DEBR.Acct_Typ_Cd = '1' and DEBR.Settle_Dt_Bal_Amt < 0
                then sum(settle_dt_bal_amt)
                else sum(0)
                end as Typ_1_Settle_Dt_Bal_Amt
            ,case when DEBR.Acct_Typ_Cd = '1' and DEBR.Settle_Dt_Bal_Amt < 0
                then sum(Csh_Free_Cr_Amt)
                else sum(0)
                end as Csh_Free_Cr_Amt
            ,case when DEBR.Acct_Typ_Cd = '1' and DEBR.Settle_Dt_Bal_Amt < 0
                then coalesce(DEBR.Cr_Avbl_Amt,0)
                end as Credit_Aval_Amt
        From Cool.DataStuff DEBR
        Where DEBR.Date_ID = &lm_bus_dID.
        Group by DEBR.Acct_Ref_Id, DEBR.Acct_Typ_Cd, DEBR.Cr_Avbl_Amt, DEBR.Settle_Dt_Bal_Amt
        Order by DEBR.Acct_Ref_ID asc offset 0 rows
    );
    Disconnect from Oracle;

Currently, the EG project looks like this:

I'm trying desperately to get all 5 of those pieces on the right to run at the same time, but alas, every time I try to do that, I get errors involving the passing of macro variables and not being able to connect to multiple sessions.
Has anyone had any luck doing this before? Could you maybe tell me what I'm missing here?
Thanks!

A: If you have SAS/CONNECT installed, you can break everything out into rsubmit blocks that will all run in parallel. You can ensure that each session gets the required macro vars using %syslput.
When running things in rsubmit blocks, think of each block as its own unique, independent worker session that's running code - almost like a thread. This worker lives in its own world and only knows what is in its session. The main session which kicked off the worker sessions is free to do whatever it pleases while the workers perform their specific tasks.

Below is an example of how to set this up.
Setup code
This will handle signing on to a metadata server in a new session automatically and make all code run asynchronously.
options autosignon=yes
        sascmd='!sascmd'
        connectwait=no
;

Create Macro Variables and pass them to your worker sessions
This will do two things:

*

*Start a new asynchronous session

*Send your macro variables from your main session to your worker session

..
<code to create macro vars>;

/* Send macro variables over to a new remote session */
%syslput mymacrovar / remote=worker1;
...

If you want to, you can use %syslput _USER_ / remote=worker1 to send all user-made macro variables to a new session.
Enclose all worker code in rsubmit blocks
libname workmain "%sysfunc(getoption(work))";

rsubmit remote=worker1 inheritlib=(<my libraries here> workmain);
    <code here>;
endrsubmit;

Note the libname statement, workmain. rsubmit cannot inherit the work library of the main session. This is by design since each of these sessions have their own work library whose name cannot be overwritten. You can get around it by creating a new library that points to your main session's work library.
Wait for everything to finish
Finally, you can add one last piece of code to wait for everything to finish up - or, you're free to have the main thread run more independent light tasks.
waitfor _ALL_;


text:
Q: Azure SQL Database rename fails (Error 1801: already exists) but DB does not exist I am attempting to rename an Azure SQL DB using SSMS (both via UI and ALTER).
I get an 1801: Database 'mydatabase' already exists. Choose a different database name.
However it seems to not exist (verified via Azure portal and attempting to connect using SSMS).
An hour or so ago I attempted to create a new DB called 'mydatabase' from import from BACPAC, using SSMS.  The process seemed to not be progressing so I cancelled/aborted.  I think this has caused some element(s) of the 'mydatabase' to be created.
I repeated the import using a different DB name 'mydatabaseNEW'.  When attempting to rename 'mydatabaseNEW' to 'mydatabase' I get this error.
The original 'mydatabase' cannot be seen.  I cannot DROP the db (even when connected to master) or make any connection to it using the SQL Server admin account.
Appreciate ideas on how I can resolve.

A: I withdraw my question.
It may have been a matter of time, as the rename attempt has just worked successfully.  Was about 1 hour since the aborted import.  I assume somewhere between Azure and SQL that there was a clean up.


text:
Q: Copy a Column from a table towards another table with conditions =======
I'm a newbie in SQL. What i've been trying to do for a day (after going through dozens of topics here and on the internet ) is a simple task :
I want to move the column "number" from table B to table A with the condition that the number is attributed corresponding to the same name and surname as in table B.
Table AAA:
- [NAME], [SURNAME], [NUMBER]

 - Bob , Dylan  ,
 - Jimi, Hendrix ,

etc
Table BBB:
- [TYPE] [AGE] [TOWN] [NAME] [SURNAME] [NUMBER]
- Guitarist , 95 , Denver , Bob , Dylan  , 45
- Guitar , 45 , Paris , Jimi, Hendrix , 47
- Dancer , 40, New-york , Jimmy, Page , 69
- etc..

UPDATE AAA A
set A.NUMBER = B.NUMBER
FROM A INNER JOIN BBB B on A.NAME = B.name and A.SURNAME = B.SURNAME ;

It does not work :(
Sorry for being a disturbing noob but I really don't know how to do.
ERROR near A syntax ?

A: It seems sqlite doesn't support joins on UPDATE.
You can work around it in two ways:
IF NAME and SURNAME are PRIMARY KEY in AAA you could do:
INSERT OR REPLACE INTO "AAA"(NAME,SURNAME,NUMBER)
SELECT "AAA".NAME,"AAA".SURNAME,"BBB".NUMBER
FROM "AAA"
INNER JOIN "BBB" ON "BBB".NAME = "AAA".NAME
                AND "BBB".SURNAME = "AAA".SURNAME

This will do an INSERT OR REPLACE for every record in AAA with NUMBER from BBB.
sqlfiddle demo
Otherwise you can do:
UPDATE "AAA"
SET NUMBER = (SELECT NUMBER
                  FROM "BBB"
                  WHERE "BBB".NAME = "AAA".NAME
                    AND "BBB".SURNAME = "AAA".SURNAME);

sqlfiddle demo


text:
Q: Use a Jquery variable in PHP I have a very long program, and I have this problem. I have the following code:

    CP:
    <input id="edit_cp" type="text" name="edit_cp" placeholder="Postal Code" required />

And In PHP:
$query = "SELECT    * FROM           shops";

$result = mysql_query($query);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "
 <input type='radio' name='tienda' value='$row[ID]' required> $row[Nombre] ($row[Direccion])";
    }

mysql_close($link);

This is only a two parts of my program, so I can't use a form and get the $_POST or similar. I have to use the result of the edit_cp variable and use it into the php. I want it to calculate a nuber. For example if the entered number is for example 2 and in the while the number is 2, it will be selected.

A: Try
$.post( "path/to/handler", { edit_cp : $('#edit_cp').val()}).done(function( data ) {
    alert( "Data Loaded: " + data );
});

Don't forget to bind this script to some action, ex.:
$('#post').once('click',function(){
    $.post( "path/to/handler", { edit_cp : $('#edit_cp').val()}).done(
        function( data ) {alert( "Data Loaded: " + data );
        });
});


text:
Q: Hyperlink in Silverlight AccordionItem HeaderTemplate I have created a HeaderTemplate for my accordions where I want to display a text block on one side of the header and a hyperlink on the right side. The display is working correctly, but the click event is not called when the user clicks, I'm guessing b/c the header itself is trapping the click for expand/contract.
    <layoutToolkit:Accordion>
        <layoutToolkit:AccordionItem IsSelected="True">
            <layoutToolkit:AccordionItem.HeaderTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Height="20">
                        <TextBlock Margin="0,0,700,0">Cancel Postcards</TextBlock>
                          <HyperlinkButton Content="Next Call" Foreground="Blue" Click="NextCancel_Click" />
                      </StackPanel>
                  </DataTemplate>
            </layoutToolkit:AccordionItem.HeaderTemplate>
..... more code ....

Is there a way to get the hyperlink to respond to events without practically creating a new control?
Update: It looks like the header sets all child controls to disabled when expanded which is why the link doesnt work. It will work when you collapse that accordionitem. So, the question now is, how do i prevent the hyperlink from being disabled?

A: Hey Charlie, I just happened to answer this same question for Epic720.  You have to change the Locked VisualState.
Interactive items in Silverlight Accordion Header
Here is the LockedStates VisualStateGroup of the AccordionItem which you should alter.  I can post the whole style if you need, though it's quite verbose.
<VisualStateGroup x:Name="LockedStates">
    <VisualStateGroup.Transitions>
        <VisualTransition GeneratedDuration="0"/>
    </VisualStateGroup.Transitions>
    <VisualState x:Name="Locked">
        <Storyboard>
            <!--
            <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="IsEnabled" Storyboard.TargetName="ExpanderButton">
                <DiscreteObjectKeyFrame KeyTime="0" Value="False"/>
            </ObjectAnimationUsingKeyFrames>
            -->
        </Storyboard>
    </VisualState>
    <VisualState x:Name="Unlocked">
        <Storyboard>
            <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="IsEnabled" Storyboard.TargetName="ExpanderButton">
                <DiscreteObjectKeyFrame KeyTime="0" Value="True"/>
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>
    </VisualState>
</VisualStateGroup>