问:
Blue green deploy for codedeploy fails ( The deployment failed because no instances were found in your green fleet. (Error code: NO_INSTANCES))

I'm trying to setup a blue/green deployment with CodeDeploy. So far I've set it up with to manually provision instances using an autoscaling group that I've created. Additionally I've enabled load balancing and linked it to an ALB.

The ASG I created has a minimum number of 1 instances running with 2 max.

When I trigger a deploy, I see the following error:

This confuses me as it seems to skip provisioning replacement instances and states that there were no instances found in the green fleet.

Any ideas?

答:
For a Blue/Green deployment you have two options when creating the deployment group:

Manually provision instances

Automatically copy Auto Scaling group

When you choose Manually provision instances you would specify the green fleet yourself while creating the deployment. In this case CodeDeploy will not provision a new ASG (Auto-Scaling Group) for you and that's why step 1 is skipped.

For step 2 it looks like the ASG that you manually specified as your green fleet does not have any instances in running state, you might want to cross check that. Also make sure the green fleet size is same as the original blue fleet size.


来源: stackexchange

问:
cobbler reposync referencing old repo data
This one has me scratching my head:

I added a repo to my cobblerd box, which was otherwise a happy CentOS7 cobbler server for a few small repos:

```<code>cobbler repo add --name spacewalk-client25-6-x86_64 --mirror http://yum.spacewalkproject.org/2.5-client/RHEL/7/x86_64
cobbler reposync --only spacewalk-client25-6-x86_64
</code>```

Then I noticed I had the URL wrong.  Doh!  6 is not like 7.

```<code>cobbler repo edit --name spacewalk-client25-6-x86_64  --mirror http://yum.spacewalkproject.org/2.5-client/RHEL/6/x86_64
</code>```

On the resync, though, first odd things happened:  It didn't download anything new, and kept the EL7 stuff.  So I whacked the tree: (nukeItFromOrbit.gifv)

```<code>rm -rf /var/www/cobbler/repo_mirror/spacewalk-client25-6-x86_64
cobbler reposync --only spacewalk-client25-6-x86_64
</code>```

And then bad things happened:  it was complaining about not finding some EL7 stuff, even though it shouldn't even be looking!

```<code>:
:
rhn-virtualization-common-5.4. FAILED
:
rhnpush-5.5.98-1.el7.noarch.rp FAILED
:
spacewalk-backend-libs-2.5.43-1.el7.noarch: [Errno 256] No more mirrors to try.
spacewalk-client-cert-2.5.3-1.el7.noarch: [Errno 256] No more mirrors to try.
:
:
</code>```

Very weird -- you see where it's still looking for EL7 stuff?  So I cursed, shook my fist, and cobbler synced in the hopes of clearing any lingering cache-like nuisance.  But that didn't fix it hard enough, so I removed the repo, and synced THAT, and then re-added it and reposynched.  No dice.  Restarted cobblerd.  Nope.  Killed the repo, restarted cobblerd, synched it twice, re-added the repo.  Nope.  And yes, the URL was the right one.  ;-)

So I got crafty:  define a new repo ('86_64 2') , synch ITS data, and slide that over into the name (which can't be changed easily for config-management and $releasevar reasons):

```<code>cobbler repo add --name spacewalk-client25-6-x86_642 --mirror http://yum.spacewalkproject.org/2.5-client/RHEL/6/x86_64
cobbler reposync --only spacewalk-client25-6-x86_642
cobbler repo rename --name spacewalk-client25-6-x86_642 --newname spacewalk-client25-6-x86_64
cobbler reposync --only spacewalk-client25-6-x86_64

:
:
Removing obsolete spacewalk-client-cert-2.5.3-1.el6.noarch.rpm
Removing obsolete rhn-setup-gnome-2.5.16-1.el6.noarch.rpm
Removing obsolete yum-rhn-plugin-2.5.5-1.el6.noarch.rpm
Removing obsolete spacewalk-oscap-2.5.3-1.el6.noarch.rpm
:
:
spacewalk-client-repo-2.5-3.el FAILED
spacewalk-koan-2.5.2-1.el7.noa FAILED
spacewalk-oscap-2.5.3-1.el7.no FAILED
yum-rhn-plugin-2.5.5-1.el7.noa FAILED
rhnpush-5.5.98-1.el7.noarch: [Errno 256] No more mirrors to try.
rhn-virtualization-common-5.4.55-1.el7.noarch: [Errno 256] No more mirrors to try.
:
:
</code>```

Yeah, really.

Something's up, but strace -e trace=file didn't pop anything out either.  Anyone seen this?  Do you want to see a full reposynch run on that repo, for kicks?

(feel free to adjust the 'repository' tag to be 'reposync' so it's more accurate.  I can't do it on my lame rep)

答:
As luck has it, I fell over the answer almost right after posting.

/var/cache/yum has a redundant cache of usually-tasty repo data, but it even keeps the sour ones deleted long ago: I found a spacewalk-client25-6-x86_642 in there from the crafty attempt above, as well as the old spacewalk-client25-6-x86_64 one that it then refused to update.

I whacked that, chuckling malevolently, and resynched.

```<code>rm -rf /var/cache/yum/*
cobbler reposync --only spacewalk-client25-6-x86_64
</code>```

And life was good.

ContentLicense: CC BY-SA 3.0

Body:
This one has me scratching my head:

I added a repo to my cobblerd box, which was otherwise a happy CentOS7 cobbler server for a few small repos:

cobbler repo add --name spacewalk-client25-6-x86_64 --mirror http://yum.spacewalkproject.org/2.5-client/RHEL/7/x86_64
cobbler reposync --only spacewalk-client25-6-x86_64

Then I noticed I had the URL wrong.  Doh!  6 is not like 7.

cobbler repo edit --name spacewalk-client25-6-x86_64  --mirror http://yum.spacewalkproject.org/2.5-client/RHEL/6/x86_64

On the resync, though, first odd things happened:  It didn't download anything new, and kept the EL7 stuff.  So I whacked the tree: (nukeItFromOrbit.gifv)

rm -rf /var/www/cobbler/repo_mirror/spacewalk-client25-6-x86_64
cobbler reposync --only spacewalk-client25-6-x86_64

And then bad things happened:  it was complaining about not finding some EL7 stuff, even though it shouldn't even be looking!

:
:
rhn-virtualization-common-5.4. FAILED
:
rhnpush-5.5.98-1.el7.noarch.rp FAILED
:
spacewalk-backend-libs-2.5.43-1.el7.noarch: [Errno 256] No more mirrors to try.
spacewalk-client-cert-2.5.3-1.el7.noarch: [Errno 256] No more mirrors to try.
:
:

Very weird -- you see where it's still looking for EL7 stuff?  So I cursed, shook my fist, and cobbler synced in the hopes of clearing any lingering cache-like nuisance.  But that didn't fix it hard enough, so I removed the repo, and synced THAT, and then re-added it and reposynched.  No dice.  Restarted cobblerd.  Nope.  Killed the repo, restarted cobblerd, synched it twice, re-added the repo.  Nope.  And yes, the URL was the right one.  ;-)

So I got crafty:  define a new repo ('86_64 2') , synch ITS data, and slide that over into the name (which can't be changed easily for config-management and $releasevar reasons):

cobbler repo add --name spacewalk-client25-6-x86_642 --mirror http://yum.spacewalkproject.org/2.5-client/RHEL/6/x86_64
cobbler reposync --only spacewalk-client25-6-x86_642
cobbler repo rename --name spacewalk-client25-6-x86_642 --newname spacewalk-client25-6-x86_64
cobbler reposync --only spacewalk-client25-6-x86_64

:
:
Removing obsolete spacewalk-client-cert-2.5.3-1.el6.noarch.rpm
Removing obsolete rhn-setup-gnome-2.5.16-1.el6.noarch.rpm
Removing obsolete yum-rhn-plugin-2.5.5-1.el6.noarch.rpm
Removing obsolete spacewalk-oscap-2.5.3-1.el6.noarch.rpm
:
:
spacewalk-client-repo-2.5-3.el FAILED
spacewalk-koan-2.5.2-1.el7.noa FAILED
spacewalk-oscap-2.5.3-1.el7.no FAILED
yum-rhn-plugin-2.5.5-1.el7.noa FAILED
rhnpush-5.5.98-1.el7.noarch: [Errno 256] No more mirrors to try.
rhn-virtualization-common-5.4.55-1.el7.noarch: [Errno 256] No more mirrors to try.
:
:

Yeah, really.

Something's up, but strace -e trace=file didn't pop anything out either.  Anyone seen this?  Do you want to see a full reposynch run on that repo, for kicks?

(feel free to adjust the 'repository' tag to be 'reposync' so it's more accurate.  I can't do it on my lame rep)

Body:
As luck has it, I fell over the answer almost right after posting.

/var/cache/yum has a redundant cache of usually-tasty repo data, but it even keeps the sour ones deleted long ago: I found a spacewalk-client25-6-x86_642 in there from the crafty attempt above, as well as the old spacewalk-client25-6-x86_64 one that it then refused to update.

I whacked that, chuckling malevolently, and resynched.

rm -rf /var/cache/yum/*
cobbler reposync --only spacewalk-client25-6-x86_64

And life was good.


问:
TFS 2015 Build Definitions
We have a project that creates and edits pdfs on the file system. When we fire a tfs build, it deletes the generated pdfs in the folder (and we need them to stay). Is there a way to tell the build to exclude deleting the pdf's that are in the folder every time we do a deployment?</p>

答:
i was a google click away - sorry. the answer was in msbuild arguments. /p:DeleteExistingFiles=False
/p:SkipExtraFilesOnServer=True
/p:ReplaceMatchingFiles=True</p>

ContentLicense: CC BY-SA 4.0

Title: TFS 2015 Build Definitions


问:
Which css style has least effect on an element?
Today I was trying to create a dummy css rule for testing and investigation.

```<code>.dummy {
  some-style : somevalue;
}
</code>```

Ideally the class should have no visible effect.  I want to be able to apply the class to elements but cause the least visible effect possible on any elements it is applied to.  For example

 should look and behaves as much as possible like

I did not want the class to be empty.  Can anyone suggest a style that I could add to the class that would have the least visible impact when applied to a general html element?  I can't think of anything completely harmless.

UPDATE: I wanted to add the style to some existing html.  The reason was to use the style as a marker for diagnostic purposes.  It would help me see when and where styles and stylesheets were getting loaded/cached and where and why some styles were getting overridden, sometimes by the browser defaults which seemed odd.  At the time I didn't have exclusive use of the system I was working on so I wanted something that was going to be invisible to other users but I could see in Developer Tools.

UPDATE 2 : the html/css wasn't written by me and I didn't have my own environment in which to work. I was trying to investigate some problems in-situ in someone else's system.  I had tried using DevTools in the browser but wasn't getting anywhere with that.  I wanted to be able to make some small changes to their html/css to aid my diagnostics.  I didn't want them to have any obvious effect on the system for other people (except in DevTools, viewed by me).

It was a Wordpress site and they only had two environments, one for live and one for testing.  I was working with the test system.  There were other people testing at the time, though mainly checking content.

The real thorny problem was why was the font-size in the calendar widget much larger than everything else on the site?  Inspecting using DevTools I could see the font-size style was getting overridden by the browser default style when it seemed to me there were other css selectors that should have taken precedence.  It looked bizarre.  In the end it turned out to be a missing !DOCTYPE tag in the html.  So nothing to do with the css itself.

I didn't like this way of working, fiddling in someone's system, but there wasn't much else to do and it did help to resolve the problem for them.

Hopefully I don't have to do this again, but ever since I have been wondering what was the most harmless style that I could have used?

I thought I would ask here as there must be people who know CSS better than me.

答:
You can use this:</p>
```<code>.dummy{
    min-width: 0;
}
</code>```

Body:
Today I was trying to create a dummy css rule for testing and investigation.

.dummy {
  some-style : somevalue;
}

Ideally the class should have no visible effect.  I want to be able to apply the class to elements but cause the least visible effect possible on any elements it is applied to.  For example

 should look and behaves as much as possible like

I did not want the class to be empty.  Can anyone suggest a style that I could add to the class that would have the least visible impact when applied to a general html element?  I can't think of anything completely harmless.

UPDATE: I wanted to add the style to some existing html.  The reason was to use the style as a marker for diagnostic purposes.  It would help me see when and where styles and stylesheets were getting loaded/cached and where and why some styles were getting overridden, sometimes by the browser defaults which seemed odd.  At the time I didn't have exclusive use of the system I was working on so I wanted something that was going to be invisible to other users but I could see in Developer Tools.

UPDATE 2 : the html/css wasn't written by me and I didn't have my own environment in which to work. I was trying to investigate some problems in-situ in someone else's system.  I had tried using DevTools in the browser but wasn't getting anywhere with that.  I wanted to be able to make some small changes to their html/css to aid my diagnostics.  I didn't want them to have any obvious effect on the system for other people (except in DevTools, viewed by me).

It was a Wordpress site and they only had two environments, one for live and one for testing.  I was working with the test system.  There were other people testing at the time, though mainly checking content.

The real thorny problem was why was the font-size in the calendar widget much larger than everything else on the site?  Inspecting using DevTools I could see the font-size style was getting overridden by the browser default style when it seemed to me there were other css selectors that should have taken precedence.  It looked bizarre.  In the end it turned out to be a missing !DOCTYPE tag in the html.  So nothing to do with the css itself.

I didn't like this way of working, fiddling in someone's system, but there wasn't much else to do and it did help to resolve the problem for them.

Hopefully I don't have to do this again, but ever since I have been wondering what was the most harmless style that I could have used?

I thought I would ask here as there must be people who know CSS better than me.

Body:
You can use this:

.dummy{
    min-width: 0;
}


问:
Changing video source javascript
My solution:
http://jsfiddle.net/g7mrs/22/

```<code>function loadVideo(event) {
  videojs("myPlayer").src({
    type: "video/youtube",
    src: "https://youtu.be/ZSn3Tvc7jQU"
  });
  event.preventDefault();
}
</code>```

I got a working solution, however I would like to have only 1 function instead of 4

Any ideas?

答:
You can pass YouTube URL as a parameter:

```<code>function loadVideo(url) {
    videojs("myPlayer").src({ type: "video/youtube", src: url});
    event.preventDefault();
}
</code>```

And in HTML:

```<code><a href="#" onClick="loadVideo('https://youtu.be/ZSn3Tvc7jQU')">video</a>
<a href="#" onClick="loadVideo('https://youtu.be/0BhSrfNgLxs')">video2</a>
</code>```

Title: Changing video source javascript

Body:
My solution:
http://jsfiddle.net/g7mrs/22/

function loadVideo(event) {
  videojs("myPlayer").src({
    type: "video/youtube",
    src: "https://youtu.be/ZSn3Tvc7jQU"
  });
  event.preventDefault();
}

I got a working solution, however I would like to have only 1 function instead of 4

Any ideas?

Body:
You can pass YouTube URL as a parameter:

function loadVideo(url) {
    videojs("myPlayer").src({ type: "video/youtube", src: url});
    event.preventDefault();
}

And in HTML:

<a href="#" onClick="loadVideo('https://youtu.be/ZSn3Tvc7jQU')">video</a>
<a href="#" onClick="loadVideo('https://youtu.be/0BhSrfNgLxs')">video2</a>


问:
Homework Assignment: Assistance with placing a running for loop in jquery

I am trying to send the suggested text file to the xampp server but I would like to know how to strip out and only show results 1- 10 in a loop and when the button2 is pressed to show results 11-20. Then when you press the button a third time it will show results 21-30. Once I have that finished I would like to know how to reverse this order when I press a backwards button.

both buttons need to show up after I request the text file within the box1

```<code></style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    var i;
    var highlight;
        $(document).ready(function() {
            $("#button1").click(function() {
                $.get("topHits1990.txt", function(data, status) {
                    console.log("The data is below");
                    console.log(data);
                    console.log("The status is below");
                    console.log(status);
                        $("#box1").html(data);
                        $("#button2").show();
                        $("#button3").show();

});

            $("#button2").click(function() {
                    $.get("topHits1990.txt", function(data, status) {
                            for (i=0 i > 9; i++)
                                $("#box1").html(data);
                            }

                        } else if (i>10 i++) {

                });

        });

    </script>
</head>
<body>
    <h1>Favorite Songs</h1>
    <button type="button" id="button1">Show Songs</button>
    <div id="box1"></div>

</body>
</code>```

I would like to get to increment everytime you press a button and decrement when you press the backwards button and I would like to hide the forward and backward buttons within the running function. I am sorta a beginner at jQuery mixed with Javascript so any creative criticism is welcome.

It only shows the whole text file and does not limit how much data you are able to see which I am trying to limit it to 10 entries at a time everytime you press either of the buttons.

The function does not work as you have to use a xampp server with my requested files as it is an ajax, jquery and javascript task.

答:
I am trying to send the text file to box 1,  but only 10 entries instead of the whole 30

First you need to know how to only get x entries.  You do this by splitting the text file into records - You need to determine what separates each record, ie the separator.

Is topHits1990.txt a text file that has one row per line?  Or is it comma separated?  Possibly, separated by ;.   You use this separator to split thre block of data into records.

Assuming it's one row per line, the separator would be newline or \n.

You then convert/break-up the single text file into "records", in this case:

```<code>var records=data.split("\n");
</code>```

or

```<code>var records=data.split(",");
</code>```

This gives you an array which you can then manipulate as required.

You could loop through the array, for simplicity, eg:

```<code>var records=data.split(",");
var result = "";
for (var i=0; i<10; ++i) {
    result = result + records[i] + "\n";
}
$("#box1").text(result);
</code>```

or you could use something a bit fancier, such as slice combined with join, eg:

```<code>var records=data.split("\n");  // use whatever separator is required here
$("#box1").text(records.slice(0, 9).join("\n"));
</code>```

To show the 'next' set of records, you just need to change the starting position.

Putting it all together:

// This would be the result of your $.get
var data = "row1,row2,row3,row4,row5,row6,row7,row8,row9,row10";

// number of rows to show - 3 for demo, change to 10
var rowstoshow = 3;

// current position, clicking the button moves to the *next* position
// so need to indicate we haven't started yet
var position = -1;

$("#btn").click(function() {

    // split the data into rows
    var rows = data.split(",");

    // Move to next position, check if first, reset if too far
    position = position < 0 ? 0 : position + rowstoshow;
    if (position > rows.length) position = 0

    // slice the array to get the correct records then join them using \n for output
    var newtxt = rows.slice(position, position+rowstoshow).join("\n")
    $("#box1").text(newtxt);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows=10 cols=60 id='box1'></textarea>
<button id='btn'>click me</button></code>```

To reverse the action, add another button and in its click event subtract the number of rows to show from position, checking for < 0 and resetting to rows.length - rowstoshow (not just rows.length as it shows from that position).

Note: As this is a homework assignment and you're relatively new to coding, the solution above uses something called 'global variables' in "real" code this is not best practice and you would want to avoid these as they pollute the global namespace, so you would use scope and/or namespaces to store these, or even store them directly in the html using data- attributes.

Body:
I am trying to send the suggested text file to the xampp server but I would like to know how to strip out and only show results 1- 10 in a loop and when the button2 is pressed to show results 11-20. Then when you press the button a third time it will show results 21-30. Once I have that finished I would like to know how to reverse this order when I press a backwards button.

both buttons need to show up after I request the text file within the box1

</style>

Favorite Songs

    <button type="button" id="button1">Show Songs</button>

I would like to get to increment everytime you press a button and decrement when you press the backwards button and I would like to hide the forward and backward buttons within the running function. I am sorta a beginner at jQuery mixed with Javascript so any creative criticism is welcome.

It only shows the whole text file and does not limit how much data you are able to see which I am trying to limit it to 10 entries at a time everytime you press either of the buttons.

The function does not work as you have to use a xampp server with my requested files as it is an ajax, jquery and javascript task.

Body:
I am trying to send the text file to box 1,  but only 10 entries instead of the whole 30

First you need to know how to only get x entries.  You do this by splitting the text file into records - You need to determine what separates each record, ie the separator.

Is topHits1990.txt a text file that has one row per line?  Or is it comma separated?  Possibly, separated by ;.   You use this separator to split thre block of data into records.

Assuming it's one row per line, the separator would be newline or \n.

You then convert/break-up the single text file into "records", in this case:

var records=data.split("\n");

or

var records=data.split(",");

This gives you an array which you can then manipulate as required.

You could loop through the array, for simplicity, eg:

var records=data.split(",");
var result = "";
for (var i=0; i<10; ++i) {
    result = result + records[i] + "\n";
}
$("#box1").text(result);

or you could use something a bit fancier, such as slice combined with join, eg:

var records=data.split("\n");  // use whatever separator is required here
$("#box1").text(records.slice(0, 9).join("\n"));

To show the 'next' set of records, you just need to change the starting position.

Putting it all together:

// This would be the result of your $.get
var data = "row1,row2,row3,row4,row5,row6,row7,row8,row9,row10";

// number of rows to show - 3 for demo, change to 10
var rowstoshow = 3;

// current position, clicking the button moves to the *next* position
// so need to indicate we haven't started yet
var position = -1;

$("#btn").click(function() {

    // split the data into rows
    var rows = data.split(",");

    // Move to next position, check if first, reset if too far
    position = position < 0 ? 0 : position + rowstoshow;
    if (position > rows.length) position = 0

    // slice the array to get the correct records then join them using \n for output
    var newtxt = rows.slice(position, position+rowstoshow).join("\n")
    $("#box1").text(newtxt);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows=10 cols=60 id='box1'></textarea>
<button id='btn'>click me</button>

To reverse the action, add another button and in its click event subtract the number of rows to show from position, checking for < 0 and resetting to rows.length - rowstoshow (not just rows.length as it shows from that position).

Note: As this is a homework assignment and you're relatively new to coding, the solution above uses something called 'global variables' in "real" code this is not best practice and you would want to avoid these as they pollute the global namespace, so you would use scope and/or namespaces to store these, or even store them directly in the html using data- attributes.


问:
Is is possible to have a semi-transparent layer over another one without blocking/catching clicks in CSS/JS
Basically, I want to have a layer on top of another without catching input.

The goal is to have a PNG over my webpage that will create an effect, a bit like a filter.

My problem is if it’s over, the text becomes unselectable & unclickable.

Any ideas?

答:
It depends on your needs, but in the past when there was a specific element that I wanted to be able to click through a layer.  I would position a transparent div absolutely positioned to the exact position as the underlying that would trigger the event for the underneath element.  It is very easy to match positions with javascript and just set the z-index higher than the overlay.

Of course this is easy If you are dealing with a single element or even two, could get exponentially cumbersome to use this for an entire page under an overlay for example.

ContentLicense: CC BY-SA 2.5


问:
Babel fails to compile ES6 object cloning with spread operator
I use grunt-babel to compile my ES6 code. But it returns Warning: dist/app.js: Unexpected token (321:9) Use --force to continue. when I try to use {...obj} to copy and extend object. Following code is working perfect in console of Chrome v61 but Babel doesn't like it. What is the problem?

```<code>let a = { a: 12 };
let b = { ...a, b: 15 };
</code>```

I am using env preset. (babel-core v.6.26.0 and babel-preset-env v.1.6.1)

答:
You probably would want to add these plugins to your .babelrc. This Github issue has a lot of solutions unexpected token (rest spread operator). I am trying these out now.

```<code>{
  "presets": ["react", "es2015"],
  "plugins": ["transform-es2015-destructuring", "transform-object-rest-spread"]
}
</code>```

npm install --save-dev babel-plugin-transform-es2015-destructuring

npm install --save-dev babel-plugin-transform-object-rest-spread

Body:
I use grunt-babel to compile my ES6 code. But it returns Warning: dist/app.js: Unexpected token (321:9) Use --force to continue. when I try to use {...obj} to copy and extend object. Following code is working perfect in console of Chrome v61 but Babel doesn't like it. What is the problem?

let a = { a: 12 };
let b = { ...a, b: 15 };

I am using env preset. (babel-core v.6.26.0 and babel-preset-env v.1.6.1)

Body:
You probably would want to add these plugins to your .babelrc. This Github issue has a lot of solutions unexpected token (rest spread operator). I am trying these out now.

{
  "presets": ["react", "es2015"],
  "plugins": ["transform-es2015-destructuring", "transform-object-rest-spread"]
}

npm install --save-dev babel-plugin-transform-es2015-destructuring

npm install --save-dev babel-plugin-transform-object-rest-spread


问:
React twilio.Js Library Accept Incoming Call
I am trying to accept incoming calls with the twilio.Js Library. (https://www.twilio.com/docs/api/client)

I am listening for the incoming calls like this:

componentDidMount() {
    Twilio.Device.incoming((conn) => {
        console.log('Incoming connection from ' + conn.parameters.From);
    });
}```
</div>
</div>
</p>

<p>I know that I can just call conn.accept(); in the Twilio.Device.incoming function, however for my component to work, I would need to be able to accept the call outside of the componentDidMount() function.</p>

<p>So preferably I would have a function like this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>acceptCall() {
 // Do something to accept call
}</code>```

Is there any expert here, that could quickly help me?

答:
Ok I figured it out myself.

What I need to do is the following:

constructor(props){
    super(props);

    this.state = {
        inboundConn: null
    };
}

// Initialize after component creation
componentDidMount() {
   Twilio.Device.incoming((conn) => {
      this.setState({
         inboundConn: conn
      });
   });
}

acceptCall() {
   this.state.inboundConn.accept();
}```

Body:
I am trying to accept incoming calls with the twilio.Js Library. (https://www.twilio.com/docs/api/client)

I am listening for the incoming calls like this:

componentDidMount() {
    Twilio.Device.incoming((conn) => {
        console.log('Incoming connection from ' + conn.parameters.From);
    });
}

I know that I can just call conn.accept(); in the Twilio.Device.incoming function, however for my component to work, I would need to be able to accept the call outside of the componentDidMount() function.

So preferably I would have a function like this:

acceptCall() {
 // Do something to accept call
}

Is there any expert here, that could quickly help me?


问:
What is the best way to retrieve states from a state controller?
For a school project, the goal is to make a real-time system that exists out of 3 processes, lets say "process calculate" and "process execute". On top of these 2 processes, there is a state holder, lets call it "process StateCommunication", of the 2 processes. whenever the state of the statecommunication changes, the 2 processes should then read the state of the statecommunication, and if it's a state that is used in that process, then an action has to be executed within that process. What is the best way to retrieve the state of the statecommunication process? As this state controls what happens in the 2 other processes.
A last thing, all the statecommunication does is adjust the state accordingly to the two other processes, so it doesn't calculate anything whatsoever, this all happens in the other 2 processes.

For the communication between calculate and execute, we've decided to use a FIFO to send the data from the calculation to the executer. But, this doesn't seem to be the optimal solution for the statecommunication, as this should then have to be a FIFO that can be read by multiple processes. But in a FIFO, once the data gets read by one process, all the data disappears from the pipe.

Now my question is, what would be the best way to retrieve the state from the "statecommunication", which can continuously be retrieved by multiple processes?

答:
Below is one approach to implementing a state machine in C. In the example below, I used forking to create the processes you mentioned and I used a thread to emulate some input that transitions the state. I've used this pattern for cases where I have a device that implements a state machine with input from some external source.

This can be done a bunch of ways, but the core idea behind this approach is to have the worker threads (or processes) watching a state variable, have a main thread (or process) watching a state transition variable(s) and changing the state variable accordingly, and then an independent thread (or process) that changes the state transition variable(s) according to the external data received.

Keep in mind that it is necessary for the main thread to "reset" the state transition variable so that it doesn't immediately transition out of the new state. I did this by creating a NO OP transition state. Since both the main and ExternalSource write to the state transition variable, I used a mutex for protection.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <string.h>

pthread_mutex_t mutex;

typedef enum _State{
    EXECUTE,
    IDLE,
    CALCULATE
} State;

typedef enum _StateTransition{
    TRANS_EXECUTE,
    TRANS_IDLE,
    TRANS_CALCULATE,
    TRANS_NOOP
} StateTransition;

void Calculate(State *state_p){
    int flag = 0; // Only calculate once per state transition
    while (1){
        if ((*state_p == CALCULATE) && flag){
            puts("Calculated");
            flag = 0;
        } else if (*state_p != CALCULATE){
            flag = 1;
        }
    }
}

void Execute(State *state_p){
    int flag = 0; // Only execute once per state transition
    while (1){
        if ((*state_p == EXECUTE) && flag){
            puts("executed");
            flag = 0;
        } else if (*state_p != EXECUTE){
            flag = 1;
        }
    }
}

void * ExternalSource(void * param){
    StateTransition * transition_p = (StateTransition*) param;

    // Emulate External input
    while(1){
        sleep(2);
        puts("Transiton to idle");
        pthread_mutex_lock(&mutex);
        *transition_p = TRANS_IDLE;
        pthread_mutex_unlock(&mutex);

        sleep(2);
        puts("Transition to calculate");
        pthread_mutex_lock(&mutex);
        *transition_p = TRANS_CALCULATE;
        pthread_mutex_unlock(&mutex);

        sleep(2);
        puts("Transition to execute");
        pthread_mutex_lock(&mutex);
        *transition_p = TRANS_EXECUTE;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t externalThread;
    int rv;
    pid_t pidExecute;
    pid_t pidCalculate;
    volatile StateTransition transition;
    State * state;

    // Setup Initial Values
    transition = TRANS_NOOP;
    state = mmap(NULL, sizeof(State), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
    *state = IDLE;

    // Create Processes for Calculate and Execute
    pidExecute = fork();
    if (pidExecute == 0){
        Execute(state);
    } else{
        pidCalculate = fork();
        if (pidCalculate == 0){
            Calculate(state);
        }
    }

    // Create Thread for Input Emulation
    rv = pthread_create(&externalThread, NULL, ExternalSource, (void*)&transition);
    if (rv){
        perror("ERROR Unable to create thread");
        return -1;
    }

    while(1){ //Implement State Machine

        switch (*state){

        case IDLE:
            if (transition == TRANS_CALCULATE){
                // Do some transition stuff

                *state = CALCULATE; // Update new state
                pthread_mutex_lock(&mutex);
                transition = TRANS_NOOP; // Reset transition
                pthread_mutex_unlock(&mutex);

            }
            break;

        case CALCULATE:
            if (transition == TRANS_EXECUTE){
                // Do some transition stuff

                *state = EXECUTE; // Update new state
                pthread_mutex_lock(&mutex);
                transition = TRANS_NOOP; // Reset transition
                pthread_mutex_unlock(&mutex);
            }
            break;

        case EXECUTE:
            if (transition == TRANS_IDLE){
                // Do some transition stuff

                *state = IDLE; // Update new state
                pthread_mutex_lock(&mutex);
                transition = TRANS_NOOP; // Reset transition
                pthread_mutex_unlock(&mutex);
            }
            break;

        default:
            break;
        }
    }

    return 0;
}
</code>```

This code does compile, but it is not platform independent. This is really just to demonstrate the idea. If you're going to use this code as a starting place, make sure understand what's going on in each line, or else it will end up taking you more time in the long run.

Body:
Below is one approach to implementing a state machine in C. In the example below, I used forking to create the processes you mentioned and I used a thread to emulate some input that transitions the state. I've used this pattern for cases where I have a device that implements a state machine with input from some external source.

This can be done a bunch of ways, but the core idea behind this approach is to have the worker threads (or processes) watching a state variable, have a main thread (or process) watching a state transition variable(s) and changing the state variable accordingly, and then an independent thread (or process) that changes the state transition variable(s) according to the external data received.

Keep in mind that it is necessary for the main thread to "reset" the state transition variable so that it doesn't immediately transition out of the new state. I did this by creating a NO OP transition state. Since both the main and ExternalSource write to the state transition variable, I used a mutex for protection.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <string.h>

pthread_mutex_t mutex;

typedef enum _State{
    EXECUTE,
    IDLE,
    CALCULATE
} State;

typedef enum _StateTransition{
    TRANS_EXECUTE,
    TRANS_IDLE,
    TRANS_CALCULATE,
    TRANS_NOOP
} StateTransition;

void Calculate(State *state_p){
    int flag = 0; // Only calculate once per state transition
    while (1){
        if ((*state_p == CALCULATE) && flag){
            puts("Calculated");
            flag = 0;
        } else if (*state_p != CALCULATE){
            flag = 1;
        }
    }
}

void Execute(State *state_p){
    int flag = 0; // Only execute once per state transition
    while (1){
        if ((*state_p == EXECUTE) && flag){
            puts("executed");
            flag = 0;
        } else if (*state_p != EXECUTE){
            flag = 1;
        }
    }
}

void * ExternalSource(void * param){
    StateTransition * transition_p = (StateTransition*) param;

    // Emulate External input
    while(1){
        sleep(2);
        puts("Transiton to idle");
        pthread_mutex_lock(&mutex);
        *transition_p = TRANS_IDLE;
        pthread_mutex_unlock(&mutex);

        sleep(2);
        puts("Transition to calculate");
        pthread_mutex_lock(&mutex);
        *transition_p = TRANS_CALCULATE;
        pthread_mutex_unlock(&mutex);

        sleep(2);
        puts("Transition to execute");
        pthread_mutex_lock(&mutex);
        *transition_p = TRANS_EXECUTE;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t externalThread;
    int rv;
    pid_t pidExecute;
    pid_t pidCalculate;
    volatile StateTransition transition;
    State * state;

    // Setup Initial Values
    transition = TRANS_NOOP;
    state = mmap(NULL, sizeof(State), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
    *state = IDLE;

    // Create Processes for Calculate and Execute
    pidExecute = fork();
    if (pidExecute == 0){
        Execute(state);
    } else{
        pidCalculate = fork();
        if (pidCalculate == 0){
            Calculate(state);
        }
    }

    // Create Thread for Input Emulation
    rv = pthread_create(&externalThread, NULL, ExternalSource, (void*)&transition);
    if (rv){
        perror("ERROR Unable to create thread");
        return -1;
    }

    while(1){ //Implement State Machine

        switch (*state){

        case IDLE:
            if (transition == TRANS_CALCULATE){
                // Do some transition stuff

                *state = CALCULATE; // Update new state
                pthread_mutex_lock(&mutex);
                transition = TRANS_NOOP; // Reset transition
                pthread_mutex_unlock(&mutex);

            }
            break;

        case CALCULATE:
            if (transition == TRANS_EXECUTE){
                // Do some transition stuff

                *state = EXECUTE; // Update new state
                pthread_mutex_lock(&mutex);
                transition = TRANS_NOOP; // Reset transition
                pthread_mutex_unlock(&mutex);
            }
            break;

        case EXECUTE:
            if (transition == TRANS_IDLE){
                // Do some transition stuff

                *state = IDLE; // Update new state
                pthread_mutex_lock(&mutex);
                transition = TRANS_NOOP; // Reset transition
                pthread_mutex_unlock(&mutex);
            }
            break;

        default:
            break;
        }
    }

    return 0;
}

This code does compile, but it is not platform independent. This is really just to demonstrate the idea. If you're going to use this code as a starting place, make sure understand what's going on in each line, or else it will end up taking you more time in the long run.


问:
How to iterate xpath having same id
How to iterate xpath having same id

My Code:

```<code>if data3 == 'Passed':
    elem2 = driver.find_elements_by_xpath('(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[1]')
    for span in elem2:
        span.click()
    print(data3)~working

if data3 == 'Passed':
    elem2 = driver.find_elements_by_xpath('(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[j]')
    for span in elem2:
        span.click()
    print(data3)
</code>```

j=j+1  ~not working

and code takes more time to execute but the first method not.

答:
You're storing j as a part of your string, as a letter instead of a variable, so j=j+1 will not work.

Try adding the value of j to the xpath using string formatting

```<code>'(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[{0}]'.format(j)
</code>```

if the value of j is 5, the above string formatting will return

```<code>'(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[5]'
</code>```

Title: How to iterate xpath having same id

Body:
How to iterate xpath having same id

My Code:

if data3 == 'Passed':
    elem2 = driver.find_elements_by_xpath('(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[1]')
    for span in elem2:
        span.click()
    print(data3)~working

if data3 == 'Passed':
    elem2 = driver.find_elements_by_xpath('(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[j]')
    for span in elem2:
        span.click()
    print(data3)

j=j+1  ~not working

and code takes more time to execute but the first method not.

Body:
You're storing j as a part of your string, as a letter instead of a variable, so j=j+1 will not work.

Try adding the value of j to the xpath using string formatting

'(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[{0}]'.format(j)

if the value of j is 5, the above string formatting will return

'(//*[@id="questionsTable"]/tbody/tr[1]/td[2]/div/div/span[1]/input)[5]'


问:
findContours in opencv Java
```<code>  if (DETECT_RED_OBJECTS_ONLY)
  {
    Imgproc.cvtColor(inputFrame, gray,
    Imgproc.COLOR_BGR2RGB);
  }
  else
  {
     Imgproc.cvtColor(inputFrame, gray, Imgproc.COLOR_BGR2GRAY);
  }
     Imgproc.cvtColor(inputFrame, dst, Imgproc.COLOR_BGR2RGB);

     // down-scale and upscale the image to filter out the noise
     Imgproc.pyrDown(gray, downscaled, new Size(gray.cols() / 2, gray.rows()  2));
     Imgproc.pyrUp(downscaled, upscaled, gray.size());

     if (DETECT_RED_OBJECTS_ONLY) {
         // convert the image from RGBA to HSV
         Imgproc.cvtColor(upscaled, hsv, Imgproc.COLOR_RGB2HSV);
         // threshold the image for the lower and upper HSV red range
         Core.inRange(hsv, HSV_LOW_RED1, HSV_LOW_RED2, lowerRedRange);
         Core.inRange(hsv, HSV_HIGH_RED1, HSV_HIGH_RED2, upperRedRange);
         // put the two thresholded images together

         Core.addWeighted(lowerRedRange, 1.0, upperRedRange, 1.0, 0.0, bw);
         // apply canny to get edges only
         System.out.println(bw);
         Imgproc.Canny(bw, bw, 0, 255);
     } else {
         // Use Canny instead of threshold to catch squares with gradient shading
         Imgproc.Canny(upscaled, bw, 0, 255);
     }

    // dilate canny output to remove potential
     // holes between edge segments
     Imgproc.dilate(bw, bw, new Mat(), new Point(-1, 1), 1);

     // find contours and store them all as a list
     List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
     contourImage = bw.clone();
     Imgproc.findContours(
             contourImage,
             contours,
             hierarchyOutputVector,
             Imgproc.RETR_EXTERNAL,
             Imgproc.CHAIN_APPROX_SIMPLE
     );

     System.out.println("contours" + contours);

     // loop over all found contours
     for (MatOfPoint cnt : contours) {
         MatOfPoint2f curve = new MatOfPoint2f(cnt.toArray());

         // approximates a polygonal curve with the specified precision
         Imgproc.approxPolyDP(
                 curve,
                 approxCurve,
                 0.02 * Imgproc.arcLength(curve, true),
                 true
         );

         int numberVertices = (int) approxCurve.total();
</code>```

When I use triangle as an input image , this one works and detect triangle[counters become 1 and numberVertices becomes 3]. But when i input a rectangle image , contours become 2 and numberVertices becomes 2. It must be 4 . Isn't it. Can anyone help me to find the bug.

答:
If you are using this in latest visual studio, I suggest you to use :

```<code>JavaList List<MatOfPoint> contours = new JavaList<MatOfPoint>();
</code>```

this might change the behavior of your contours. Please let me know if this fixed your bug. Otherwise  lets try with something else

Title: findContours in opencv Java

Body:
  if (DETECT_RED_OBJECTS_ONLY)
  {
    Imgproc.cvtColor(inputFrame, gray,
    Imgproc.COLOR_BGR2RGB);
  }
  else
  {
     Imgproc.cvtColor(inputFrame, gray, Imgproc.COLOR_BGR2GRAY);
  }
     Imgproc.cvtColor(inputFrame, dst, Imgproc.COLOR_BGR2RGB);

     // down-scale and upscale the image to filter out the noise
     Imgproc.pyrDown(gray, downscaled, new Size(gray.cols() / 2, gray.rows()  2));
     Imgproc.pyrUp(downscaled, upscaled, gray.size());

     if (DETECT_RED_OBJECTS_ONLY) {
         // convert the image from RGBA to HSV
         Imgproc.cvtColor(upscaled, hsv, Imgproc.COLOR_RGB2HSV);
         // threshold the image for the lower and upper HSV red range
         Core.inRange(hsv, HSV_LOW_RED1, HSV_LOW_RED2, lowerRedRange);
         Core.inRange(hsv, HSV_HIGH_RED1, HSV_HIGH_RED2, upperRedRange);
         // put the two thresholded images together

         Core.addWeighted(lowerRedRange, 1.0, upperRedRange, 1.0, 0.0, bw);
         // apply canny to get edges only
         System.out.println(bw);
         Imgproc.Canny(bw, bw, 0, 255);
     } else {
         // Use Canny instead of threshold to catch squares with gradient shading
         Imgproc.Canny(upscaled, bw, 0, 255);
     }

    // dilate canny output to remove potential
     // holes between edge segments
     Imgproc.dilate(bw, bw, new Mat(), new Point(-1, 1), 1);

     // find contours and store them all as a list
     List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
     contourImage = bw.clone();
     Imgproc.findContours(
             contourImage,
             contours,
             hierarchyOutputVector,
             Imgproc.RETR_EXTERNAL,
             Imgproc.CHAIN_APPROX_SIMPLE
     );

     System.out.println("contours" + contours);

     // loop over all found contours
     for (MatOfPoint cnt : contours) {
         MatOfPoint2f curve = new MatOfPoint2f(cnt.toArray());

         // approximates a polygonal curve with the specified precision
         Imgproc.approxPolyDP(
                 curve,
                 approxCurve,
                 0.02 * Imgproc.arcLength(curve, true),
                 true
         );

         int numberVertices = (int) approxCurve.total();

When I use triangle as an input image , this one works and detect triangle[counters become 1 and numberVertices becomes 3]. But when i input a rectangle image , contours become 2 and numberVertices becomes 2. It must be 4 . Isn't it. Can anyone help me to find the bug.

Body:
If you are using this in latest visual studio, I suggest you to use :

JavaList List<MatOfPoint> contours = new JavaList<MatOfPoint>();

this might change the behavior of your contours. Please let me know if this fixed your bug. Otherwise  lets try with something else


问:
bash handling of quotation marks in filename
I am trying to remove and replace quotation marks that are present in a file name. For example, I would like to change:

```<code>$ ls
abc"def"ghi"jkl"mno
</code>```

to this

```<code>$ ls
abc:def:ghi:jkl:mno
</code>```

In trying to solve this, I came across How to rename a bunch of files to eliminate quote marks, which is exactly what I want to do. However, it didn't work for my case. To figure out why, I tried creating a test file like this:

```<code>$ touch abba\"abba\"cde\"cde\"efef
</code>```

With this file, the solutions I came across (such as mentioned above) worked. But why didn't it work for the first file?

One thing I discovered was that bash command completion sees them differently. If I type in

```<code>$ ls abb<tab>
</code>```

bash will complete the filename like so:

```<code>$ abba\"abba\"cde\"cde\"efef
</code>```

just as I created it. But for the original file, bash completion went like this:

```<code>$ ls abc<tab>
</code>```

results in

```<code>$ abc"def"ghi"jkl"mno
</code>```

So in the test case file, there is an escape of the quotation marks, and in the other case (the file I really want to rename), there is no escaping of the the quotation marks. I don't know how the original files were named.

Can anyone explain why bash sees these names differently, and how I would go about renaming my file?

答:
Here is two ways to rename a file with "(quotation) mark,

option 1: With escape character \

```<code>mv abc\"cdf\"efg\"hij newFileName
</code>```

option 2: By using '(single quote)

```<code>mv 'abc"cdf"efg"hij' newFileName
</code>```

Note: using special charaters like :(colon) in file name might not be a good idea,

and regarding the auto completion, it usually fill the name with escape character, example

ls abc<tab> will complete the name to ls abc\"cdf\"efg\"hij

unless you start the name with a quote, example

ls 'abc<tab> will complete the name to ls 'abc"cdf"efg"hij'

Body:
I am trying to remove and replace quotation marks that are present in a file name. For example, I would like to change:

$ ls
abc"def"ghi"jkl"mno

to this

$ ls
abc:def:ghi:jkl:mno

In trying to solve this, I came across How to rename a bunch of files to eliminate quote marks, which is exactly what I want to do. However, it didn't work for my case. To figure out why, I tried creating a test file like this:

$ touch abba\"abba\"cde\"cde\"efef

With this file, the solutions I came across (such as mentioned above) worked. But why didn't it work for the first file?

One thing I discovered was that bash command completion sees them differently. If I type in

$ ls abb<tab>

bash will complete the filename like so:

$ abba\"abba\"cde\"cde\"efef

just as I created it. But for the original file, bash completion went like this:

$ ls abc<tab>

results in

$ abc"def"ghi"jkl"mno

So in the test case file, there is an escape of the quotation marks, and in the other case (the file I really want to rename), there is no escaping of the the quotation marks. I don't know how the original files were named.

Can anyone explain why bash sees these names differently, and how I would go about renaming my file?

Body:
Here is two ways to rename a file with "(quotation) mark,

option 1: With escape character \

mv abc\"cdf\"efg\"hij newFileName

option 2: By using '(single quote)

mv 'abc"cdf"efg"hij' newFileName

Note: using special charaters like :(colon) in file name might not be a good idea,

and regarding the auto completion, it usually fill the name with escape character, example

ls abc<tab> will complete the name to ls abc\"cdf\"efg\"hij

unless you start the name with a quote, example

ls 'abc<tab> will complete the name to ls 'abc"cdf"efg"hij'


问:
Difference between mat and md in angular 2
I am new to angular2. I would like to know the difference between using md and mat in angular2. I tried googling but cant find the answers that I expect. I am using Angular 2 in Visual Studio 2015. Can someone please help me with the answers.

Thanks

答:
mat- and md- are prefixes in two different versions of angular materials.
"md" prefix is deprecated from material version 2.0.0-beta.11.
deprecation-of-md-prefix</p>


问:
How do I enter a query with a PREFIX in RDF4J Console?
```<code>sparql> PREFIX ab: <http://learningsparql.com/ns/addressbook#>
Executing update...
Update executed in 160 ms
sparql> SELECT ?craigEmail WHERE { ?person ab:firstName "Craig" }
Malformed query: org.eclipse.rdf4j.query.parser.sparql.ast.VisitorException:
QName 'ab:firstName' uses an undefined prefix

sparql> SELECT ?craigEmail WHERE { ?person
<http://learningsparql.com/ns/addressbook/firstName> "Craig" }
Evaluating SPARQL query...
+-----------------------------------------------------------------------------+
| craigEmail                                                                  |
+-----------------------------------------------------------------------------+
+-----------------------------------------------------------------------------+
0 result(s) (64 ms)
</code>```

答: Try putting the prefix on the same line as the query (so everything is on one line).</p>


问:
Is it a good practice to share constants/enums between microservices
In my application there are 9 micro-services, lets say two of them uses an enum for a operation. Is it a good practice to place the enum in common place and add commons jar as a dependency to both the microservices ?</p>

答:
Micro-service theory says, you shouldn't do that. But I think, from practical point of view, it is often necessary. At least, if you want to ensure some level of governance across the organization. Because, yes, most of the enums are primarily owned by some microservices or bounded contexts. But it doesn't mean, you don't need to use them in others...Take for example mobile banking...You want to open a banking account via mobile application (with its own backend). This mobile app is communicating (via its own backend) (directly or through some messaging layer) with core banking system.
Your mobile app needs to know the product code(among lot of other things)of an account you want to open, and of course, core banking system needs to know it as well (it is in the domain which masters this information).
Also, I don't think that sharing enums via library is the only way. You can read the enums dynamically via the REST API , or messages. It is always a trade-off of what you need and what is the cost of doing that. But I don't agree, that not-sharing is always the best option.</p>


问:
how flex-basis: 0% and flex-grow factor calculates the computed width?
I have the below html, where I set default flex properties are being used.

```<code><div class="container">
  <div class="box"> BOX 1</div>
  <div class="box"> BOX 2</div>
  <div class="box box2"> BOX 3 .</div>
</div>
</code>```

and styles are:

```<code>.container {
  border: 1px solid #59c;
  width: 60vw;
  background: #ccc;
  height: 200px;
  margin: 0 auto;
  display: flex;
  padding: 30px;
}

.box {
  font-size: 18px;
  font-weight: 800;
  background: #e5f;
  border: 1px solid #99c;
  padding: 20px;
}
</code>```

Now, in my chrome browser I do see box 1 and box 2 has computed width of 94.52px, and box3 has 103.52px. The fiddle b666tkj9. Now when I do add below style:

```<code>.box2 {
   flex: 2 1;
}
</code>```

and flex: 1 1; to the .box {} rules, the computed width becomes now
226.5px for Box 1 and 2, and Box 3 got 411px.

My parent container width is 864px. So, 864 - 103.53 + (94.52 * 2) is equal to 571.43px. So this amount of space is distributed then, but I am not able to do the math which can show how each box got its final width.

Can anyone help by explaining this?

答:
The flex-grow CSS property specifies the flex grow factor of a flex item. It specifies what amount of space inside the flex container the item should take up. The flex grow factor of a flex item is relative to the size of the other children in the flex-container.

— flex-grow MDN Article

As you can see, the size is relative to the other children.  Given that your container is 864px wide, the children will be 184.5px wide not including padding or borders.  We get to that number by dividing the width by the total grow values after subtracting the padding and border widths of the flex children out of the total width: (864 - 21*6) / 4 = 184.5 (21*6 accounts for three left borders, three right borders, three left padding values, and three right padding values).  So with flex-grow set to 1,1,2, you get 184.5px,184.5px,369px respectively.  Include the padding and border to get to the original width total: 184.5+184.5+369 + 40+40+40 + 2+2+2 = 864. So you have the right idea.  It's just that the "width" of the children is the width excluding padding and border width.

Ultimately, you can see this illustrated below. 1,1,2 translates to 184.5px,184.5px,369px when only calculating using the "content" portion of the box model width for the flex children:

.container {
  border: 1px solid #59c;
  width: 864px;
  background: #ccc;
  height: 200px;
  margin: 0 auto;
  display: flex;
  padding: 30px;
}

.box {
  font-size: 18px;
  font-weight: 800;
  background: #e5f;
  border: 1px solid #99c;
  padding: 20px;

  flex: 1 1;
}

.box2 {
   flex: 2 1;
}

.box{position:relative}
.box:after{content:'184.5px';position:absolute;left:20px;right:20px;bottom:50%;text-align:center;border-bottom:2px solid;}
.box:before{content:'';position:absolute;left:20px;right:20px;bottom:50%;border:1px solid;border-width:0 2px;height:8px;margin-bottom:-3px;}
.box2:after{content:'369px';}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"> BOX 1</div>
  <div class="box"> BOX 2</div>
  <div class="box box2"> BOX 3 .</div>
</div></code>```

Body:
I have the below html, where I set default flex properties are being used.

 BOX 1

 BOX 2

 BOX 3 .

and styles are:

.container {
  border: 1px solid #59c;
  width: 60vw;
  background: #ccc;
  height: 200px;
  margin: 0 auto;
  display: flex;
  padding: 30px;
}

.box {
  font-size: 18px;
  font-weight: 800;
  background: #e5f;
  border: 1px solid #99c;
  padding: 20px;
}

Now, in my chrome browser I do see box 1 and box 2 has computed width of 94.52px, and box3 has 103.52px. The fiddle b666tkj9. Now when I do add below style:

.box2 {
   flex: 2 1;
}

and flex: 1 1; to the .box {} rules, the computed width becomes now
226.5px for Box 1 and 2, and Box 3 got 411px.

My parent container width is 864px. So, 864 - 103.53 + (94.52 * 2) is equal to 571.43px. So this amount of space is distributed then, but I am not able to do the math which can show how each box got its final width.

Can anyone help by explaining this?

Body:
The flex-grow CSS property specifies the flex grow factor of a flex item. It specifies what amount of space inside the flex container the item should take up. The flex grow factor of a flex item is relative to the size of the other children in the flex-container.

— flex-grow MDN Article

As you can see, the size is relative to the other children.  Given that your container is 864px wide, the children will be 184.5px wide not including padding or borders.  We get to that number by dividing the width by the total grow values after subtracting the padding and border widths of the flex children out of the total width: (864 - 21*6) / 4 = 184.5 (21*6 accounts for three left borders, three right borders, three left padding values, and three right padding values).  So with flex-grow set to 1,1,2, you get 184.5px,184.5px,369px respectively.  Include the padding and border to get to the original width total: 184.5+184.5+369 + 40+40+40 + 2+2+2 = 864. So you have the right idea.  It's just that the "width" of the children is the width excluding padding and border width.

Ultimately, you can see this illustrated below. 1,1,2 translates to 184.5px,184.5px,369px when only calculating using the "content" portion of the box model width for the flex children:

.container {
  border: 1px solid #59c;
  width: 864px;
  background: #ccc;
  height: 200px;
  margin: 0 auto;
  display: flex;
  padding: 30px;
}

.box {
  font-size: 18px;
  font-weight: 800;
  background: #e5f;
  border: 1px solid #99c;
  padding: 20px;

  flex: 1 1;
}

.box2 {
   flex: 2 1;
}

.box{position:relative}
.box:after{content:'184.5px';position:absolute;left:20px;right:20px;bottom:50%;text-align:center;border-bottom:2px solid;}
.box:before{content:'';position:absolute;left:20px;right:20px;bottom:50%;border:1px solid;border-width:0 2px;height:8px;margin-bottom:-3px;}
.box2:after{content:'369px';}

<div class="container">
  <div class="box"> BOX 1</div>
  <div class="box"> BOX 2</div>
  <div class="box box2"> BOX 3 .</div>
</div>


问:
PHP: user is successfully logout but after logout refresh home page it shows that undefined variable:
Email is the user session email after successfully logout there is no email exist but on index page is shows undefined index as there is no email after logout.</p>

```<code>Notice: Undefined index: email in C:\xampp\htdocs\CMS\index.php on line 9
    <?session_start();
?>
<?php
    require("conection/connect.php");
    $username=$_SESSION['email'];
    $sel= "select * from users where email= '$username'";
    $run_name = mysqli_query($con, $sel);
    $row_user=mysqli_fetch_array($run_name);
    $name=$row_user['name'];
    $userid=$row_user['user_id'];
    $teacherid=$row_user['teacher_id'];
    $userid=$row_user['stu_id'];
    $usertype=$row_user['type'];
?>
</code>```

答:
Just verify that it's set. That will probably be useful to you anyway, because I assume if it isn't set you may want to do something different.

```<code><?php

if (!isset($_SESSION['email'])) {
    // maybe redirect to login?
    // or at least don't show them logged-in user type stuff
}

// your code (in an else block if you didn't redirect in the if)
</code>```

Body:
Email is the user session email after successfully logout there is no email exist but on index page is shows undefined index as there is no email after logout.

Notice: Undefined index: email in C:\xampp\htdocs\CMS\index.php on line 9
    <?session_start();
?>
<?php
    require("conection/connect.php");
    $username=$_SESSION['email'];
    $sel= "select * from users where email= '$username'";
    $run_name = mysqli_query($con, $sel);
    $row_user=mysqli_fetch_array($run_name);
    $name=$row_user['name'];
    $userid=$row_user['user_id'];
    $teacherid=$row_user['teacher_id'];
    $userid=$row_user['stu_id'];
    $usertype=$row_user['type'];
?>

Body:
Just verify that it's set. That will probably be useful to you anyway, because I assume if it isn't set you may want to do something different.

<?php

if (!isset($_SESSION['email'])) {
    // maybe redirect to login?
    // or at least don't show them logged-in user type stuff
}

// your code (in an else block if you didn't redirect in the if)


问:
Adding my own tags inside HTML blocks in Perl
Is there a way to receive a html page, look for  blocks and enclose text with my own characters?

For example given the following html:

```<code><html>
<head>
    <title>Appleseed Farm</title>
</html>
<body>
<table>
    <tr>
        <td>Col1</td>
        <td>Col2</td>
        <td><img src="blah/blah.jpg"></td>
        <td></td>
    </tr>
</table>
<div>Some random text</div>
<p>Random image of the day: <img src="random.jpg"></p>
</body>
</html>
</code>```

Becomes the following with my '@' tag around text:

```<code><html>
<head>
     <title>@Appleseed Farm@</title>
</html>
<body>
<table>
    <tr>
        <td>@Col1@</td>
        <td>@Col2@</td>
        <td><img src="blah/blah.jpg"></td>
        <td></td>
    </tr>
</table>
<div>@Some random text@</div>
<p>@Random image of the day:@ <img src="random.jpg"></p>
</body>
</html>
</code>```

答:
Sorry for the bad question. I did figure it out after going through the HTML::Element page. </p>

```<code>use strict;
use warnings;
use HTML::TreeBuilder;
use feature ':5.10';

my $root = HTML::TreeBuilder->new_from_file(\*DATA);
$root->elementify;

for my $e ($root->look_down (
    sub {
      my $tag = $_[0]->tag();
      grep( /^$tag$/, qw(td div p title span) )
      }
  ))
{
    #Do an in-place replacement
    foreach my $item_r ($e->content_refs_list) {
        next if ref $$item_r;
        $$item_r =~ s/^(.+)$/\@$1\@/g;
    }
}

say $root->as_HTML (undef, "  ", {});

__DATA__
<html>
<head>
    <title>Appleseed Farm</title>
</html>
<body>
<table>
    <tr>
        <td>Col1</td>
        <td>Col2</td>
        <td><img src="blah/blah.jpg">Col 3</td>
        <td>cat</td>
    </tr>
</table>
<div>Some random text</div>
<p>Random image of the day: <img src="random.jpg"></p>
</body>
</code>```

Body:
Is there a way to receive a html page, look for  blocks and enclose text with my own characters?

For example given the following html:

    <title>Appleseed Farm</title>

        Col1
        Col2

Some random text

Random image of the day:

Becomes the following with my '@' tag around text:

     <title>@Appleseed Farm@</title>

        @Col1@
        @Col2@

@Some random text@

@Random image of the day:@

Body:
Sorry for the bad question. I did figure it out after going through the HTML::Element page.

use strict;
use warnings;
use HTML::TreeBuilder;
use feature ':5.10';

my $root = HTML::TreeBuilder->new_from_file(\*DATA);
$root->elementify;

for my $e ($root->look_down (
    sub {
      my $tag = $_[0]->tag();
      grep( /^$tag$/, qw(td div p title span) )
      }
  ))
{
    #Do an in-place replacement
    foreach my $item_r ($e->content_refs_list) {
        next if ref $$item_r;
        $$item_r =~ s/^(.+)$/\@$1\@/g;
    }
}

say $root->as_HTML (undef, "  ", {});

__DATA__
<html>
<head>
    <title>Appleseed Farm</title>
</html>
<body>
<table>
    <tr>
        <td>Col1</td>
        <td>Col2</td>
        <td><img src="blah/blah.jpg">Col 3</td>
        <td>cat</td>
    </tr>
</table>
<div>Some random text</div>
<p>Random image of the day: <img src="random.jpg"></p>
</body>


问:
Numbering child elements in ReactJS
I'm new to React, and I'm confused about how it's supposed to work.

I want to make a little assessment app with questions, sections, and a totals section.

I marked up what I want inside of a home page component like this:

```<code>export default class Home extends React.Component {
    public render() {
        return <SurvivalTest>
            <Section title="Requirements">
                <Question>
                    Does the project have a clear, unambiguous vision statement
                    or mission statement?
                </Question>
                <Question>
                    Do all team members believe the vision is realistic?
                </Question>
                <Question>
                    Does the project have a business case that details the
                    business benefit and how the benefit will be measured?
                </Question>
            </Section>
            <Section title="Planning">
                <Question>
                    Does the project have a detailed, written Software
                    Development Plan?
                </Question>
                <Question>
                    Were the schedule and budget estimates officially updated
                    at the end of the most recently completed phase?
                </Question>
                <Question>
                    Does the project have detailed, written architecture and
                    design documents?
                </Question>
            </Section>
            <TotalsSection />
        </SurvivalTest>;
    }
}
</code>```

The questions each have 4 possible answers, scored 0-3.  The answers are the same for all questions and they are: "No", "Not really", "Probably", and "Yes".  The Section component the table element and labels for the answers are in the table headers.

```<code>export class Question extends React.Component {
    constructor() {
        super();
        this.state = { score: 0 };
    }

    public render() {
        return <tr>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 0 })} checked={this.state.score === 0} />
            </td>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 1 })} checked={this.state.score === 1} />
            </td>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 2 })} checked={this.state.score === 2} />
            </td>
            <td>
                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 3 })} checked={this.state.score === 3} />
            </td>
            <td>
                {??? + '. ' + this.props.children}
            </td>
        </tr>;
    }
}
</code>```

How do I number the questions automatically?  I want to display a question number before the question text, and I also want to name the input fields based on the question number (e.g. q1, q2, etc.)

Can each Question component ask its parent (Section) component for its question number?

答:
Have a inline logic in jsx .Some thing like

```<code>render() {
  let questionIndex = 0
  return ( < div > {
      json.map((element, index) => {
        //Can create jsx according to need
        questionIndex += 1
        return ( < div key = {
            questionIndex
          } >
          < p >
          Question number {
            questionIndex
          } < /p> < Options / >
          < Input / >
          < AnyOtherComponent / >
          < /<div>

        )
      })
    } < /div>

  )

}
</code>```

Please let me know if that helped. It may give you some hints

Title: Numbering child elements in ReactJS

Body:
I'm new to React, and I'm confused about how it's supposed to work.

I want to make a little assessment app with questions, sections, and a totals section.

I marked up what I want inside of a home page component like this:

export default class Home extends React.Component {
    public render() {
        return <SurvivalTest>

                <Question>
                    Does the project have a clear, unambiguous vision statement
                    or mission statement?
                </Question>
                <Question>
                    Do all team members believe the vision is realistic?
                </Question>
                <Question>
                    Does the project have a business case that details the
                    business benefit and how the benefit will be measured?
                </Question>

                <Question>
                    Does the project have a detailed, written Software
                    Development Plan?
                </Question>
                <Question>
                    Were the schedule and budget estimates officially updated
                    at the end of the most recently completed phase?
                </Question>
                <Question>
                    Does the project have detailed, written architecture and
                    design documents?
                </Question>

            <TotalsSection />
        </SurvivalTest>;
    }
}

The questions each have 4 possible answers, scored 0-3.  The answers are the same for all questions and they are: "No", "Not really", "Probably", and "Yes".  The Section component the table element and labels for the answers are in the table headers.

export class Question extends React.Component {
    constructor() {
        super();
        this.state = { score: 0 };
    }

    public render() {
        return

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 0 })} checked={this.state.score === 0} />

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 1 })} checked={this.state.score === 1} />

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 2 })} checked={this.state.score === 2} />

                <input name={'q' + ???} type="radio" onClick={() => this.setState({ score: 3 })} checked={this.state.score === 3} />

                {??? + '. ' + this.props.children}

;
    }
}

How do I number the questions automatically?  I want to display a question number before the question text, and I also want to name the input fields based on the question number (e.g. q1, q2, etc.)

Can each Question component ask its parent (Section) component for its question number?

Body:
Have a inline logic in jsx .Some thing like

render() {
  let questionIndex = 0
  return ( < div > {
      json.map((element, index) => {
        //Can create jsx according to need
        questionIndex += 1
        return ( < div key = {
            questionIndex
          } >
          < p >
          Question number {
            questionIndex
          } < /p> < Options / >
          < Input / >
          < AnyOtherComponent / >
          < /<div>

        )
      })
    } < /div>

  )

}

Please let me know if that helped. It may give you some hints


问:
Symfony 3 Validate embedded entities dynamically
I am writing several forms with symfony 3. My form is very like the given example in the symfony reference:

http://symfony.com/doc/current/reference/constraints/Valid.html
I also have an user and an embedded address-entity. My configuration is done via yml:

PARENT User:

```<code>// src/Entity/User.php
namespace App\Entity;

class User
{
    protected $firstName;
    protected $lastName;
    protected $address;

    protected $mailOptIn;
}
</code>```

CHILD Address:

```<code>// src/Entity/Address.php
namespace App\Entity;

class Address
{
    protected $street;
    protected $zipCode;
}
</code>```

YML:

```<code># config/validator/validation.yaml
App\Entity\Address:
    properties:
        street:
            - NotBlank:  { groups: [group01, group02] }
        zipCode:
            - NotBlank:  { groups: [group01, group02] }
            - Length: { min: 3, groups: [group01, group02] }

App\Entity\User:
    properties:
        firstName:
            - NotBlank: ~
            - Length:
                min: 4
        lastName:
            - NotBlank: ~
        address:
            - Valid: { groups: [group01, group02] }
</code>```

BUT in some cases (depending on other fields in the parent-user-entity) it is
not necessary to validate the embedded address-entity.

Now I've read a lot about callback and getter-validators, but my problem is, that I do not know, how to handle this. Another part which makes the case even more complex for me is, that i need to use validation-groups (https://symfony.com/doc/current/form/validation_groups.html ) in the address entity, due to the fact, that i validate about 20 countries, where each of them has its own validation fields.

Can anybody give me hint, how to go on? The address-validation with the groups works perfectly, i think i just need to implement some cool magic stuff in the parent-user-entity, right?

UPDATE:

I just added TWO things:

in class USER -> protected $mailOptIn

in YML-User -> address: -Valid: { groups: [group01, group02] }

The validation with the valid-key works.

What I want to implement now is, that the address-validation is only done, if the user has set mailOptIn to true, because only in that case, I need the address.
Please note, that i do need groups for the address-validation, depending on what country the given address is placed.

答:
You can do it in your controller action :</p>

```<code>use Symfony\Component\Form\FormError;

class MyClass {

    public function createAction(Request $request) {
        // your actual code

        // dynamic form validation
        if($form->isSubmitted()){
            $zip= $form->get('address')->get('zip')->getData();
            $street= $form->get('address')->get('street')->getData();
            if($zip == '1234' && count($street)>150){
                 $form->get('address')->get('zip')->addError(new FormError('Address cant have more than 150 char for ZIP 1234')); // add error on the ZIP field
            } else if($zip == '465' && count($street) < 3) {
                 $form->get('address')->get('street')->addError(new FormError('Address must have more than 3 char for ZIP 456')); // add error on the address field
            }
        }

        // your actual code
        if($form->isSubmitted() && $form->isValid()){

        }
    }
}
</code>```

Body:
I am writing several forms with symfony 3. My form is very like the given example in the symfony reference:

http://symfony.com/doc/current/reference/constraints/Valid.html
I also have an user and an embedded address-entity. My configuration is done via yml:

PARENT User:

// src/Entity/User.php
namespace App\Entity;

class User
{
    protected $firstName;
    protected $lastName;
    protected $address;

    protected $mailOptIn;
}

CHILD Address:

// src/Entity/Address.php
namespace App\Entity;

class Address
{
    protected $street;
    protected $zipCode;
}

YML:

# config/validator/validation.yaml
App\Entity\Address:
    properties:
        street:
            - NotBlank:  { groups: [group01, group02] }
        zipCode:
            - NotBlank:  { groups: [group01, group02] }
            - Length: { min: 3, groups: [group01, group02] }

App\Entity\User:
    properties:
        firstName:
            - NotBlank: ~
            - Length:
                min: 4
        lastName:
            - NotBlank: ~
        address:
            - Valid: { groups: [group01, group02] }

BUT in some cases (depending on other fields in the parent-user-entity) it is
not necessary to validate the embedded address-entity.

Now I've read a lot about callback and getter-validators, but my problem is, that I do not know, how to handle this. Another part which makes the case even more complex for me is, that i need to use validation-groups (https://symfony.com/doc/current/form/validation_groups.html ) in the address entity, due to the fact, that i validate about 20 countries, where each of them has its own validation fields.

Can anybody give me hint, how to go on? The address-validation with the groups works perfectly, i think i just need to implement some cool magic stuff in the parent-user-entity, right?

UPDATE:

I just added TWO things:

in class USER -> protected $mailOptIn

in YML-User -> address: -Valid: { groups: [group01, group02] }

The validation with the valid-key works.

What I want to implement now is, that the address-validation is only done, if the user has set mailOptIn to true, because only in that case, I need the address.
Please note, that i do need groups for the address-validation, depending on what country the given address is placed.

Body:
You can do it in your controller action :

use Symfony\Component\Form\FormError;

class MyClass {

    public function createAction(Request $request) {
        // your actual code

        // dynamic form validation
        if($form->isSubmitted()){
            $zip= $form->get('address')->get('zip')->getData();
            $street= $form->get('address')->get('street')->getData();
            if($zip == '1234' && count($street)>150){
                 $form->get('address')->get('zip')->addError(new FormError('Address cant have more than 150 char for ZIP 1234')); // add error on the ZIP field
            } else if($zip == '465' && count($street) < 3) {
                 $form->get('address')->get('street')->addError(new FormError('Address must have more than 3 char for ZIP 456')); // add error on the address field
            }
        }

        // your actual code
        if($form->isSubmitted() && $form->isValid()){

        }
    }
}


问:
wpf style trigger on dynamic path
In the following style, is there a way to make the Binding Path generic so that this style can be used by multiple consumers, each supplying a different binding path?</p>

```<code><Style x:Key="OptionalBackground"
       TargetType="{x:Type DataPresenter:CellValuePresenter}"
       BasedOn="{StaticResource OptionalFieldCellPresenter}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},
                                       Path=Record.DataItem.IsEditAllowed}"
                     Value="False">
            <Setter Property="Background" Value="{StaticResource ReadOnlyField}" />
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

答:
You can derive from Style to create a shorthand notation that looks like this:

```<code><local:BackgroundStyle
    x:Key="OptionalBackground"
    TargetType="{x:Type DataPresenter:CellValuePresenter}"
    BasedOn="{StaticResource OptionalFieldCellPresenter}"
    Path="Record.DataItem.IsEditAllowed"
    Value="{StaticResource ReadOnlyField}"/>
</code>```

and an implementation for this example might be:

```<code>public class BackgroundStyle : Style, ISupportInitialize
{
    public string Path { get; set; }
    public object Value { get; set; }

    public void BeginInit() { }

    public void EndInit()
    {
        var trigger = new DataTrigger
        {
            Binding = new Binding
            {
                Path = new PropertyPath(Path),
                RelativeSource = new RelativeSource(RelativeSourceMode.Self)
            },
        };
        trigger.Setters.Add(new Setter(Control.BackgroundProperty, Value));
        Triggers.Add(trigger);
    }
}
</code>```

Title: wpf style trigger on dynamic path

Body:
In the following style, is there a way to make the Binding Path generic so that this style can be used by multiple consumers, each supplying a different binding path?

</Style>

Body:
You can derive from Style to create a shorthand notation that looks like this:

<local:BackgroundStyle
    x:Key="OptionalBackground"
    TargetType="{x:Type DataPresenter:CellValuePresenter}"
    BasedOn="{StaticResource OptionalFieldCellPresenter}"
    Path="Record.DataItem.IsEditAllowed"
    Value="{StaticResource ReadOnlyField}"/>

and an implementation for this example might be:

public class BackgroundStyle : Style, ISupportInitialize
{
    public string Path { get; set; }
    public object Value { get; set; }

    public void BeginInit() { }

    public void EndInit()
    {
        var trigger = new DataTrigger
        {
            Binding = new Binding
            {
                Path = new PropertyPath(Path),
                RelativeSource = new RelativeSource(RelativeSourceMode.Self)
            },
        };
        trigger.Setters.Add(new Setter(Control.BackgroundProperty, Value));
        Triggers.Add(trigger);
    }
}


问:
"Address already in use": I'm misunderstanding UDP
Is it possible for two or more programs to monitor UDP packages on a single port?  We have a device that converts RS-232 data to UDP on port 55110, but it appears I can only have one listener running on a given computer. Attempts at a second cause "Address already in use". Apparently there is some other program on the computer listening, because REUSE => 1 doesn't help. Multiple users would like to sample the data. I apologize for so basic a question.</p>

答:
It is possible for two programs to listen on the same UDP port, but both programs have to specify that they want to allow the port to be shared.  Here is an excerpt from my code that tells the OS to do this (called just before calling bind() on the UDP socket):</p>

```<code>if (allowShared)
{
   const int trueValue = 1;
   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &trueValue, sizeof(trueValue));
#ifdef __APPLE__   // MacOS/X requires an additional call also
   setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &trueValue, sizeof(trueValue));
#endif
}
</code>```

Body:
It is possible for two programs to listen on the same UDP port, but both programs have to specify that they want to allow the port to be shared.  Here is an excerpt from my code that tells the OS to do this (called just before calling bind() on the UDP socket):

if (allowShared)
{
   const int trueValue = 1;
   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &trueValue, sizeof(trueValue));
#ifdef __APPLE__   // MacOS/X requires an additional call also
   setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &trueValue, sizeof(trueValue));
#endif
}


问:
Wordpress 3.9.x - remove inline width from figure element
Starting in Wordpress 3.9, you can add a line of code to functions.php to tell Wordpress to output images with captions with the more semantic figure and figcaption elements:

```<code>add_theme_support( 'html5', array(
'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
) );
</code>```

This is great. But for some reason Wordpress adds an inline style for width to the figure element, which prevents the whole unit from being responsive. That's not great. I'd like to add some code to the functions.php that tells Wordpress to not include the inline width.

In the media.php file, I found the caption shortcode that addresses my issue:

```<code>$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
if ( $output != '' )
return $output;

$atts = shortcode_atts( array(
'id'      => '',
'align'   => 'alignnone',
'width'   => '',
'caption' => '',
'class'   => '',
), $attr, 'caption' );

$atts['width'] = (int) $atts['width'];
if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
return $content;

if ( ! empty( $atts['id'] ) )
$atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';

$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );

if ( current_theme_supports( 'html5', 'caption' ) ) {
return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
. do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
}
</code>```

Any ideas how to remove the inline style width from the figure element?

Edit: I found the solution here.

答:
There is a filter for your question:

Any ideas how to remove the inline style width from the figure
  element?

```<code>add_filter('img_caption_shortcode_width', '__return_false');
</code>```

This leaves the figure element without any style attribute crap

Body:
Starting in Wordpress 3.9, you can add a line of code to functions.php to tell Wordpress to output images with captions with the more semantic figure and figcaption elements:

add_theme_support( 'html5', array(
'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
) );

This is great. But for some reason Wordpress adds an inline style for width to the figure element, which prevents the whole unit from being responsive. That's not great. I'd like to add some code to the functions.php that tells Wordpress to not include the inline width.

In the media.php file, I found the caption shortcode that addresses my issue:

$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
if ( $output != '' )
return $output;

$atts = shortcode_atts( array(
'id'      => '',
'align'   => 'alignnone',
'width'   => '',
'caption' => '',
'class'   => '',
), $attr, 'caption' );

$atts['width'] = (int) $atts['width'];
if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
return $content;

if ( ! empty( $atts['id'] ) )
$atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';

$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );

if ( current_theme_supports( 'html5', 'caption' ) ) {
return '
'
. do_shortcode( $content ) . '
' . $atts['caption'] . '

';
}

Any ideas how to remove the inline style width from the figure element?

Edit: I found the solution here.

Body:
There is a filter for your question:

Any ideas how to remove the inline style width from the figure
  element?

add_filter('img_caption_shortcode_width', '__return_false');

This leaves the figure element without any style attribute crap


问:
Specify path to files
First of all, I'm totally new to PHP, so I'll need a bit more explanation. I'm trying to make a Multi-language site using PHP, the problem is; when I create a new folder like: domain.tld/test/location (location is new in this case), the language files which are located at domain.tld/test, are of course not imported. How can you clarify where these files NEED to be coming from?

Script

```<code><?php
// include language configuration file based on selected language
echo realpath(dirname(__FILE__));
$lang = "en";
if(isset($_GET['lang'])){
    $lang = $_GET['lang'];
}
require_once("lang.".$lang.".php");
?>
</code>```

答:
Paths in php are like path in many languages. If you want to go backward, you add ../ before the path

```<code>require_once('../file/in/prev/dir');
</code>```

I really suck at path, so whenever I have to make sure of one, I try it in my terminal. Maybe this can help you figure out where your file is.

However, I don't get why and how you need to do it this way... I mean, if you have one file for each language, why not doing it in HTML ? The main point of dealing with PHP is that you don't want to duplicate files, which is what you're doing.

You might be looking for Relational Database in which you'd have a table with generic content and another one with tranlated content. For example

Article :

|id| date |

|1 |8/8/08|

Translated Content :

|id| content |lang|

|1 | Hello   | en |

|2 | Bonjour | fr |

and intermediate table :

|article_id|content_id|

| 1 | 1 |

| 1 | 2 |

Hope it helps

Title: Specify path to files

Body:
First of all, I'm totally new to PHP, so I'll need a bit more explanation. I'm trying to make a Multi-language site using PHP, the problem is; when I create a new folder like: domain.tld/test/location (location is new in this case), the language files which are located at domain.tld/test, are of course not imported. How can you clarify where these files NEED to be coming from?

Script

<?php
// include language configuration file based on selected language
echo realpath(dirname(__FILE__));
$lang = "en";
if(isset($_GET['lang'])){
    $lang = $_GET['lang'];
}
require_once("lang.".$lang.".php");
?>

Body:
Paths in php are like path in many languages. If you want to go backward, you add ../ before the path

require_once('../file/in/prev/dir');

I really suck at path, so whenever I have to make sure of one, I try it in my terminal. Maybe this can help you figure out where your file is.

However, I don't get why and how you need to do it this way... I mean, if you have one file for each language, why not doing it in HTML ? The main point of dealing with PHP is that you don't want to duplicate files, which is what you're doing.

You might be looking for Relational Database in which you'd have a table with generic content and another one with tranlated content. For example

Article :

|id| date |

|1 |8/8/08|

Translated Content :

|id| content |lang|

|1 | Hello   | en |

|2 | Bonjour | fr |

and intermediate table :

|article_id|content_id|

| 1 | 1 |

| 1 | 2 |

Hope it helps


问:
Showing TabBar in DrawerNavigator screen
I currently have this structure:

```<code>const Tabs = TabNavigator({
  Home: {screen: Home},
  Store:{screen: Store}
  More: {screen: More,
    navigationOptions: {
      tabBarLabel: 'More',
      tabBarIcon: <Entypo name='dots-three-horizontal' size={25}/>,
      header: null
      },
    }
  },
  {
  initialRouteName: 'Home',
  tabBarPosition: 'bottom',
  navigationOptions: ({ navigation }) => ({
            tabBarOnPress: (scene, jumpToIndex) => {
                if (scene.route.routeName === "More") {
                  navigation.navigate('DrawerToggle')
                }
                else{
                  jumpToIndex(scene.index);
                }
            },
        }),
      },
    )

const Drawer = DrawerNavigator(
  {
   Tabs: {screen: Tabs,
     navigationOptions: {
           drawerLabel: () => null
      }
   },
   Profile: {screen: Profile},
   Search: {screen: Search}
  },
  {
   initialRouteName: 'Tabs',
   headerMode: 'none',
   drawerPosition: 'right'
  }
)

export const Root = StackNavigator(
  {
  LoginScreen: {screen: Login},
  Drawer: {screen: Drawer},
 },
  {
   initialRouteName: 'LoginScreen'
  }
)
</code>```

Everything works great. When I click (for example) 'Profile' the page is loaded normally and when click 'More', drawer menu opens up.

The functionality I would like to achieve is that I would like to show TabBar inside 'Profile' page(DrawerNavigator screen). How is that possible?

答:
```<code>const Drawer = DrawerNavigator(
  {
   Profile: {screen: Tabs},
   Search: {screen: Search}
  }
</code>```

You can nest a navigator in another navigator. The Tabs navigator is a component and you can use that component as a "screen" for a different navigator.

A navigator is a component. And a screen must be a component.

Body:
I currently have this structure:

const Tabs = TabNavigator({
  Home: {screen: Home},
  Store:{screen: Store}
  More: {screen: More,
    navigationOptions: {
      tabBarLabel: 'More',
      tabBarIcon: <Entypo name='dots-three-horizontal' size={25}/>,
      header: null
      },
    }
  },
  {
  initialRouteName: 'Home',
  tabBarPosition: 'bottom',
  navigationOptions: ({ navigation }) => ({
            tabBarOnPress: (scene, jumpToIndex) => {
                if (scene.route.routeName === "More") {
                  navigation.navigate('DrawerToggle')
                }
                else{
                  jumpToIndex(scene.index);
                }
            },
        }),
      },
    )

const Drawer = DrawerNavigator(
  {
   Tabs: {screen: Tabs,
     navigationOptions: {
           drawerLabel: () => null
      }
   },
   Profile: {screen: Profile},
   Search: {screen: Search}
  },
  {
   initialRouteName: 'Tabs',
   headerMode: 'none',
   drawerPosition: 'right'
  }
)

export const Root = StackNavigator(
  {
  LoginScreen: {screen: Login},
  Drawer: {screen: Drawer},
 },
  {
   initialRouteName: 'LoginScreen'
  }
)

Everything works great. When I click (for example) 'Profile' the page is loaded normally and when click 'More', drawer menu opens up.

The functionality I would like to achieve is that I would like to show TabBar inside 'Profile' page(DrawerNavigator screen). How is that possible?

Body:
const Drawer = DrawerNavigator(
  {
   Profile: {screen: Tabs},
   Search: {screen: Search}
  }

You can nest a navigator in another navigator. The Tabs navigator is a component and you can use that component as a "screen" for a different navigator.

A navigator is a component. And a screen must be a component.


问:
How to pass object data to a window.open()
Is there anyway to pass JavaScript objects to a window.open() without having the objects in a URL. I know i can do this when loading a url into a div:

```<code>$("#myDiv").load(urlForWindow, { data: data });
</code>```

But is there a way i can do this for a window:

```<code>var win = window.open(urlForWindow, '_blank', { data: data });
</code>```

答:
```<code> function openWithData(url, data){
   window.open(url, "page");
   const ping = setInterval(() => {
      window.postMessage(data, "*");
   }, 100);

  window.addEventListener("message", ({data}) => {
     if(data === "received") clearInterval(ping);
  });
}
</code>```

On the loaded page:

```<code> window.addEventListener("message", ({data}) => {
   window.postMessage("received","*");
   //Do whatever with data
});
</code>```

Body:
Is there anyway to pass JavaScript objects to a window.open() without having the objects in a URL. I know i can do this when loading a url into a div:

$("#myDiv").load(urlForWindow, { data: data });

But is there a way i can do this for a window:

var win = window.open(urlForWindow, '_blank', { data: data });

Body:
 function openWithData(url, data){
   window.open(url, "page");
   const ping = setInterval(() => {
      window.postMessage(data, "*");
   }, 100);

  window.addEventListener("message", ({data}) => {
     if(data === "received") clearInterval(ping);
  });
}

On the loaded page:

 window.addEventListener("message", ({data}) => {
   window.postMessage("received","*");
   //Do whatever with data
});