text:
Q: How cmp assembly instruction sets flags (X86_64 GNU Linux) Here is a simple C program:
void main()
{
       unsigned char number1 = 4;
       unsigned char number2 = 5;

       if (number1 < number2)
       {
               number1 = 0;
       }
}

So here we are comparing two numbers. In assembly it will be done using cmp.
cmp works by subtracting one operand from other.
Now how cmp is subtracting operands? Is it subtracting 1st operand from 2nd or vice versa? In any case, this should go like this:
case # 1:
4 - 5 = (0000 0100 - 0000 0101) = (0000 0100 + 1111 1010 + 1) = (0000 0100 + 1111 1011)
= 1111 1111 = -1
So since the sign bit = 1 so SF should be 1.
No carry, so CF should be = 0.
case # 2:
5 - 4 = (0000 0101 - 0000 0100) = (0000 0101 + 1111 1011 + 1)
= (0000 0101 + 1111 1100) = 1 0000 0001
so here, CF should be = 1
since result is positive, SF should be = 0
Now I compile and run program (linux x86_64, gcc, gdb), place a breakpoint after cmp instruction to see register states.
Breakpoint hit after cmp:
Breakpoint 2, 0x0000000000400509 in main ()
(gdb) disassemble
Dump of assembler code for function main:
   0x00000000004004f6 <+0>:     push   %rbp
   0x00000000004004f7 <+1>:     mov    %rsp,%rbp
   0x00000000004004fa <+4>:     movb   $0x4,-0x2(%rbp)
   0x00000000004004fe <+8>:     movb   $0x5,-0x1(%rbp)
   0x0000000000400502 <+12>:    movzbl -0x2(%rbp),%eax
   0x0000000000400506 <+16>:    cmp    -0x1(%rbp),%al
=> 0x0000000000400509 <+19>:    jae    0x40050f <main+25>
   0x000000000040050b <+21>:    movb   $0x0,-0x2(%rbp)
   0x000000000040050f <+25>:    pop    %rbp
   0x0000000000400510 <+26>:    retq
End of assembler dump.

Register dump after cmp has been executed:
(gdb) info reg
rax            0x4  4
rbx            0x0  0
rcx            0x0  0
rdx            0x7fffffffe608   140737488348680
rsi            0x7fffffffe5f8   140737488348664
rdi            0x1  1
rbp            0x7fffffffe510   0x7fffffffe510
rsp            0x7fffffffe510   0x7fffffffe510
r8             0x7ffff7dd4dd0   140737351863760
r9             0x7ffff7de99d0   140737351948752
r10            0x833    2099
r11            0x7ffff7a2f950   140737348041040
r12            0x400400 4195328
r13            0x7fffffffe5f0   140737488348656
r14            0x0  0
r15            0x0  0
rip            0x400509 0x400509 <main+19>
eflags         0x297    [ CF PF AF SF IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
(gdb)

So we can see that after cmp has been executed, both CF=1, SF=1.
So the actual resulted flags (CF=1 & SF=1) are not equal to flags we calculated in
Case # 1 (CF=0 & SF=1) or case # 2 (CF=1 & SF=0)
Whats happening then? How cmp is actually setting the flags?

A: Operation of CMP
CMP performs a subtraction but does not store the result.
For this reason the effect on the flags is exactly the same between:
cmp eax,ecx
sub eax,ecx

As per the documentation:

Operation
  temp ← SRC1 − SignExtend(SRC2);
  ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*)
Flags Affected
  The CF, OF, SF, ZF, AF, and PF flags are set according to the result.

Effects on the flags
So the following flags are affected like so:
Assume result = op1 - op2

CF - 1 if unsigned op2 > unsigned op1
OF - 1 if sign bit of OP1 != sign bit of result
SF - 1 if MSB (aka sign bit) of result = 1
ZF - 1 if Result = 0 (i.e. op1=op2)
AF - 1 if Carry in the low nibble of result
PF - 1 if Parity of Least significant byte is even

I suggest you read up on the OF and CF here: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt
Order of the operands
I see that you like pain and are using the braindead variant of x86 assembly called ATT-syntax.
This being the case you need to take into account that
CMP %EAX, %ECX  =>  result for the flags = ECX - EAX
CMP OP2, OP1    =   flags = OP1 - OP2

Whereas Intel syntax is
CMP ECX, EAX    =>  result for the flags = ECX - EAX
CMP OP1, OP2    =>  flags = OP1 - OP2

You can instruct gdb to show you Intel syntax using: set disassembly-flavor intel

A: I think i understand it now. This is how i think it goes (borrow flag is set)
4 - 5

1st operand = 4 = 0000 0100
2nd operand = 5 = 0000 0101

So we have to perform

      1st operand
    - 2nd operand
    --------------

      7654 3210 <-- Bit number
      0000 0100
    - 0000 0101
    ------------

Lets start.

Bit 0 of 1st operand = 0
Bit 0 of 2nd operand = 1

so

  0
- 1
 ===
  ?

to do this,
let's borrow a 1 from left side of bit 0 of 1st operand.
so we see bit 2 of 1st operand is 1.
when bit 2 is = 1, it means 4.
we know that we can write 4 as 2 + 2. So we can write 4 as two 2s.
      7654 3210 <-- Bit number
             1
             1
      0000 0000
    - 0000 0101
    ------------

So in above step, we have written bit 4 of 1st operand as two 2s (two 1 on top of bit 2 of 1st operand.)
Now again as we know, a 2 can be written as two 1s.
So we borrow one 1 from bit 1 of 1st operand and write two 1s on bit 0 of 1st operand.
      7654 3210 <-- Bit number
              1
             11
      0000 0000
    - 0000 0101
    ------------

Now we are ready to perform subtraction on bit 0 and bit 1.
      7654 3210 <-- Bit number
              1
             11
      0000 0000
    - 0000 0101
    ------------
             11

So after solving bit 0 and bit 1, lets see bit 2.
We again see same problem.
Bit 2 of 1st operand = 0
Bit 2 of 2nd operand = 1
to do this, let's borrow a 1 from left side of bit 2 of 1st operand.
    8 7654 3210 <-- Bit number
              1
             11
    1 0000 0000
    - 0000 0101
    ------------
             11

Now you see, bit 8 of 1st operand is 1. We have borrowed this 1.
At this stage, carry flag will be set. So CF=1.
Now, if bit 8 is 1, it means 256.
256 = 128 + 128
if bit 7 is 1, it means 128. We can rewrite as
    8 7654 3210 <-- Bit number
      1       1
      1      11
      0000 0000
    - 0000 0101
    ------------
             11

As previously, we can re-write it as:
    8 7654 3210 <-- Bit number
       1      1
      11     11
      0000 0000
    - 0000 0101
    ------------
             11

As previously, we can re-write it as:
    8 7654 3210 <-- Bit number
        1     1
      111    11
      0000 0000
    - 0000 0101
    ------------
             11

As previously, we can re-write it as:
    8 7654 3210 <-- Bit number
         1    1
      1111   11
      0000 0000
    - 0000 0101
    ------------
             11

As previously, we can re-write it as:
    8 7654 3210 <-- Bit number
           1  1
      1111 1 11
      0000 0000
    - 0000 0101
    ------------
             11

As previously, we can re-write it as:
    8 7654 3210 <-- Bit number
            1 1
      1111 1111
      0000 0000
    - 0000 0101
    ------------
             11

At last we can solve this.
Subtracting 2nd operand from all above it will give
    8 7654 3210 <-- Bit number
            1 1
      1111 1111
      0000 0000
    - 0000 0101
    ------------
      1111 1111

So result = 1111 1111

Notice, sign bit in result = bit 7 = 1
so sign flag will be set. i.e SF=1
And therefore SF=1, CF=1 after 4 - 5


text:
Q: Nlog : With mail target - SecurityProtocol I have issue Nlog with mail target.
Appllication build in framwork 4.5.2.
Nlog : 4.7.14
Now Nlog configration is as below,
<target name="mail" xsi:type="Mail" html="true" smtpServer="smtp.office365.com" smtpUserName="name@companyname.com"
 smtpPassword="*****" smtpPort="587" enableSsl="true" from="name@companyname.com"
 to="name@companyname.com" subject="Exception from Applicaion"
 useSystemNetMailSettings="False" smtpAuthentication="Basic" />

 <logger name="*" levels="Error" writeTo="mail" />

This is my code. I dont know how to add SecurityProtocol in nlog file?
Nlog mailkit is supported in framwork 5.0 or heiher version.
Please suggest.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change svg path width on hover I have an issue I can't find an helpful answer. I have a svg arrow, the arrow has to grow when the user hovers over with the mouse. The problem is that only the line has to change size not the arrow head. I just want the line to grow horizontally.
This is the svg code
<svg width="51" height="8" viewBox="0 0 51 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M50.3536 4.35355C50.5488 4.15829 50.5488 3.84171 50.3536 3.64645L47.1716 0.464466C46.9763 0.269204 46.6597 0.269204 46.4645 0.464466C46.2692 0.659728 46.2692 0.976311 46.4645 1.17157L49.2929 4L46.4645 6.82843C46.2692 7.02369 46.2692 7.34027 46.4645 7.53553C46.6597 7.7308 46.9763 7.7308 47.1716 7.53553L50.3536 4.35355ZM0 4.5H50V3.5H0V4.5Z" fill="black"/>
</svg>

And this is the code the I have working right now
svg {
    width: 50px;
    overflow: visible;
    transition: width 0.5s ease;
}

svg:hover {
    width: 100px;
}

I also have a Codepen link
https://codepen.io/godhandkiller/pen/xxRZeYv
The problem here is that I'm manipulating the whole SVG but I only need to change the like size.

A: A possible solution: you can use a line path with a marker-end. The marker is the tip of the arrow. For the animation I'm using SMIL animations changing the d attribute of the path from M1,4L25,4 to M1,4L50,4. The animate element has a begin attribute making the animation to begin when you mouse over the overlaying rectangle: begin="theRect.mouseover". Another animate element animates the path on mouse out: begin="theRect.mouseout"

svg {
  border: 1px solid red;
  transition: width 0.5s ease;
}
<svg id="theSVG" fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 51 8" stroke="#000" stroke-linecap="round">
  <defs>
    <marker id="m" overflow="visible" markerUnits="userSpaceOnUse">
      <path d="M-3,-3L0,0 -3,3" />
    </marker>

  </defs>

  <path d="M1,4L25,4" marker-end="url(#m)">
    <animate attributeName="d" to="M1,4L50,4" dur="1s" begin="theRect.mouseover" repeatCount="1" fill="freeze" />
    <animate attributeName="d" to="M1,4L25,4" dur="1s" begin="theRect.mouseout" repeatCount="1" fill="freeze" />
  </path>

  <rect width="100%" height="100%" stroke="none" pointer-events="all" id="theRect" />
</svg>


text:
Q: A problem solving strategy that appears to work, but doesn't? I'm teaching problem solving to my students and I'm looking for a problem at the high school level to demonstrate a problem-solving technique that appears as though it might work, but doesn't. I want to be able to show my students that a strategy may look like a good fit for a problem, but in fact a different strategy will work better.
Any help will be appreciated! Thanks!

A: Two (similar) examples that come to mind are the "tennis tournament problem" and the "two trains and a fly" problem.
The tennis tournament puzzle is as follows: Suppose there are 100 participants in a knock-out style tennis tournament. How many games must be played until there is a winner?
A brute force approach would be to calculate how many games are in each round, and how many players are eliminated in each round, all the way to the quarter-finals, semi-finals and the final. On the other hand, you could easily solve the puzzle by noticing that exactly one player is eliminated per game, so there is a winner after exactly 99 games (i.e. when 99 players have been eliminated).
The classic two trains and a fly problem is similar in that there is an obvious 'brute force' approach but there is also a trick to solving the problem which one might initially miss.
There are, of course, lots of other neat puzzles in which a simple trick/'strategy' gives a solution (e.g. the mutiliated chessboard problem), but often these don't have an 'obvious' but inefficient strategy that one could also use to solve the problem.

As noted in the comments, your question is a bit vague - I'm not sure if these examples are the sort of thing you are looking for; whilst the 'correct' strategy in each case is making an observation that immediately simplifies the problem, crucially, there is also a more obvious 'brute force' strategy that one may be tempted to use in each case.
I've also tried to avoid simply giving examples of fallacious proofs since these really aren't 'problem-solving strategies'.


text:
Q: Custom view on android I created a custom view MyView:
package com.example;

public class MyView extends View {

    public MyView(Context context) {
        super(context);
    }
}

And use it in layout xml:
<com.example.MyView android:id="@+id/imageView"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">
</com.example.MyView>

It throws error:
09-02 16:43:07.114: ERROR/AndroidRuntime(1387): FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity
        ComponentInfo{com.example/com.example.MyActivity}: android.view.InflateException: Binary XML file line #13:
           Error inflating class com.example.MyView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
        at android.app.ActivityThread.access$1500(ActivityThread.java:117)

How to fix it?

A: You should try to define another constructor for it to work.
public MyView(Context context, AttributeSet attrs){
    super(context, attrs);
}


text:
Q: Click Class Button Having Same Classname With Javascript I have this code on my webform

Question 3 of 3

About how many times

do you use facebook per week?

<3

4-7

7-10

10+

These are four buttons I do not want to click first button which have innerhtml > "<3" but want to click any one from which have inner html "4-7" "7-10" and
"10+"  All of them have class "ansbtns" so how do i click a specific one for example the the one which have "7-10" inner html
i try to use this but this does not click a single of the buttons
WebView1.EvalScript("document.getElementsByClassName('ansbtns')[0].click();")

Webview1 is EO webbrowser control web control which execute Javascript using
Webview1.evalScript function.ofcourse i am doing this in VB.NET Visual studio
Any help would be greatly appreciated thanks

A: You can maybe try to use :contains for this:
WebView1.EvalScript("$('.ansbtns:contains(\"4-7\")').click();");


text:
Q: Cannot create record when LWC input fields populated from Google chrome save address I cannot create a new Case record when the custom LWC input fields, to capture the address, are populated from the Google Chrome browser saved address. I am getting the below error when I click on the Continue button.

I am aware of this error, and usually, we would get it when the User doesn't have access to the respective object or create record permissions. But, with the same user credentials, I can create a new record successfully when I input values manually or select any existing record on the component.
I couldn't find any issue with code and getHasInvalidFields() seems working fine in all other case. I have done some research regarding the issue but didn't find any solution specific to this issue. Could you please help me if anyone has thoughts on this?
Create shipping Address component controller
import { LightningElement, track, api, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import dxMessageChannel from '@salesforce/messageChannel/dxMessageChannel__c';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import COUNTRY_FIELD from '@salesforce/schema/Shipping_Address__c.Country__c';
import { CurrentPageReference } from 'lightning/navigation';
import saveAddressRecord from '@salesforce/apex/portalGetCaseRecord.createShippingAddressMyAccount';

export default class CreateShippingAddress extends LightningElement {
    @api textReturnAddress
    @api textSaveButton
    @api textCompanyName
    @api textReqCompanyName
    @api textAddressLine1
    @api textReqAddressLine1
    @api textAddressLine2
    @api textAddressLine3
    @api textTownCity
    @api textReqTownCity
    @api textPostalZip
    @api textReqPostalZip
    @api textCompanyCountry
    @api textReqCountry
    @api textExistingAddress

    pickListValues;
    hasInvalidFields;
    showSaveButton = false;
    buttonDisabled = true;

    @track shippingRecord = {Name:'',Address_Line_1__c:'',Address_Line_2__c:'',Address_Line_3__c:'',County__c:'',Post_Code__c:'',Country__c:''};

    @wire(MessageContext) messageContext;

    // Get the Record ID from the URL
    @wire(CurrentPageReference)
        setCurrentPageReference(currentPageReference) {
            this.currentPageReference = currentPageReference;
            this.currentPage = currentPageReference.attributes.name;
            this.myRecordId = this.currentPageReference?.state?.c__recordId;
            if(this.currentPage === 'My_Account__c') {
                this.showSaveButton = true;
            } else {
                this.showSaveButton = false;
            }
        }

    @wire(getPicklistValues, { recordTypeId: '012000000000000AAA', fieldApiName: COUNTRY_FIELD })
    setObjectInfo({data}) {
        if (data) {
            this.pickListValues = data.values;
        }
    }

    hideScreen(){
        this.sendGlobalMessage(null, 'AddressSwitch');
        this.dispatchEvent(new CustomEvent('showlist'));
    }

    handleNewAddress(event){
        // If on the my account page we can save the record directly as its not part
        // of the create case journey.
        this.hasInvalidFields = this.getHasInvalidFields();
        if(event.target.name === 'companyName'){
            this.shippingRecord.Name = event.target.value;
        }else if(event.target.name === 'address1'){
            this.shippingRecord.Address_Line_1__c = event.target.value;
        }else if(event.target.name === 'address2'){
            this.shippingRecord.Address_Line_2__c= event.target.value;
        }else if(event.target.name === 'address3'){
            this.shippingRecord.Address_Line_3__c = event.target.value;
        }else if(event.target.name === 'city'){
            this.shippingRecord.Town = event.target.value;
        }else if(event.target.name === 'zipcode'){
            this.shippingRecord.Address__PostalCode__s = event.target.value;
        }else if(event.target.name === 'country'){
            this.shippingRecord.Country__c = event.target.value;
        }
        if(this.shippingRecord.Country__c === '') this.hasInvalidFields = true;
        if (this.hasInvalidFields === false) {
            if(this.currentPage !== 'My_Account__c') {
                this.sendGlobalMessage(JSON.stringify(this.shippingRecord), 'ShippingManualInputted');
            } else {
                this.buttonDisabled = false;
            }
        } else {
            if(this.currentPage === 'My_Account__c') {
                this.buttonDisabled = true;
            }
        }
    }

    saveAddressRecord() {
        saveAddressRecord({
            Address1:this.shippingRecord.Address_Line_1__c,
            Address2:this.shippingRecord.Address_Line_2__c,
            Address3:this.shippingRecord.Address_Line_3__c,
            town:this.shippingRecord.Town,
            zipcode:this.shippingRecord.Address__PostalCode__s,
            country:this.shippingRecord.Country__c,
            companyName:this.shippingRecord.Name
        }).then((result) => {
            console.log(result);
            this.hideScreen();
        })
        .catch((error) => {
            this.error = error;
        });
    }

    sendGlobalMessage(theData, process){
        const message = {
            userSelected: theData,
            processIndicator: process
        }
        publish(this.messageContext, dxMessageChannel, message);
    }

      getHasInvalidFields() {
          const inputComponents = [...this.template.querySelectorAll('lightning-input')];
          // Trigger fields validation
          inputComponents.forEach((inputComponent) => {
              inputComponent.reportValidity();
          });
          this.hasInvalidFields = inputComponents.some((inputComponent) => inputComponent.checkValidity() === false);
          return this.hasInvalidFields;
      }

}

<template>

{textReturnAddress}

            <button
                class="slds-button slds-button_text-destructive slds-float_left slds-p-left_medium slds-p-right_medium slds-p-bottom_xx-small slds-p-top_xx-small buttonBordered buttonSolid saveButton"
                onclick={saveAddressRecord} disabled={buttonDisabled}>{textSaveButton}</button>

                <fieldset class="slds-form-element slds-form-element_compound ">

                            {textCompanyName}

                                <lightning-input type="text" id="input-01" placeholder="e.g megger" name="companyName"
                                    class="Myinput" required message-when-value-missing={textReqCompanyName}
                                    onkeyup={handleNewAddress}>
                                </lightning-input>

                            {textAddressLine1}

                                <lightning-input type="text" id="input-02" placeholder="e.g 58 My Street"
                                    name="address1" class="Myinput" required
                                    message-when-value-missing={textReqAddressLine1} onkeyup={handleNewAddress}>
                                </lightning-input>

                            {textAddressLine2}

                                <lightning-input type="text" id="input-03" placeholder="e.g street 34" name="address2"
                                    class="Myinput" onkeyup={handleNewAddress}></lightning-input>

                            {textAddressLine3}

                                <lightning-input type="text" id="input-04" placeholder="e.g street 12" name="address3"
                                    class="Myinput" onkeyup={handleNewAddress}></lightning-input>

                                    {textTownCity}

                                        <lightning-input type="text" id="input-05" placeholder="e.g Newyork" name="city"
                                            required message-when-value-missing={textReqTownCity} class="Myinput"
                                            onkeyup={handleNewAddress}></lightning-input>

                                    {textPostalZip}

                                        <lightning-input type="text" id="input-06" placeholder="e.g xt1234" required
                                            message-when-value-missing={textReqPostalZip} name="zipcode" class="Myinput"
                                            onkeyup={handleNewAddress}>
                                        </lightning-input>

                                <lightning-combobox class="Myinput" name="country" placeholder="e.g Canada"
                                    options={pickListValues} label={textCompanyCountry} required
                                    message-when-value-missing={textReqCountry} onchange={handleNewAddress}>
                                </lightning-combobox>

                </fieldset>

 {textExistingAddress}

</template>

Buttons component where the buttons enabled disabled based on shipping component input values
import { LightningElement, wire, track, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { CurrentPageReference } from 'lightning/navigation';
import createACase from '@salesforce/apex/portalGetCaseRecord.createACase';
import { subscribe, unsubscribe, APPLICATION_SCOPE, MessageContext } from 'lightning/messageService';
import dxMessageChannel from '@salesforce/messageChannel/dxMessageChannel__c';

export default class buttonSection extends NavigationMixin(LightningElement) {
  @track buttonDisabled = true;
  @track currentPageName;
  @api caliberaterecid;
  @api repairrecid;
  @api productId;
  @api textCountinueButton='Continue';
  @api textBackToDashboard='Back to dashboard';
  @api textBack='Back';

  recordId;
  theProduct;
  sourceSystem;
  recordTypeSelect;
  calibrationSelected;
  calibrationValue;
  servicePrioritySelected;
  servicePriorityValue;
  addressSelected;
  addressValue;
  fileSelected;
  fileName = null;
  fileData = null;
  description = null;
  createNewShippingRec;
  backButtonText;

  @wire(CurrentPageReference)
  getpageRef(pageRef) {
    this.currentPageName = pageRef.attributes.name;
    if (this.currentPageName === 'Registered_Product_List__c') {
      this.backButtonText = this.textBackToDashboard;
    } else {
      this.backButtonText = this.textBack;
    }
    this.productId = pageRef.state.product_Id;
  }

  @wire(MessageContext) context;

  connectedCallback() {
    this.subscribeMsg();
  }

  subscribeMsg() {
    if (this.subscription) {
      return;
    }
    this.subscription = subscribe(this.context, dxMessageChannel, (message) => this.handleMessage(message), {
      scope: APPLICATION_SCOPE,
    });
  }

  handleMessage(message) {
    if (
      this.currentPageName === 'Registered_Product_List__c' ||
      this.currentPageName === 'registered_product_list__c'
    ) {
      this.theProduct = message.product;
      this.buttonDisabled = false;
    } else if (this.currentPageName === 'Case_Type__c' || this.currentPageName === 'case_type__c') {
      this.recordTypeSelect = message.userSelected;
      if (this.recordTypeSelect === 1 || this.recordTypeSelect === 3) {
        this.buttonDisabled = false;
      } else {
        this.buttonDisabled = true;
      }
    } else if (this.currentPageName === 'Create_A_Case__c' || this.currentPageName === 'create_a_case__c') {
      if (message.processIndicator === 'caseDescription') {
        this.description = message.userSelected;
      } else if (message.processIndicator === 'caseFile') {
        if (message.fileName !== null) {
          this.fileSelected = true;
          this.fileName = message.fileName;
          this.fileData = message.fileData;
        } else {
          this.fileSelected = false;
          this.fileName = null;
          this.fileData = null;
        }
      } else if (message.processIndicator === 'CalibrationType') {
        if (this.calibrationValue === message.userSelected) {
          this.calibrationSelected = false;
          this.calibrationValue = null;
        } else {
          this.calibrationSelected = true;
          this.calibrationValue = message.userSelected;
        }
      } else if (message.processIndicator === 'ServicePriorities') {
        if (this.servicePriorityValue === message.userSelected) {
          this.servicePrioritySelected = false;
          this.servicePriorityValue = null;
        } else {
          this.servicePrioritySelected = true;
          this.servicePriorityValue = message.userSelected;
        }
      } else if (message.processIndicator === 'ShippingSelected') {
        if (this.addressValue === message.userSelected) {
          this.addressSelected = false;
          this.addressValue = null;
          this.createNewShippingRec = false;
        } else {
          this.addressSelected = true;
          this.addressValue = message.userSelected;
          this.createNewShippingRec = false;
        }
      } else if (message.processIndicator === 'ShippingManualInputted') {
        this.addressSelected = true;
        this.addressValue = message.userSelected;
        this.createNewShippingRec = true;
      } else if (message.processIndicator === 'AddressSwitch') {
        this.addressSelected = false;
        this.addressValue = null;
        this.createNewShippingRec = false;
      }

      //next process
      let typeName = sessionStorage.getItem('CaseRecordTypeName');

      if (typeName === 'Repair And Calibration' && typeName !== undefined) {
        if (
          this.addressSelected === true &&
          this.servicePrioritySelected === true &&
          this.calibrationSelected === true &&
          this.description !== null &&
          this.description !== ''
        ) {
          this.buttonDisabled = false;
        } else {
          this.buttonDisabled = true;
        }
      } else if (typeName === 'Repair' && typeName !== undefined) {
        if (
          this.addressSelected === true &&
          this.servicePrioritySelected === true &&
          this.description !== null &&
          this.description !== ''
        ) {
          this.buttonDisabled = false;
        } else {
          this.buttonDisabled = true;
        }
      } else if (typeName === 'Calibration' && typeName !== undefined) {
        if (this.addressSelected === true && this.calibrationSelected === true) {
          this.buttonDisabled = false;
        } else {
          this.buttonDisabled = true;
        }
      }
    }
  }

  createTheCase() {
    const regProduct = JSON.parse(sessionStorage.getItem('meggerORDProduct'));
    const arecordType = sessionStorage.getItem('CaseRecordTypeId');
    const fullShippingAddress = JSON.parse(this.addressValue);

    createACase({
      assetId: regProduct.recordId,
      recordType: arecordType,
      description: this.description,
      filename: this.fileName,
      fileblob: this.fileData,
      calibration: this.calibrationValue,
      services: this.servicePriorityValue,
      address1: fullShippingAddress.Address_Line_1__c,
      address2: fullShippingAddress.Address_Line_2__c,
      address3: fullShippingAddress.Address_Line_3__c,
      town: fullShippingAddress.Town,
      country: fullShippingAddress.Country__c,
      zipcode: fullShippingAddress.Address__PostalCode__s,
      createShipping: this.createNewShippingRec,
      companyName: fullShippingAddress.Name,
      addrId: fullShippingAddress.Id,
    })
      .then((result) => {
        sessionStorage.setItem('CaseId', result.Id);
        sessionStorage.setItem('CaseNumber', result.CaseNumber);
        this.error = undefined;
        this.goToFinalPage();
      })
      .catch((error) => {
        console.log('the case creation error = ' + error);
      });
  }

  goToFinalPage() {
    this.buttonDisabled = true;
    this[NavigationMixin.Navigate]({
      type: 'comm__namedPage',
      attributes: {
        name: 'Case_Details_Submitted__c',
      },
    });
  }

  unsubscribeMC() {
    unsubscribe(this.subscription);
    this.subscription = null;
  }

  disconnectedCallback() {
    this.unsubscribeMC();
  }

  navigateBack() {
    if (this.currentPageName === 'case_type__c' || this.currentPageName === 'Case_Type__c') {
      this[NavigationMixin.Navigate]({
        type: 'comm__namedPage',
        attributes: {
          name: 'Registered_Product_List__c',
        },
      });
    } else if (this.currentPageName === 'create_a_case__c' || this.currentPageName === 'Create_A_Case__c') {
      this[NavigationMixin.Navigate]({
        type: 'comm__namedPage',
        attributes: {
          name: 'Case_Type__c',
        },
      });
    } else if (
      this.currentPageName === 'registered_product_list__c' ||
      this.currentPageName === 'Registered_Product_List__c'
    ) {
      console.log('Inside Reg Product');
      this[NavigationMixin.Navigate]({
        type: 'comm__namedPage',
        attributes: {
          name: 'Home',
        },
      });
    }
  }

  navigateNext() {
    if (
      this.currentPageName === 'Registered_Product_List__c' ||
      this.currentPageName === 'registered_product_list__c'
    ) {
      sessionStorage.setItem('meggerORDProduct', JSON.stringify(this.theProduct));
      this.buttonDisabled = true;
      this[NavigationMixin.Navigate]({
        type: 'comm__namedPage',
        attributes: {
          name: 'Case_Type__c',
        },
      });
    } else if (this.currentPageName === 'case_type__c' || this.currentPageName === 'Case_Type__c') {
      if (
        sessionStorage.getItem('CaseRecordTypeId') !== undefined &&
        sessionStorage.getItem('CaseRecordTypeId') !== null
      ) {
        this.buttonDisabled = true;
        this[NavigationMixin.Navigate]({
          type: 'comm__namedPage',
          attributes: {
            name: 'Create_A_Case__c',
          },
        });
      }
    } else if (this.currentPageName === 'create_a_case__c' || this.currentPageName === 'Create_A_Case__c') {
      this.createTheCase();
    }
  }
}

Template
<template>

      <button
        class="slds-button slds-button_text-destructive slds-float_left slds-p-left_medium slds-p-right_medium slds-p-bottom_xx-small slds-p-top_xx-small buttonBordered"
        onclick={navigateBack}>{backButtonText}</button>

      <button
        class="slds-button continue slds-button_neutral slds-float_right slds-p-left_medium slds-p-right_medium slds-p-bottom_xx-small slds-p-top_xx-small buttonSolid"
        disabled={buttonDisabled} onclick={navigateNext}>{textCountinueButton}</button>

</template>

A: The problem is the way you are capturing the values from the screen, you are using the handleNewAddress as listening to the event keyup, and when google auto-populates it the event is not triggered, so the values are going as null to the backend, and probably the error is a validation rule saying is required.
My recommendation is to you change your saveAddressRecord method to capture all inputs from the DOM ->

    saveAddressRecord() {
        const lstUserInput = [... this.template.querySelectorAll('lighting-input')]
        let objInputNameInputValue = lstUserInput.reduce( (obj ,element) => {
            return {... obj, [element.name]: element.value }
        }, {});
        console.log(JSON.stringify(objInputNameInputValue ));
        let params = {
            Address1: objInputNameInputValue.address1,
            //TODO finish params
        }
        saveAddressRecord( params )
        .then((result) => {
            console.log(result);
            this.hideScreen();
        })
        .catch((error) => {
            this.error = error;
        });
    }


text:
Q: Query an array of DNS records with dnspython, and proceed to the next element based on a custom timeout I'm querying a bunch of DNS records with dnspython, it seems to timeout when no reply is received (dns.exception.Timeout: The DNS operation timed out after 30.0006685256958 seconds).
Here's the function:
def dnstest(domain):
    dnsrecords = []
    record_types = ['A', 'AAAA', 'CNAME', 'MX', 'SRV', 'TXT', 'SOA', 'NS']
    dnsResolver = dns.resolver.Resolver()
    for record in record_types:
        dnsAnswer = dnsResolver.query(domain, record)
        for rdata in dnsAnswer:
            dnsrecords.append(rdata)
    return(dnsrecords)

print(dnstest("github.com"))

whereas, if I query the DNS records that exist, an answer is received:
dnsAnswer = dnsResolver.query(domain, 'A')
I'm guessing this is because certain records (such as SRV, AAAA etc.) doesn't exist for github.com. However, they do exist for other domains. Is there a way I can include a timeout (like say, 5 seconds) per query within the for loop?
Something like -
if no response in 5 seconds, move to next element in the array
Or is there a better approach to exclude non-existent records?

A: The following worked for me after some quick googling.
import dns.resolver

def dnstest(domain):
    dnsrecords = []
    record_types = ['A', 'AAAA', 'CNAME', 'MX', 'SRV', 'TXT', 'SOA', 'NS']
    dnsResolver = dns.resolver.Resolver()
    dnsResolver.timeout = 1
    dnsResolver.lifetime = 1
    for record in record_types:
        try:
            dnsAnswer = dnsResolver.query(domain, record)
            for rdata in dnsAnswer:
                dnsrecords.append(rdata)
        except:
            pass

    return(dnsrecords)


text:
Q: How do I create a legend for both color and shape in ggplot2 I have a scatter plot where I am graphing statistics for two sets. The shape of the points indicate which X-axis population that data point is for and the color of the point indicates what Y-axis population that is for
My table looks as such
comp    source2 y   SEy source1 x   SEx color   shape
PopA    PopAlpha    0.3 0.002   PopOne  0.1 0.2 green   1
PopB    PopAlpha    0.5 0.1 PopOne  0.3 0.8 green   1
PopC    PopAlpha    0.4 0.1 PopOne  0.2 0.4 green   1
PopA    PopBeta 0.3 0.1 PopOne  0.1 0.1 blue    1
PopB    PopBeta 0.2 0.01    PopOne  0.1 0.1 blue    1
PopC    PopBeta 0.1 0.1 PopOne  0.213501    0.00204 blue    1
PopA    PopAlpha    0.3 0.2 PopTwo  0.2 0.2 green   8
PopB    PopAlpha    0.1 0.2 PopTwo  0.2 0.01    green   8
PopC    PopAlpha    0.3 0.1 PopTwo  0.2 0.9 green   8
PopA    PopBeta 0.2 0.4 PopTwo  0.3 0.1 blue    8
PopB    PopBeta 0.3 0.1 PopTwo  0.3 0.1 blue    8
PopC    PopBeta 0.1 0.1 PopTwo  0.2 0.1 blue    8

and my code is such
read.table("example.txt", header = TRUE) -> tbl
require(ggplot2)
plot <- ggplot(data = tbl,aes(x = x,y = y)) +
  geom_point(colour=tbl$color, mapping=aes(shape=tbl$shape)) +
  geom_errorbar(aes(ymin = y-SEy,ymax = y+SEy,width=0),colour=tbl$color) +
  geom_errorbarh(aes(xmin = x-SEx,xmax = x+SEx,height=0),colour=tbl$color) +
  geom_abline(intercept = 0, slope = 1) + scale_shape_identity()
  #+ scale_colour_manual(name = "Y population",labels = c("PopAlpha", "PopBeta"),values = c("green", "blue"))
  #+ scale_shape_manual(name = "X population",labels = c("PopOne","PopTwo"),values = c(1,8))
ggsave(plot=plot,height=6,width=7, filename="example2.pdf", useDingbats=FALSE)
plot(plot)
dev.off()

When I try to uncomment out the legend lines, I get "Error in +scale_shape_manual(name = "X population", labels = c("PopOne",  :
invalid argument to unary operator"
Can someone help me figure what I am doing wrong? Thanks!
I need the legend to have one portion indicating color and one indicating shape. My actual dataset has four colors and seven shapes, so I can't have a legend that explains all combinations.
structure(list(comp = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("PopA", "PopB", "PopC"), class = "factor"), source2 = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("PopAlpha", "PopBeta"), class = "factor"), y = c(numbers), SEy = c(numbers), source1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("PopOne", "PopTwo"), class = "factor"), x = c(numbers), SEx = c(numbers), color = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("blue", "green"), class = "factor"), shape = c(1L, 1L, 1L, 1L, 1L, 1L, 8L, 8L, 8L, 8L, 8L, 8L)), .Names = c("comp", "source2", "y", "SEy", "source1", "x", "SEx", "color", "shape"), class = "data.frame", row.names = c(NA, -12L))

A: You need to have the + at the end of the line rather than the start of the next.
ggplot(data = tbl,aes(x = x,y = y)) +
  geom_point(colour=tbl$color, mapping=aes(shape=tbl$shape)) +
  geom_abline(intercept = 0, slope = 1) + scale_shape_identity()

Code this far is syntactically complete. So the next lines are taken as being added together rather than being added to the previous.
 + scale_colour_manual(name = "Y population",labels = c("PopAlpha", "PopBeta"),values = c("green", "blue"))
 + scale_shape_manual(name = "X population",labels = c("PopOne","PopTwo"),values = c(1,8))

Simply move the +s to the ends of the previous lines so the lines are not complete.
I make this mistake every time I get ggplot2 out.

A: If you want to obtain a variable in the legend, you just need to map it including that variable in aes.
Moreover as shape is a numeric variable, it needs to be converted to factor
ggplot(data = tbl,aes(x = x,y = y)) +
geom_point(mapping=aes(shape=factor(shape),color=color)) +
geom_abline(intercept = 0, slope = 1) +
scale_colour_manual(name = "Y population",labels = c("PopBeta", "PopAlpha"),values = c("blue", "green"))+
scale_shape_manual(name = "X population",labels = c("PopOne","PopTwo"),values = c(1,8))


text:
Q: Xcode unit testing not recognizing nil? I am using Xcode Version 7.2 (7C68) in a pure Swift project. I ran into this monstrosity! Anyone knows how to "fix" this?

retrievedDate is declared as
var endDate: NSDate?

A: I would rather check that the retrievedEndData is an option. For example:
let retrievedEndDate : NSDate? = nil

should yield true when asserting like:
XCTAssertNil(retrievedEndDate)

A: Probably
XCTAssert(retrievedEndDate == nil, "retrievedEndDate is nil")
Would work.
Also, you could rephrase your test to use XCTAssertNotNil instead.
Or as a workaround you could do:
guard let endDate = retrievedEndDate else { XCTFail("retrievedEndDate is nil") }

But that's not really pretty.


text:
Q: Vlookup Based on Data validation lists I have two drop down lists: Cable type and length. So a user could choose "LC-LC SM", and then choose the length "5m". Based on these two inputs, I want to use Vlookup to pull their price.
I have all cables listed in order of type, by length. For example:
Cables
Cable type and length are the inputs, how do I use those two separate inputs to call the price? This is the input screen; I want to use the Vlookup function in the MSRP cell.
Inputs

A: Check this. I assumed your inputs are in A2 and B2 and price data is in G2:H4.
=VLOOKUP($A2 & " " & $B2 & "m", $G$2:$H$4, 2, 0)

A: =VLOOKUP(A2,Sheet1!A2:B4,2,0)
A2 is the display sheet, Sheet1!A2: B4 here is the cable data, 2 is the MSRP values ,0 is the exact values enter image description here


text:
Q: Шашка перемещается не туда Jquery Пишу шашки и тут такая проблема:
Если ходишь второй шашкой, то происходит какая-то каша.
Код:

$(document).ready(function() {
  $('

').appendTo('body');
  var is = false;
  for(let i = 0; i < 8; i += 1) {
    $('
').appendTo('table');
    console.log('create-tR');
    is = !is;
    for(let j = 0; j < 8; j += 1) {
      is = !is;
      $('').appendTo('tr:last');
      $('

').appendTo('td:last');
      if(is) {
        $('#'+i+j).css('background-color', '#362416');
      } else {
        $('#'+i+j).css('background-color', '#edd3a2');
      }
      if(is && (i <= 2 || i >= 5)) { //if hahka
        if(i <= 2) {
          $('

').appendTo('#'+i+j);
        } else {
          $('

').appendTo('#'+i+j);
        }
      }
      $('	').appendTo('tr:last');
      $('
').appendTo('table');
    }
  }
  //--↑ place in top is a placing chessboard ↑--//
  var plhod = true,
    i = 0;
  //console.log('create-td');
  if(plhod) { //if player walk now
    $('.hahka.wh').click(function() {
      var pos = parseInt($(this).attr('id').slice(1));
      var off = $(this);
      //off-elem of hahka\
      alert(pos);
      $('#'+String(pos - 8 - 1)).css('background-color', 'yellow');
      $('#'+String(pos - 8 - 3)).css('background-color', 'yellow');
      $('.cage').click(function() {
        if($(this).css('background-color') == 'rgb(255, 255, 0)') {
          console.log($(this).offset());

          alert($(this).attr('id'));
          $("#"+off.attr('id')).offset($(this).offset());

          $('#'+String(pos - 8 - 1)).css('background-color', '#362416');
          $('#'+String(pos - 8 - 3)).css('background-color', '#362416');
          $(off).attr('id', 'h'+$(this).attr('id')+i);
        }
      });
    });
  }
});
div {
  width: 70px;
  height: 70px;
}

.hahka {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

div td tr {
  margin: 0;
  padding: 0;
}

.bl {
  background-color: red;
}

.wh {
  background-color: white;
}

table {
  background-color: black;
}

/* fix snippet */
.as-console-wrapper,
.as-console-wrapper div {
  width: auto;
  height: auto;
}

Сначала норм

И тут норм

Когда переставляешь 2 шашку, то на ее место идёт предыдущая шашка. Что делать?

Спасибо!

A: Не назначайте обработчики событий внутри других обработчиков событий.
$('.hahka.wh').click(function() {
  ...
  $('.cage').click(function() {

Делая так, Вы (при клике на $('.hahka.wh')) навешиваете все новые и новые обработчики на $('.cage').click, которые все выстреливают при клике на $('.cage').


text:
Q: Comment is above one with earlier timestamp I posted a comment on an answer, and refreshed the page.  I then noticed that someone else had also posted a comment.  His comment had an earlier timestamp, but was below mine.

What happened?  (I'm using the Android app, if that matters.)

A: I think you're basically just seeing a UI glitch re: merging data; perhaps it used the local device time for simulating a fast UI update for your answer as you added it ("fake it until you make it"), but basically: your comment was genuinely there first. You can see this in the main web app by hovering on the times; yours is 2016-05-26 18:49:32Z, the second one is 2016-05-26 18:49:45Z. Or at the database:

So: the only thing wrong is the relative date displayed in the Android app at the point the comment is first created. In reality, it is a very edge condition; but we should keep it on the list to check whether we want to tweak the app to update itself with the times (etc.) after they have been saved.


text:
Q: same string but it return false while using equals method with two StringBuilder objects Scanner s = new Scanner(System.in);
        char[] ch = s.next().toCharArray();
        Arrays.sort(ch);
        StringBuilder sb = new StringBuilder();
        sb.append(ch);
        int n = s.nextInt();
        while (n-- > 0) {
            char[] book = s.next().toCharArray();
            Arrays.sort(book);
            StringBuilder sb2 = new StringBuilder();
            sb2.append(book);
            System.out.println(sb.equals(sb2));

        }
it returns false.
input
act
1
cat
output
false

i tried to check two string are same or not without working with array but input will be in array.


text:
Q: Add unique rows to dataframe (opposite of intersect) I am relatively new to R but slowly finding my way. I encountered a problem, however, and hope someone can help me.
Let's say I two dataframes (lets call them A and B), both containing survey responses. A contains all responses from the first set of people. B contains the responses of the second set of people, plus the people of the first set but with their responses set to NA. An example:
Dataframe A:
Household Individual Answer_A Answer_b
1         2          5        6
1         3          6        6
2         1          2        3

Dataframe B:
Household Individual Answer_A Answer_b
1         1          3        6
1         2          NA       NA
1         3          NA       NA
2         1          NA       NA
2         2          4        7

I want to get one dataframe with all individuals and their responses:
Dataframe C:
Household Individual Answer_A Answer_b
1         1          3        6
1         2          5        6
1         3          6        6
2         1          2        3
2         2          4        7

If I only have two datasets I can use rbind.fill, with rbind.fill(B, A) to get dataframe C, as then the NAs in B are overwritten with answers in A.
But... if I would have to add a third dataset, D, that would consist of NAs for people in A and B, I would not be able to use this solution. What would I be able to do then? I've looked at intersect, outersect, different forms of join, but can't seem to think of a good solution.
Any thoughts?

A: Maybe you can left_join and then use coalesce
library(dplyr)

left_join(B, A, by = c("Household", "Individual")) %>%
  mutate(Answer_A = coalesce(Answer_A.x, Answer_A.y),
         Answer_B = coalesce(Answer_b.x, Answer_b.y)) %>%
  select(-matches("\\.x|\\.y"))

#  Household Individual Answer_A Answer_B
#1         1          1        3        6
#2         1          2        5        6
#3         1          3        6        6
#4         2          1        2        3
#5         2          2        4        7

data
A <- structure(list(Household = c(1L, 1L, 2L), Individual = c(2L,
3L, 1L), Answer_A = c(5L, 6L, 2L), Answer_b = c(6L, 6L, 3L)), class = "data.frame",
row.names = c(NA, -3L))

B <-  structure(list(Household = c(1L, 1L, 1L, 2L, 2L), Individual = c(1L,
2L, 3L, 1L, 2L), Answer_A = c(3L, NA, NA, NA, 4L), Answer_b = c(6L,
NA, NA, NA, 7L)), class = "data.frame", row.names = c(NA, -5L))


text:
Q: Vector calculation out of two vectors When I have vectors
$\vec r_1=(4,0,0)$, $\vec v_1=(-2,-1,-2)$,
$\vec r_2=(-2,0,3)$, and $\vec v_2=(-1,0,1)$, and unknown vectors $\vec r_3$ and $\vec v_3$ that satisfy
$m_1 \vec{r_1} \times \vec v_1 + m_2 \vec r_2 \times \vec v_2 + m_3 \vec r_3 \times \vec v_3=0$, for scalars $m_1=1$, $m_2=2$, and $m_3=3$,
How can I calculate $\vec r_3$ and $\vec v_3$ out of these ?
Thanks a lot.

A: We have $(4,0,0)\times(-2,-1,-2) + 2(-2,0,3)\times(-1,0,1) +3\vec r_3\times\vec v_3 = 0$. Thus,
$$\vec r_3 \times \vec v_3 = \frac{-1}{3}\left((0,8,-4) + (0,-2,0)\right) = \frac{1}{3}(0,-6,4).$$
Unfortunately, there is no way to determine $\vec r_3$ and $\vec v_3$ from this: in particular, if $(\vec r_3, \vec v_3)$ is a pair of vectors satisfying this equation, then so is $(\alpha\vec r_3, \frac{1}{\alpha}\vec v_3)$ for any scalar $\alpha \neq 0$. We cannot even determine $\vec r_3$ and $\vec v_3$ up to scaling, as also $(\vec r_3 + \vec v_3,\vec v_3)$ satisfies the same equation.
However, expanding out what that equation means, with $\vec r_3 = (a,b,c)$, and $\vec v_3 = (d,e,f)$, we obtain the following equations:
$bf - ce = 0$
$cd - af = -2$
$ae - bd = \frac{4}{3}$.
Now, when $a = 0$, a general solution to these is given in terms of $d\neq 0$ and $e$ by
$d \neq 0$, $c = \frac{-2}{d}, b = \frac{-4}{3d}$, $f = \frac{2e}{3}$.
When $a \neq 0$, we have $f = \frac{2-cd}{a}$, and $e = \frac{4 + 3bd}{3a}$. Substituting these into the first equation and simplifying, we have $6b-3bcd - 4c - 3bcd = 0$, so $c = \frac{3b}{2}$. Substituting that back through, we have $f = \frac{4-3bd}{2a}$, which gives our general solution in terms of $a\neq 0$, $b$, and $d$.


text:
Q: How to use package in Laravel framework? I have new to Laravel and have installed the Laravel Dynamic Menu package which is installed successfully in the Vendor folder named rapidwebltd/laravel-dynamic-menu.
I don't know how can I use this package in my application to create
the dynamic menu.
One more thing I already run the command
 php artisan migrate

and required tables for this package were created. Can anyone please
guide me to use this package?

A: You need to see the documentation of the package it will be avaiable in github or in its official website


text:
Q: Knockout drag and drop : On drag enter hiding div and on drag leave show div [Mine is different] I am new to knockout JavaScript. in my project I am using Knockout drag and drop functionality. by initially i have two divisions one is visible and another one have property display none. when I am doing drag enter function I need to hide first division and show second division. once drag leave hide 2nd division and showing first division. But problem is when I was drag enter the second division functionality is changing I don't want to hide second division until drop. Please help me to resolve.
I don't want to change any html in ".typeTextareaSection"(which is having in code) block.
here is my fiddle Knockout Drag and drop Fiiddle

function ViewModel(){
    var self = this;
    this.dropZones = ko.observableArray([{
        'elements' : ko.observableArray([])  // just to see that the output is correct
    }]);

    this.dragoverTextarea = function(e){
        console.log('dragOver');
        e.stopPropagation();
        e.preventDefault();
    }

    this.dropTextarea = function(e, data){
        console.log('drop');
        e.stopPropagation();
        e.preventDefault();
        var files = e.dataTransfer.files;
        for (var i = 0, f; f = files[i]; i++) {
            data.elements.push(f.name);
        }
        $('.typeTextarea').children('.typeTextareaSection').css('display', 'block');
   $('.typeTextarea').children('#dragtimeTextarea').css('display', 'none');

    }

    this.dragenterTextarea = function(e, index){
        console.log('dragEnter');
              $('.typeTextarea').eq(index).children('.typeTextareaSection').css('display', 'none');
   $('.typeTextarea').children('#dragtimeTextarea').css('display', 'block');
    }

    this.dragleaveTextarea = function(e, index){
        console.log('end');
        $('.typeTextarea').children('.typeTextareaSection').css('display', 'block');
   $('.typeTextarea').children('#dragtimeTextarea').css('display', 'none');
    }
}

ko.applyBindings(new ViewModel());

                <textarea  class="ediitableTestAreaPlaceHolders" maxlength="25000" style="margin-bottom: 0px; height: 70px; width: 99%;" placeholder="drop files here..." ></textarea>

  <textarea id="dragtimeTextarea" placeholder="Over this area to check my problem" style="display:none;font-size:20px;color:#000;"></textarea>

A: Your approach to this problem is not structured enough.
The most important thing to internalize is that every time you modify the DOM from within your viewmodel you are doing something wrong. Your viewmodel must not know anything about your page structure, elements, CSS classes or DOM events. Your view is supposed to depend on your viewmodel, not the other way around.
The only place to do DOM interaction is: In a binding. If there is no built-in binding that does what you need then you can create a custom one.
In your case you want to encapsulate the operation of dropping files onto an element. This should have two effects:

*

*some elements should react visibly when you hover something

*the dropped files should go into an observable array

This effectively determines the interface of your binding:

*

*an observable that will store true when hovering and false otherwise

*an observable that will receive the dropped files

So let's call the new binding filedrop, and that's how it's going to be used:

where hovering and files are observables in your viewmodel. Here's how the binding could look like:
ko.bindingHandlers.filedrop = {
    init: function (element, valueAccessor) {
        var options = valueAccessor();

        ko.utils.registerEventHandler(element, "dragenter", function (e) {
            if (ko.isWriteableObservable(options.hover)) options.hover(true);
            e.preventDefault();
        });
        ko.utils.registerEventHandler(element, "dragleave", function (e) {
            if (ko.isWriteableObservable(options.hover)) options.hover(false);
            e.preventDefault();
        });
        ko.utils.registerEventHandler(element, "dragover", function (e) {
            e.preventDefault();
        });
        ko.utils.registerEventHandler(element, "drop", function (e) {
            if (ko.isWriteableObservable(options.drop)) {
                if (typeof options.drop.push === "function") {
                    options.drop.push.apply(options.drop, e.dataTransfer.files);
                } else {
                    options.drop(e.dataTransfer.files);
                }
            }
            if (ko.isWriteableObservable(options.hover)) options.hover(false);
            e.preventDefault();
        });
    }
};

Now you can clean up your viewmodel graph by creating a dedicated DropZone viewmodel that contains the hovering and files observables and other associated things:
function DropZone() {
    var self = this;
    self.text = ko.observable();
    self.files = ko.observableArray();
    self.hovering = ko.observable(false);
    self.filenames = ko.computed(function () {
        return ko.utils.arrayMap(self.files(), function (element) {
            return element.name;
        });
    });
}

Now your main view model is what it should be: A list of dropzones.
function ViewModel() {
    var self = this;
    self.dropZones = ko.observableArray([
        new DropZone()
    ]);
}

After that building the view is no problem anymore, either.

            <textarea maxlength="25000" data-bind="value: text" placeholder="Start typing here…"></textarea>

Drop files here…

All of this leaves you with

*

*a custom binding that you can re-use in a different place or project

*a set of viewmodels that actually contain only what they should contain

*an overall clean and maintainable setup

http://jsfiddle.net/kd7umbj4/2/


text:
Q: Bind to Collection Count Where My question is similar to this one: Bind to Count of List where Typeof
But how does this work for Classes?
In my MainWindow I have the following Collection and a Selected Count Property
private ObservableCollection<MyClass> _myClassCollection = new ObservableCollection<MyClass>();
public ObservableCollection<MyClass>
{
    get => _myClassCollection;
    set
    {
        if(_myClassCollection == value) return;
        _myClassCollection = value;
        OnPropertyChanged("MyClassCollection");
    }
}

public int SelectedCount
{
    get => MyClassCollection.Where(x => x.IsSelected == true).Count();
}

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

My MyClass:
public class MyClass : INotifyPropertyChanged
{
    // .. Properties
    private bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set
        {
            if(_isSelected == value) return;
            _isSelected = value;
            OnPropertyChanged("IsSelected");
        }
    }
}

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

So how can I "run" the SelectedCount Property, if the IsSelected Property of MyClass changed ? I want to show the number of Selected Items of the ObservableCollection in real time.

A: You can just add an OnPropertyChaned for SelectedCountin the setter of the other operations where a change may have occurred.  For instance on setting the my class collection.  This will tell stuff listening to that particular property something may have changed, get the value again.
set
{
    if(_myClassCollection == value) return;
    _myClassCollection = value;
    OnPropertyChanged("MyClassCollection");
    OnPropertyChanged("SelectedCount");  // Make the change Here.
}

From the comments it would seem you need to listen to each element's property changed explicitly.  Here is an example of how that would look in your setter with an event handler.
set
{
    // remove subscriptions
    if(_myClassCollection != null)
    {
       foreach(var element in _myClassCollection)
       {
          element.PropertyChanged -= ElementChanged;
       }
    }

     // set to new collection
    _myClassCollection = value;

    // subscribe to new elements.
    if(_myClassCollection != null)
    {
       foreach(var element in _myClassCollection)
       {
          element.PropertyChanged += ElementChanged;
       }
    }

    OnPropertyChanged("MyClassCollection");
    OnPropertyChanged("SelectedCount");  // Make the change Here.
}

private void ElementChanged(object sender, PropertyChangedEventArgs e)
{
    if(e.PropertyName == nameof(MyClass.IsSelected))
    {
         OnPropertyChanged("SelectedCount");
    }
}

Now if you are adding or removing elements from your collection without creating a new collection, you will need to subscribe or remove subscriptions inside a CollectionChanged event handler.

A: You can use DynamicData to make it more readable:
var allObjects = new SourceList<MyClass>(); // this is what you populate with your objects

SelectedObjects = allObjects.Connect().Filter(x => x.IsSelected).AsObservableList();

If SelectedObjects is a public property, you can bind like:
<TextBloc Text="{Binding SelectedObjects.Count}"/>

A: You have to handle the CollectionChanged from your ObservableCollection.
There you have to call OnPropertyChanged("SelectedCount") like in the linked Question.
In your set:
_myClassCollection.CollectionChanged += Handle_CollectionChanged;

In the event handler:
private void Handle_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    OnPropertyChanged("SelectedCount");
}


text:
Q: sum of a column after select from SQL I am trying to select a column from a table, not only display each row with its value but also display the total of the column according to the query.
As shown in the code provided below, each row is displayed perfectly, however, when comes to the total of the column, only the value of the first called row is displayed as a total.
Please look at the picture provided below. Only the first row selected with value of 25:18 is displayed as a total.
The expected total value at the bottom of the table should be 51:19+50:41+25:18, but the total again is just the first row (DESC). Please advise
table display after selected from sql
if (($user != "") && ($date !="")){
    $mysql=("SELECT inet_ntoa(conv(hex(location_ip), 16, 10)) as ip, conv(hex(idvisitor), 16, 10) as visitorId,
    visit_last_action_time, visit_first_action_time, visitor_localtime,  user_id, visit_total_time
    FROM piwik_log_visit WHERE user_id='".$user."' AND date(visit_first_action_time) ='".$date."'
    Order by visit_first_action_time DESC");}

$query= mysqli_query($conn, $mysql) or die ("SQL Error: ".mysqli_error($conn));
while ($row = mysqli_fetch_array($query))
        {
            $time =date('F d, Y | h:i:s a', strtotime($row['visitor_localtime']));
            $time =date('h:i:s a', strtotime($row['visitor_localtime']));
            $idaction_url = $row['idaction_url'];
            $ip =$row['ip'];
            $visitor = $row['visitorId'];

            $first = date('F d, Y |', strtotime($row['visit_first_action_time']));
            $date = $first.' '.$time;

            ///total time added
            $sum = array($row['visit_total_time']);
            $sum_total = array_sum($sum);
            $sum_time = gmdate('H:i:s', $sum_total);

            $total = gmdate('i:s', $row['total_time']);

A: You could try
$sum_total = 0;
foreach($sum as $key=>$value)
{
   $sum_total+= $value;
}
echo $sum_total;

A: I got the total time to work through this code:
$sql=("SELECT SUM(total_visit_time) as total_time....);

while ($row=mysqli_fetch_assoc($sql)){

$total_time_spent += $row['total_time'];
}

echo $total_time_spent;


text:
Q: How do I remove an EventListener in an ItemRenderer? I'm creating an actionscript custom itemRenderer, and I have:
override protected function createChildren():void {
        super.createChildren();
        addEventListener(MouseEvent.CLICK, clicked,false,0,true);
}

Where do I put my removeEventListener when I'm done with the itemRenderer?

A: override protected function createChildren():void {
        super.createChildren();
        addEventListener(Event.ADDED_TO_STAGE, activateDeactivate, false, 0, true);
        //will be removed by GC due to weak reference
}

private function activateDeactivate( evt:Event ):void
{
    switch( evt.type )
    {
        case Event.ADDED_TO_STAGE:
            addEventListeners();
            break;
        case Event.REMOVED_FROM_STAGE:
            removeEventListeners();
            break;
    }
}

protected function addEventListeners( ):void
{
    addEventListener(Event.REMOVED_FROM_STAGE, activateDeactivate, false, 0, true);

    //add all other event listeners here or override this method in your class
}

protected function removeEventListeners( ):void
{
    removeEventListener(Event.REMOVED_FROM_STAGE, activateDeactivate);

    //Remove all other event listeners here or override this method in your class
}

A: You can remove the event listeners when Event.REMOVED is dispatched. But first, you should add an event listener to receive it.


text:
Q: Showing that a sequence of function converge with subsequence Most examples that I have read apply continuity argument to limit question like this:
$$L = \lim_{n \to \infty} \sin(1/n) = \sin(\lim_{n \to \infty} 1/n) = \sin(0) = 0$$
Clearly the sine function is continuous. But then it comes to me that if we let $n = \frac{1}{2\pi k}$, we can construct new subsequence $\sin(2\pi k$), which for integer $k$ is always null, thus the original sequence must be null as well.
My question is, ist this the valid way of constructing new subsequence? (Adding a factor of $2\pi$)?
Thank You

A: Just because a subsequence is always null wouldn't mean a sequence is null as well. For example, consider the sequence $(0,1,2,3,0,1,2,3,0,1,2,3\cdots)$ and the subsequence $(0,0,0,0\cdots)$


text: Q: what's TransactionID and RowID and Roll Point size in InnoDB I'm reading a MySQL internal book, but it use InnoDB 3.23.49 as example, and I'm currently use MySQL 5.6 and find that it's inconsistent with the book.How can I get the size of TransactionID and RowID and Roll Point?


text:
Q: Union query and C++ I use MySQL database and C++ programming language.
In my database there are 20 tables. I produce different messages from these tables.
All tables include dateTime columns and I want to sort produced messages.
I did it by using union. But query is so long.
Do you think it has another way or my way is correct.
Thans a lot.

A: It sounds like you're trying to get a sorted list of items from multiple unrelated tables.
In that case I would get the messages from each table individually and then in C++ programmatically sort them into the order you desired. That might make your queries much less complex than having them do the union and sort across many tables.
EDIT:
Unfortunately I don't think there is an absolute objective answer as to whether to do this in SQL or programatically in C++. I would suggest a pragmatic approach: Code it the way that's easiest and most clear (usually the two are the same) and see how it performs. If performance is acceptable then you're done. If it's slow, then profile it. If you discover your method is the slow point then you can try the other approach and see how it performs instead.

A: I don't know if MySQL suports this, but you could put all your unions as a sub-select and do the sorting from the outer select, like this:
select
  f1, f2
from (
  select
    f1, f2
  from
    T1
  union
  select
    f5, f6
  from
    T2
)
order by
  2


text:
Q: Why does jslint hightlight ++? I have the following code:
for (i = 0; i < json.AnsData.length; i++) {

jsLint is telling me:
Warning 96  JS Lint: Unexpected '++'.

Does anyone know why this is?

A: From http://www.jslint.com/lint.html:

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. Also, preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose. There is a plusplus option that allows the use of these operators.

JSLint is very strict and reflects the views of its author, Douglas Crockford. Crockford is awesome, but he's also very opinionated and some people find his opinions go too far for their tastes. If you find that avoiding ++ isn't something you can get behind, try JSHint instead of JSLint (or set the option in JSLint to tolerate ++).


text:
Q: Add Delta Lake packages to AWS EMR Notebook Delta jardelta-core_2.11-0.6.1.jar is added to EMR Master node "SPARK_HOME/jars" directory. However calling Delta API from EMR Notebook I am getting following error:
# Though Notebook comes with default SPARK instant so following line I didn't execute
# spark = SparkSession.builder.appName("MyApp") \
#    .config("spark.jars.packages", "io.delta:delta-core_2.11:0.6.1") \
#    .getOrCreate()

from delta.tables import * # ModuleNotFoundError: No module named 'delta'

CLI command pyspark --packages "io.delta:delta-core_2.11:0.6.1" is working fine in Master node. I am able to access Delta APIs in CLI mode.
Is there any way I can use Delta APIs directly in Notebook. Please suggest.

A: The tables.py file containing the DeltaTable class can be found in the delta repo on github.
You can find it here - https://github.com/delta-io/delta/tree/master/python/delta
You can either clone the repo (Remember to select the correct branch) or copy the file and upload that to Jupyter.  Either way it'll need adding as a dependency, so you'll need something like
import sys
sys.path.append('mnt/jupyterhome/<username>/<folder_containing_tables.py>)

Hopefully that'll get you up and running!


text:
Q: TextBlock Set in a specific Co ordinate inside an image in wpf C# I'm stuck in a problem . I can calculate distance from 2 points . And I want to set the TextBlock after I Draw Line . Please not that I don't use any Graphics property to write inside image . I use TextBlock because that is not write inside image . Here is my XAML code ..
 <Canvas Margin="10" IsEnabled="{Binding IsEnableCanvas}"  Visibility="{Binding Path=ISCanvasVisible, Converter={StaticResource Converter}}">
                <!--<Canvas Margin="10,10,0,10" IsEnabled="{Binding IsEnableCanvas}" Background="Gray"  Visibility="{Binding Path=ISCanvasVisible, Converter={StaticResource Converter}}" HorizontalAlignment="Left" Width="150"  >-->
                <Image Source="{Binding DIIMG_For_Folder}"    cal:Message.Attach="[Event MouseDown] = [Action MDownCalCulateDistance_Right($source, $eventArgs)];
                [Event MouseUp] = [Action MUpCalCulateDistance_Right($source, $eventArgs)];
                [Event MouseMove] = [Action MMoveCalCulateDistance_Right($source, $eventArgs)]" Stretch="Uniform" />
                <Line Visibility="{Binding Path=ISLineDistanceVisible, Converter={StaticResource Converter}}"  IsHitTestVisible="False"  X1="{Binding FirstPoint_Right.X}" Y1="{Binding FirstPoint_Right.Y}"
                  X2="{Binding SecondPoint_Right.X}" Y2="{Binding SecondPoint_Right.Y}"
                  Stroke="Red" StrokeThickness="3">
                </Line>
                <TextBlock Text="{Binding Path=DisTanceInMM_Right, Mode=OneWay}" Margin="15" FontSize="20" Foreground="Red" ></TextBlock>
            </Canvas>

As you can See I use  property to connect two point and show the Line. But You also see The TextBlock I set a fixed point that is Margin 15 . I want to set when I draw the line after the secondpoint.x and Secondpoint.Y. Here is my C# code
            try
            {
                if (_firstPointRight.X == 0 && _firstPointRight.Y == 0)
                {
                    System.Windows.Point px1 = e.GetPosition((System.Windows.Controls.Image)sender);

                    _firstPointRight = px1;
                }
                else
                //if (_secondPointRight.X == 0 && _secondPointRight.Y == 0)
                {
                    System.Windows.Point px2 = e.GetPosition((System.Windows.Controls.Image)sender);
                    _secondPointRight = px2;
                    var geometry = new FrameGeometry(DicomDataSet);
                    var patientCoord1 = geometry.TransformImagePointToPatient(new Point2(Convert.ToInt32(_firstPointRight.X), Convert.ToInt32(_firstPointRight.Y)));
                    var patientCoord2 = geometry.TransformImagePointToPatient(new Point2(Convert.ToInt32(_secondPointRight.X), Convert.ToInt32(_secondPointRight.Y)));
                    double distanceInMM = patientCoord1.Distance(patientCoord2);
                    DisTanceInMM_Right = Convert.ToDouble(distanceInMM.ToString("N3"));
                }
            }
            catch (DicomDataException)
            {
                MessageBox.Show("This Dicom File Not Suported", "Alert", MessageBoxButton.OK, MessageBoxImage.Error);
            }

The DisTanceInMM_Righ is the property I set the distance between two points and show the distance using TextBlock. I want to set after Secondpoint can it possible . I don't want to use as Margin property or Fixed place TextBlock use. Please Note I use Caliburn.Micro Framework .

A: As far as I understood you want your TextBlock to appear after second line point. If so you can use Canvas.Left and Canvas.Top attached properties on TextBlock:
<TextBlock Canvas.Left="{Binding SecondPoint_Right.X}" Canvas.Top="{Binding SecondPoint_Right.Y}" Text="{Binding Path=DisTanceInMM_Right, Mode=OneWay}" FontSize="20" Foreground="Red"></TextBlock>


text:
Q: How to find if observation within group has certain values Say that I have this MWE:
clear all
input str2 person enr_year enr_term
"a" 2000 1
"a" 2000 2
"a" 2000 2
"a" 2000 3
"a" 2000 3
"a" 2001 1
"a" 2001 2
"a" 2001 3
"a" 2002 2
"a" 2002 2
"a" 2003 2
"a" 2006 1
"a" 2006 2
"a" 2008 2
"b" 2000 2
"b" 2001 3
end

label define term 1 "Summer" 2 "Fall" 3 "Spring"
label values enr_term term

Some explanation is in order. This is school enrollment data.  person is an person, and everything needs to be done within person.
enr_year is an academic year. enr_term is an academic term. The reason that Summer and Fall come before Spring is because the year is academic year, not calendar year.
Each line in the data implicitly means that the person enrolled in the given year and term.
My task is to create two indicator variables: enr_this_spring and enr_next_fall. I can successfully get enr_this_spring. I have included my code to do so in case that logic would be helpful to figure out how to get enr_next_fall.
*These indicator variables should only be created for the observations with fall enrollment.
enr_this_spring means that the person enrolled the following spring. Because we only make this variable for the fall semester, this will be 1 if there is a spring observation in the same year. It will be 0 otherwise, even if there is a spring observation in the next year.
enr_next_fall will be 1 if there is a fall observation from the next year. As will be described below, the problem I am not sure how to overcome arises if there is a situation in which the student enrolls in the fall of x, not in the fall of x+1, but again the fall of x+n,
where n>1.
If there are two fall observations within the same year (multiple enrollment periods, perhaps the student was enrolled at two schools at the same time), they will both take on the same values.
Here is what I want to get:
clear all
input str2 person enr_year enr_term enr_this_spring enr_next_fall
"a" 2000 1  .   . // missing because not Fall
"a" 2000 2  1   1 // 1 b/c a/2000/3; 1 b/c a/2001/2
"a" 2000 2  1   1 // same reasons as line directly above
"a" 2000 3  .   . // missing because not Fall
"a" 2000 3  .   . // missing because not Fall
"a" 2001 1  .   . // missing because not Fall
"a" 2001 2  1   1 // 1 b/c a/2001/3; 1 b/c a/2002/2
"a" 2001 3  .   . // missing because not Fall
"a" 2002 2  0   1 // 0 b/c no a/2002/3; 1 b/c a/2003/2
"a" 2002 2  0   1 // same reasons as line directly above
"a" 2003 2  0   0 // 0 b/c no a/2003/2; 0 b/c no a/2004/2
"a" 2006 1  .   . // missing because not Fall
"a" 2006 2  0   0 // 0 b/c no a/2006/3; 0 b/c no a/2007/2
"a" 2008 2  0   0 // 0 b/c no a/2008/3; 0 b/c no a/2009/2
"b" 2000 2  0   0 // 0 b/c no a/2000/3; 0 b/c no a/2001/2
"b" 2001 3  .   . // missing because not Fall
end
label define term 1 "Summer" 2 "Fall" 3 "Spring"
label values enr_term term

Starting with the original data, I first can successfully get enr_this_spring as follows:
*Create indicators for if the term is spring and if term is fall
gen is_spring = enr_term == 3
gen is_fall = enr_term ==2
*Get the maximum value, within person and year
bys person enr_year: egen enr_this_spring = max(is_spring)
replace enr_this_spring=. if is_fall!=1

I am not sure how to create an indicator for if ther person enrolled next fall.
Here is what I have tried, with an explanation for why it doesn't work following the code:
*Preserve the data. We are going to process it and merge back on
preserve
*We only are concerned about fall attendance for this part
keep if enr_term==2
*We only want one observation per term, as duplicates mess up the code
bys person enr_year enr_term: keep if _n==1
*Make a variable that is a constant 1
gen one = 1
*Make a variable, enr_next_fall that is 1 if the person enrolled in the fall
* in the following observation. Note that we do this within group and sort
* by enr_year
bys person (enr_year): gen enr_next_fall = one[_n+1]
* Replace missing with 0. This only affects the final observation within group
replace enr_next_fall = 0 if missing(enr_next_fall)
*Create temporary file, to be merged on
tempfile a
save `a'
restore
*Merge on the temporary file
merge m:1 person enr_year enr_term using `a'
drop is_spring is_fall one _merge

This does not get me what I want in the cases where the person did not enroll in the fall of the next year, but came back. Maybe they got sick and missed an entire school year. How should I fix this?

A: I think I have figured it out:
clear all
input str2 person enr_year enr_term
"a" 2000 1
"a" 2000 2
"a" 2000 2
"a" 2000 3
"a" 2000 3
"a" 2001 1
"a" 2001 2
"a" 2001 3
"a" 2002 2
"a" 2002 2
"a" 2003 2
"a" 2006 1
"a" 2006 2
"a" 2008 2
"b" 2000 2
"b" 2001 3
end

label define term 1 "Summer" 2 "Fall" 3 "Spring"
label values enr_term term

*Create indicators for if the term is spring and if term is fall
gen is_spring = enr_term == 3
gen is_fall = enr_term ==2
*Get the maximum value, within person and year
bys person enr_year: egen enr_this_spring = max(is_spring)
replace enr_this_spring=. if is_fall!=1

*Create enr_next_fall variable. Merge back on
preserve
keep if enr_term==2
bys person enr_year: keep if _n==1
bys person (enr_year): gen next = enr_year[_n+1]
replace next = next - 1
gen enr_next_fall = enr_year==next
drop next
tempfile fall
save `fall'
restore
merge m:1 person enr_year using `fall'
drop _merge
replace enr_next_fall = . if enr_term!=2


text:
Q: Diffusion of a chemical species inside a Y-shaped tube I'm trying to model diffusion of a chemical species X inside a Y-shaped tube, whose diameter (thickness) is constant everywhere. The diffusion constant of X is $D$ ($\mu$m$^2$/s), so the concentration of X, denoted by $u$, follows the diffusion equation
$$\frac{\partial u}{\partial t}=D\frac{\partial^2 u}{\partial x^2},$$
except for the branch point in the center. (Here $x$ is a one-dimensional spatial coordinate.)
My question is how to numerically calculate the temporal concentration profile, correctly taking the Y-shaped geometry (especially the branch point) into account. Is there any good (and preferably simple) method for this? I'm using MATLAB for numerical simulation and I know how to numerically calculate diffusion in a one-dimensional tube. Thank you.
Note: The actual equation I'm trying to solve is
$$\frac{\partial u}{\partial t}=D\frac{\partial^2 u}{\partial x^2}-k(u-u_0),$$
where $k$ and $u_0$ are positive constants. i.e. the chemical species X can "leak"
out of the tube when $u$ is higher than the basal value $u_0$.
Note 2: The diameter of the tube is approximately 0.1 $\mu$m (or less), whereas the length of each branching tube is approximately 10 $\mu$m. The concentration of X at the far ends of the branching tubes are kept at $u_0$ (Dirichlet boundary condition). Because the tube is thin, I expect that diffusion is mostly one-dimensional except for the branch point.


text:
Q: MVC Persist Model per Browser Tab I have an MVC app and I've run into a problem with modern multitab browsers.
I have a screen that creates a model and stores it in this.TempData["MyViewModel"]
I then open the same screen in a 2nd tab and as it calls the same controller methods this.TempData["MyViewModel"] is once again set.
If I then go back to Tab 1 and refresh the page, I am presented with the data I entered in Tab 2.
Is there a way to store data in TempData uniquely per browser tab ?
I have toyed with the idea of creating a unique TempData key and persist it between requests using either the querystring or a hidden field but this seems messy.
Any ideas / advice would be most welcome. :o)

What I have so far is a concept of a 'ProcessID'.
In my first partial view I have a form with a hidden field which is loosely bound to my Model.ProcessID.  When the form is posted this hidden field ProcessID is used as the TempData key...
Example:
public sealed class MyViewModel
{
    public MyViewModel()
    {
        this.ProcessID = Guid.NewGuid().ToString();
    }

    public string ProcessId { get; set; }
    // other fields
}

Partial View 1:
@model Models.MyViewModel

@using (Ajax.BeginForm("PartialView1", "Home", new { }, new AjaxOptions() { UpdateTargetId = "myDivToUpdate" }, new { }))
{
    @Html.HiddenFor(m => m.ProcessId);

    // other fields...

    <input type="submit" value="next" />
}

public ActionResult PartialView1(FormCollection form)
{
    return this.PartialView("PartialView1", new Models.MyViewModel());
}

[HttpPost]
public ActionResult PartialView1(FormCollection form)
{
    Models.MyViewModel vm = new Models.MyViewModel();

    this.UpdateModel(vm, form);

    this.TempData[vm.ProcessId] = vm;

    return this.PartialView("PartialView2", vm);
}

In my 2nd partial view form I once again have a hidden field loosely bound to the same Model.ProcessID.  When this form is posted I can use the Model.ProcessID to retrieve my viewmodel from TempData and update it:
Partial View 2:
@model Models.MyViewModel

@using (Ajax.BeginForm("PartialView2", "Home", new { }, new AjaxOptions() { UpdateTargetId = "myDivToUpdate" }, new { }))
{
    @Html.HiddenFor(m => m.ProcessId);

    // other fields (different to partial view 1)...

    <input type="submit" value="finish" />
}

[HttpPost]
public ActionResult PartialView2(FormCollection form, Models.MyViewModel vm)
{
    vm = (this.TempData[vm.ProcessId] as Models.MyViewModel);

    this.UpdateModel(vm, form);

    return this.Json(new { result = true, message = "success" }, JsonRequestBehavior.AllowGet);
}

A: By default I believe MVC uses session state to store TempData using the SessionStateTempDataProvider and therefore each TempData will be stored in the same place for that session. Using session the only around this that I can see is to use some identifier as you suggested.
However you can implement the ITempDataProvider interface to use your own provider that could then store this data in some other form of storage (such as cookies or sql).


text:
Q: Tensor of Hom spaces over an algebra Given a field $k$ of null caracteristic, an associative/commutative/unital $k$-algebra $A$ and two free $k$-modules $M,N$, denote by $Hom_k(M,A)$ the space of $k$-linear maps from $M$ to $A$.
I want to show that the following map is injective:
$Hom_k(M,A)\otimes_A Hom_k(N,A) \longrightarrow Hom_k(M \otimes_k N,A)$
$ f \otimes_A g \mapsto \Big( v \otimes_k w \mapsto f(v)g(w)\Big)$
I might understand this in the finite dimensional case using the following string of isomorphisms
$Hom_k(V,A) \otimes_A Hom_k(W,A) \simeq (V^* \otimes_kA)\otimes_A(W^*\otimes_kA)\simeq V^* \otimes_k W^* \otimes_k A \simeq (V \otimes_k W)^* \otimes_k A \simeq Hom_k(V\otimes_kW,A) $
But for some reason I can't figure it out in the general case.
Can someone give me some hint or a reference for it ?

A: For infinite-dimensional algebras this is not true.
As it is mentioned in the comments, the claim is equivalent to the injectivity of the coordinate-wise product map $u:A^I \otimes_A A^J \to A^{I\times J}$ (where now the exponent stands for products, not coproducts).
For a counterexample, consider the commutative, unital, associative algebra $A=\Bbbk [x_i \; (i \in \mathbb{N})]/(x_i x_j \; (i,j \in \mathbb{N}))$, let $I=J=\mathbb{N}$ and $\alpha = (x_i)_{i \in \mathbb{N}} \in A^I$. Then clearly $u(\alpha \otimes \alpha)=0$, but one can prove that $\alpha \otimes \alpha$ is nonzero in $A^I \otimes_A A^I$.
Indeed, $A^I \otimes_A A^I = (A^I \otimes_{\Bbbk} A^I)/U$, where $U$ is spanned by the elements of the form
$$\lambda x_i \otimes \mu - \lambda \otimes x_i \mu,\quad
\lambda x_i \otimes \beta,\quad
\beta \otimes x_i \lambda$$
for all $i \in \mathbb{N}$, $\lambda, \mu\in \Bbbk^I$, $\beta \in N^I$ denoting $N=\mathrm{Span}(x_k \mid k \in \mathbb{N})$. These elements do not span $\alpha \otimes \alpha$ in $A^I \otimes_{\Bbbk} A^I$.
(Edit, response to the comment: If $A$ is finite-dimensional then $u$ is injective. Indeed, given a $\Bbbk$-basis $b_1, \dots, b_d$ in $A$, the elements of the form $\lambda \otimes \mu\, b_k$ span $A^I \otimes_A A^J$, where $k=1,\dots,d$, $\lambda \in \Bbbk^I$, $\mu \in \Bbbk^J$. Hence it is enough to prove the statement for $A=\Bbbk$.
Assume that $u$ vanishes on the nonzero element $\sum_{k=1}^m \lambda^{(k)} \otimes \mu^{(k)}$ where $\lambda^{(k)},\mu^{(k)}$ are as above. We may assume that $\lambda^{(1)},\dots,\lambda^{(m)}$ are independent and similarly for $\mu$. Consequently, $\{(\lambda_i^{(k)})_k\mid i\in I\}$ spans $\Bbbk^m$ by a rank-argument.
On the other hand, as $u$ vanishes on the sum, we have
$\sum_{k=1}^m \lambda_i^{(k)}\cdot \mu_j^{(k)}=0$ for all $i,j$, i.e. $(\mu_j^{(k)})_k$ is orthogonal to a spanning set with respect to the obvious bilinear form on $\Bbbk^m$. This is a contradiction.)


text:
Q: about tables linking in sql server I have a table t1 in sql with following fields (id,s_name)
id   s_name
1    priya
2    radhika
3    aniket
4    abhiskek

and another table t2 with following fields
(id,s_name,guide)

id   s_name   guide
1    priya    Mr.XYZ
4    abhishek Mr.ABC

I want to form a single table joining these both as follow
id   s_name   guide
1    priya    Mr.XYZ
2    radhika  NULL
3    aniket   NULL
4    abhishek Mr.ABC

Please help me find out an appropriate SQL QUERY for the above

A: SELECT a.id, a.s_name, b.guide
FROM t1 a
LEFT JOIN t2 b ON a.id = b.id
ORDER BY a.id

A: CREATE TABLE #Table1
    ([id] int, [s_name] varchar(8))
;

INSERT INTO #Table1
    ([id], [s_name])
VALUES
    (1, 'priya'),
    (2, 'radhika'),
    (3, 'aniket'),
    (4, 'abhiskek')
;
CREATE TABLE #Table122
    ([id] int, [s_name] varchar(8), [guide] varchar(6))
;

INSERT INTO #Table122
    ([id], [s_name], [guide])
VALUES

    ('1', 'priya', 'Mr.XYZ'),
    ('4', 'abhishek', 'Mr.ABC')
;
select a.id,a.s_name,guide from #Table1 A left join
#Table122 B on a.id=b.id

output
id  s_name       guide
1   priya        Mr.XYZ
2   radhika      null
3   aniket       NULL
4   abhiskek    Mr.ABC


text:
Q: Can Selenium and Chrome buildpack installs be cached on HerokuCI? I've just started using HerokuCI. I have a few Selenium tests so I've added buildpacks in my app.json.
{
  "buildpacks": [
    { "url": "heroku/ruby" }
  ],
  "environments": {
    "test": {
      "addons": ["heroku-postgresql:in-dyno", "heroku-redis:in-dyno"],
      "buildpacks": [
        { "url": "heroku/ruby" },
        { "url": "https://github.com/notvad/heroku-buildpack-selenium" },
        { "url": "https://github.com/heroku/heroku-buildpack-chromedriver" },
        { "url": "https://github.com/heroku/heroku-buildpack-google-chrome" }
      ],
      "env": {
        "REDIS_PROVIDER": "REDIS_URL",
        "RAILS_ENV": "test",
        "RACK_ENV": "test",
        "MALLOC_ARENA_MAX": 2,
        "LANG": "en_US.UTF-8",
        "TEST_API": 1
      },
      "scripts": {
        "test-setup": "./bin/setup-cc-test-reporter",
        "test": "./bin/test-with-cc-test-reporter"
      }
    }
  }
}

These keep getting rebuilt along with all their dependencies.
-----> Selenium app detected
bash: /tmp/buildpacks/b5ae60a477f2ba582d00a4ba23348059d40dea69cea6d982947f7c6afa72d2b8d69252449d43cbcf97a23341fd57300a3fef3224ace95482e1c0deaf8a844e4d/export: No such file or directory
bash: /tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/export: No such file or directory
-----> Updating apt caches
       Hit:1 http://apt.postgresql.org/pub/repos/apt bionic-pgdg InRelease
       Hit:2 http://archive.ubuntu.com/ubuntu bionic InRelease
       Hit:3 http://archive.ubuntu.com/ubuntu bionic-security InRelease
       Hit:4 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
       Reading package lists...
-----> Fetching .debs for xserver-xorg-core libgl1-mesa-dri xvfb libglide3 xfs unzip
       Reading package lists...
       Building dependency tree...
       Package xfs is not available, but is referred to by another package.
       This may mean that the package is missing, has been obsoleted, or
       is only available from another source

E: Package 'xfs' has no installation candidate
-----> Installing adwaita-icon-theme_3.28.0-1ubuntu1_all.deb
-----> Installing at-spi2-core_2.28.0-1_amd64.deb

...and so on...

-----> Downloading and installing Selenium
-----> Writing profile script
-----> chromedriver app detected
bash: /tmp/buildpacks/b5ae60a477f2ba582d00a4ba23348059d40dea69cea6d982947f7c6afa72d2b8d69252449d43cbcf97a23341fd57300a3fef3224ace95482e1c0deaf8a844e4d/export: No such file or directory
bash: /tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/export: No such file or directory
bash: /tmp/buildpacks/f55d0db8af2b8c70f2c0e028ef5430955852d9e4f07a06e333e54eb5264a81b9d1e77d1cc02851b4c7da30f6da47b13959e18a24c630212b899920d05f32a566/export: No such file or directory
-----> Looking up latest chromedriver version...
-----> Downloading chromedriver v2.43...
Archive:  /tmp/chromedriver.zip
  inflating: /app/.chromedriver/bin/chromedriver
-----> Creating chromedriver export scripts...
-----> Google Chrome app detected
bash: /tmp/buildpacks/b5ae60a477f2ba582d00a4ba23348059d40dea69cea6d982947f7c6afa72d2b8d69252449d43cbcf97a23341fd57300a3fef3224ace95482e1c0deaf8a844e4d/export: No such file or directory
bash: /tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/export: No such file or directory
bash: /tmp/buildpacks/f55d0db8af2b8c70f2c0e028ef5430955852d9e4f07a06e333e54eb5264a81b9d1e77d1cc02851b4c7da30f6da47b13959e18a24c630212b899920d05f32a566/export: No such file or directory
bash: /tmp/buildpacks/27353aa3b5edb2f8361186206e863f5d481f02805d02f0efdec439f3d30349a4fbdad2951af33a0492023fb0d90d26dafda6fe76f1b2d34f68564a98545f7022/export: No such file or directory
-----> Installing Google Chrome from the stable channel.
-----> Updating apt caches
       Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease
       Hit:2 http://apt.postgresql.org/pub/repos/apt bionic-pgdg InRelease
       Hit:3 http://archive.ubuntu.com/ubuntu bionic-security InRelease
       Hit:4 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
       Reading package lists...
-----> Fetching .debs for gconf-service

...and so on...

This is taking up most of the test run time.
Can these installs be cached?

A: If you have the caches enabled as described here it does not seem like there is much more you can do to cache the installs. If this is a serious problem you could always point to local packages that you cloned from the remote repos to speed things up.

A: After various search and try, I bring good news.
The key issue is your errors in log files, like:
bash: /tmp/buildpacks/b5ae60a477f2ba582d00a4ba23348059d40dea69cea6d982947f7c6afa72d2b8d69252449d43cbcf97a23341fd57300a3fef3224ace95482e1c0deaf8a844e4d/export: No such file or directory

This auto-generated directory is obviously a cache directory one, which is generated automatically when not fixed.
Fore instance, this can be confirmed inside the heroku-buildpack-selenium buildpack, defined in your app.json file:
# parse and derive params
BUILD_DIR=$1
CACHE_DIR=$2
LP_DIR=`cd $(dirname $0); cd ..; pwd`

It is confirmed by this official documentation I found:

The contents of CACHE_DIR will be persisted between builds. You can
  cache the results of long processes like dependency resolution here to
  speed up future builds.

So the key solution is to define this CACHE_DIR variable within your installation; so I guess it is either directly in your app.json file, or directly in your GitHub Hook.
Let me know if you need further help.


text:
Q: Random для ArrayList Сделал заполнение коллекции рандомными элементами. Вопрос, как добавить в рандом буквы? И задавать длину элемента?
static void Main(string[] args)
    {
        Console.Write("Введит количество элементов коллекции: ");
        int i = Int32.Parse(Console.ReadLine());
        ArrayList list = NewCollection(i);
        WriteMyCollection(list);
        Console.ReadLine();
    }
    public static ArrayList NewCollection(int i)
    {
        Random rand = new Random();
        ArrayList arr = new ArrayList();

        for (int j = 0; j < i; j++)
            arr.Add(rand.Next());
        return arr;
    }

    public static void WriteMyCollection(ArrayList arr)
    {
        foreach (int a in arr)
            Console.Write("{0}\t", a);
        Console.WriteLine("\n");
    }

A: Ну например так:
static void Main(string[] args)
{
    ArrayList al = new ArrayList();
    var collectionLength = 20;
    for (int i = 0; i < collectionLength; i++)
        al.Add(CreateRandomString());
    foreach (var s in al)
        Console.WriteLine(s);
}

static Random r = new Random();
static int maxStringLength = 10;

static string chars = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static string CreateRandomString()
{
    var length = r.Next(maxStringLength) + 1;
    var sb = new StringBuilder(length);
    for (int i = 0; i < length; i++)
    {
        var randomIndex = r.Next(chars.Length);
        sb.Append(chars[randomIndex]);
    }
    return sb.ToString();
}

У меня вывело:

1JE
  I0v7e4Tz4
  AYq7QLXc
  a17EEP
  25Kke
  A5cNhWu5D6
  tbduDUIhO0
  QAvQh
  2OOJsEnkT
  t
  H
  wVc0r
  Vn012q
  7eChqEG2
  g00xP9JQe
  6FW
  nknHSDDMG2
  g6gL2l1rG
  30UKMEj
  Lj60jeX2


text:
Q: SQL QUERY JOIN with multiple conditions Sorry for this question, but I can't find a solution to this simple problem.
I have 2 tables:
TABLE A
R_ID integer
CID1 integer
CID2 integer
CID3 integer
CID4 integer

TABLE C
CID integer
NAME varchar(50)

what I'm trying to do is a query that will output, for every table A row, the name of CID1,  CID2 and so on, considering that CID1 has always a value, CID2, CID3 and CID4 could be NULL, I can't use UNION and in my s
This is my starting point:
SELECT a.R_ID, c.NAME
FROM A a, C c
WHERE (a.CID1 = c.CID or a.CID2 = c.CID or a.CID3 = c.CID or a.CID4 = c.CID)

But as you can see, it only works if all CIDs are valued, otherwise some results will have a blank NAME field.
Any tip on how to remove unwanted rows will be really appreciated.
EDIT :
I have to print a list of: Room # - name of the student in that room, so the outputted table must be in the form : R_ID, NAME
Suppose:
TABLE A
1,1,2,NULL,NULL
2,3,NULL,NULL,NULL
3,4,NULL,NULL,NULL

TABLE B
1, Mark
2, John
3, Steve
4, Nick

My target is to obtain a table like this:
R_ID - NAME
1 - Mark
1 - John
2 - Steve
3 - Nick

What I got is:
1 - Mark
1 - John
1 -
1 -
2 - Steve
2 -
2 -
2 -
3 - Nick
3 -
3 -
3 -

The solution of 4 LEFT JOINs is not applicable because I can't use NAME1,NAME2 and so on, but only 1 field NAME.
A query like:
SELECT r.R_ID, c.NAME
FROM A a LEFT JOIN C c on a.CID1 = c.CID
LEFT JOIN C as c1 on a.CID2 = c1.CID
LEFT JOIN C as c2 on a.CID3 = c2.CID
LEFT JOIN C as c3 on a.CID4 = c3.CID

will output:
1 - Mark
2 - Steve
3 - Nick

The solution NAME is not NULL  works perfectly on SQLFiddle, but still presents rows with no name on my mysql 5.5.15 (also tried on firebird 2.5, the only other DB Server I've on my pc, but with the same result)

A: You need 3 separate joins for each CID column in TableA.
SELECT
  R_ID,

  c1.Name As CID1Name,
  c2.Name As CID2Name,
  c3.Name As CID3Name
FROM
  TableA a
  LEFT JOIN TableC c1 ON a.CID1 = c1.CID
  LEFT JOIN TableC c2 ON a.CID2 = c2.CID
  LEFT JOIN TableC c3 ON a.CID3 = c3.CID

A: Your query returns a name for every cid value, see SQLFiddle
What might be an issue are empty or NULL entries in the name columns, see SQLFiddle
You can fix this with a simple join on tables a and c and an additional where clause
select a.r_id, c.name
from a
join c on c.cid in (a.cid1, a.cid2, a.cid3, a.cid4)
where c.name is not null

SQLFiddle
Of course, you can achieve the same with your implicit join by adding the same clause
SELECT a.R_ID, c.NAME
FROM A a, C c
WHERE (a.CID1 = c.CID or a.CID2 = c.CID or a.CID3 = c.CID or a.CID4 = c.CID)
      and c.name is not null

SQLFiddle
If you have empty strings instead of NULL values, you can wrap name in trim to cope with whitespace too
and trim(c.name) <> ''


text:
Q: Fail to launch ghcid in terminal in VSCode -----showing terminated with exit code: 1 I'm very new to vscode as well as ghcid. When I follow the instruction to open the Command Palette and type " Start Ghcid", then it shows
" The terminal process "ghcid '--outputfile=/var/folders/4k/0c49wtss7dgb9n872y99hzh40000gn/T/ghcid-15bcb70c9b4c8926f1ca.txt'" terminated with exit code: 1." on the bottom right.
I have googled it, but the issue is only related with the special characters in the name which is not relate with my problem. I can open my terminal successfully, only failed when I try to launch the ghcid.
Since I just start to learn Haskell by myself, if you could answer my question step by step, I would really appreciate it!!!! Thanks.