text:
Q: Strong Semaphore Queuing Discipline and Starvation In William Stallings' book on Operating Systems, he defines a strong semaphore as one that has a FIFO queuing discipline, and a weak semaphore one that is unordered. Surely there are other queuing disciplines for strong semaphores, such as by priority? Or would this no longer be a strong semaphore, since starvation would become possible? (Stallings says that strong semaphores do not allow for starvation.) Is the primary distinction between strong and weak ordered/unordered, or starvation possible/impossible?

A: Yes, one non-FIFO non-starving possibility (among many) is to select the next process in a round-robin manner. For example, if the order is 1, 2, 3, 4, and while 1 is holding the semaphore, 4 and then 3 request it, then the next process up is 3. No process P starves because, after each request of P, each other process has at most one critical section before P's request is granted.
Definitions of "strong semaphore" in the first pages of hits from Google are split between "no starvation" and "FIFO". Which one is "right" is a matter of taste – given this mess (and the general overuse of strong as an adjective in mathematical writing), I'd probably use neither.

A: When it comes to the literature on semaphores, I have never seen (with my limited knowledge) anyone using FIFO or some form of ordering as the criteria for weak/strong categorization. In fact, starvation-freedom is not always the criteria either. The initial literatures (due to viz. Morris('79), Martin and J. R. Burch('85), Udding('86), Friedberg and Peterson('87), and Haldar and Subramanian('88)) used certain characteristics of 'P' and 'V' operations to define weak-semaphore. Interestingly, all of the definitions from the cited researchers eventually imply possible presence of starvation in case of weak semaphores. Further, though FIFO guarantees starvation-freedom, referring to the term FIFO or some form of ordering, in my opinion, restricts the behavior of the semaphore. One form of restriction could be that, for example, a FIFO ordering would imply that a semaphore has some kind of buffer attached to it in order to keep track of the blocked processes/threads on the 'P' operation. For hardware implementation of semaphores, this definition might be too restrictive. Another form of restrictions could be that instead of considering all possible ordering schemes with same bounded overtaking by k (i.e. no process will be overtaken more than k times), one would be restricted to consider each scheme as one different kind of semaphore. Thus, my personal opinion is to define a weak-semaphore as one that does NOT guarantee starvation-freedom (but guarantees dead-lock-freedom). However, if you're more deep into research-grade activities, then by all means feel free to use more mathematical or/and fine-grained definitions as you prefer.

A: I think there is no starvation with a priority queue with a predefined priority on queue elements. As you can see it's just a regular queue except the next element has the highest priority. So if you implement priorities with FIFO logic (first in has the highest priority) there will be no starvation. Otherwise it can cause starvation.


text:
Q: Removing Ubuntu from Triple Boot Windows OS? So if I'm currently running a triple boot system of Windows, Xubuntu and Ubuntu would I follow these steps below:

*

*Boot Gparted or Ubuntu installation USB/CD and run Gparted.

*Turn Swap off.

*Unmount desired partition.

*Delete desired partition which will result in Unallocated partition.

*Turn Swap back on.

*Resize remaining partitions or leave Unallocated partition for a later install.

*Update Grub.

*Reboot.

Or did I forget something since I have yet to find a particular topic regarding the removal of Ubuntu from a Windows triple boot system?

A: Insert a live CD or USB for your Linux distribution and start up its partition manager (like Gparted). Find your Windows partition in Gparted's menu—it'll be listed as an NTFS drive.
Right-click on that Windows partition and choose "Delete" from the menu. Your machine may have other Windows-related partitions as well, like "System Reserved" and recovery partitions. If you want, you can delete these as well (but make sure you have recovery discs handy if you're going to delete a recovery partition).
Right-click on your Linux partition and choose "Resize/Move." Resize it so it takes up the rest of the now-free space on your drive.
Click the "Apply All Operations" button in the toolbar to perform the selected tasks. It may give you a warning saying that your computer may not boot, but with most Linux installations this shouldn't be a problem (though if it is, check out this article to fix it). This process may take some time, so let it be!
If you want to clean up, use
sudo update-grub

to remove them.

A: You can use the free tool OS un-installer to remove an os from your triple boot system. It's easy to use too
To install,
Download/Install OS-Uninstaller in Ubuntu :
either add 'ppa:yannubuntu/boot-repair' to your Software Sources via the Software Centre or, for speeds-sake, add it using a new Terminal session:
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update && sudo apt-get install -y os-uninstaller

OS-Uninstaller can be installed & used from any Ubuntu session (normal session, or live-CD, or live-USB).
PPA packages are available for current versions of Ubuntu.
Use OS-Uninstaller:
Launch it from System->Administration->OS-Uninstaller menu if you use Gnome, or search "os" in the dash if you use Unity. Then follow the menus...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delay in showing live view as diffuse content of SCNMaterial for sphere geometry I want to show a live spherical image using SceneKit. I am using SCNMaterial's diffuse content to show it but there is some delay in showing live view. Following code is my attempt to accomplish it. Please guide if you come across such case.
    @IBOutlet weak var sceneView: SCNView!
    let scene = SCNScene()

    sceneView.scene = scene
    sceneView.backgroundColor = UIColor.black

    let material = SCNMaterial()
    material.diffuse.mipFilter = .linear
    material.diffuse.magnificationFilter = .linear
    material.diffuse.contentsTransform = SCNMatrix4MakeScale(-1, 1, 1)
    material.diffuse.wrapS = .repeat
    material.cullMode = .front

    let sphere = SCNSphere(radius: 8)
    sphere.segmentCount = 300

    httpConnection.startLiveView { (data) in
        DispatchQueue.main.async {
           let image = UIImage(data: data!)
            material.diffuse.contents = image
        }
    }

    sphere.firstMaterial = material

    let sphereNode = SCNNode()
    sphereNode.geometry = sphere

    scene.rootNode.addChildNode(sphereNode)

in httpConnection.startLiveView block I am getting live view's image data.


text:
Q: Button on click declared in js doesn't work I am trying to create a new p tag after the button is clicked yet nothing happens after it's clicked:
(function() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 403) {
      var heading = document.getElementById("head");
      var para = document.createElement("P");
      para.innerHTML = "Accept the T&Cs to Continue";
      var button = document.createElement("BUTTON"); // button created here
      button.classList.add("theButton");
      var theButton = document.getElementsByClassName("theButton");
      theButton.onclick = function() { // button doesn't work onclick
        var newP = document.createElement("P");
        newP.innerHTML = "DONE";
        heading.appendChild(newP);
        heading.appendChild(para);
        heading.appendChild(button);
      };
    }
  };
  xhttp.open("GET", "/content.ajax", true);
  xhttp.send();
})();

Can someone help me with this?

A: I´m assuming that document.getElementsByClassName("theButton") should get your button, because it uses the same class.

*

*That´s unnecessary because you already have a reference to your button.

*Your button (and para) did not get attached to the DOM, so getElementsByClassName would return an empty result.

*document.getElementsByClassName() returns a HTMLCollection (a list), not a single element. You can´t add a listener function to a HTMLCollection.

*The button only gets added to the DOM when it is clicked. But you can only click it after it got added to the DOM.

Also you should consider using addEventListener because your listener can´t be overwritten that way and you can add multiple listeners.
(function () {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if(this.readyState ==4 && this.status == 403){
            var heading = document.getElementById("head");
            var para = document.createElement("P");
            para.innerHTML = "Accept the T&Cs to Continue";

            var button = document.createElement("BUTTON"); // button created here
            button.classList.add("theButton");
            button.addEventListener("click", function() {
                var newP = document.createElement("P");
                newP.innerHTML = "DONE";
                heading.appendChild(newP);
            });

            heading.appendChild(para);
            heading.appendChild(button);
        }
    };
    xhttp.open("GET","/content.ajax",true);
    xhttp.send();
})();


text:
Q: XPath expression of serialized XML file I have a custom object that I have serialized to XML.
The class structure looks like this:
public partial class MyWebForm : System.Web.UI.Page
{
    [DataContract, Serializable]
    public class MyObjectRoot
    {
        public MyObjectRoot(List<MyObject> myobjects)
        {
            this.Objects = myobjects;
        }

        [DataMember]
        public List<MyObject> Objects { get; set; }
    }

    [DataContract, Serializable]
    public class MyObject
    {
        public MyObject(string property1, string property2, string property3)
        {
            this.Property1 = property1;
            this.Property2 = property2;
            this.Property3 = property3;
        }

        [DataMember]
        public string Property1 { get; set; }

        [DataMember]
        public string Property2 { get; set; }

        [DataMember]
        public string Property2 { get; set; }
    }
}

The serialized XML looks like this:
`<?xml version="1.0" encoding="utf-8"?>
 <MyWebForm.MyObjectRoot xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyApplication">
<Objects>
    <MyWebForm.MyObject>
      <Property1>Testing123</Property1>
      <Property2>Testing456</Property2>
      <Property3>Testing789</Property3>
    </MyWebForm.MyObject>
  </Objects>
</MyWebForm.MyObjectRoot >`

Can I use XPath to get the nodes on a serialized XML file? If so what would be the expression to grab each property of my object, aka the values in my MyWebForm.MyObject?
So far I have tried this and no luck:
XPath("MyWebForm.MyObjectRoot/Objects/MyWebForm.MyObject/Property1[1]")

A: This xpath //*[starts-with(name(), 'Property')] should work.
using  Linq2Xml :
var xDoc = XDocument.Parse(xmlstring); //or XDocument.Load(xmlfile);
var properties = xDoc.XPathSelectElements("//*[starts-with(name(), 'Property')]")
                     .ToList();

A: Here is an Xpath statement that will get the values of all the children of MyWebForm.MyObject
MyWebForm.MyObjectRoot/Objects/MyWebForm.MyObject/*/text()


text:
Q: Android Emulator taking up whole screen I am doing some Android programming tutorials, but when the emulator opens up it takes up most of the screen, which is much bigger than a normal phone looks like.
Here is a picture of my screen: http://i.imgur.com/gEuHs.jpg
And it doesn't let me resize the emulator.  Are all emulators this big, and is there any way to make it smaller or resize it?

A: You can use a smaller resolution.
Alternatively, if you want to keep the same resolution, you can change the property "Abstracted LCD density" and check "Scale display to real size" when you start the emulator. Increasing the density will make the emulator window proportionally smaller.

A: You can try getting a bigger desktop, or adjust scale of window when it starts. Also, i don't recommend changing the dpi because it blurs the icons (framework-res.apk has only mdpi and hdpi drawables i think).


text:
Q: Cannot execute shell commands in bash script  #!/bin/bash
#general security monitoring
PATH=/var/log
echo "The IP addresses of users with more than 2 failed login attempts are:"
IPFAILEDLOGINS=$(grep "Failed password" /var/log/secure | cut -d: -f4 | awk '{print $6}' | uniq -c | awk '{if ($1>=2) print $2}')
echo "$IPFAILEDLOGINS"

RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
echo "The current rsyslog clients are: $RSYSLOGCLIENTS"

error: ./securityanalysis.sh: line 7: find: command not found
find is located under /bin, which is included in my PATH. I also put the directory this script was being executed in into the PATH but it didn't make a difference.
Replacing the echo.. line with eval $RSYSLOGCLIENTS also gave me the same error.
Can someone please explain what is happening?
Note: I assume this is extremely bad practice, but this script is located in the home directory of root. Could this have something to do with it?

A:
find is located under /bin, which is included in my PATH

No, it isn't.  Your PATH is redefined in line 3 of the script to be:
PATH=/var/log

Observe that the find command works before but not after PATH is reassigned:
$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
$ PATH=/var/log
$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
bash: find: command not found

The general lesson here is, when defining shell variables for your script, never use all capitals.  The shell uses all caps for its important variables, like PATH.  You don't want to overwrite them.  Use lower or, at least, mixed case for your internal script variables.
For example, the path variable is assigned a value and it does not affect the ability of the shell to find find:
$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
$ path=/var/log
$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
$

In shell, variable names are case-sensitive and, therefore, PATH and path are separate and independent variables.


text:
Q: Calculating the sum of a series? This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:
sum = 0
k = 1
while k <= 0.0001:
     if k % 2 == 1:
       sum = sum + 1.0/k
     else:
      sum = sum - 1.0/k
 k = k + 1
 print()

This is my assignment :

Create a python program named sumseries.py that does the following:
  Put comments at the top of your program with your name, date, and
  description of what the program does.
Write a program to calculate and display the sum of the series:
1 - 1/2 + 1/3 - 1/4 + ...
until a term is reached that is less than 0.0001.

The answer with 10,000 iterations appears to be 0.6930971830599583
I ran the program with 1,000,000,000 (billion) iterations and came up with a number of 0.6931471810606472. I need to create a loop to programmably create the series.

A: Actually, you could write this shorter:
Answer = sum(1.0 / k if k % 2 else -1.0 / k for k in range(1, 10001))

What this code does:

*

*the innermost part is a generator expression, which computes the elements of a series 'on the fly'

*

*1.0 / k if k % 2 else -1.0 / k results in 1.0 / k if k is odd and -1.0 / k otherwise (a - b is the same as a + (-b))

*for k in range(1, 10001) goes through all ks in range from 1 (included) to 10001 (excluded)

*sum can compute the sum of any sequence (any iterable, to be precise), be it a list, a tuple, or a generator expression

The same without generator expressions:
Answer = 0
for k in range(1, 10001):
    if k % 2:
        Answer += 1.0 / k
    else:
        Answer -= 1.0 / k

    # or simply:
    # Answer += 1.0 / k if k % 2 else -1.0 / k

A: You're  almost there, all you need to do is to replace
while k <= 0.0001:

with:
 while term <= 0.0001:

term is naturally 1/k

A: To make the teacher happy, you must follow the details of the problem, as well as the spirit of the problem. The problem clearly states to print the sum, not all the partial sums. You will anger the teacher by submitting a solution that spews 10000 lines of crap not requested.
Some have suggested pre-calculating a loop limit of 10000, but that was not the requested algorithm. Instead, one is to calculate successive terms (1, -1/2, 1/3, -1/4, ...) until reaching a term less than 0.0001.
The reason the problem was specified that way is that one ends up with a more generally useful program, applicable to a wide class of term formulas. Not a fragile one that gets the wrong answer if the term formula is changed from (-1)**(k-1)/k, to say 1/k or 1/k^2.
The teacher's wording "term less than 0.0001" is imprecise and assumed some math knowledge. They want the magnitude (absolute value) of the term to be less than 0.0001. Otherwise, iteration would stop at the second term -1/2, as someone pointed out.
So, this answer would not be complete without a pompous pedantic solution that skips ahead a chapter. ;) Note that previous some answers will not work in Python2.x without a conversion to float.
def term(k):
    return (-1)**(k - 1) / float(k)

err = 0.0001

def terms():
    k = 1
    t = term(k)
    while abs(t) >= err:
        yield t
        k += 1
        t = term(k)

print(sum(terms()))

A: Here is the answer your teacher is looking for for full credit.
until < .0001 means while >= 0.0001  This modifies your code the least, so makes it a correction of what you wrote
sum = 0
k = 1
while 1.0/k >= 0.0001:
     if k % 2 == 1:
       sum = sum + 1.0/k
     else:
       sum = sum - 1.0/k
     k = k + 1
print(sum)

A: Absolutly simplest way would be the following
sum((-1)**(k) / k for k in range(1, 10001))


text:
Q: Multiple Windows ( or Multiple Boxes actings as psuedo multi window ) in Pygame Hello I am new to python, but I do have some experience in Visual Basic
I am trying to code a (preferably as cross-platform as possible) program in Python with the 'pygame' library, and I want it to have several different simultaneous windows.
I have looked extensively on the internet for ways to do this, with many different options, but no results. My attempts have been such:

*

*I originally tried to find a way to make multiple windows but a similar question on this site clarified that as a result of pygame being based off of SDL, this was not possible, thus I had to "fake" it.

*My second idea was to have one big transparent window with smaller surface objects within to give the illusion of multiple windows, but no matter what I tried (transparency key, surface alpha, filling with a transparent colour) the window remained a thoroughly non-transparent black.

*The third idea I found was again to "fake" transparency by taking a screenshot of the image behind the window and putting that as the surface object background, but I have not found a way to code that.
So my question is how I might be able to create/fake a multiple window program? Yes, tall order I know, but to make it taller, may I ask that you explain any possible answers with a decent amount of explanation?
P.S. Bonus Points if you can find a way so that when the "transparent" part of the display surface is clicked, the whole thing minimizes (so far the only ways I've found draw a rectangle around the desired target and check for collisions but that wouldn't work for me as that would be triggered anywhere you click)
EDIT: Any possible solutions do not have to be specifically in pygame, I just mentioned that so that you might appreciate what libraries I'm working with
EDIT: Thank you user 3424423 for your answer, I have installed PyQt and I am able to take screenshots, save them to a directory and blit them to the pygame window. The only problem I have is that the screenshot includes the program's own window, I coded it so the first image is taken before the window is created, but even then, afterwards the screenshots displayed on the window will include itself, so its not truly 'transparent'. Any ideas?


text:
Q: SPFX web part to add Text and show it inside a Popup when clicking on a button I am trying to achieve this using SPFX web part:-

*

*The web part will render a Button and has a text field inside its settings.

*The user add the Web Part >> edit it >> enter the text inside the text field (inside the setting page) >> save the web part>> then the web part will render a button >> if the user clicks on the button a popup will be shown with the entered text.
Now I found this link @ https://www.c-sharpcorner.com/article/conecpt-of-react-portal-in-spfx/ which almost achieves what I am looking for, except that the Popup text inside the example is been hard-coded inside the .tsx file.. so what are the steps to make the Popup text configurable inside the web part settings instead of been hard-coded?
Thanks
Here is my ReactPortalWebPart.ts file:-
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import * as strings from 'ReactPortalWebPartStrings';
import ReactPortal from './components/ReactPortal';
import { IReactPortalProps } from './components/IReactPortalProps';

export interface IReactPortalWebPartProps {
  description: string;
}

export default class ReactPortalWebPart extends BaseClientSideWebPart<IReactPortalWebPartProps> {

  public render(): void {
    const element: React.ReactElement<IReactPortalProps> = React.createElement(
      ReactPortal,
      {
        description: this.properties.description
      }
    );

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

and here is the ReactPortal.tsx:-
import * as React from 'react';
    import { IReactPortalProps } from './IReactPortalProps';
    import Myportal from "./Myportal";
    export default class ReactPortal extends React.Component<IReactPortalProps, {}> {
      public render(): React.ReactElement<IReactPortalProps> {
        return (

          <Myportal/>

        );
      }
    }

Here is the Myportal.tsx:-
    import* as React from "react";
    import usePortal from "react-cool-portal";
    import "./mystyle.scss";
    const  Myportal = () => {
     // const { Portal } = usePortal({ containerId: "my-portal-root" });
      const { Portal, show, hide } = usePortal({ defaultShow: false,containerId:"my-portal-root" });
      const handleClickBackdrop = (e: React.MouseEvent) => {
        const { id } = e.target as HTMLDivElement;
        if (id === "modal") hide();
      };

      return (

          <button className="btn" onClick={show} type="button">
            Who we are
          </button>

          <button className="btn" onClick={show} type="button">
            Our value
          </button>
          <Portal>

                  <button
                    className="modal-close"
                    onClick={hide}
                    type="button"
                    aria-label="Close"
                  >
                    ×
                  </button>

 Who we are

.................................................

Our overriding purpose is to dramatically improve the reliability, efficiency........

          </Portal>

      );
    };
    export default Myportal;

A: I think you need to re-write MyPortal as a React Component; bellow I'm tried written some example about this change that needed on MyPortal.tsx and ReactPortal.tsx, but I do not test then.
ReactPortal.tsx:
import * as React from 'react';
    import { IReactPortalProps } from './IReactPortalProps';
    import { IMyportalProps } from './IMyportalProps';
    import Myportal from "./Myportal";
    export default class ReactPortal extends React.Component<IReactPortalProps, {}> {
      public render(): React.ReactElement<IReactPortalProps, IMyportalProps> {
        return (

          <Myportal title="Who we are" body="Our overriding purpose is to dramatically improve the reliability, efficiency........"/>

        );
      }
    }

MyPortal.tsx
    import* as React from "react";
    import usePortal from "react-cool-portal";
    import "./mystyle.scss";
    export interface IMyportalProps {
       title: string;
       body: string
    }
    class Myportal extends React.Component
<IMyportalProps> {
       constructor(props: IUnderstandStateComponentProps) {
       super(props);
    }
    public render(): React.ReactElement
    <IMyportalProps> {
      const { Portal, show, hide } = usePortal({ defaultShow: false,containerId:"my-portal-root" });
      const handleClickBackdrop = (e: React.MouseEvent) => {
        const { id } = e.target as HTMLDivElement;
        if (id === "modal") hide();
      };

      return (

          <button className="btn" onClick={show} type="button">
            Who we are
          </button>

          <button className="btn" onClick={show} type="button">
            Our value
          </button>
          <Portal>

                  <button
                    className="modal-close"
                    onClick={hide}
                    type="button"
                    aria-label="Close"
                  >
                    ×
                  </button>

{this.props.title}

.................................................

{this.props.body}

          </Portal>

      );
    };

A: My attempt :)
The idea is, you pass the "description" from the web part down to the dialog.
Please read the link above, how to pass properties in React from parent to the child components (or some basic React tutorial), it is highly recommended if you have chosen to work with SPFx using React.
Please note that an easier approach to create dialogs in SPFx coulod be, to use the Microsoft Fluent UI library, it works great with SPFx, has many tutorials, supports SharePoint themes, etc. In particular, it has the "Dialog" component built-in, among dozens of other useful components and controls.
Anyway, here we go with 'react-cool-portal'. Check out the comments in the code below.
ReactPortal.tsx
import * as React from 'react';
    import { IReactPortalProps } from './IReactPortalProps';
    import Myportal from "./Myportal";
    export default class ReactPortal extends React.Component<IReactPortalProps, {}> {

      // pass further the parameter that was received from the web part.
      // The "description was passed to "ReactPortal" from WebPart with:
      // React.createElement(
      //   ReactPortal,
      //   {
      //     description: this.properties.description
      //   }

      public render(): React.ReactElement<IReactPortalProps> {
        return (

          <Myportal description={this.props.description} />

        );
      }
    }

Myportal.tsx
    import* as React from "react";
    import usePortal from "react-cool-portal";
    import "./mystyle.scss";

    // accept properties (added "props" argument)
    // and use it below in HTML {props.description}

    const  Myportal = (props) => {
     // const { Portal } = usePortal({ containerId: "my-portal-root" });
      const { Portal, show, hide } = usePortal({ defaultShow: false,containerId:"my-portal-root" });
      const handleClickBackdrop = (e: React.MouseEvent) => {
        const { id } = e.target as HTMLDivElement;
        if (id === "modal") hide();
      };

      return (

          <button className="btn" onClick={show} type="button">
            Who we are
          </button>

          <button className="btn" onClick={show} type="button">
            Our value
          </button>
          <Portal>

                  <button
                    className="modal-close"
                    onClick={hide}
                    type="button"
                    aria-label="Close"
                  >
                    ×
                  </button>

 Who we are

{props.description}

          </Portal>

      );
    };
    export default Myportal;

A: You can achieve this in two ways.

*

*Storing the popup content as part of the page property that is persisted once you edit the page

*Storing the popup content in a list and fetching the data whenever the page is render. FYI, haven't fully thought about how to achieve it via this way.

I have updated relevant sections of the code you provided to show how to achieve the expected by storing the popup content as part of the page property.
Added another property to the props to store the popup content
export interface IReactPortalWebPartProps {
description: string;
content?: string;
}

Updated the render method of the component ReactPortalWebPart.ts
    public render(): void {
      const element: React.ReactElement<any> = React.createElement(
        ReactPortal,
        {
          mode: this.displayMode, //used to determine if to display the text input or not based on the current state of the webpart.
          content: this.properties.content, //the contents property of the webpart which is persisted in the page properties.
          description: this.properties.description,
          updateWebPartContent: this.updateWebPartContentProperty.bind(this) // the function that would be called from the portal component when the content is saved by the user
        }
      );

    private updateWebPartContentProperty(htmlcontent) {
      //console.log( htmlcontent )
      //console.log( this.properties.content )
      this.properties.content = htmlcontent;
      this.onPropertyPaneFieldChanged( 'content', this.properties.content, htmlcontent );
      //console.log( this.properties.content )
    }

Passing the properties from ReactPortal to the Myportal functional component.
      <Myportal
        _mode={ this.props.mode }
        _content={ this.props.content }
        _updateWebPartContent={ this.props.updateWebPartContent }
      />

Updated the functional component with the props object, added the hook to save the input from the user and also using the current mode of the page to determine if the text area should be displayed or not.
const  Myportal = (props) => {
  const [ content, setContent ] = React.useState(props._content);
//abbreviated
  return (

     { props._mode == 2 &&

       <textarea name="conent" id="conent" cols={30} rows={10} value={ props._content } onChange={ (evt) => { setContent(evt.target.value); } }
 </textarea>

  <button className="btn" onClick={ () => { props._updateWebPartContent(content) } } type="button" >Save Content</button>

 }

  { props._content }


text:
Q: 4 points and Ellipse I have 4 points.. i can draw a polygon usign this code
var p = new Polygon();
p.Points.Add(new Point(0, 0));
p.Points.Add(new Point(70, 0));
p.Points.Add(new Point(90, 100));
p.Points.Add(new Point(0, 80));

How i can draw an 'ellipse' that will fit in this polygon, using Silverlight?

Question is still unanswared!!!

A: One way is use QuadraticBezierSegment or BezierSegment.
For example, like this:
    <Path Stroke="Red" StrokeThickness="2" >
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,40">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                <BezierSegment Point1="0,93"
                                           Point2="90,117"
                                           Point3="80,50"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>
<Path Stroke="Red" StrokeThickness="2" >
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,40">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                <BezierSegment Point1="0,-13"
                                           Point2="70,-17"
                                           Point3="80,50"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>
<Polygon Points="0,0 70,0 90,100 0,80"></Polygon>

it's not exact solution, for exact you must colculate exact points for curves and use 4 QuadraticBezierSegment
Edit:
Example for QuadraticBezierSegment
<Path Stroke="Red" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,40">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                    <QuadraticBezierSegment Point1="6,79"
                                           Point2="45,90"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>
    <Path Stroke="Red" StrokeThickness="1">
        <Path.Data>
            <PathGeometry>
                <PathGeometry.Figures>
                    <PathFigureCollection>
                        <PathFigure StartPoint="45,90">
                            <PathFigure.Segments>
                                <PathSegmentCollection>
                                    <QuadraticBezierSegment Point1="80,91"
                                           Point2="80,50"
                                           />
                                </PathSegmentCollection>
                            </PathFigure.Segments>
                        </PathFigure>
                    </PathFigureCollection>
                </PathGeometry.Figures>
            </PathGeometry>
        </Path.Data>
    </Path>
    <Path Stroke="Red" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,40">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                    <QuadraticBezierSegment Point1="2,3"
                                           Point2="35,0"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>
    <Path Stroke="Red" StrokeThickness="1">
        <Path.Data>
            <PathGeometry>
                <PathGeometry.Figures>
                    <PathFigureCollection>
                        <PathFigure StartPoint="35,0">
                            <PathFigure.Segments>
                                <PathSegmentCollection>
                                    <QuadraticBezierSegment Point1="72,8"
                                           Point2="80,50"
                                           />
                                </PathSegmentCollection>
                            </PathFigure.Segments>
                        </PathFigure>
                    </PathFigureCollection>
                </PathGeometry.Figures>
            </PathGeometry>
        </Path.Data>
    </Path>
    <Polygon Name="pol"  Points="0,0 70,0 90,100 0,80" Stroke="Red" StrokeThickness="1"</Polygon>

it still an experimental, not calculate point, but it quite exact.
Edit2:
You may calculate points of curves with use of this image and my comments:

curves have a startpoint, midle point and endpoint. In this image start and end piont are L,M,N,O; and midle are W,X,Y,Z.
How for example we calculate point L:
Whith help of equation of line y = k * x + b we find equation of line AB,DC,AC,DB,AD. How cross of AC and DB we find R. How cross of AB and DC we find E. After that we find equation of line ER and how cross of ER and AD we find L.
How we calculate point W:
Whith help of equation for length l = sqrt(sqr(x2 - x1) + sqr(y2 - y1)) find length of AR. AW = AR/(4*pi) and whith help of this coefficient, and equation of line and equation for length, after solving of square equation we find W.
Other points we find similarly.
This algorithm not work only for polygon which have parallel line, but in this case algorithm is more easier. And coefficient for length are the same.
Whith help of this algorithm i find point for 3 curves of your example:
<Path Stroke="Red" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,36">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                    <QuadraticBezierSegment Point1="4.7,74.6"
                                           Point2="39.9,88.9"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>
    <Path Stroke="Red" StrokeThickness="1">
        <Path.Data>
            <PathGeometry>
                <PathGeometry.Figures>
                    <PathFigureCollection>
                        <PathFigure StartPoint="39.9,88.9">
                            <PathFigure.Segments>
                                <PathSegmentCollection>
                                    <QuadraticBezierSegment Point1="83.43,92.7"
                                           Point2="78.8,43.9"
                                           />
                                </PathSegmentCollection>
                            </PathFigure.Segments>
                        </PathFigure>
                    </PathFigureCollection>
                </PathGeometry.Figures>
            </PathGeometry>
        </Path.Data>
    </Path>
    <Path Stroke="Red" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,36">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                    <QuadraticBezierSegment Point1="3.55,3.94"
                                           Point2="31.8,0"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>

And it curves exactly the same as ellipse line. Image below:

You may translate this algorithm to 'formula' and so find your solution.
You need 4 function for that:
1) find line coefficients from coordinates of 2 pionts
2) find coordinates of piont how cross of 2 lines from it's coefficients
3) find length of segment from coordinates of 2 points
4) find coordinates of piont whiсh lies on line with this start point and this length from line coefficients and coordinates of start point and length which you find in previous function divided by (4*pi)
Edit3:
You may optimize this solution, it have some defects, how parallel line etc. But it fast and if you optimise it may satisfy your requirements.
Xaml:
<Path Stroke="Red" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                        <PathFigure x:Name="pathleftdown" StartPoint="0,0">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                    <QuadraticBezierSegment x:Name="bezleftdown" Point1="0,0"
                                           Point2="0,0"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>
    <Path Stroke="Red" StrokeThickness="1">
        <Path.Data>
            <PathGeometry>
                <PathGeometry.Figures>
                    <PathFigureCollection>
                        <PathFigure x:Name="pathrigthdown" StartPoint="0,0">
                            <PathFigure.Segments>
                                <PathSegmentCollection>
                                    <QuadraticBezierSegment x:Name="bezrigthdown" Point1="0,0"
                                           Point2="0,0"
                                           />
                                </PathSegmentCollection>
                            </PathFigure.Segments>
                        </PathFigure>
                    </PathFigureCollection>
                </PathGeometry.Figures>
            </PathGeometry>
        </Path.Data>
    </Path>
    <Path Stroke="Red" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                        <PathFigure x:Name="pathleftup"  StartPoint="0,0">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                    <QuadraticBezierSegment x:Name="bezleftup" Point1="0,0"
                                           Point2="0,0"
                                           />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>
    <Path Stroke="Red" StrokeThickness="1">
        <Path.Data>
            <PathGeometry>
                <PathGeometry.Figures>
                    <PathFigureCollection>
                        <PathFigure x:Name="pathrigthup"  StartPoint="0,0">
                            <PathFigure.Segments>
                                <PathSegmentCollection>
                                    <QuadraticBezierSegment x:Name="bezrigthup" Point1="0,0"
                                           Point2="0,0"
                                           />
                                </PathSegmentCollection>
                            </PathFigure.Segments>
                        </PathFigure>
                    </PathFigureCollection>
                </PathGeometry.Figures>
            </PathGeometry>
        </Path.Data>
    </Path>

    <Polygon Name="pol"  Points="0,0 250,0 251,340 0,341" Stroke="Red" StrokeThickness="1"></Polygon>
    <Button Content="Generate" Width ="80" Height="30" HorizontalAlignment="Right" VerticalAlignment="Top"  Click="Button_Click"></Button>

and code:
private class pointXY
    {
        public double x;
        public double y;
    }
    private class lineKB
    {
        public double k;
        public double b;
        public bool flagXconst = false;
        public double xConst = 0;
    }

    private lineKB GetLineFromPonts(pointXY A, pointXY B)
    {
        lineKB line = new lineKB();
        if ((B.x - A.x) != 0)
        {
            line.k = (B.y - A.y) / (B.x - A.x);
            line.b = A.y - A.x * line.k;
        }
        else
        {
            line.xConst = A.x;
            line.flagXconst = true;
        }
        return line;
    }

    private pointXY GetPointFromLines(lineKB a, lineKB b)
    {
        pointXY point = new pointXY();
        if (a.flagXconst)
        {
            point.x = a.xConst;
            point.y = a.xConst * b.k + b.b;
        }else
            if (b.flagXconst)
            {
                point.x = b.xConst;
                point.y = b.xConst * a.k + a.b;
            }
            else
            {
                point.x = (a.b - b.b) / (b.k - a.k);
                point.y = a.k * point.x + a.b;
            }
        return point;
    }

    private double LengthOfLine(pointXY A, pointXY B)
    {
        return Math.Sqrt((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y));
    }

    private pointXY GetMidlePoint(pointXY S, double l, lineKB line, bool leftright)
    {
        double b = -2 * S.x - 2 * line.k * (-line.b + S.y);
        double a = (1 + line.k * line.k);
        double c = (S.x * S.x - l * l + (-line.b + S.y) * (-line.b + S.y));
        double d = b*b - 4 * a * c;
        double x1 = (-b + Math.Sqrt(d)) / (2 * a);
        double x2 = (-b - Math.Sqrt(d)) / (2 * a);
        pointXY ret = new pointXY();
        if (leftright)
            if (x1 > S.x) ret.x = x1;
            else ret.x = x2;
        else
            if (x1 < S.x) ret.x = x1;
            else ret.x = x2;
        ret.y = line.k * ret.x + line.b;
        return ret;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        pointXY A = new pointXY();
        A.x = pol.Points[0].X;
        A.y = pol.Points[0].Y;
        pointXY B = new pointXY();
        B.x = pol.Points[1].X;
        B.y = pol.Points[1].Y;
        pointXY C = new pointXY();
        C.x = pol.Points[2].X;
        C.y = pol.Points[2].Y;
        pointXY D = new pointXY();
        D.x = pol.Points[3].X;
        D.y = pol.Points[3].Y;
        lineKB AC = GetLineFromPonts(A, C);
        lineKB BD = GetLineFromPonts(B, D);
        pointXY R = GetPointFromLines(AC, BD);

        lineKB AB = GetLineFromPonts(A, B);
        lineKB BC = GetLineFromPonts(B, C);
        lineKB CD = GetLineFromPonts(C, D);
        lineKB DA = GetLineFromPonts(D, A);

        pointXY E = GetPointFromLines(AB, CD);
        lineKB ER = GetLineFromPonts(E, R);
        pointXY L = GetPointFromLines(ER, DA);
        pointXY N = GetPointFromLines(ER, BC);

        pointXY F = GetPointFromLines(BC, DA);
        lineKB FR = GetLineFromPonts(F, R);
        pointXY M = GetPointFromLines(FR, AB);
        pointXY O = GetPointFromLines(FR, CD);

        pointXY W = GetMidlePoint(A, (LengthOfLine(A, R) / (4 * Math.PI)), AC, true);
        pointXY X = GetMidlePoint(B, (LengthOfLine(B, R) / (4 * Math.PI)), BD, false);
        pointXY Y = GetMidlePoint(C, (LengthOfLine(C, R) / (4 * Math.PI)), AC, false);
        pointXY Z = GetMidlePoint(D, (LengthOfLine(D, R) / (4 * Math.PI)), BD, true);

        pathleftup.StartPoint = new Point(L.x, L.y);
        bezleftup.Point1 = new Point(W.x, W.y);
        bezleftup.Point2 = new Point(M.x, M.y);

        pathleftdown.StartPoint = new Point(L.x, L.y);
        bezleftdown.Point1 = new Point(Z.x, Z.y);
        bezleftdown.Point2 = new Point(O.x, O.y);

        pathrigthdown.StartPoint = new Point(O.x, O.y);
        bezrigthdown.Point1 = new Point(Y.x, Y.y);
        bezrigthdown.Point2 = new Point(N.x, N.y);

        pathrigthup.StartPoint = new Point(M.x, M.y);
        bezrigthup.Point1 = new Point(X.x, X.y);
        bezrigthup.Point2 = new Point(N.x, N.y);

    }

A: With the information given by Jeff M I created a function that returns an ellipse fitting in a polygon:
Ellipse FitEllipse(Polygon poly)
    {
        double W0 = poly.Points[0].X;
        double W1 = poly.Points[0].Y;
        double X0 = poly.Points[1].X;
        double X1 = poly.Points[1].Y;
        double Y0 = poly.Points[2].X;
        double Y1 = poly.Points[2].Y;
        double Z0 = poly.Points[3].X;
        double Z1 = poly.Points[3].Y;

        double A =  X0 * Y0 * Z1 - W0 * Y0 * Z1 - X0 * Y1 * Z0 + W0 * Y1 * Z0 - W0 * X1 * Z0 + W1 * X0 * Z0 + W0 * X1 * Y0 - W1 * X0 * Y0;
        double B =  W0 * Y0 * Z1 - W0 * X0 * Z1 - X0 * Y1 * Z0 + X1 * Y0 * Z0 - W1 * Y0 * Z0 + W1 * X0 * Z0 + W0 * X0 * Y1 - W0 * X1 * Y0;
        double C =  X0 * Y0 * Z1 - W0 * X0 * Z1 - W0 * Y1 * Z0 - X1 * Y0 * Z0 + W1 * Y0 * Z0 + W0 * X1 * Z0 + W0 * X0 * Y1 - W1 * X0 * Y0;
        double D =  X1 * Y0 * Z1 - W1 * Y0 * Z1 - W0 * X1 * Z1 + W1 * X0 * Z1 - X1 * Y1 * Z0 + W1 * Y1 * Z0 + W0 * X1 * Y1 - W1 * X0 * Y1;
        double E = -X0 * Y1 * Z1 + W0 * Y1 * Z1 + X1 * Y0 * Z1 - W0 * X1 * Z1 - W1 * Y1 * Z0 + W1 * X1 * Z0 + W1 * X0 * Y1 - W1 * X1 * Y0;
        double F =  X0 * Y1 * Z1 - W0 * Y1 * Z1 + W1 * Y0 * Z1 - W1 * X0 * Z1 - X1 * Y1 * Z0 + W1 * X1 * Z0 + W0 * X1 * Y1 - W1 * X1 * Y0;
        double G =  X0 * Z1 - W0 * Z1 - X1 * Z0 + W1 * Z0 - X0 * Y1 + W0 * Y1 + X1 * Y0 - W1 * Y0;
        double H =  Y0 * Z1 - X0 * Z1 - Y1 * Z0 + X1 * Z0 + W0 * Y1 - W1 * Y0 - W0 * X1 + W1 * X0;
        double I =  Y0 * Z1 - W0 * Z1 - Y1 * Z0 + W1 * Z0 + X0 * Y1 - X1 * Y0 + W0 * X1 - W1 * X0;

        double detT = A * E * I + B * F * G + C * D * H - A * F * H - B * D * I - C * E * G;

        double J = (E * I - F * H) / detT;
        double K = (C * H - B * I) / detT;
        double L = (B * F - C * E) / detT;
        double M = (F * G - D * I) / detT;
        double N = (A * I - C * G) / detT;
        double O = (C * D - A * F) / detT;
        double P = (D * H - E * G) / detT;
        double Q = (B * G - A * H) / detT;
        double R = (A * E - B * D) / detT;

        double a = J * J + M * M + P * P;
        double b = J * K + M * N - P * Q;
        double c = K * K + N * N - Q * Q;
        double d = J * L + M * O - P * R;
        double f = K * L + N * O - Q * R;
        double g = L * L + O * O - R * R;

        double Ex = (c * d - b * f) / (b * b - a * c);
        double Ey = (a * f - b * d) / (b * b - a * c);

        double Ea = Math.Sqrt(2.0 * (a * f * f + c * d * d + g * b * b - 2.0 * b * d * f - a * c * g) / ((b * b - a * c) * (Math.Sqrt((a - c) * (a - c) + 4.0 * b * b) - (a + c))));
        double Eb = Math.Sqrt(2.0 * (a * f * f + c * d * d + g * b * b - 2.0 * b * d * f - a * c * g) / ((a * c - b * b) * (Math.Sqrt((a - c) * (a - c) + 4.0 * b * b) + (a + c))));

        double phi = 0;

        if (b == 0 && a < c) {
            phi = 0;
        } else if (b == 0 && a > c) {
            phi = Math.PI / 2;
        } else if (b != 0 && a < c) {
            phi = (Math.PI / 2 - Math.Atan((a - c) / (2 * b))) / 2;
        } else if (b != 0 && a > c) {
            phi = (Math.PI / 2 - Math.Atan((a - c) / (2 * b))) / 2 + Math.PI / 2;
        }

        Ellipse el = new Ellipse();
        el.Height = Ea * 2;
        el.Width  = Eb * 2;

        el.RenderTransform = new RotateTransform(phi * 180 / Math.PI);

        return el;
    }

A: Although four bezier curves should do it quite fine (and is probably the simplest solution), I am proposing a different method here, just for kicks.  :-)
Think of your problem this way: Given a regular rectangle, draw an ellipse inside, then deform the rectangle into your final shape.
I don't think your deform transformation is linear, so you probably can't simply find a matrix for it (note: I may be wrong, and would love to be proven wrong; any math buffs here?)  Also see edit below.
One method is: draw your ellipse, then pull/push each of the four corners one by one.  By deforming only one corner of a shape, you can always interpolate any point on the ellipse curve to its new position by keeping the diagonal between the left and right corners intact.
EDIT: TRANSFORM
Start with a square (and a circle inside).

*

*Rotate by 45 degress such that the diagonals are axes

*Scale both axes to the right scales so that they match the relative lengths of the new shape's two diagonals

*Skew one axis to the angle between the two diagonals of the new shape

*Translate one axis to make the origin point match the crossing-point of the new shape's diagonals

Notice that all four transformations are either pure linear or affine (i.e. linear + translation), so they are each representable with a transformation matrix.  The end result is another affine transformation, which can also be represented by a matrix.
So your circle shape gets transformed by this matrix into the new shape.
I hope I haven't made a mistake in my math...

A: There's a small bug in Karsten's code around
} else if (b != 0 && a < c) {
    phi = (Math.PI / 2 - Math.Atan((a - c) / (2 * b))) / 2;
} else if (b != 0 && a > c) {

It returns phi = 0 when a==c, which is incorrect. Instead, the above lines should be
} else if (b != 0 && a < c) {
    phi = (Math.PI / 2 - Math.Atan((a - c) / (2 * b))) / 2;
} else if (b != 0 && a >= c) {

or
} else if (b != 0 && a <= c) {
     phi = (Math.PI / 2 - Math.Atan((a - c) / (2 * b))) / 2;
} else if (b != 0 && a > c) {


text:
Q: How to get the assembly name(not qualified name) from type(only assembly name without version or culture or publickeyToken) in c# How to get the assembly name (only name ) without namespace or culture or public key token;typeof (MyClass).AssemblyQualifiedName ---> give me the fully qualified name and i want only the assembly name not the qualified name

A: To get simple name of the assembly, try
typeof(MyClass).Assembly.GetName().Name


text:
Q: displayformatattribute to custom format a string I want to be able to mark properties in my viewmodel to be formatted using a custom format when displayed in my MVC view.
I assume I need my own displayformatattribute and set the displayformat but I am not sure how to set this displayformat or where. If I want to show a number as currency it is easy, just set DataFormatString to "{0:C}" in the constructor of the attribute.
But if for example I want to mask email addresses (so remove the domain name), how would I do this using either a displayformatattribute or maybe a datatypeattribute?
So it is a string field that I want to transform.
I know there are other approaches e.g. custom display templates but then I would lose some of the inbuilt htmlhelper functionality. I just want to change the format of the string nothing else. And preferably make it as simple as adding an attribute to those fields that need masking
The DataFormatString doesn't seem to be able to take a custom formatter?
cheers
Phil

A: Somewhate similar to : How to make configurable DisplayFormat attribute
public class CustomDisplayFormatAttribute : DisplayFormatAttribute {
    public CustomDisplayFormatAttribute() {
        //MSDN Custom Date Format string rules:http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
        DataFormatString = "{0;dddd dd MMMM YYYY}";
    }
}

Then you can use it and the base attributes e.g. ApplyFormatInEditMode, as so:
[CustomDisplayFormatAttribute(ApplyFormatInEditMode = false)]
public DateTime? CreatedOn { get; set; }

Note for dates there is a server vs client Culture setting, http://msdn.microsoft.com/en-us/library/bb882561(v=vs.110).aspx discusses (but doesn't answer) how to do this in javascript.


text:
Q: C++ AES Decrypt and Nodejs AES Decrypt producing different outputs I've reimplemented this AES c++ decryption in nodejs.
The "buffer" contains the encrypted content.
The "decryptKey" contains the key to decrypt the "buffer".
The "expectedOutput" contains the expected output.
In order to bypass the bad decrypt exception thrown by node I had to disable the autoPadding in my crypt object.
To simplify I added the c++ code and I added tests to three different algorithms (AES-128-ECB, AES-192-ECB, AES-256-ECB). None of the decrypt results match the C++ output.
What am I missing?
var crypto = require('crypto');

var buffer = new Buffer([
    0x5e,0x51,0xa3,0x53,0x9d,0xe7,0xe5,0xd3,
    0xee,0x30,0xbb,0xf8,0x0c,0x72,0x9f,0x80
]);

var decryptKey = new Buffer([
    0x36, 0x46, 0xb4, 0xf6,
    0x8e, 0x6d, 0xdc, 0xf4,
    0xb0, 0x31, 0x7e, 0x81,
    0x6b, 0x5d, 0x96, 0x55
])

/*
After looking to my C++ code I noticed that despite of providing a 32 length key the 128 argument ensures that only the first 16 bytes are used
var decryptKey = new Buffer([
    0x36, 0x46, 0xb4, 0xf6,
    0x8e, 0x6d, 0xdc, 0xf4,
    0xb0, 0x31, 0x7e, 0x81,
    0x6b, 0x5d, 0x96, 0x55, // 16
    0x15, 0x9c, 0x78, 0x54,
    0x8c, 0xca, 0x3e, 0x39,
    0x2d, 0x49, 0x75, 0x5d,
    0xa1, 0x1a, 0xc3, 0xe3  // 32
])*/

var expectedOutput = new Buffer([
    0xc8,0x6c,0x8f,0x2b,0xe8,0x21,0xc4,0x2e,
    0xfb,0x4a,0x8e,0x8b,0xc3,0x94,0x19,0xc2
]);

// aes_context aes_ctx;
function decrypt(data, password, algorithm, padding){
  if (padding === void 0) padding = true;
  algorithm = algorithm || 'aes-128-ecb';

  //aes_setkey_dec( &aes_ctx, digest, 128 );
  var crypt = crypto.createDecipher(algorithm,password);
  crypt.setAutoPadding(padding);
  // aes_crypt_ecb( &aes_ctx, AES_DECRYPT, buffer, buffer );
  var res = crypt.update(data, null, 'hex')
  res += crypt.final('hex');

  return new Buffer(res,'hex');
}

// aes_setkey_dec( &aes_ctx, digest, 128 );
var algoList = [
    'aes-128-ecb',
    'aes-192-ecb',
    'aes-256-ecb'
];

for (var i = 0; i<= 1; i++){
    console.log('\n ******* AUTO PADDING: ' + (padding ? 'ON': 'OFF') + ' ********* ');
    var padding = i === 0;
    for (let algo of algoList){
        try {
            var output = decrypt(buffer, decryptKey, algo, padding);
            console.log(algo + ' => ' + output.toString('hex') + ' < ' + (Buffer.compare(expectedOutput, output) === 0 ? 'ok' : 'ko'))
        } catch (err){
            console.log('Failed to perform ' + algo + ' with autopadding ' + (padding ? ' on ': ' off ') + ' due to ' + err.message);
        }
    }
}

/*
 ******* AUTO PADDING: OFF *********
Failed to perform aes-128-ecb with autopadding  on  due to error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
Failed to perform aes-192-ecb with autopadding  on  due to error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
Failed to perform aes-256-ecb with autopadding  on  due to error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

 ******* AUTO PADDING: ON *********
aes-128-ecb => d9817f142f9bca262b67f6a6be570345 < ko
aes-192-ecb => 9181784373bb6060c04c9ba75de26322 < ko
aes-256-ecb => c5945203368de477e5f0dbeedeb2189f < ko
*/

Heres the c++ code
#include "aes.h"
#include "sha2.h"

int main(int argc, char *argv[]) {

    unsigned char data[16] = {
        0x5e,0x51,0xa3,0x53,0x9d,0xe7,0xe5,0xd3,0xee,0x30,0xbb,0xf8,0x0c,0x72,0x9f,0x80
    };

    unsigned char key[32] = {
        0x36, 0x46, 0xb4, 0xf6,
        0x8e, 0x6d, 0xdc, 0xf4,
        0xb0, 0x31, 0x7e, 0x81,
        0x6b, 0x5d, 0x96, 0x55, // 16
        0x15, 0x9c, 0x78, 0x54,
        0x8c, 0xca, 0x3e, 0x39,
        0x2d, 0x49, 0x75, 0x5d,
        0xa1, 0x1a, 0xc3, 0xe3  // 32
    };

    aes_context aes_ctx;
    aes_setkey_dec(&aes_ctx, key, 128);
    aes_crypt_ecb(&aes_ctx, AES_DECRYPT, data, data);

    for (int i = 0; i< sizeof(data); ++i)
        std::cout << std::hex << (int)data[i];

    /* Output => c86c8f2be821c42efb4a8e8bc39419c2*/
}

references:

*

*https://tls.mbed.org/discussions/generic/question-about-using-aes

*http://aes.online-domain-tools.com/link/133660agcLyPgFri4s/ - Example of decryption online

The solution based in answer below
var crypto = require('crypto')
var buffer = new Buffer([
    0x5e,0x51,0xa3,0x53,0x9d,0xe7,0xe5,0xd3,
    0xee,0x30,0xbb,0xf8,0x0c,0x72,0x9f,0x80
]);

var decryptKey = new Buffer([
    0x36, 0x46, 0xb4, 0xf6,
    0x8e, 0x6d, 0xdc, 0xf4,
    0xb0, 0x31, 0x7e, 0x81,
    0x6b, 0x5d, 0x96, 0x55
])

var expectedOutput = new Buffer([
    0xc8,0x6c,0x8f,0x2b,0xe8,0x21,0xc4,0x2e,
    0xfb,0x4a,0x8e,0x8b,0xc3,0x94,0x19,0xc2
]);

// aes_context aes_ctx;
function decrypt(data, password, algorithm, padding){
  if (padding === void 0) padding = true;
  algorithm = algorithm || 'aes-128-ecb';

  //aes_setkey_dec( &aes_ctx, digest, 128 );
  var crypt = crypto.createDecipheriv(algorithm,password, new Buffer([]));//new Buffer(32).fill(0).byteLength
  crypt.setAutoPadding(padding);
  // aes_crypt_ecb( &aes_ctx, AES_DECRYPT, buffer, buffer );
  var res = crypt.update(data, null,'hex')
  + crypt.final('hex');

  return new Buffer(res,'hex');
}

// aes_setkey_dec( &aes_ctx, digest, 128 );
var output = decrypt(buffer, decryptKey, 'aes-128-ecb', false);
console.log(Buffer.compare(expectedOutput, output) === 0 ? 'ok' : 'ko');

A: The deprecated crypto.createDecypher() derives the key from the password argument:

The implementation of crypto.createDecipher() derives keys using the OpenSSL function EVP_BytesToKey with the digest algorithm set to MD5, one iteration, and no salt.

What you want instead is to use a raw key. For that you should use crypto.createDecipheriv() instead:
  var crypt = crypto.createDecipheriv(algorithm,password,new Buffer([]));

(In ECB mode the IV can be empty)
Of course, the key length must then match the requested algorithm (128, 192 or 256 bits). You key is 128 bits, so only aes-128-ecb will work.

A: The reason you need to pass false to setAutoPadding is that your ciphertext is not padded. You haven't included your encryption code that generates the ciphertext, but I can tell from the length of it that it is not padded, because a plaintext of one block size in length, when encrypted using PKCS#7 padding, will produce a ciphertext that is two block sizes in length, rather than the single block that you have.
The reason this decrypts with aes_crypt_ecb is that it looks like aes_crypt_ecb simply performs individual block encryption/decryption, so does not do any padding or unpadding. The Javscript code though, if passed true to the setAutoPadding function, will be expecting padding (probably PKCS#7). Which will of course fail because your encryption has not used padding.
Ideally you should modify your encryption code so that it uses proper padding when doing the encryption, as this is much more secure than not using padding. Otherwise you will need to make sure that your call to setAutoPadding is passing false when doing the decryption, so the Javascript knows there is no padding.


text:
Q: Can you create a file that you can't access for unit testing to test for a permission error I am in the process of creating a function that will loop over a large amount of files. However, the function will not have access to all of the files. I have added something to the main part of the function which catches the permission errors. However, I am wanting to create a unit test to test for that so I don't need to run it over the large amount of data.
for the unit test, I am currently using pytest and tmpdir to generate the temporary files and for unit testing. I am trying to make one of the files I generate result in a permission error but I can't figure out how. I have looked at using os.chmod(file, ...) but that can't change the permissions on the file to what I want.
Is there a way to make it so that the when I try to access the file I've made, it throws up a permission error? The section in the function that throws up the permission error is an os.stat(file) function.
Edit: In addition, the reason I may not be able to access the files is that they may be in directories that I cannot access. Is there a way to create fake temporary directories with files in but I don't have permission to access the files in the directory?


text:
Q: No haddock generated when upload package to hackages After I upload my package into hackages, it didn't generate haddock as others packages.
Anything I missed?
What I did is:

*

*cabal dist and a package generated under dist directory.

*open hackage web upload interface and upload the package.

*open the URL and turns out package uploaded successfully but no haddock.
(the package do have a few docs)

Thank you.

A: Docs take a little bit of time to generate.  I believe they are ran at midnight GMT.

A: In addition to Thomas's answer, run cabal haddock in your package directory and look for any errors.
Haddock is incredibly finicky in my experience, especially wrt. code blocks. If you get a parse error, just start deleting comments until docs can be generated. I usually use some extensively-documented package as a reference.

A: It looks like the documentation is missing because your package didn't build correctly. I found this near the end of the build log:
src/Network/OAuth2/HTTP/HttpClient.hs:18:8:
    Could not find module `Control.Monad.Trans.Resource'
    It is a member of the hidden package `resourcet-0.3.2.1'.
    Perhaps you need to add `resourcet' to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

To avoid these sorts of problems, make sure your package builds locally with Cabal before uploading. Building with GHC directly will often mask these sorts of problems, since it will happily use whatever packages you have installed, regardless of whether you've mentioned them in your .cabal file or not.


text:
Q: Is using Titan Graph DB the right choice? I am planning to use Titan Graph DB for my project.
The reason for selecting it is because it is the only graph database which can use DynamoDB as the storage backend. Thus I can free myself of the scalability/throughput worries.
But when I am trying to find any tutorial to get started with Titan, I am not finding many of them. This makes me doubt whether to use Titan or choose another graph database, like Neo4j or OrientDB.
Can someone tell me if Titan being used widely?
Is the community active?
Can I expect proper releases?
The last blogpost on ThinkAurelius is dated Feb 3, 2015 regarding acquisition by DataStax. DataStax website has no mentioning about Titan.

A: Your question is more of an opinion question which might be suited for a different forum, but I will attempt to answer the main questions you stated anyway.

*

*Is Titan being used widely? This is hard to tell since Aurelius doesn't disclose much information publicly about their users other than their client list. The Amazon Fulfillment gave a session on their usage of Titan with DynamoDB. This blog post identifies NASA's Jet Propulsion Laboratory and AdAgility as users also.

*Is the community active? Somewhat. There are discussions occurring on the Titan mailing list and new messages come in every day. Commits are being made on the titan11 stream in GitHub. The most recent commit was on April 4, 2016.

*Can I expect proper releases? "Expecting" releases of software is not something I would recommend in general. Software (both open source and proprietary) is released when the maintainers think the code is ready. For Titan specifically, the core maintainers have largely been absent from the community because they are busy working on DataStax Enterprise Graph.


text:
Q: Gradle dependency for subprojects does not work I created a project with spring initializr with kotlin and gradle to study hexagonal architecture in microservices. I'm using IntelliJ with modules to dividing the code but the spring-jpa dependency doesn't work in module (or subproject).
The start build.gradle.kts is:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

    plugins {
        id("org.springframework.boot") version "2.5.9-SNAPSHOT"
        id("io.spring.dependency-management") version "1.0.11.RELEASE"
        kotlin("jvm") version "1.5.32"
        kotlin("plugin.spring") version "1.5.32"
        kotlin("plugin.jpa") version "1.5.32"
    }

    group = "com.donadon.studyhexagonal"
    version = "0.0.1-SNAPSHOT"
    java.sourceCompatibility = JavaVersion.VERSION_11

    repositories {
        mavenCentral()
        maven { url = uri("https://repo.spring.io/milestone") }
        maven { url = uri("https://repo.spring.io/snapshot") }
    }

    dependencies {
        implementation("org.springframework.boot:spring-boot-starter-data-jpa")
        implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive")
        implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
        implementation("org.springframework.boot:spring-boot-starter-security")
        implementation("org.springframework.boot:spring-boot-starter-web")
        implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
        implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
        implementation("org.jetbrains.kotlin:kotlin-reflect")
        implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
        implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
        runtimeOnly("org.postgresql:postgresql")
        testImplementation("org.springframework.boot:spring-boot-starter-test")
        testImplementation("io.projectreactor:reactor-test")
        testImplementation("org.springframework.security:spring-security-test")
    }

    tasks.withType<KotlinCompile> {
        kotlinOptions {
            freeCompilerArgs = listOf("-Xjsr305=strict")
            jvmTarget = "11"
        }
    }

    tasks.withType<Test> {
        useJUnitPlatform()
    }

I move the repositories and dependencies to subprojects method e I put some plugins together but the follow error happened:
subprojects {
    apply {
        plugin("kotlin")
        plugin("kotlin-jpa")
        plugin("io.spring.dependency-management")
    }

    repositoreis { ... }
    dependencies {
        implementation("org.springframework.boot:spring-boot-starter-data-jpa")
        ...
    }
}

The error:
Configuration with name 'implementation' not found.
    at Program.execute(Unknown Source)
Caused by: org.gradle.api.artifacts.UnknownConfigurationException: Configuration with name 'implementation' not found.
    at Build_gradle$2$2.invoke(build.gradle.kts:29)

How I make for dependencies work to all subprojects?
I read the gradle doc and others questions here but nothing helped me.
Thanks for while.
EDIT
I created a module with name database and when I try to use @Entity, it is not found but if I use in some class in main src, it founds the annotation.

A: Couple things:

*

*Some gradle configurations cannot be shared using the subprojects method. This includes dependencies. Check out this StackOverflow question for information on how to share dependency versions.

*According to gradle, reusing logic through subprojects is discouraged: Another, discouraged, way to share build logic between subproject is cross project configuration via the subprojects {} and allprojects {} DSL constructs. (Link)


text:
Q: Find list of id's which have another column change values multiple times I have a dataframe new_df which has a list of customer id's, dates, and a customer segment for each day. Customer segment can take multiple values. I am looking to identify a list of customers whose segment has changed more than twice in the past 15 days.
Currently, I am using the following to check how many times each segment appears for each customer id.
segment_count = new_df.groupby(new_df['customer_id'].ne(new_df['customer_id'].shift()).cumsum())['segment'].value_counts()

My thinking is if a customer has more than 2 segments which have a count of >1, then they must have migrated from one segment to another at least twice. 2 sample customers may look like this:
|customer_id|day|segment|
|-----------|---|-------|
|12345|'2021-01-01'|G|
|12345|'2021-01-02'|G|
|12345|'2021-01-03'|M|
|12345|'2021-01-04'|G|
|12345|'2021-01-05'|M|
|12345|'2021-01-06'|M|
|6789|'2021-01-01'|G|
|6789|'2021-01-02'|G|
|6789|'2021-01-03'|G|
|6789|'2021-01-04'|G|
|6789|'2021-01-05'|G|
|6789|'2021-01-06'|M|

As an output, I would want to return the following:

customer_id
migration_count

12345
3

6789
1

Anyone have any advice on best way to tackle this or if there are any built in functions I can use to simplify?Thanks!


text:
Q: Converting an ASCII character to decimal within a generator Goal: Parse a fastQ file made up of four lines of strings:
1) an ID line (seqID) and possible comment (comm) on the same line;
2) a DNA or protein sequence (seq);
3) an extra line
4) a quality (qual) sequence where each character corresponds to protein or DNA seq (line2)
Question: How do I convert all characters each of my qual strings using ord() ??
What I have tried:
The qual line in the fastQ is a line of strings, and I want to loop through all of them and convert them to decimal format with ord() . However, when I run a generator that yields seqID seq qual and comm, it seems I can't just throw in qual = ord(block[3]) where I define these newly parsed variables since I get the following error when I attempt to parse my fastQ file:
Traceback (most recent call last):
  File "fast_splitter_v1.py", line 91, in <module>
    for q in split:
  File "fast_splitter_v1.py", line 28, in read_fastq
    seqID, seq, qual = line1[0][1:], block[1], ord(block[3])
TypeError: ord() expected a character, but string of length 1550 found

I assume this way is attempting to apply ord() to all qual characters in my file (of which there are 1550 of them).  This seemed like the best way to do it, but now I'm looking for a solution that works.
Here is my code:
def read_fastq(f):
    '''reads in fastaq file-like object in conventional 4-line NCBI format and
    yields a tuple of lists comprising seqID (sequence ID/name/title),
    seq (sequence), and qual (monomer read quality)'''
    ###CONVERT ALL QUAL SCORES TO INTEGER WITH ORD()
    lines = f.readlines()
    while len(lines) > 3:
        block = [lines.pop(0)[:-1] for z in range(4)]
        line1 = block[0].split(' ', 1)
        if len(line1) ==2:
            comm = line1[1]
        else:
            comm = ''
        seqID, seq, qual = line1[0][1:], block[1], block[3]
        yield seqID, seq, qual, comm

Question summary:
With the above code, how can I convert everything in qual from ASCII to decimal format with ord() and keep my generator function?
Sample FastQ:
`@SEQ_ID
GATTTGGGGTTCAAAGCAGTATCGATCAAATAGTAAATCCATTTGTTCAACTCACAGTTT
 +
 !''*((((***+))%%%++)(%%%%).1***-+*''))**55CCF>>>>>>CCCCCCC65`

A: I'm probably still not understanding the question but what's there to stop you from doing final line as follows:
yield seqID, seq, map(ord, qual), comm

OR
yield seqID, seq, [ord(c) for c in qual], comm


text:
Q: How to specialize template member function? I have the following template method:
struct MyStruct
{
  // ...
  template<typename T>
  void readField(std::istream& in, T& data)
  {
      read(in, data);
      data = ntohl(data);
  }
};

template<>
void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data)
{
    read(in, data);
}

But I get those strange linker errors:

/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/exception:62:
  multiple definition of `void MyStruct::readField(std::basic_istream >&, unsigned
  char&)'
  ../Lib/obj/MyStruct.o:/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/exception:62:
  first defined here collect2: ld returned 1 exit status make: ***
  [Lib] Error 1

How can I specialize this member function?
EDIT
This approach works:
struct MyStruct
{
  // ...
  template<typename T>
  void readField(std::istream& in, T& data)
  {
    read(in, data);
    data = ntohl(data);
  }

  void readField(std::istream& in, uint8_t& data)
  {
    read(in, data);
  }
};

or with inlines or specializing it outside the class with inline
struct MyStruct
{
  // ...
  template<typename T>
  void readField(std::istream& in, T& data)
  {
      read(in, data);
      data = ntohl(data);
  }
};

template<>
inline void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data)
{
    read(in, data);
}

A: You can inline the specialization to avoid multiple definitions.
template<>
inline void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data)
{
    read(in, data);
}

Just to be complete, the other option you have is to create an implementation in the .cpp file, and export the implementation through the header.
//MyStruct.h

#ifdef MYSTRUCT_EXPORTS
#ifdef __GNUC__
#ifndef __linux__
#define MYSTRUCT_API __attribute__ ((dllexport))
#else
#define MYSTRUCT_API __attribute__ ((visibility ("default")))
#endif
#else
#define MYSTRUCT_API __declspec(dllexport)
#endif
#else
#ifdef __GNUC__
#ifndef __linux__
#define MYSTRUCT_API __attribute__ ((dllimport))
#else
#define MYSTRUCT_API __attribute__ ((visibility ("default")))
#endif
#else
#define MYSTRUCT_API __declspec(dllimport)
#endif
#endif

template<>
void MYSTRUCT_API MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data);

//MyStruct.cpp

template<>
void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data)
{
    read(in, data);
}

A: As Igor mentioned, you can implement the generic version in the header file, and then the specialization in the cpp file, for example:
// MyStruct.h

struct MyStruct {
  // ...
  template <typename T>
  void readField(std::istream& in, T& data) {
    read(in, data);
    data = ntohl(data);
  }
};

Then in the cpp file you can implement the specialization, for example:
// MyStruct.cpp

template <>
void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data) {
  read(in, data);
}

Update: After reading the comments, the specialization can also be in the same header file as the primary template, but not within the struct, for example (I verified this by compiling and running a similar example without error):
// MyStruct.h

struct MyStruct {
  // ...
  template <typename T>
  void readField(std::istream& in, T& data) {
    read(in, data);
    data = ntohl(data);
  }
};

template <>
inline void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data) {
  read(in, data);
}

// End MyStruct.h


text:
Q: How can I remove the branding from the free getbutton.io? I received this, I want to remove the branding. Is there any why to do so? please note that I'm not a developer myself and use elementor builder. Thanks in advance

<!-- GetButton.io widget -->
<script type="text/javascript">
    (function () {
        var options = {
            whatsapp: "123456789", // WhatsApp number
            call_to_action: "Call US", // Call to action
            position: "right", // Position may be 'right' or 'left'
        };
        var proto = document.location.protocol, host = "getbutton.io", url = proto + "//static." + host;
        var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
        s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
        var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
    })();
</script>
<!-- /GetButton.io widget -->

A: This is only available in the Pro version according to the plugin page.

Get more chats and sales with PRO features:
Enable the Greeting Message.
**Remove the 'GetButton' link.**
Add up to ten buttons to the widget.
Choose any custom color for the button.

// https://wordpress.org/plugins/whatshelp-chat-button/


text:
Q: Silverlight / Blend - How to create FontSize dependency property with dropdown list In my custom behavior I have created the following dependency property:
public double FontSize
{
    get { return (double)GetValue(FontSizeProperty); }
    set { SetValue(FontSizeProperty, value); }
}

public static readonly DependencyProperty FontSizeProperty = DependencyProperty.Register(
        "FontSize",
        typeof (double),
        typeof (CustomBehavior),
        new PropertyMetadata(11, null));

*

*How to bind value, 'couse In Blend binding button is disabled.

*How to show dropdown list of standart font sizes like for Textblock in Text category

A: I don't know if this helps or if you already found the answer but I here it goes for ...
Part 2 of your question:
You first declare an enum of items:
public enum DDItems
{
    Default = 0,
    Item1 = 1,
    Item2 = 2,
    Item3 = 3,
    Item4 = 4,
    Item5 = 5
}

And then you have the dependency property like this:
    public DDItems TextSearchModeABC
    {
        get
        {
            return (DDItems)GetValue(MyItemProperty);
        }
        set
        {
            SetValue(MyItemProperty, value);
        }
    }

    public static readonly DependencyProperty MyItemProperty =
        DependencyProperty.Register("MyItemProperty", typeof(DDItems), typeof(MyControlType), new PropertyMetadata(null));

Hope this helps.


text:
Q: Insert into test database is not executed in @DataJpaTest I created a @DataJpaTest class to test a JpaRepository in my SpringBoot project, this test class is setup like so:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureEmbeddedDatabase
public class MyRepositoryTest {

    @Autowired private TestEntityManager entityManager;

    @Autowired private MyRepository myRepository;

    private MyEntity testEntity;

    @Test
    public void shouldReturnAllEntities() {
        myEntity = new MyEntity();

        myRepository.save(myEntity);

        assertEquals(1, myRepository.findAll().size());
    }
}

@AutoConfigureEmbeddedDatabase is an annotation provided by a package for testing with an embedded PostgreSQL database, which is embedded-database-spring-test.
This test fails miserably, with a list size of 0 instead of the expected 1.
When executing this test, I see a transaction is being started by DataJpaTest at the beginning of test execution (which I expected) and then some SQL logs:

*

*a select nextval of the myEntity table sequence, which gets executed two times (Why? No idea.)

*the select request issued by the call to findAll

*in the meantime, no insert has been made.

After failing, the transaction rolls back as expected from a DataJpaTest (as I can see from the logs).
I tried investigating this situation: my entity is sucessfully persisted in the EntityManager but the insert action is queued/not executed. When I add a flush call somewhere between the save and the findAll calls, test crashes because there is no ongoing transaction.
I have no clue how to "trigger" the actual insert into my test database, and thought it would occur automatically in such a simple setup.
Feel free to ask for more details, at this point I will take any hint I can get.
Thanks in advance

A: After hours of rummaging through documentation and trying every possible combination of annotations in the test class, I finally figured out this is not actually a problem one can see in the code I posted (sorry guys...) but a very random side-effect of another annotation I'm using in my SpringBoot application : @EnableBatchProcessing
It occurred to me while reading this related issue: https://github.com/spring-projects/spring-boot/issues/10703
While this seems totally unrelated at first sight, this annotation (on the application class) changes the transactions handling in the app and gets picked up by my test class, among other stuff.
This annotation caused the errors I got when trying to flush after saving entities, saying there was no transaction in progress.
I first tried removing it from the main application class (monkey-testing, obviously) and saw that after this change, I could flush changes and see normal behaviour for my entityManager and repository in the test class.
Then, I figured out a solution to avoid breaking my Spring Batch production code but make my tests work. I moved the annotation in another class, annotated with @Configuration:
@Configuration
@EnableBatchProcessing
public class BatchConfig {
}

This class gets scanned by the application so there is no side effet when we start it. To avoid having it in my test setup, I created a new class:
public class DaoTestConfiguration {

    @MockBean BatchConfig batchConfig;
}

I found this quite elegant, but maybe there are better ways to ignore this annotation in specific classes. To use this new class, I added this annotation to my test class:
@Import(DaoTestConfiguration.class)

Works like a charm! I can now execute my tests as I wanted, saving and then flushing without errors and getting expected results in find methods.
I hope this can help others stumbling on this weird issue.

A: Here you have complete example that actually works
@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories
@EntityScan
@SpringBootTest(classes = MyRepo.class)
public class SampleTest {
    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private MyRepo myRepo;

    private MyEntity testEntity;

    @Test
    public void shouldReturnAllEntities() {
        MyEntity myEntity = new MyEntity();
        myEntity.setId(100l);
        myRepo.save(myEntity);

        Assertions.assertThat(myRepo.findAll()).hasSize(1);
    }
}

@Repository
interface MyRepo extends JpaRepository<MyEntity, Long> {

}

@Entity
@Data
class MyEntity {
    @Id
    Long id;
}

What I recently did, to test underlying persistence logic is that I annotated test class with
@EnableJpaRepositories("mypackage")
@EntityScan("mypackage")
@SpringBootTest
@DataJpaTest

I don't know which of those can be ommited, but it works
Unfortunetly my integration tests involves db interaction via service (so its not 1:1 your test case), in in test method I have call to @Transactional annotated. Terefore I don't know if wil make difference if you annotate test method directly with @Transactional or not. Try out both scenarios, so there will be something to move on from.


text:
Q: Encoding issues when posting custom fields via wordpress xmlrpc api I've a problem with wordpress xml-rpc api. My code gets some data from an xml and posts to a blog. Page title posted well, there is no problem on blog but custom fields are broken.
Code file, xml, blog settings and database tables they are all utf-8 encoded.
function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$thumbnail,$cfields,$category,$keywords='',$encoding='UTF-8') {

$title = html_entity_decode(htmlentities($title,ENT_NOQUOTES,$encoding));
$body = html_entity_decode(htmlentities($body,ENT_NOQUOTES,$encoding));
$keywords = html_entity_decode(htmlentities($keywords,ENT_NOQUOTES,$encoding));
array_walk($cfields,arr_encoding); // this function does the same thing with above

$content = array(
    'title'=>$title,
    'description'=>$body,
    'mt_allow_comments'=>0,  // 1 to allow comments
    'mt_allow_pings'=>0,  // 1 to allow trackbacks
    'post_type'=>'post',
    'mt_keywords'=>$keywords,
    'categories'=>array($category),
    'custom_fields' => $cfields
);

$params = array(0,$username,$password,$content,true);
$request = xmlrpc_encode_request('metaWeblog.newPost',$params);

$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_ENCODING, "UTF-8" );
$results = curl_exec($ch);
if(curl_errno($ch))
    echo '
curl error:'.curl_error($ch)."
";
curl_close($ch);
return $results;}

and this is arr encoding function:
function arr_encoding($cfields){
if(is_array($cfields))
    array_walk($cfields, 'arr_encoding');
else if(is_string($cfields))
    $cfields = html_entity_decode(htmlentities($cfields,ENT_NOQUOTES,"UTF-8"));}

Do you have any idea?

A: OK, here it is:
Don't use
xmlrpc_encode_request('blogger.newPost',$params);

and use:
xmlrpc_encode_request('blogger.newPost',$params,
                            array('encoding'=>'UTF-8','escaping'=>'markup'));


text:
Q: git - squash before rebasing I have two branches: master and test-branch (which is branched off of master). My work has looked something like the following:

*

*git checkout master

*git checkout -b test-branch

*make a bunch of changes and commit them

*make more changes and do another commit

*git checkout master

*git pull -> out other people have made changes master

*git checkout test-branch

*git rebase -i master

*Change all but the first pick in the interactive console to s

*I have to resolve two merge conflicts for, one for the first commit and another for the second commit

What I'd like to do is to squash all of the commits on test-branch before rebasing so that I only have to solve merge conflicts once. Is this possible? If so, how?

A: Of course it possible, yoiu simply need to type: git rebase -i HEAD~<# of commits to squash>
The -i is for interactive rebase. once you do it you will see the vi with instructions what to so next per commit.
A very details post about it can be found here Rewriting history:

A: It is possible, even easy.  Git being what it is, there are many different ways to do it.
To literally do what you suggested originally:

... squash all of the commits on test-branch before rebasing

is easiest if you do it before running git merge while on branch master.  (I know you didn't list git merge as a command, but you did run git merge in your step 6:

*git pull -> out other people have made changes master

because git pull is just git fetch followed by git merge.)  But it's still pretty easy to do after; we just need to target the correct commit-ID.
Let's make a drawing of the commit graph that you have at step 4:
...<- o <- *            <-- master, origin/master
             \
               A <- B   <-- HEAD=test-branch

What this drawing shows is that there are two labels1 pointing to the commit I marked *, namely master and origin/master.  Commit * points back to commit o which points back to yet more commits: that's the history of branch master.
The label for the branch you created (and are now on, hence the HEAD= part) points to commit B.  Commit B then points to commit A, which points to commit *.  That's the history of branch test-branch: you created it when at *, then added A, then added B.
Here are two ways you can easily squash commits A and B at this point:

*

*git rebase -i master
This gives you an interactive edit session where you can "pick" the first commit and then "squash" the second, and it will gather together both commit messages and let you edit the result, in the usual way.  It then makes a (single) new commit whose tree is that of commit B.

*git reset --soft master; git commit
This does not open an interactive edit session for the rebase: it just keeps the staging-area-and-tree from commit B (that's the --soft part of git reset --soft), moves the label test-branch back to point to commit * directly (that's the git reset part of git reset --soft), and makes a new commit as usual (git commit).
The drawback is that you have to compose a new commit message, but you can recover the commit message from commit A or B in any number of ways.  For instance, you can use the -c or -C flag to git commit (you'd have to identify commit A or B, e.g., using @{1} or @{1}^ or @{yesterday} or some other reflog specifier).  Or, before doing the git reset --soft, you can use git log and save the log message(s) in a file, or whatever.
(This second method shines when instead of just two commits to squash, you have 42 or so.)
Both of these methods really do the same thing: they add a new commit (let's call it AB), leaving A and B behind and kind of greyed-out, which I can't really draw correctly:
              AB        <-- HEAD=test-branch
             /
...<- o <- *            <-- master, origin/master
             \
               A <- B   [ghost version of test-branch]

The ghost-version of your branch is invisible to most normal usage, and eventually (after 30 days or so by default) is garbage-collected away.  (Until then it's still in your repository, and in your reflogs, so that you can find original commits A and B in case you need them after all.)
What if you've already done step 6?  In that case, you must still identify commit *.  You can do it the way jsexpert suggested while I was writing this up, or you can find it with git merge-base:
$ mergebase=$(git merge-base HEAD master)
# then pick just ONE of the next two
$ git rebase -i $mergebase
$ git reset --soft $mergebase; git commit

Here's how this works.  After git checkout master; git fetch; git merge; git checkout test-branch (steps 5 and 6, more or less), your commit-graph now looks more like this:
...<- o <- * <- o       <-- master, origin/master
             \
               A <- B   <-- HEAD=test-branch

That new o commit that master and origin/master are pointing to—or it may be a whole chain of commits—are "in the way", but the "merge base" of test-branch (where you are now) and master is commit *: the nearest shared commit before the two branches diverge.
We then simply target the rebase or reset --soft at that commit.  When we're done and have a single new AB commit, it looks like this:
              AB        <-- HEAD=test-branch
             /
...<- o <- * <- o       <-- master, origin/master
             \
               A <- B   [ghost version of test-branch]

Once you have the squashed AB commit, you can then git rebase that onto master in the usual way.
Note that the other answer is doing exactly the same thing, it's just identifying commit * by counting commits.  If you know there are two commits between the tip of test-branch and the "interesting" commit *, HEAD~2 identifies the same commit as $(git merge-base HEAD master).  Using git merge-base just allows you to avoid counting.

1"References" is the actual general git term.  In this case they're branch names, and I am using the word "label" to distinguish them from the branch history formed by this commit graph.  The word "branch" in git is used to refer to at least these two different things, and it gets confusing.


text:
Q: solution of $\bar{z}=\xi z$ Does $\bar{z}=\xi z$ has solution in $z$ (complex number) for all values of $\xi \in \mathbb{C}$?
I was trying to use normal method but its coming quite complicated.

A: First, for any $\;\xi\in\Bbb C\;,\;\;z=0\;$ is a solution to $\;\overline z=\xi z\;$. Now, if we want non-zero solutions to this equation, we get that
$$\overline z=\xi z\implies |z|=|\xi|\,|z|\stackrel{\text{since}\;z\neq 0}\iff |\xi|=1\;$$
Thus, the answer to question in the first line of your post is yes, since $\;z=0\;$ does the job , and if we consider only $\;z\neq 0\iff z\in\Bbb C^*\;$, the answer then is no, as only the complex elements $\;\xi\in S^1=\{z\in\Bbb C\;:\;\;|z|=1\}\;$ have a chance to solve the given equation .
Added on request: If $\;\xi=\cos\theta+i\sin\theta\in S^1\;$, putting $\;z=r(\cos t+i\sin t)\;$ we get
$$\overline z=r(\cos t-i\sin t)=r\left(\cos\theta\cos t-\sin\theta\sin t+(\cos\theta\sin t+\sin\theta\cos t)i\right)\implies$$
$$\cos t-i\sin t=\cos(t+\theta)+i\sin(t+\theta)$$
This gives us two equations:
$$\begin{align*}&\cos t=\cos(t+\theta)\iff t=t+\theta\,,\,\,\text{or}\;\;t=-t-\theta\\{}\\
&\sin t=-\sin(t+\theta)\iff t=-t-\theta\;\;or\;\;t=\pi+t+\theta\end{align*}$$
So we can always find a non-zero solution.

A: As mentioned in another answer, $z=0$ is always a solution and we must have $|\xi|=1$ in order for a nonzero solution $z$ to exist.
To find a solution, consider this: if $|\alpha|=1$ then $\bar{\alpha} = \alpha^{-1}$. Thus
$$\bar z = \xi z \quad \Leftrightarrow \quad \xi^{-\frac{1}{2}} \bar z = \xi^{\frac{1}{2}} z \quad \Leftrightarrow \quad \overline{\xi^{\frac{1}{2}}z} = \xi^{\frac{1}{2}}z$$
So what can you say about $\xi^{\frac{1}{2}}z$ in relation to $z$ being a solution to $\bar z = \xi z$?


text:
Q: Como crear un WorkManager para activar una alarma? Necesito crear una alarma estaba utilizando AlarmManager y todo iba bien pero cuando reinicio el teléfono esta se activa a los minutos de encenderlo y no acata las fechas y horas establecidas para que esta suene.
Me sugirieron crear un WorkManager ya lo implemente pero no se como hacer que este se me active (ejemplo: todos los lunes a las 8:30 am).
Espero me puedan ayudar.
Mil Gracias
private void startWork(){

    Constraints constraints = new Constraints.Builder()
            .setRequiresBatteryNotLow(true)
            .setRequiresCharging(true)
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build();

    PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(WorkTecno.class, 8, TimeUnit.DAYS)
            .setInitialDelay(10, TimeUnit.SECONDS)
            .setConstraints(constraints).build();
    WorkManager.getInstance(getContext()).enqueue(periodicWorkRequest);

}