text:
Q: How do I screenshot a uiview without adding it to the subview? I have multiple subviews on a parent view, and I need to convert the uiview to a uiimage but of only certain subviews. So I added a tag to the views I  needed to take a screenshot of and added it to its own view, but when I try to screenshot that I get a black screen. However, when I use the regular parent view I get a photo with all the subviews.
let viewPic = UIView()

            for subview in self.view.subviews {

                if(subview.tag == 6) {
                    viewPic.addSubview(subview)
                }

                if(subview.tag == 8) {
                    viewPic.addSubview(subview)
                }
            }

            let picImage = viewPic.getSnapshotImage() //This is a black screen

getSnapshotImage
extension UIView {
    public func getSnapshotImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
        let snapshotItem: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return snapshotItem
    }
}

A: First of all, your viewPic doesn't set the frame size so the default will be zero frame which may cause the issue.
Secondly, I tried to use your getSanpshotImage() on my sample project, but I always get the blank image.
Have a look at the demo code, I can get what you want (see the screenshot):
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let viewPic = UIView()
        viewPic.frame = self.view.frame

        let view1 = UIView()
        view1.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        view1.backgroundColor = UIColor.red
        viewPic.addSubview(view1)

        let view2 = UIView()
        view2.frame = CGRect(x: 0, y: 200, width: 100, height: 100)
        view2.backgroundColor = UIColor.blue
        viewPic.addSubview(view2)

        let picImage = viewPic.convertToImage() //This is a black screen
        print(picImage)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension UIView {
    func convertToImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}


text:
Q: How to logout and segue to the viewcontroller correctly? My idea is creating a log in app, when I log in I will segue to a new view controller and do something, and my code is like that:
 @IBAction func signUp(sender: AnyObject) {
    var error = ""

    if username.text == "" || password.text == "" {

        error = "Please enter a username and password"

    }
    if error != "" {
        displayAlert("Error in form", error: error)

    } else {

        activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))     //waiting animation
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        view.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        UIApplication.sharedApplication().beginIgnoringInteractionEvents()

        if signupActive == true {

            var user = PFUser()
            user.username = username.text
            user.password = password.text

            user.signUpInBackgroundWithBlock {
                (succeeded: Bool, signupError: NSError?) -> Void in

                self.activityIndicator.stopAnimating()

                UIApplication.sharedApplication().endIgnoringInteractionEvents()

                if signupError == nil {
                    println("signed up")

                } else {
                    if let errorString = signupError!.userInfo?["error"] as? NSString
                    {

                        error = errorString as! String

                    } else {

                        error = "Please try again later"

                    }

                    self.displayAlert("Could not sign up", error: error)
                }
            }

        } else {

            PFUser.logInWithUsernameInBackground(username.text as String!, password:password.text as String!) {
                (user: PFUser?, signupError: NSError?) -> Void in

                self.activityIndicator.stopAnimating()
                UIApplication.sharedApplication().endIgnoringInteractionEvents()

                if signupError == nil {

                    println("logged in")

                    self.performSegueWithIdentifier("push", sender: nil)

                } else {

                    if let errorString = signupError!.userInfo?["error"] as? NSString {

                        // Update - added as! String

                        error = errorString as! String

                    } else {

                        error = "Please try again later."

                    }

                    self.displayAlert("Could Not Log In", error: error)

                }
            }

        }

    }

}

I put sign-up and log-in into the same button, and I use signUpActive to take them apart, and I put self.performSegueWithIdentifier("push", sender: nil) in the log-in part, so when I input the correct password and username I can segue to a new view controller.
It works well. But when I add a new button in that new view controller which is log-out, when I click that button, I will segue to the first view controller and I use PFuser.logout() to logout, and I need to re-input the correct username and password.
Then here comes a question, even if I input the wrong username, it will segue to the second view controller, although it will show an alert saying that the username is not valid. Meanwhile, even if I click sign up not log in, it will segue too. why does it happen? Can anyone help me?

A: after trying one day, I found the answer, by using unwinded segue, this problem can be easily fixed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Strange interaction with display:flex and rowspans in IE I was trying to position: absolute an element within a table, and found that for cells which span multiple rows, it would only reach the bottom of the first cell, and that this would only happen in IE. After some tinkering, it seemed the cause of this problem was that the table was nested in a div with display: -ms-flexbox, and removing this css meant the element could reach the bottom of the second row which the cell spanned.
Here is a JS Fiddle showing what I mean. In Chrome this would work correctly, in IE10, the green boxes aren't aligned to the base of the rowspan cell.
https://jsfiddle.net/LomLdtxg/8/
Can anyone explain how these two pieces of CSS interact, and why this happens? This seems to only be an IE explorer issue, is there some workaround / hack that needs to be done in order to have it render correctly?


text:
Q: Replace single line-feed characters, keep multiples I am parsing a text file and want to remove all in-paragraph line breaks, while actually keeping the double line feeds that form new paragraphs.  e.g.
This is my first poem\nthat does not make sense\nhow far should it go\nnobody can know.\n\nHere is a seconds\nthat is not as long\ngoodbye\n\n
When printed out, this should look like this:
This is my first poem
that does not make sense
how far should it go
nobody can know.

Here is a seconds
that is not as long
goodbye

should become
This is my first poem that does not make sense how far should it go nobody can know.\n\nHere is a seconds that is not as long goodbye\n\n
Again, when printed, it should look like:
This is my first poem that does not make sense how far should it go nobody can know.

Here is a seconds that is not as long goodbye

The trick here is in removing single occurrances of '\n', while keeping the double line feed '\n\n', AND in preserving white space (i.e. "hello\nworld" becomes "hello world" and not "helloworld").
I can do this by first substituting the \n\n with a dummy string (like "$$$", or something equally ridiculous), then removing the \n followed by reconversion of "$$$" back to \n\n...but that seems overly circuitous.  Can I make this conversion with a single regular expression call?

A: You may replace all newlines that are not enclosed with other newlines with a space:
re.sub(r"(?<!\n)\n(?!\n)", " ", s)

See the Python demo:
import re
s = "This is my first poem\nthat does not make sense\nhow far should it go\nnobody can know.\n\nHere is a seconds\nthat is not as long\ngoodbye\n\n"
res = re.sub(r"(?<!\n)\n(?!\n)", " ", s)
print(res)

Here, the (?<!\n) is a negative lookbehind that fails the match if a newline is receded with another newline, and (?!\n) is a negative lookahead that fils the match of the newline is followed with another newline.
See more about Lookahead and Lookbehind Zero-Length Assertions here.


text:
Q: Gitlab Runner error exec: "sh": executable file not found in $PATH I have this error when running a container on Gitlab CI
ERROR: Job failed (system failure): Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "sh": executable file not found in $PATH: unknown (exec.go:57:0s)
My .Dockerfile
FROM golang:1.16-alpine AS builder
ENV \
    OUTDIR='/out' \
    GO111MODULE='on'

WORKDIR /app
COPY go.mod /app/
COPY go.sum /app/
RUN go mod download
COPY . /app/
RUN CGO_ENABLED=0 GOBIN=${OUTDIR}/usr/bin/ go install .

FROM scratch
COPY --from=builder /out/ /
ENTRYPOINT ["/usr/bin/app-cli"]

My .gitlab-ci.yml
stages:
  - validation

validation:
  image:
    name: gitlab.mycompany.net:4567/myteam/app-cli:latest
    entrypoint: [""]
  stage: validation
  rules:
    - if: '$CI_MERGE_REQUEST_IID'
  script:
    - ls

Is this error related to my dockerfile or the gitlab ci ?
I can run this locally by
docker run --rm -ti gitlab.mycompany.net:4567/myteam/app-cli:latest
but not at gitlab runner

A: Giving an empty entrypoint and not giving the entrypoint at all are not the same thing.
In the docker run command, you are not giving any entrypoint. Hence, the docker image runs with the default entrypoint  ENTRYPOINT ["/usr/bin/app-cli"].
In the gitlab-ci, you are overwriting the default entrypoint with an empty one entrypoint: [""] where executable file not found.
Try this:
validation:
  image:
    name: gitlab.mycompany.net:4567/myteam/app-cli:latest
    entrypoint: ["/usr/bin/app-cli"]

A: Besides overwriting the entrypoint as already pointed out, the issue is that you are calling ls as the script which requires a shell.
Try just calling your application in the script part /usr/bin/app-cli.

A: found the answer
I just need to change the
FROM scratch to
FROM alpine:latest
so now I can use the sh


text:
Q: Firebase on OS X persistent file location? I enabled persistence on my Mac app, but even though I've reset the data on Firebase server and there is now an internet connection, the Mac app isn't updating with the server data neither is the server updating with the Mac data...
Aside from the fact that this is weird and I'd expect data to sync one way or the other, where is the local offline file stored so I can delete it?

A: No replies so answering my own question.
Managed to track down the local files to this location
~/.firebase/default/<yourfirebaseurl>_appname


text:
Q: Binding entire object with converter to text I have a ListBox with a the entire bound object being passed in to the converter (needed), and the object doesn't seem to be updating correctly. Here's the relevant XAML
<TextBlock
          Text="{Binding Converter={StaticResource DueConverter}}"
          FontSize="{StaticResource PhoneFontSizeNormal}"
          Foreground="{StaticResource PhoneDisabledBrush}" />

And the Converter
public class DueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;
        Task task = (Task)value;
        if (task.HasReminders)
        {
            return task.Due.Date.ToShortDateString() + " " + task.Due.ToShortTimeString();
        }
        else
        {
            return task.Due.Date.ToShortDateString();
        }
    }

    //Called with two-way data binding as value is pulled out of control and put back into the property
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And finally the due DateTime from the data model.
private DateTime _due;

    [Column(CanBeNull=false)]
    public DateTime Due
    {
        get { return _due; }
        set
        {
            if (_due != value)
            {
                NotifyPropertyChanging("Due");
                _due = value;
                NotifyPropertyChanged("Due");
            }
        }
    }

The NotifyPropertyChanging/Changed work, because other controls bound to different properties update correctly.
My goal is to have the due date TextBlock update whenever Due is changed, but the format of the output is dependent on another property of the Task object.
Any thoughts?

A: The TextBlock.Text property is bound to a Task instance, it doesn't care about "Due". Whenever you change the value of "Due" you also need to raise the property changed event for "Task", for that binding to update itself.


text:
Q: Viewing a generated data file in a directory from graylog My application generates few data files/output files in a folder
I want to Open and view these files from gralog web. Is there any tools which I can use

A: Graylog itself doesn't support reading from files directly. In order to view the files contents in the Graylog web interface, you first need to index them.
For ingesting those files into Graylog, you have several possibilities:

*

*rsyslog with imfile input module: http://www.rsyslog.com/doc/v8-stable/configuration/modules/imfile.html

*nxlog with file input module: http://nxlog-ce.sourceforge.net/nxlog-docs/en/nxlog-reference-manual.html#im_file

*logstash with file input plugin: https://www.elastic.co/guide/en/logstash/current/plugins-inputs-file.html

*Filebeat: https://www.elastic.co/guide/en/beats/filebeat/current/index.html
All of those support sending data to Graylog, e. g. directly via GELF.


text:
Q: Python madlib while loop issue My attempt at a Python switch statement basically. Cant get this loop to work. just prints same thing each time.
choice = input("Do you want to play a game? (y) or (n)")
while choice == "y":
while True:
    print("1. Fun story")
    print("2. Super Fun story")
    print("3. Kinda Fun story")
    print("4. Awesome Fun story")
    print("5. Some Fun story")

    choice2 = int(input("Which template of madlib would you like to    play(Enter the number of your choice"))

if choice2 == 1:
    noun1 = input("Enter a noun: ")
    plural_noun = input("Enter a plural noun: ")
    noun2 = input("Enter another noun: ")
    print("Be kind to your {}-footed {}, or a duck may be somebody's {}".format(noun1, plural_noun, noun2))

else:
    print("Goodbye")

A: Very easy to create problems when using "while True". You may want to end your program with a proper exit condition, but a few adjustments to your indentation and a break statement solves the problem. Before, the if conditional was never reached, as it was outside of the second while loop, causing the story choices to be printed out again after your choice2 was made. This should work:
choice = input("Do you want to play a game? (y) or (n)")
while choice == "y":
    while True:
        print("1. Fun story")
        print("2. Super Fun story")
        print("3. Kinda Fun story")
        print("4. Awesome Fun story")
        print("5. Some Fun story")

        choice2 = int(input("Which template of madlib would you like to play (Enter the number of your choice) "))
        break # break out of this while loop to reach if/else

    if choice2 == 1:
       noun1 = input("Enter a noun: ")
       plural_noun = input("Enter a plural noun: ")
       noun2 = input("Enter another noun: ")
       print("Be kind to your {}-footed {}, for a duck may be somebody's {}".format(noun1, plural_noun, noun2))

    else:
        choice = "n" # Assume user does not want to play, reassign choice to break out of first while loop (exit condition to prevent infinite loop of program)
        print("Goodbye")


text:
Q: When I print Word document to pdf the page numbers change to {PAGE } When I print Word document to pdf the page numbers change to {PAGE }.
How do I solve this?

A: Most probably you've activated the option print field codes instead of their values.

I assume this option is checked for you


text:
Q: How to stop Someone to delete the application from iPhone device I am working on one application in which I need that My application not get deleted by someone. If someone wants to delete the application from iPhone, then the pop up will appear to ask the password. If the password is correct then the application gets deleted.
But I have studied that,
go to the Settings app on your device's home screen, tap "General", scroll down, tap "Restrictions", tap "Enable Restrictions", create a four digit passcode and enter it again when prompted, and then toggle "Deleting Apps" to OFF.
But this procedure will be applied for all the applications in the iPhone device. But if I want to restrict one app with password and to not be deleted by User, then what I should do for this?

A: I don't think you can do this as the deletion of apps is handled by the operating system and not by individual apps.

A: This type of feature can be abused, forcing iOS users to have a certain app installed. That's probably why this feature doesn't exist. And just like what Abraham mentioned, iOS handles the deletion.


text:
Q: Swapping two numbers by reference and using pointers? I tried to make a program of swapping two numbers, but when i run this program its shows error and i am confused how to do it by using pointers and reference.
A program to swap two numbers by using reference and pointers.
    #include <iostream>
using namespace std;
void swap(int &, int &);
int main()
{
    int a, b;
    cout<<"Enter the value of a and b:";
    cin>>a>>b;
    cout<<"Before swapping......";
    cout<<"A=" <<*a;
    cout<<"\nB=" <<*b;
    swap(a,b);
    cout<<"\nAfter swapping......";
    cout<<"\nA="  <<a;
    cout<<"\nB="  <<b;
    return 0;
}
void swap(int & *x, int & *y)
{
    int temp;
    temp=x;
    x=y;
    y=temp;
}

Here i got error.

There are the statements in which i am having errors.
cout<<"A=" <<*a;

cout<<"\nB=" <<*b;

void swap(int & *x, int & *y)

A: Error message clearly says in what part of program you are having an error. You are using multiplication (*) in your cout. It should be just like this:
cout << "A = " << a;
cout << "\nB = " << b;

Also in your swap method, it should be like this:
void swap(int x, int y)
{
    int temp;
    temp=x;
    x=y;
    y=temp;
}


text:
Q: Can I perform conformance checking for process mining in R? I am new to process mining field and I am trying to do process mining in R with "bupaR" package.
is there a way to perform conformance checking in R?
I know there is a package called "pmineR" that performs conformance checking, I have tried this but I can't figure out the result.
unfortunately, online help about this function in "pmineR" package doesn't provide sufficient support.
below, you can find the code that I have used for conformance checking:
library(pMineR)

confCheck_easy(verbose.mode = TRUE)

all in all, I want to know if it is possible to do conformance checking in R and if so, I would be thankful if the right package and the guide to use that package could be provided.
thanks in advance

A: Yes, this is possible with the bupaR package in R. Install it via install.packages("bupar") or check out the website.


text:
Q: Перемещение содержимого файла Необходимо организовать перемещение содержимого файла блоками. Например скопировать первые 20 байт в другой файл, а в исходном их удалить.
Пробовал так:
if(result == QDialog::Accepted)
    {
        QFile source("/home/vivo/test");
        source.open(QIODevice::ReadWrite);
        QFile destination("/home/vivo/testcopy");
        if (!destination.exists())
        {
            creat("/home/vivo/testcopy", 0777);
        }
        destination.open(QIODevice::WriteOnly | QIODevice::Append);
        if (destination.isOpen() && source.isOpen())
        {
            bool OK;
            int block = QInputDialog::getInt(nullptr, "Размер блока", "Укажите размер блока: ", QLineEdit::Normal, 0, 100, 2, &OK);
            if(OK)
            {
                QByteArray empty(block, 0x0);
                QByteArray buffer;
                buffer = source.read(block);
                destination.write(buffer);
                source.seek(0);
                source.write(empty);
            }
            else
            {
                QByteArray buffer;
                QByteArray empty(source.size(), 0x0);
                buffer = source.readAll();
                destination.write(buffer);
                source.write(empty);
            }
            destination.close();
            source.close();
        }
        else
        {
            QMessageBox::warning(this,"Ошибка", "Не удалось открыть Ошибка", "Не удалось открыть файл");
        }
    }

Это работает, но только 1 раз. При повторном перемещении MessageBox не выскакивает, файлы открываются, но данные не перемещаются.
В чем моя ошибка?

A: Вы не удаляете первые 20 байт из исходного файла, а перезаписываете их нулями. Соответственно во второй раз у вас копируются нули, которые потом оказываются во втором файле. Вам следует перечитать всё содержимое исходного файла начиная с 20-й позиции и перезаписать начало файла.


text:
Q: Feed rendered jsp pages through htmltidy I have a Java project running on Glassfish that renders some ugly looking HTML. Its a side effect from using various internal and external JSP libraries. I would like to set up some sort of post-render filter that would feed the final HTML through HTMLTidy so that the source is nice and neat to aid debugging. Is this possible?
Is there a built in mechanism to perform some action after the server renders the JSPs into HTML?
Can that action get the generated HTML as a string and manipulate it?
Is there some easy built-in option to do this without extra coding?

A: JTidyFilter

A: This behaviour can also be eliminated to a certain degree by setting the JSP 2.1 property trimDirectiveWhitespaces to true. This can be enabled in individual JSP files by:
<%@page trimDirectiveWhitespaces="true" %>

Or on all JSP files by the following entry in web.xml (which needs to be declared Servlet 2.5!):
<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <trim-directive-whitespaces>true</trim-directive-whitespaces>
    </jsp-property-group>
</jsp-config>

In pre-JSP 2.1 containers or in JSP 2.1 containers which actually doesn't support this for some internal reasons, such as Tomcat, you need to consult its JspServlet documentation for any initialization parameters. In for example Tomcat, you can configure it as well by setting the trimSpaces init-param of JspServlet to true in Tomcat's /conf/web.xml:
<init-param>
    <param-name>trimSpaces</param-name>
    <param-value>true</param-value>
</init-param>

Noted should be that the both approaches doesn't really "reformat" the HTML code. It actually only trims the whitespace which is left by taglibs and scriptlets. Also see this Sun article. So for example the following..

    <c:forEach items="${list}" var="item">

${item}

    </c:forEach>

..would basically end up in

item1

item2

item3

Thus with double indentation. You can actually workaround this by reformatting the code as such that JSP tags are half-indented:

  <c:forEach items="${list}" var="item">

${item}

  </c:forEach>

But I think the JTidyFilter is easier here :)

A: If you can alter control flow so that you get the html output before it's returned to the browser, then jtidy may help you.
I would view this as a worst-case fix though. In the long run, what should help more is to separate your html generating code and refactor that. Even in large, complex projects, you should be able to do this in small pieces and you'll get a gradual improvement. Otherwise, if the your problems grow to the point where tidy can't help, you'll be back where you started (and with even more unwieldily code to deal with).


text:
Q: Remove characters from string when passing as parameter I've tried Googling this and tested every permutation I could come up with, but I'm just not getting it. :(
I have a function which accepts an identified input string:
[user@Dreadnaught /]$ myfunction -w InputString

The function has several input options, so I need to identify that I'm passing my string to the -w option. The string I'm getting from another program has dashes in it:
In-put-St-ring

I can remove those dashes when testing an echo:
[user@Dreadnaught /]$ echo "In-put-St-ring" |tr -d -
InputString

But I can't figure out how to strip the dashes when passing to the function. I've tried (unsuccessfully):
[user@Dreadnaught /]$ OldString="In-put-St-ring"
[user@Dreadnaught /]$ echo $OldString
In-put-St-ring
[user@Dreadnaught /]$ NewString=$OldString|tr -d -
[user@Dreadnaught /]$ echo $NewString

[user@Dreadnaught /]$ NewString=$($OldString|tr -d -)
-ash: In-put-St-ring: not found
[user@Dreadnaught /]$ NewString=$("$OldString"|tr -d -)
-ash: In-put-St-ring: not found
[user@Dreadnaught /]$ NewString=$(""$OldString"|tr -d -")
-ash: In-put-St-ring|tr -d -: not found

and...
[user@Dreadnaught /]$ myfunction -w $("In-put-St-ring" |tr -d -)
-ash: In-put-St-ring: not found
myfunction: option requires an argument -- 'w'

and... a few more.
I'm sure it's simple for someone with more bash experience than me, but I'm stumped. Thanks for your help!

A: You forgot to use echo.
A pipe doesn't send variables to a command – a pipe connects one command's output to the other command's input. That is, the whole echo "In-put-St-ring" is first processed and only then its output is sent to tr; not the other way around.
In other words, every time a pipe is used, you can interpret it like this:
(echo "$OldString") | (tr -d -)

Because the syntax used inside $( ... ) substitution is exactly the same as in the "main" command line, you also need to use echo to actually produce the variable's contents as output before they can be piped:
NewString=$(echo "$OldString" | tr -d -)

myfunction -w "$(echo "$OldString" | tr -d -)"

That said, there is actually an alternative bash-specific method to pipe just some text without a whole command (although it's not necessarily better; in some cases perhaps even worse):
NewString=$(tr -d - <<< "$OldString")

myfunction -w "$(tr -d - <<< "$OldString")"

But instead of either, you should just use parameter expansion:
NewString=${OldString//-}

myfunction -w "${OldString//-}"


text:
Q: How to dependency inject Microsoft Graph client in ASP.Net Core 6 Web Api I'm trying to setup a web api using ASP.Net Core 6 so that users can hit my end points and then I do some work in Teams using a privileged account. I don't think I am wiring up the DI part correctly because I get the following error when making the request to Teams:
MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.

Here is how everything is setup:
Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApi(builder.Configuration, "AzureAd")
            .EnableTokenAcquisitionToCallDownstreamApi()
               .AddMicrosoftGraph(builder.Configuration.GetSection("Graph"))
            .AddInMemoryTokenCaches();

appsettings.json
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "<< domain >>",
    "TenantId": " <<tenant id >>",
    "ClientId": " << client id >>",
    "ClientSecret": " << client secret >>"
  },

  "Graph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "https://graph.microsoft.com/.default"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Teams.cs
namespace GraphApiService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class Teams : ControllerBase
    {
        private readonly GraphServiceClient _graphServiceClient;

        public Teams(GraphServiceClient graphServiceClient)
        {
            _graphServiceClient = graphServiceClient;
        }

        // GET: api/<Teams>
        [HttpGet]
        public  IEnumerable<string> Get()
        {
            //Throws an error here!
            var teams = _graphServiceClient.Teams[<< team id >>].Request().GetAsync().Result;

            return new string[] { "value1", "value2" };
        }
   }
}

Now if I skip the DI part and just setup the client in the constructor, it works fine.
public Teams()
{
   var scopes = new[] { "https://graph.microsoft.com/.default" };
   var tenantId = " << tenand id >>";
   var clientId = "<< client id >>";
   var clientSecret = "<<client secret>>";

   var options = new TokenCredentialOptions
   {
       AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
   };

   var clientSecretCredential = new ClientSecretCredential(
       tenantId, clientId, clientSecret, options);

  _graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);

}

Any help would be appreciated. Thanks!

A: Well this always happens. Spend two days looking for an answer. Post to a forum, and find the answer a few hours later. I got it to work by using 'WithAppOnly()' like this:
var teams = _graphServiceClient.Teams[teamId].Request().WithAppOnly().GetAsync().Result;

All the examples online use delegated user permissions, so it was hard to find anything on how to to handle app permissions.


text:
Q: Converting Mongo db result to JSON I am using Phalcon framework with MongoDB database, this project is a restful project and i need json output from each controller, i have a collection in MongoDB database and when i reading it and converting to json, i am getting a result like below :
{
    "_meta": {
        "status": "SUCCESS",
        "count": 1
    },
    "records": {
        "_id": {
            "$id": "5659c36e9dd39ed34024f9a1"
        },
        "name": "main",
        "cities": [
            {
                "_id": {
                    "$id": "5659c36e9dd39ed34024f9a2"
                },
                "name": "child1"
            },
            {
                "_id": {
                    "$id": "5659c36e9dd39ed34024f9bd"
                },
                "name": "child2"
            },
            {
                "_id": {
                    "$id": "5659c36e9dd39ed34024f9be"
                },
                "name": "child2"
            }
        ]
    }
}

And as you can see , we have a field with "$id" name, i think it is not good, because i am using this result in mobile apps, and it will case a problem for me when i want to parse this json to POJO classes.
I know why we have "$id" in output, but i don't know how can i replace it, i don't want to use str_replace or foreach syntax, i believe phalcon or mongodb model in Phalcon, should have a solution for it.
What is the solution?

A: Iterate recursively through the object and unset the property

A: I guess something like that:
If we assume that the object you get from the db is $result:
// Object from db
$result;

// Get only records
$records = $result->records;

// Unset undesired properties recursively
$this->iterateRecursively($records);

public function iterateRecursively($object, $properties = ['_id'])
{
    foreach ($object as $key => $value){

         // Unset undesired properties
         foreach ($properties as $property){
              if ($key === $property){
                 unset($object->{$property});
             }
         }

         // Dig deeper into object
         if (is_object($value)){
             $this->iterateRecursively($value);
         }
    }
}


text:
Q: Upload WAR file to an FTP server I've just finished a web project, working with Struts2, and now I want to add this project to my FTP site. The site runs smoothly on Tomcat 8, but I am not sure how to deploy it to an actual site.
How do I add this .WAR file that has .jsp and .xml files to a website? I've tried to just put it in a directory and launch it with fileZilla, and it doesn't work.
What should I do to launch my Struts2 project to my FTP site?

A: I assume you need to deploy it again on your FTP site. You need to deploy it into your webapps folder of your server. You may look at this link. This might help you :)

A: *

*In FileZilla put your user name and password.

*In left side will show your machine file

*On right side put path of your webapp folder, It will come in mail when you buy any server from hosting providers or ask them.

*Upload your .WAR file in webapp folder.

*Restart Tomcat.


text:
Q: What is the connection between the electroweak energy scale and the vacuum expectation value? I am quite confused about energy scale and  vacuum expectation value (VEV). For example, this wiki page says 246Gev is VEV of Higgs field. Does it mean if we go to a higher energy scale (like 24600Gev) for a lower energy scale (like 0.0246Gev), we will not observe Higgs field as well as other electroweak process?

A: You have $v\equiv 246$GeV, whence the Fermi constant $G_F=v^2/\sqrt 2$ controlling weak interactions with energies much below your conjectural v/100  is all these interactions "know" about the Standard Model. The masses of the W & Z vector bosons are about a third of v and their effect on the relevant interactions is indirect at these energies.
The mass of the Higgs boson  happens to be about half of v, by "accident", and it is hard to see any effects of it in your conjectural v/100  energies, beyond the theoretical explanation of all fermions masses; so it is a "pie in the sky" issue at these energies.
By contrast, at your higher conjectural energies of 100v, you are well above threshold for production of W, Z, and the higgs, and, in fact, you would expect to start seeing "equivalence theorem" features of EW unification, as v/E  will then be a "small" number! A small perturbative correction to expected SM amplitudes "before breaking" and the inner workings of the SM.


text:
Q: Xamarin iOS Unwind Segue or DismissViewController programmatically and pass back data I have created a segue in my storyboard.  It is a modal segue and I gave it an identifier of LoginSegue.
In my controller, I do:
PerformSegue("LoginSegue", this);

All is well.  New controller comes up as expected.
To return to the calling view, I can use an unwind segue by wiring a button to the unwind segue in the calling controller.  This works fine.
Or I can call (from code):
DismissViewController(true, null);

The thing is that I want to pass back some data.
The ParentViewController is null.
I do need to do some validation before I return to the calling view, so doing the auto unwind from a button is not an option.
   [Action("UnwindToCaller:")]
   public void UnwindToCaller(UIStoryboardSegue seque)
   {
       var loginViewController = (LoginViewController)seque.SourceViewController;
       var data = loginViewController.getData();
       Console.WriteLine("Unwind to Caller Here.");
   }

I also cannot seem to find a way to give the unwind segue a storyboard Id.
If I could perform the unwind segue from code everything would be good, or if I could pass some data back with the DismissViewController that would be good too.
Again, this seems like a pretty common thing to do.

A: OK, found a solution.  Hope this helps others.
So in my calling view controller, when I PrepareForSegue, I pass a reference to the calling view controller.  Then I have a method that is called from the modal view.
Here is the Xamarin reference: http://developer.xamarin.com/recipes/ios/general/storyboard/storyboard_a_tableview/
public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
   {
       if (segue.Identifier == "LoginSegue")
       {
           var destCtrl = segue.DestinationViewController as LoginViewController;
           if (destCtrl != null)
           {
               // pass in a reference to THIS view controller.
               destCtrl.SetData(this);
           }
       }
       base.PrepareForSegue(segue, sender);
   }

Also in the Calling View Controller
   public void LoggedIn (string someFlag)
   {
       Console.WriteLine("Logged in with : " + someFlag);
       DismissViewController(true, null);
   }

And the LoginViewController
public void SetData (CallingViewController callingCtrl)
    {
        calllingViewController = callingCtrl;
    }

Then when I am ready to return.
callingViewController.LoggedIn("the flag");


text:
Q: How to copy files from a remote computer? I have set up a new pc, and I want to copy data from my old pc to it, without having to manually copy everything to an external drive.
I guess I could do something with rsync over ssh, but have no idea of how to accomplish that.
Anyone?

A: rsync is pretty easy to use. You will need to know the ip address or name of the machine. So if your new machine is called shiny and the old machine is called abandoned, and you have the same user on both machine then to copy to the data over you would type this on shiny:
rsync avz username@abandoned:/home/user /home/user

Substitute the IP addresses if you don't know the names. You should be able to ping the other machine if they are on the same network. You can get the IP address by typing ifconfig.
Alternatively, you could take the old hdd and mount it either on the machine physically if its a desktop in the spare slot and just copy the files over. Or use a sata/usb lead to mount it, or one of these toasters:

A: You can easily use Nautilus to copy your data from a remote PC: Connect both units via ethernetfor example, open Nautilus on the new machine, press F3 to have two file browsers in your window, navigate the left one to your destination directory and the right one to your source directory (using "network", you need to know username and password of the old machine). Now you can simply drag and drop items from left to right and vice versa.


text:
Q: Possible reasons why my shadowsocks not working on virmach's server? I'm a new comer to using the overseas server. Recently I bought a vps from virmach in order to see foreign websites like google and wiki.
I've been trying for a long time configuring my shadowsocks on my server.
However, when I was using shadowsocks-qt5 to connect my server, it was timeout.
And of course I can't access google correctly.
What I want to ask is the reason why I failed.
Here are things that I do remember to do:

*

*stop the firewall on both computers;

*build the .json file which I referred to blogs in China.

Here are the outline of my shadowsocks.json on my server:

{
       "server":"0.0.0.0",
       "server_port":8388,
       "local_address":"127.0.0.1",
       "local_port":1080,
       "password":"XXXX",
       "timeout":600,
       "method":"aes-256-cfb"
  }

Other useful(maybe) information:

*

*my client OS version: Ubuntu 18.04.3 LTS

*my server OS version: Ubuntu 16.04.6 LTS

*the client I choose is from: https://github.com/shadowsocks/shadowsocks-qt5
I could not help but wandered, are there any other possible reasons I've forgot? Can anyone inform me some helpful details to solve this puzzling problems? Thanks a lot!

A: I have not set up my own VPS but I have instead subscribed to the server provided by caonima.io, so I can't speak for any server related issues. Additionally, I have no affiliation with caonima.io. I did however successfully set up my client on Ubuntu 16.04 after having some issues connecting to GFW-blocked (China's Great FireWall) websites.
From what I understand from my solution, the client configuration is NOT the only step of setup. There are two layers of proxy access that need to be completed:

*

*Client Configuration. Configure your client with the server and connection information. A successful connection looked like this for me with my command line interface

shadowsocks-libev command line client successful connection

*System or Browser Proxy Configuration. You will need to configure either your browser or web access tool to use a proxy, or set system-wide proxy settings. To set system wide proxy settings, go to system settings > network > network proxy and enter the proxy information. Setting Socks host to localhost:1080 resulted in successful GFW-blocked website access (as shown below)!

Ubuntu network settings proxy manual configuration


text:
Q: Database error in code. What isn't working is the grade query $Prereq = "SELECT PreReqId FROM PreReq WHERE CourseId ='$CCourseId'";
$Query1= mysqli_query($db,$Prereq);
$array1 = mysqli_fetch_array($query1,MYSQLI_ASSOC);
$value= $array1['PreReqId'];

foreach($value as $i => $test)
{
    $Grade = "SELECT Grade FROM Enrolled WHERE CourseId = '$test' AND UserId ='$UserId'";
    $query2= mysqli_query($db,$Grade);
    $array2= mysqli_fetch_array($query2,MYSQLI_ASSOC);
    $value2= $array2['Grade'];

    if($value2 == 'A' || $value2 == 'B' || $value2 == 'C')
    {
        return result = 1;

    }
    else
    {
        return result =0;
    }
}

I have to check for preqrequitie grades for courses before a user can enroll in a class. As is I am able to get and echo the right prereqId. What isn't working is the grade query. Not sure why.

A: Though the question is rather unclear. I can suggest the following;

*

*Your first query $Prereq only selects one value: PreReqId

*You
have a typo in $Query1and than using it as mysqli_fetch_array($query1,MYSQLI_ASSOC)

*It is not clear where $UserId is being set.

*Try using Prepared statements to prevent Sql injections

Try the following:
$Prereq = "SELECT * FROM PreReq WHERE CourseId ='$CCourseId'";
$query1= mysqli_query($db, $Prereq);

// loop through query results
while ($row = mysqli_fetch_array($query1, MYSQLI_ASSOC))
{
    // For each row perform another query
    $Grade = "SELECT Grade FROM Enrolled WHERE CourseId = '".$row['PreReqId ']."' AND UserId ='$userId'";
    $query2= mysqli_query($db, $Grade);
    while ($row2 = mysqli_fetch_array($query2, MYSQLI_ASSOC))
    {
        if($row2['Grade'] == 'A' || $row2['Grade']== 'B' || $row2['Grade'] == 'C')
        {
            return result = 1;

        }
        else
        {
            return result =0;
        }
    }
}

A: Why not have your database perform this logic and just check if any prerequisites are missing?
function isStudentAllowedToEnroll($UserId, $CCourseId) {
    $student_may_enroll = false;

    // I assumed your MySQL connection is in the global scope, if not you can
    // also just pass it in as another argument to the function if you'd like
    global $db;

    // Find all prerequisites for the course, exclude the ones the student
    // has passed, then count how many are left
    $query = "
        SELECT COUNT(*)
        FROM   PreReq
          LEFT JOIN Enrolled
          ON        Enrolled.CourseId = PreReq.PreReqId
          AND       Enrolled.UserId = ?
          AND       Enrolled.Grade IN ('A', 'B', 'C')
        WHERE  PreReq.CourseId = ?
        AND    Enrolled.CourseId IS NULL
    ";

    if ($stmt = $db->prepare($query)) {
        // I'm assuming your ids are integers, if they're strings change "ii" to "ss"
        $stmt->bind_param("ii", $UserId, $CCourseId);

        if ($stmt->execute()) {
            $stmt->bind_result($missing_prerequisites);
            $stmt->fetch();

            if ($missing_prerequisites == 0) {
                // No missing prerequisites, student is allowed to enroll
                $student_may_enroll = true;
            }
        } else {
            trigger_error($stmt->error, E_USER_WARNING);
        }

        $stmt->close();
    } else {
        trigger_error($db->error, E_USER_WARNING);
    }

    return $student_may_enroll;
}

I can understand if the query is a bit confusing. What it does is find all prerequisites for the course from the PreReq table. For each prerequisite, it tries to find a matching course in the Enrolled table for the given student with a passing grade. It then discards those matches, so in the end it counts the number of prerequisites that the student has not passed; either because the student hasn't enrolled in it or because they don't have a passing grade for it.

A: If the user id is an int value you should remove the single quotes.


text:
Q: Document.ready not working when using grunt server I have those scripts in my index.html for testing grunt build web app, but I found that, it actually not running the function when DOM ready, if in a normal way to run this index.html, it works, but in grunt, it not, is there any potentials problems may cause it?
    <script>
        $(document).ready(function() {
            $('.button_1').click(function() {
                $(".voltage").show();
                $(".current").hide();
                $(".button_2").hide();
                });
            $('.button_2').click(function() {
                $(".voltage").hide();
                $(".current").show();
            });
        });
    </script>

PS. I have jquery.js loaded before running it.


text:
Q: How can I make a static array with references to trait implementations in Rust? I want to be able to iterate over an array of parsers trying to find a delegate parser from a main parsing function. The list of parsers is known at compile-time, so I want this to be a constant.
I've tried some varieties of this but I can't get it to work:
const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];

How can I achieve this?
Notes:

*

*Parser is a trait.

*CommentParser is a struct implementing Parser.

*there are other implementations of Parser but they are not shown for simplicity.

*even though all parser implementations are known at compile-time, I just want to avoid explicitly trying one by one as that would make the code worse than I think it should be.

The error I get currently:
|
11 | const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];
   |                    ^^^^^^^^^^^^ the trait `parsers::Parser` cannot be made into an object
   |
   = note: method `parse` has generic type parameters

I can't see any generics in the parse method:
pub trait Parser {
    fn opening_char(self: &Self) -> char;
    fn parse(&mut self, env: impl ParserEnv) -> ParseResult;
}

If I make the types values:
const ALL_PARSERS: [Parser; 1] = [CommentParser {}];

The error becomes:
11 | const ALL_PARSERS: [Parser; 1] = [CommentParser {}];
|                    ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn parsers::Parser + 'static)`

A: Trait references need to be marked as &dyn, e.g. &dyn Parser:
trait Parser { }

struct CommentParser { }
impl Parser for CommentParser { }

const ALL_PARSERS: [&dyn Parser; 1] = [&CommentParser {}];

fn main() {
    for &parser in &ALL_PARSERS {
        // do something with parser
    }
}

Link to playground example

Also, as this answer to a related question states, you can't have a generic parameter in your trait if you want to make a trait reference, so you'll need to either add a generic type to the trait itself, or use a trait reference instead of impl in your parser type:
// original (with error)
trait Parser {
    // impl ParserEnv is an implicit generic type
    fn parse(&mut self, env: impl ParserEnv) -> ParseResult;

    // same as:
    //   fn parser<E: ParserEnv>(&mut self, env: E) -> ParserResult;
}

// alternative 1, with trait generic type
trait Parser<E: ParserEnv> {
    fn parse(&mut self, env: E) -> ParseResult;
}

// alternative 2, with trait reference
trait Parser {
    fn parser(&mut self, env: &dyn ParserEnv) -> ParserResult;
    // may need &dyn mut ParserEnv if you want to modify env as well
}

I think the second approach may be the best, since then you can store the parsers in the array without needing to assign a particular ParserEnv type to the parsers.


text:
Q: How to get the access token from the redirect_uri? I am creating a web based application and want to get data from Basecamp using their API through OAuth2.
I have successfully redirected my page to this link my redirect_uri, but I couldnt get any access token from the page.
How to get the access token using the flask application that I have created?
Any code samples will be much appreciated.
@app.route('/')
def index():
    if 'basecamp_token' in session:
        ret = remote.get('email')
        return jsonify(ret.data)
        return redirect(url_for('login'))
    else:
        return redirect(url_for('redirecturl'))

@app.route('/login')
def login():
    return basecamp.authorize(callback=url_for('authorized', next=request.args.get('next') or request.referrer or None))

@app.route('/authorized')
@basecamp.authorized_handler
def authorized(resp):
    if resp is None:
        return 'Access denied: error=%s' % (
            request.args['error']
        )
    if 'basecamp_token' in resp:
        # session['example_oauth'] = resp
        print(resp)
        return jsonify(resp)
    return str(resp)

@app.route("/redirecturl")
def redirecturl():
    return redirect('http://basecamp.com/oauth2')

if __name__ == '__main__':
    app.secret_key = 'super_secret'
    app.run(port=8000, debug=True)


text:
Q: Что такое .col-sm в Bootstrap? вроде бы разобрался с классами .col и .offset , но не пойму .col-sm, как написано по английский , если я правильно перевёл, это сброс .offset

In addition to column clearing at responsive breakpoints, you may need to reset offsets.

, но тогда пример вообще не понятен

.col-sm-5 .col-md-6

.col-sm-5 .offset-sm-2 .col-md-6 .offset-md-0

.col-sm-6 .col-md-5 .col-lg-6

.col-sm-6 .col-md-5 .offset-md-2 .col-lg-6 .offset-lg-0

вот его результат

A: Класс col-sm-* означает количество колонок на экранах шириной ≥ 576px. Непосредственно к offset он не имеет отношения: отступ можно добавить на любых размерах экрана.
А вообще, прежде чем верстать на бутстрапе, как следует изучите документацию на русском - там всё подробно и понятно описано.


text:
Q: How can I use a string to load a variable stored in a .mat-file? I have a function which reads a .mat-file, which contains several vectors. Now I want to analyse just a single of those variables, say variableA. So what I have in the function is:
variable = variableA;

The rest of the function works on variable. Consequently, when I want to analyse variableB, I simply change it in the statement above. Is it possible to pass a string, say 'variableA', as an input to the function, so that I can assigns the values of variableA to variable?
For example something like this:
string = 'variableA';
variable = something(string);  % now variable holds the values of variableA

A construct like the above would make it easier to change between all the variables. All I have been able to find were functions which allow me to assign values to the variable defined by the string and thus not the other way around.

UPDATE
To hopefully clarify my question, say you have the following function:
function analyseFile(name)
%Load the file
load(file.mat)
toAnalyse = %variable from file.mat with name "name" from the argument
%Do some analysis e.g.
time = 0:0.001:(length(toAnalyse)-1)*0.001;
x = lsqcurvefit(@PronySeries,ones(2,1),time,toAnalyse,[0,0],[]);
%And e.g. some plotting
plot(time,toAnalyse)
hold on
plot(time,PronySeries(x,time))
end

Now, I want to specify which variable of the .mat-file should be loaded by the function and subsequently be analysed. Therefore, the argument name should be used as the variable name.
I am looking for a less error-prone method than eval. Sorry, this was not noted in the original post. The solution does not have to transform the string to a variable per se. Solutions involving cells would be perfectly fine.


text:
Q: How to parameterize a bivariate Normal distribution output for a neural network? For a neural net where the output is a Gaussian distribution, the output is usually parameterized as $(\mu=O_1, \sigma^2=e^{O_2})$. That is to say, the neural net will output the mean, and also output the log of the variance $O_2$. This is the natural choice to make all the outputs fit on the real line, and works well when training the neural net.
However, I want to output a bivariate Gaussian distribution (with 2 means $\mu_1$ and $\mu_2$, 2 variances $v_1$ and $v_2$, and a correlation $\rho$). The problem is, there are several natural ways to parameterize the variances and correlation (such that everything is a real number).
To name just 2:

*

*Each parameter gets its own output.
\begin{align}
v_1 &= e^{O_1} \\
v_2 &= e^{O_2} \\
\rho &= tanh(O_3)
\end{align}

*Say that
\begin{align}
X_1 &= Z_1 + Z_c \\
X_2 &= Z_2 + Z_c
\end{align}
where $Z_i\sim\mathcal{N}(0, e^{O_i})$ are "private information" and $Z_c\sim\mathcal{N}(0, e^{O_3})$ is a "shared" gaussian information. Then we will have that
\begin{align}
v_1 &= e^{O_1} + e^{O_3} \\
v_2 &= e^{O_2} + e^{O_3} \\
\rho &= \frac{e^{O_3}}{\sqrt{v_1 \cdot v_2}}
\end{align}
Which of these ways of parameterizing the output bivariate Gaussian distribution would be best? Or is there a better way? My main criteria would be what works best when training a neural network.
Personally, I think that the second way would be better, since the choice of correlation should be closely tied to the choice of variances, and the "private information"/"shared information" model for a bivariate Gaussian seems very natural.
Finally, I'm satisfied with just the bivariate case, but I may as well ask what one could do in the multivariate case?

A: For the multivariate case, you could try outputting a vector $d$ of diagonal entries and an $n\times k$ matrix $R$, and let $\Sigma = \text{diag}(d) + RR^T$. This would be easy to sample, easy to backpropagate through, and also you can trade off computation cost with expressivity (as $k \rightarrow n$, you have a full covariance matrix).


text:
Q: Show/Hide TextBox when MouseHover/MouseLeave How can I make TEXTBOX shown or hidden based on event mousehover or mouseleave? I placed the textbox over a picture.
I just tried coding this by making property of textbox visibility to false but nothing happened. I think there's a code missing?
Private Sub TextBox1_MouseHover(sender As Object, e As EventArgs) Handles TextBox1.MouseHover
        TextBox1.Visible = True
    End Sub

    Private Sub TextBox1_MouseLeave(sender As Object, e As EventArgs) Handles TextBox1.MouseLeave
        TextBox1.Visible = False
    End Sub

A: I assume you want to show the textbox as soon as you hover of the Picture.
The textbox will not listen to mouse_enter events when it is invisible.
Use your mouse events on the Picture box, not the textbox.
It is worth mentioning that your mouse leave will fire for the picture box the moment you hover onto the now visible textbox, which will make it invisible...
    Dim i_Am_in_the_picture_box as Boolean 'global variable to your class

    Private Sub picbox1_MouseHover(sender As Object, e As EventArgs) Handles picbox1.MouseHover
        TextBox1.Visible = True
    End Sub

    Private Sub picbox1_MouseLeave(sender As Object, e As EventArgs) Handles picbox1.MouseLeave
        TextBox1.Visible = False
    End Sub

You may have to write some code to check when your cursor is inside the bounds of the picturebox when a mouse_leave event is triggered (Becaue entering the textbox, will trigger the mouse_leave event of the picturebox).
If your cursor is still inside the picturebox bounds, then do not hide the textbox on picbox.mouse_leave
EDIT
Further to this, based on your comment,

thanks. but it shows the textbox wherever i mouseover. I have a
  picture of a teeth (lower and upper teeth) and it was a PNG file. When
  the dentist mouseover on a specific tooth the textbox will show and
  the dentist can put the tooth's treatment history ...in short, i want
  the textbox to be visible when mouseover in a specific area of the
  pic. is that possible? sorry i'm just a student. i tried googling but
  can't find any article/threads about this. :)

you will have to define custom bounds for each tooth, and then on mouse_move, check to see if the cursor location is inside one of those bounds. If it is, show the applicable textbox.
Here is actual working code to show you how this can be done.

*

*The following example, has two "invisible" panels positioned over a picture box (Lets say over "tooth1" and "tooth2".)

*We build two custom rectangles, using the invisible panels' location and size parameters.

*We catch the picture box's MouseMove event, and check if our cursor is in one of the rectangles we created. If it is, we show a particular textbox (And we hide whatever other textbox was visible)
This can be done with less code, but the example should explain exactly how the concept works.
Public Class Form2

    Dim tooth1 As New Rectangle
    Dim tooth2 As New Rectangle

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        'use the dummy invisble panel's location and size to create our wto rectnagles on the screen
        tooth1 = New Rectangle(dummyPanel_for_tooth_1.Location, dummyPanel_for_tooth_1.Size)
        tooth2 = New Rectangle(dummyPanel_for_tooth_2.Location, dummyPanel_for_tooth_2.Size)

    End Sub

    Private Sub _set_all_other_textboxes_invisible(visibleTextboxName As String)

        If TextBox1.Name <> visibleTextboxName Then TextBox1.Visible = False
        If TextBox2.Name <> visibleTextboxName Then TextBox2.Visible = False

    End Sub

    Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
        If tooth1.Contains(e.Location) Then

            'we are inside tooth 1 bounds
            TextBox1.Visible = True

            'hide the other textboxes we are not working with.
            _set_all_other_textboxes_invisible(TextBox1.Name)

            'we can exit here, no need to do any furher testing
            Exit Sub

        End If

        If tooth2.Contains(e.Location) Then

            'we are inside tooth 2 bounds
            TextBox2.Visible = True

            'hide the other textboxes we are not working with.
            _set_all_other_textboxes_invisible(TextBox2.Name)

            'we can exit here, no need to do any furher testing
            Exit Sub

        End If
    End Sub

End Class


text:
Q: TinyMCE issue in pasting the content from MSword-2010. No line break is seen if pasted directly I am using tinyMCE for pasting description on front end of the site. Issue I am having is - when I try to paste the content taken out directly from MS Word 2010 I am not able to see the same line spacing as on word document.
I have uploaded 3 images showing the document and content when pasted into the editor and the content displayed after getting post.

A: Problem here is you would need to set the editor width to exactly the same width of a Word 2010 page. In Word you may change the margins whcih will lead to another problem.
Another point is the font. You will need to apply the same font and same font-size in the editor (you may use the config param content_css for this).


text:
Q: Handling Sending Two Parameters in an API Call in Angular App I have a series of filter functions that allow a user to click on a series of filters in order to filter data displaying in a grid view. I have the filters working using observables when I build them using an individual function for each filter. We are using a kind of query built into mongoose that lets you pass a specific query by field in the body of a post call. I am using it like this:
    onFilterReceived(language) {
        if (language) {
            this.filtersService.getByFilter(this.page, this.pagesize, {
                "services.workflow.status" : "consulting",
                "languages.primary" : { $in: language },
                })
                .subscribe(resRecordsData => {
                    this.records = resRecordsData;
                    console.log('onFilterReceived: ' + language);
                },
                responseRecordsError => this.errorMsg = responseRecordsError);
        } else {
            this.filtersService.getByFilter(this.page, this.pagesize, {
                "services.workflow.status" : "consulting"
            })
                .subscribe(resRecordsData => {
                    this.records = resRecordsData;
                },
                responseRecordsError => this.errorMsg = responseRecordsError);
     }

My service function, being called here, looks like this:
getByFilter(page, pagesize, body) {
    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: this.headers });
    return this.http.post
    (`https://api.someurl.com/${this.ver}/customers/search?apikey=${this.key}&page=${page}&pagesize=${pagesize}`,
    body, options).map((res: Response) => res.json())
    .catch(this.filterErrorHandler);
}
    filterErrorHandler(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

This works as is.
However, what I want to be able to do is handle passing multiple key/value pairs, not just one.
You'll also notice that I am checking to only run the request if language exists - that is to say, if a language input has been sent via a filter click. This is necessary because otherwise the function errors out when querying the api because there is no value.
To handle two filters at a time, I tried doing this:
onFilterReceived(language, nationality) {
    // Receive filter selections for language
    if (language) {
        this.filtersService.getByFilter(this.page, this.pagesize, {
            "services.workflow.status" : "consulting",
            "languages.primary" : { $in: language },
            })
            .subscribe(resRecordsData => {
                this.records = resRecordsData;
                console.log('onFilterReceived: ' + language);
            },
            responseRecordsError => this.errorMsg = responseRecordsError);
    }

    // Receive filter selections for nationality
    if (nationality) {
        this.filtersService.getByFilter(this.page, this.pagesize, {
            "services.workflow.status" : "consulting",
            "services.service" : { $in: nationality },
            })
            .subscribe(resRecordsData => {
                this.records = resRecordsData;
                console.log('onFilterReceived: ' + nationality);
            },
            responseRecordsError => this.errorMsg = responseRecordsError);
     }
}

But this didn't work. While I am passing in two fields/values in the above:
        "languages.primary" : { $in: language },

And in the other one:
        "services.service" : { $in: nationality },

... the function doesn't work properly.
To clarify, if the "language" filter is clicked, I want to send the request on "language". But if the "nationality" filter is clicked, I want to send the request on "nationality".
But I also want to not lose one parameter in exchange for the other. In other words, if "spanish" is clicked on the "language" filter, I want that to "stick". Then when "American" is clicked from the "nationality" filter, I want the request to filter by BOTH of those parameters, not lose one in exchange for the other. How could I re-work this function to handle this?
By the way, events/values are being received from another component via Output() and EventEmitter(). The view looks like this:
        <list [records]="records"
            (sendLanguage)="onFilterReceived($event)"
            (sendNationality)="onFilterReceived($event)">
        </list>

And the html for my filters looks like this:
       <filter-option name="Language"
                        placeholder="Select Language"
                        [usePlaceholder]="!languageFilters.text"
                        [visible]="languageFilters.enabled">
            <filter-label>{{languageFilters.text}}</filter-label>
            <filter-menu>

                    <md-checkbox *ngFor="let option of languageFilters.options" [(ngModel)]="option.value">
                        {{option.language}}
                    </md-checkbox>

            </filter-menu>
        </filter-option>

        <filter-option name="Nationality"
                        placeholder="Select Nationality"
                        [usePlaceholder]="!nationalityFilters.text"
                        [visible]="nationalityFilters.enabled">
            <filter-label>{{nationalityFilters.text}}</filter-label>
            <filter-menu>

                    <md-checkbox *ngFor="let option of nationalityFilters.options" [(ngModel)]="option.value">
                        {{option.nationality}}
                    </md-checkbox>

            </filter-menu>
        </filter-option>

A: To make the code neat. This will handle multiple parameters.
onFilterReceived(para: any, type: string) {
    let body:any = {};
    body['services.workflow.status'] = 'consulting';
    if (type == 'lan')
        body['languages.primary'] =  { $in: para };
    if (type == 'nat')
        body['services.service'] =  { $in: para };

    this.filtersService.getByFilter(this.page, this.pagesize, body)
        .subscribe(resRecordsData => {
                       this.records = resRecordsData;
                   },
                   responseRecordsError => this.errorMsg = responseRecordsError
        );
}

In template:
<list [records]="records"
    (sendLanguage)="onFilterReceived($event, 'lan')"
    (sendNationality)="onFilterReceived($event, 'nat')">
</list>


text:
Q: How to display a variable as a total in an INPUT FIELD instead of a SPAN? I am having difficult displaying the contents of a variable in a total input field. Basically this code is functioning which is great:

Average product unit value <input type="text" id="product-unit-val" />

Total unit sales value <input type="text" id="total-unit-sales" />

Number of reps <input type="text" id="number-reps" />

Total sales value $

However I want to display the total value in an input field like:

Average product unit value <input type="text" id="product-unit-val" />

Total unit sales value <input type="text" id="total-unit-sales" />

Number of reps <input type="text" id="number-reps" />

Total sales value <input type ="text" id="sales-val"/>

Am I missing the obvious? I just can't seem to get this working.
Many Thanks

A: Use val to change the value of an input :
$("#sales-val").val(total);

But be careful with parseInt, always specify the radix :
parseInt('09') == 0
parseInt('09', 10) == 9


text:
Q: How to use xPath in Selenium WebDriver to grab SVG elements? I am testing an API, based on OpenLayers, with Selenium WebDriver (Java version).
I want to test a functionality that uses OpenLayers.Control.ModifyFeature. I want to click on drawn features (SVG), drag then and check if they are present, visible or hidden.
I have drawn a polygon, and I have selected it. See the image below:

The HTML of these SVG elements is here:
<svg id="OpenLayers_Layer_Vector_161_svgRoot" width="1235" height="495" viewBox="0 0 1235 495" style="display: block;">
    <g id="OpenLayers_Layer_Vector_161_root" transform="" style="visibility: visible;">
        <g id="OpenLayers_Layer_Vector_161_vroot">
            <path id="OpenLayers_Geometry_Polygon_200" d=" M 393.0000000000964,213.9999999999891 486.0000000003338,275.9999999997126 384.00000000036925,284.9999999994434 393.0000000000964,213.9999999999891 z" fill-rule="evenodd" fill="blue" fill-opacity="0.4" stroke="blue" stroke-opacity="1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="none" pointer-events="visiblePainted" cursor="pointer" />
            <circle id="OpenLayers_Geometry_Point_619" cx="439.50000000021464" cy="244.99999999985084" r="6" fill="#009900" fill-opacity="0.5" stroke="#ee9900" stroke-opacity="1" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="none" pointer-events="visiblePainted" cursor="inherit" />
            <circle id="OpenLayers_Geometry_Point_621" cx="435.00000000035106" cy="280.49999999958163" r="6" fill="#009900" fill-opacity="0.5" stroke="#ee9900" stroke-opacity="1" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="none" pointer-events="visiblePainted" cursor="inherit" />
            <circle id="OpenLayers_Geometry_Point_623" cx="388.50000000023283" cy="249.4999999997126" r="6" fill="#009900" fill-opacity="0.5" stroke="#ee9900" stroke-opacity="1" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="none" pointer-events="visiblePainted" cursor="inherit" />
            <circle id="OpenLayers_Geometry_Point_202" cx="393.0000000000964" cy="213.9999999999891" r="6" fill="#990000" fill-opacity="1" stroke="#ee9900" stroke-opacity="1" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="none" pointer-events="visiblePainted" cursor="inherit" />
            <circle id="OpenLayers_Geometry_Point_203" cx="486.0000000003338" cy="275.9999999997126" r="6" fill="#990000" fill-opacity="1" stroke="#ee9900" stroke-opacity="1" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="none" pointer-events="visiblePainted" cursor="inherit" />
            <circle id="OpenLayers_Geometry_Point_204" cx="384.00000000036925" cy="284.9999999994434" r="6" fill="#990000" fill-opacity="1" stroke="#ee9900" stroke-opacity="1" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="none" pointer-events="visiblePainted" cursor="inherit" />
        </g>
        <g id="OpenLayers_Layer_Vector_161_troot" />
    </g>
</svg>

Suppose I want to select the red points.
I tried:
String xpath = "//circle[contains(@id, 'OpenLayers_Geometry_Point') AND fill = '#990000']";
List<WebElement> vertices = driver.findElements(By.xpath(xpath));

But it always returns an empty list [].
What am I doing wrong here? Could anybody help me, please?
Thanks a lot.
EDIT 1 - Function: verticesAreVisible
Before the clicking actions, I want to get the elements and check if they are visible. I am using this function.
public static boolean verticesAreVisible(WebDriver driver, String xpath) {
    List<WebElement> list = driver.findElements(By.xpath(xpath));
    if (list.isEmpty()) {
        return false;
    }
    boolean visible = true;
    for (int i = 0; i < list.size(); i++) {
        visible = visible && list.get(i).isDisplayed();
    }
    return !verticesAreNotVisible(driver) && visible;
}

EDIT 2 - Correct xPath
// This solution from Razib is valid if the SVG is on the root node
String xpath = "/*[name()='svg']/*[name()='circle']";
// I changed it so that any descendant is valid "//"
String xpath = "//*[name()='svg']//*[name()='circle']";
// Since I wanted only the red vertices, I added this
String xpath = "//*[name()='svg']//*[name()='circle' and @fill='#990000']";

A: May be you need to use the Actions with name attribute in Xpath.
In your XPath use it -
"/*[name()='svg']/*[name()='SVG OBJECT']"

Then try the following code snippet -
WebElement svgObj = driver.findElement(By.xpath(XPATH));
Actions actionBuilder = new Actions(driver);
actionBuilder.click(svgObj).build().perform();

A: To locate the red points i.e. the elements with attribute fill="#990000" and id attribute containing OpenLayers_Geometry_Point you can use either of the following Locator Strategies:

*

*Using xpath:
//*[name()='svg']/*[name()='g']/*[name()='g']//*[name()='circle' and contains(@fill, '990000')][starts-with(@id, 'OpenLayers_Geometry_Point')]

*Using css-selectors:
svg > g > g circle[fill$='990000'][id^='OpenLayers_Geometry_Point']

Ideally, you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use either of the following Locator Strategies:

*

*Using cssSelector:
List<WebElement> vertices = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("svg > g > g circle[fill$='990000'][id^='OpenLayers_Geometry_Point']")));

*Using xpath:
List<WebElement> vertices = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[name()='svg']/*[name()='g']/*[name()='g']//*[name()='circle' and contains(@fill, '990000')][starts-with(@id, 'OpenLayers_Geometry_Point')]")));

References
You can find a couple of relevant details discussions in:

*

*How to click on SVG elements using XPath and Selenium WebDriver through Java

*Clicking on svg using selenium python

*Unable to locate SVG elements through xpath on Kendo UI chart

*Creating XPATH for svg tag

*How to access to 'rect' type element through Selenium-Python

A: Try @fill instead of fill and OpenLayers_Geometry_Point instead of OpenLayers.Geometry.Point.

A: We also faced the similar issue in one of the screens where we have SVG implementation, I resolved using action class.
Action Class Package :
java.lang.Object
org.openqa.selenium.interactions.Actions

Sample Code :
WebElement svgObject= driver.findElement(By.xpath(XPATH));
Actions actionBuilderObj = new Actions(driver);
actionBuilderObj .click(svgObject).build().perform();

A: Tried with all sort of techniques to dive Inn but atlast I found out an easy way to handle this situation.
When your desired svg doesnt have name and proper xpath changes dynamically then I used "cssSelector"
WebElement DesiredSvg = driver.findElement(By.cssSelector("#scrollable-auto-tabpanel-0 > div > div > form > div:nth-child(1) > div:nth-child(1) > div > div > div.jss10127 > div > div.jss11602 > svg:nth-child(3)"));

DesiredSvg.click();

A: To get just visibile elements you can use:
wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("bla bla")));


text:
Q: ComboBox on returning only one Item c# I am Selecting data from a database using SQL commands, I want to select data from a table to be read in a combox but it seems the combox only displays one item instead of all Items in that particular column.
Here is my sql statement:
public void SelectEmployee()
        {

            Query = "SELECT Employee_Name FROM TblEmployees";
            reader = conn.ExecuteStatement(Query);
            while (reader.Read())
            {

                ComboBox1.Text = reader["Employee_Name"].ToString();

            }

            conn.CloseConnection();

        }

This runs smoothly , the comboBox only shows one name though instead of 10 names.

A: You loop over the reader but continue to assign to the combo Text property the current value of the reader, thus overwriting the previous assignment.
Instead, add every value of the column Employee_Name to the Items collection where they will be displayed in the dropdown list of the combox and the user can select them
    public void SelectEmployee()
    {
        Query = "SELECT Employee_Name FROM TblEmployees";
        reader = conn.ExecuteStatement(Query);
        while (reader.Read())
        {
            ComboBox1.Items.Add(reader["Employee_Name"].ToString());
        }
        conn.CloseConnection();
    }

A: We don't know exactly what ExecuteStatement do exactly but with this while loop, you only set the last value of Employee_Name column to .Text property.
You can add as Items instead of assing it's .Text property like;
while (reader.Read())
{
    ComboBox1.Items.Add(reader["Employee_Name"].ToString());
}


text:
Q: Created custom radio button library, but did not check radio button while binding with reactive-form Angular library
I am trying to created a library for custom radio button with its role like warning(color yellow dot) error(color red dot) info(color blue dot) and success(color green dot) without angular library it will work fine, After that I move my css and template to library but now it is not work is expected
I have provide value from reactive from but it does not check as expect I have also added screenshot at the end what I am expecting and what I get currently
radio-button.html

        <input type="radio" #radioButton [name]="lbName" (click)="onClick($event)" [value]="lbValue"
                                              [disabled]="lbDisabled" />

            <ng-content></ng-content>

radio-button.scss
/* The container */
.container {
    display: block;
    position: relative;
    padding-left: 35px;
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 14px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* Hide the browser's default radio button */
.container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
}

/* Create a custom radio button */
.lb-radio {
    position: absolute;
    top: 0;
    left: 0;
    height: 20px;
    width: 20px;
    background-color: #eee;
    border-radius: 50%;
}

.container input ~ .lb-radio--warning {
    border: 1px solid darkorange;
}

.container input ~ .lb-radio--success {
    border: 1px solid green;
}

.container input ~ .lb-radio--error {
    border: 1px solid red;
}

.container input ~ .lb-radio--info {
    border: 1px solid blue;
}

/* When the radio button is checked, add a blue background */
.container input[type='radio']:checked ~ .lb-radio--warning {
    background-color: darkorange;
}

.container input[type='radio']:checked ~ .lb-radio--success {
    background-color: green;
}

.container input[type='radio']:checked ~ .lb-radio--error {
    background-color: red;
}

.container input[type='radio']:checked ~ .lb-radio--info {
    background-color: blue;
}

/* Create the indicator (the dot/circle - hidden when not checked) */
.lb-radio::after {
    content: '';
    position: absolute;
    display: none;
}

/* Style the indicator (dot/circle) */
.container .lb-radio::after {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 5px;
    height: 5px;
    border-radius: 50%;
    background: white;
}

/* Show the indicator (dot/circle) when checked */
.container input[type='radio']:checked ~ .lb-radio::after {
    display: block;
}

.container input[type='radio']:disabled + span {
    border: 1px solid grey;
}

.container input[type='radio']:disabled ~ span {
    background-image: none;
    background-color: none;
    color: grey;
    cursor: not-allowed;
}

.container input[type='radio']:checked:disabled + span {
    border: 1px solid grey;
    background-color: grey;
}

.container input[type='radio']:checked:disabled ~ span {
    background-image: none;
    color: grey;
    cursor: not-allowed;
}

radio-button.ts
import { Component, OnInit, Output, Input, EventEmitter, forwardRef} from '@angular/core';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

@Component({
    selector: 'lb-radio-button, [lb-radio-button]',
    templateUrl: './radio-button.component.html',
    styleUrls: ['./radio-button.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => RadioButtonComponent),
            multi: true
        }
    ]
})
export class RadioButtonComponent implements OnInit,  ControlValueAccessor {
    @ViewChild('radioButton') radioButton: ElementRef;
    className = 'lb-radio';
    value = '';
    isDisabled: boolean;
    @Output() checkBoxClick: EventEmitter<boolean> = new EventEmitter<boolean>();

    @Input() lbRole = 'info';
    @Input() lbName = 'radioButton';

    @Input()
    set lbDisabled(value: boolean) {
        this.isDisabled = coerceBooleanProperty(value);
    }
    get lbDisabled() {
        return this.isDisabled;
    }

    @Input()
    set lbValue(value: string) {
        this.writeValue(value);
        this.onChange(value);
        this.onTouched();
    }

    get lbValue(): string {
        return this.value;
    }

    onChange: any = () => {};
    onTouched: any = () => {};

    ngOnInit() {
        this.className += ` lb-radio--${this.lbRole}`;
    }

    onClick($event): boolean {
        if (this.lbDisabled) {
            return false;
        }
        this.writeValue($event.target.value);
        this.checkBoxClick.emit($event.target.value);
    }

    registerOnChange(fn) {
        this.onChange = fn;
      }

      writeValue(value) {
        if (value)
          this.value = value;
      }

      registerOnTouched(fn) {
        this.onTouched = fn;
      }
}

And used the library but male radio button does not checked as expected
**implementation.html**

<form [formGroup]="radioButtonForm">

       Male success radio button

       Female info radio button

Submit Form

</form>

**implementation.ts**

export class RadioButtonComponent implements OnInit {
    radioButtonForm: FormGroup;

    nameKey =  {
        gender: 'gender',
    };

    ngOnInit() {
        this.radioButtonForm = this.formBuilder.group({
            gender: ['Male', Validators.required],
        });
    }

    onSubmit() {
        alert(JSON.stringify(this.radioButtonForm.value))
    }

}

Expected

Currently what I get

A: Stackblitz demo (the demo contains a little bit more information than the basics described in the suggestion below).
Using the same FormControl instance bound to several components is not something I'm comfortable with. If you allow me a suggestion which BTW solves your problem with the initial value not being set in the FormControl: why don't you leverage your component by creating a "RadioGroupControl" just to be used with forms, in such a way that you can associate a FormControl to the group, instead of doing it with individual controls.
What you could do:
1) Create a LbRadioButtonGroupComponent
Its template would be a very simple one:
selector: 'lb-radio-group-control',
template: '<ng-content></ng-content>'

As the selector says, this component is supposed to be used only for grouping radio-buttons inside forms. It should just work as a wrapper.
Inside its typescript, grab all the instances of the RadioButtons.
@ContentChildren(RadioButtonComponent, { descendants: true })
_radioButtons: QueryList<RadioButtonComponent>;

Then subscribe to the event emitter inside each RadioButtonComponent. You'll need to emit more than just a boolean so that LbRadioButtonGroupComponent can set the right radio button checked state to true when you get an incoming value (set by the host with setValue(), patchValue(), or something like that). I suggest a RadioButtonChange property containing 2 attributes: target (the clicked input) and value (a convenience attribute, you can get rid of it if you want to). So we have:
ngAfterViewInit() {
  const observableList: Observable<RadioButtonChange>[] = [];
  this._radioButtons.map((rb: RadioButtonComponent) =>
    observableList.push(rb.checkBoxClick));

  merge(...observableList)
    .pipe(
      filter(Boolean),
      takeUntil(this._destroy$)
    )
    .subscribe((value: any) => {
      this._onTouch();
      this._onChange(value ? value.value : null);
    });
}

Then we would need just a way to set up which button is currently checked. The problem here is just a matter of timing because we don't really know when the method is gonna be called to set a value and we must make sure that our QueryList was already executed and this._radioButtons is populated. Once we make sure that happened the following method should set the right radio button to checked:
private _setGroupValue(value: any) {
  this._radioButtons.forEach(
    rb => (rb.radioButton.nativeElement.checked =
        rb.radioButton.nativeElement.value === value)
  );
}

2) Wrap your RadioButtonComponents with RadioButtonGroupComponent when using them in a form as a group
Once we have these pieces in place, we can use our component like this:
<form [formGroup]="radioButtonForm">
  <lb-radio-group-control formControlName="gender">

      Male success radio button

      Female info radio button

  </lb-radio-group>

Submit Form

</form>

As we already own the instances of lb-radio-buttons, there's no need to set the name on them: we can do that in LbRadioButtonGroupComponent. Of course, you can do it in such a way that it doesn't matter if you set the name, or set different names to each radio button (by mistake).

Side notes
In the code on Stackblitz, you'll find a more complete code, containing some validations, like a check to see whether inside the group there aren't any RadioButtonComponent bound to a FormControl, or whether the developer forgot to bind LbRadioButtonGroupComponent to a FormControl.
Well, this is just an overall idea to avoid binding the same FormControl to several components in the template. It's not complete and needs things like form validation, form control disabling, and ability to set the group value via an @Input() value (I started writing it in the demo, but I'm in a rush and I think you've already got the point).

A: Don't call writeValue inside lbValue setter, It will override the value set by FormControl.
@Input lbValue;

propagate value to parent Form you have to call stored onChange call back function, whenever custom control value changes.
 onClick($event): boolean {
        if (this.lbDisabled) {
            return false;
        }
        this.onChange($event.target.value);
        this.onTouched();
        this.checkBoxClick.emit($event.target.value);
    }

Example


text:
Q: ¿Cómo puedo instalar Angular Generator en VS Code? En la primera guía de Angular https://angular.io/start, muestran la siguiente imagen:

¿Cómo puedo instalar esa extensión en VS Code?

A: Eso es una captura de stackblitz. Que es un editor online de prueba que te permite crear código rápido.
Pero hay esta extension para vscode que te permite hacer algo similar a lo que estas buscando!
cyrilletuzi.angular-schematics


text:
Q: How to sort with priority and dates? I have the following PostgreSQL query.
SELECT id FROM table WHERE user_id=$user_id ORDER BY
    CASE
      WHEN (date_completed_utc='0000-00-00 00:00:00') THEN 0 ELSE 1 END ASC

Here is an example of what's in the table:

date_requested_utc is always a past date.
date_completed_utc is defaulted to '0000-00-00 00:00:00', but is later changed to a date newer than date_requested_utc.
What I'm trying to accomplish is this:
If date_completed_utc is the default, then all these rows will be above all else, but these rows are sorted by date_requested_utc descending.
But if date_completed_utc is not the default, then put these rows at the bottom and order these rows by date_completed_utc descending.
The resulting order by ID should be as follows:
26, 20, 18, 17, 15, 16, 27, 28

I've tried all these different CASE statements, but can't seem to get it right.

A: You can try to use double orders.
SELECT id
FROM table
WHERE user_id=$user_id
ORDER BY
    CASE WHEN (date_completed_utc='0000-00-00 00:00:00') THEN 0 ELSE 1 END,
    date_requested_utc DESC

EDIT
I saw your edit question.
You don't have to use UNION ALL combine two query,you can query one with CASE WHEN expression directly.
Order by the number

*

*1/(EXTRACT(epoch from age(now(),date_requested_utc)) / 86400 date_requested_utc closer the time will get larger the number.

*1/(EXTRACT(epoch from age(now(),date_completed_utc::timestamp)) / 86400)::numeric date_completed_utc closer the time will get larger the number.

you can try this.
SELECT id
SELECT id FROM table
WHERE user_id=$user_id
ORDER BY
    (
      CASE WHEN (date_completed_utc='0000-00-00 00:00:00')
        THEN (EXTRACT(epoch from age(now(),'1970-01-01')) / 86400) + 1/(EXTRACT(epoch from age(now(),date_requested_utc)) / 86400)::numeric
        ELSE  1/(EXTRACT(epoch from age(now(),date_completed_utc::timestamp)) / 86400)::numeric
      END
    )::numeric
    DESC

sqlfiddle:http://sqlfiddle.com/#!17/f5f88a/28

A: (Posted answer on behalf of the question author).
I changed my query to the following and it's now working fine.
(SELECT id FROM table WHERE user_id=$user_id AND date_completed_utc='0000-00-00 00:00:00' ORDER BY date_requested_utc DESC)
UNION ALL
(SELECT id FROM table WHERE user_id=$user_id AND date_completed_utc!='0000-00-00 00:00:00' ORDER BY date_completed_utc DESC)


text:
Q: Track the URL page the user filled in an Enquiry form I'd like to know how can I track the URL than the user filled a form.
I'm have just HTML/CSS knowledge, could someone provide me some sample code in order to incorporate in my code.
Thanks,
Bruno

A: Bruno I'm not sure if I understand your question correctly. If it is you want to track the URL that someone was on before they came to the form then you likely are going to be doing this through either a URL modification or using the document.referrer property in Javascript.
If you want to pass information on from a link to your wufoo form, let's say you have a field called 'website' which is fieldId 87 then you could send this to the hosted Wufoo form as:
http://[yourWufooUrlHere]/def/field87=stackoverflow
and it will populate whichever field you pass in the variable into the form.
However if you don't know where people are coming from you need to embed the form into your website using the Javascript method and you would change/add the line where it says:
'ssl':true}; to

'ssl':true,
'defaultValues':'field87='+document.referrer};
 assuming the field you want to change is field87.
Just tested this and it works fine. Let me know if you need a full code block example.
Good luck


text:
Q: Does EF Migrations Support Adding Not Null Foreign Keys What I'd like is to go from:
public class SomeEntity
{
    public int Id {get; set;}

    //...
}

To:
public class SomeEntity
{
    public int Id {get; set;}

    public int OtherEntityId {get; set;}

    [ForeignKey("OtherEntityId")]
    public OtherEntity Other {get; set;}

    //...
}

At the database level, I'm assuming the only way to do this is:

*

*Add a nullable foreign key

*Set valid values on the foreign key

*Add a not-null constraint

Is there some way to make this happen with EntityFramework migrations? What I'm looking for is code that could be put into the Seed method, or elsewhere, that would update the database automatically. I understand that I can add a nullable foreign key, but what I want is to add a non-nullable foreign key in one step.


text:
Q: What is the fundamental difference between jQuery $.ajax & dojo.xhrPost? I tried implementing these two methods on two buttons as shown below.
Button 1

 $.ajax({
     type: "POST",
     url: "xhrServer.xsp",
     data: "some=name=random=data",
     contentType: "application/json; charset=utf-8",
     dataType: "html"
   }).done(function() {
     alert("success");
   })
   .fail(function() {
     alert("Something went wrong. Please try again or contact system administrator.");
   })

Button 2

var xhrArgs = {
  url: "xhrServer.xsp",
  content: "some=name=random=data",
  handleAs: "text",
  load: function(data) {
    alert("Data posted.");
  },
  error: function(error) {
    alert("Error occurred while posting data.");
  }
}
dojo.xhrPost(xhrArgs);

On the firebug console, for dojo.xhrPost request, there is an additional entity with the name "Parameters" is shown.
What is that?
This is affecting the way the data is read on the server side.

A:

var xhrArgs = {
  url: "xhrServer.xsp",
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  },
  postData: "some=name=random=data",
  handleAs: "text",
  load: function(data) {
    alert("Data posted.");
  },
  error: function(error) {
    alert("Error occurred while posting data.");
  }
}
dojo.xhrPost(xhrArgs);

By default, in dojo the content type will be URL encoded & sent as parameter. If we want to specify the content type in dojo we need to set the headers property ( i.e headers: { "Content-Type": "application/json"}) in the xhrArgs object.
This sends the complete data in raw form to the server, just like jQuery $.ajax.
Thank you for the help  @frank.


text:
Q: xcrun: error: invalid active developer path, problem after zsh update for flutter I updated my shell to zsh and when I type flutter --version I get this:
'''xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools),
missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
Failed to find the latest git commit date: VersionCheckError: Command exited
with code 1: git -c log.showSignature=false log -n 1 --pretty=format:%ad
--date=iso
Standard out:
Standard error: xcrun: error: invalid active developer path
(/Library/Developer/CommandLineTools), missing xcrun at:
/Library/Developer/CommandLineTools/usr/bin/xcrun

Returning 1970-01-01 01:00:00.000 instead.
Flutter 0.0.0-unknown • channel unknown • unknown source
Framework • revision  () • 1970-01-01 01:00:00.000
Engine • revision b8752bbfff
Tools • Dart 2.10.2'''

WHAT SHOULD I DO? I'm not an expert in these things XD.
Kind regards,

A: The error messages seem to be about Xcode CLI tools? If so, try these commands to reset it:
xcode-select --install
sudo xcode-select -s /Library/Developer/CommandLineTools/

A: It looks like the Command Line tools path is not set. If you have XCode then to setup the path you need to:

*

*Open XCode

*Open Preferences (⌘,)

*Go to Locations tab

*For "Command Line Tools" select the current version

A: Install the Command Line Tools for Xcode to solve the problem. Complete installation of Xcode is not required.
https://developer.apple.com/download/more/?=command%20line%20tools

A: If you are on macOS Catalina and want to do this via the commandline/terminal, or the above solutions haven't worked, try these steps:

*

*Disable SIP (this needs to be done via recovery mode)

*Create a soft simlink linking your "Developer" directory (which contains the CommandLineTools directory/instance brew is searching for) by running: sudo ln -s /path/to/Developer /path/to/Xcode.app/Contents

*Run the simlinker built into brew, to let brew know where the CommandLineTools instance is (brew was written by default to support both instances running in the same directory and has refused to update for logical reasons their docs explain), by running: sudo xcode-select --switch /path/to/new/simlinked/directory/for/CommandLineTools
Here's an example on my system:

*

*Xcode was originally located in: /Applications/Xcode.app

*Developer directory, containing CommandLineTools was: /Library/Developer

*ran: sudo ln -s /Library/Developer /Applications/Xcode.app/Contents/

*ran: sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer/CommandLineTools

*refreshed shell (or open a new instance), and then ran: brew doctor, receiving the message: Your system is ready to brew.
For any of my new clients, I will often create these two aliases for their systems:

*

*alias xbandaid="sudo xcode-select --reset" #when permissions might be lacking

*alias xfix="sudo ln -s /Library/Developer /Applications/Xcode.app/Contents/ && sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer/CommandLineTools" #for the fix as described above
I place these aliases in their bash/zsh profile, which on Catalina is typically either .zshrc or .zprofile if they use ZSH, and .bashrc or .bash_profile if they use BASH.
Disclaimer: Though I have tried this and it has successfully worked on "BigSur" client machines, I am not promising this will work for you on those installations. The same goes for MacPorts and pkgsrc also known as pkgin put out by the Joyent Software/NetBSD Samsung Group folks. They all worked for my clients and me, but reader discretion is advised.

A: I had help from the post
You must run sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
to make Terminal start using command line tools inside Xcode