text:
Q: Handling REST SWT tokens in WCF WIF pipeline is not working I'm struggling on a setup mentioned in the subject line and am wondering if someone can help me.
Essentially, what I have is a WCF service and I want to achieve that the user can authenticate against the ACS using a custom login page (using the javascript with required information from ACS).
After doing that the user should get redirected to the WCF service using the provided SWT token. I am using the SimpleWebTokenHandler as a basis for the SWT token handling, but I'm not sure it's playing any role in this.
Here's the Web.config I'm running
<configuration>
    <configSections>

    </configSections>
    ...
    <system.serviceModel>
        <diagnostics>
        </diagnostics>
        <services>
            <service name="WcfWifSwtAcs.Service1">
                <endpoint address="xmlService" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="restPoxBehaviour" name="xmlServiceEndpoint" contract="WcfWifSwtAcs.IService1" />
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="restPoxBehaviour">
                    <webHttp helpEnabled="true" />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                    <serviceCredentials useIdentityConfiguration="true">
                        ...
                    </serviceCredentials>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add scheme="http" binding="ws2007FederationHttpBinding" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
        <bindings>
            <ws2007FederationHttpBinding>
                <binding name="">
                    <security mode="Message">
                        <message
                            issuedTokenType="http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0">
                            <issuerMetadata address="https://xxxx.accesscontrol.windows.net/v2/wstrust/13/certificate/mex" />
                        </message>
                    </security>
                </binding>
            </ws2007FederationHttpBinding>
        </bindings>
    </system.serviceModel>
    <system.webServer>
    ...
    </system.webServer>
    <system.identityModel>
        <identityConfiguration>
            <audienceUris>
                <add value="http://localhost:56782/Service1.svc" />
            </audienceUris>
            <issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                <trustedIssuers>
                    <add thumbprint="XXX" name="xxx.accesscontrol.windows.net" />
                </trustedIssuers>
            </issuerNameRegistry>
        <issuerTokenResolver type="SimpleWebToken.CustomIssuerTokenResolver, WcfWifSwtAcs" />
            <securityTokenHandlers>
                <clear/>
                <add type="SimpleWebToken.SimpleWebTokenHandler, WcfWifSwtAcs"/>
            </securityTokenHandlers>
        </identityConfiguration>
    </system.identityModel>
</configuration>

Now I can see, that the authentication happens and that the browser is redirected with the body to the service. I can also see that the SimpleWebToken handler get's instantiated and the token type URI is being requested. But that's almost all that happens. No actual token handling verification and whatsoever is happnening.
This is the token that get's sent to the service (after parsing).
wa=wsignin1.0&
wresult=
<t:RequestSecurityTokenResponse
xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<t:Lifetime>
    <wsu:Created
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2013-02-13T23:14:30.159Z</wsu:Created>
    <wsu:Expires
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2013-02-13T23:24:30.159Z</wsu:Expires>
</t:Lifetime>
<wsp:AppliesTo
    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <EndpointReference
        xmlns="http://www.w3.org/2005/08/addressing">
        <Address>http://localhost:56782/Service1.svc</Address>
    </EndpointReference>
</wsp:AppliesTo>
<t:RequestedSecurityToken>
    <wsse:BinarySecurityToken
        wsu:Id="uuid:58e2fb15-dd1a-40bd-8ff0-ae24e22e6efe"
        ValueType="http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0"
        EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"          xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
        BASE64 DATA==
    </wsse:BinarySecurityToken>
</t:RequestedSecurityToken>
<t:TokenType>http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0</t:TokenType>
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
</t:RequestSecurityTokenResponse>

Service itself is braindead simple, with following signature.
[OperationContract]
[WebInvoke(UriTemplate = "/GetData/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string GetData(string id);

Any ideas? I've been verifying that the uri's, hostnames, thumbprints etc. are all valid. Also the service tracing doesn't really show up anything that is related either to token handling or exceptions in the token verification.
Somehow it almost seems that the token doesn't get even passed to the handler. At least all the claims and other authentication information is missing (null).
I would appreciate if someone points me to a direction of either where can I debug or if I'm missing something really obvious (which might also always be the case).
P.S. I know I could achieve it with custom authentication modules and whatsoever, I'd rather get it running with WIF (it's becoming fundamental as I've spend more time on this as I really wanted and I'm very stubborn :p).

A: Soo, dedication will bring one to a solution. Although I initially thought that this can't be done, it's apparent that it actually can. I'll put the solution here, as maybe there are other people who find it useful.
First of all, WCF REST services are using webHttpBinding, which according to MS documentation does not support the Windows Identity Foundation and claims handling in the pipeline. Actually it does. Not in the WCF pipeline, but as the IIS module in web authentication flow.
First, you need to add the following modules to Web.config file.
<system.webServer>
    <modules runManagedModulesForAllRequests="true">
        <add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" preCondition="managedHandler" />
        <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" preCondition="managedHandler" />
    </modules>
 </system.webServer>

There's a caveat tho. You need still the <configSections> from my original posting. The problem is that you need, in VisualStudio, to mark the System.IdentyModel* assemblies as CopyLocal items (in the properties window). Otherwise you'll get some cryptic exception that assembly cannot be loaded for the configuration section. NB! It only happens if you are loading these two modules and doesn't happen when those modules are not getting loaded. Didn't have any will to investigate that thing further, perhaps someone knows better what's the cause there.
Next if for any reason you plan to use the SWT token handling sample from MS WIF code, there are a couple of bugs that need to be fixed, otherwise the token parsing just won't happen or you will get invalid signatures out of the token verification.
SimpleWebToken.cs you need to fix the SwtBaseTime as it is initialized incorrectly and the security token creation fails afterwards:
From
    public static DateTime SwtBaseTime = new DateTime( 1970, 1, 1, 0, 0, 0, 0 ); // per SWT psec
To
public static DateTime SwtBaseTime = new DateTime( 1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc ); // per SWT psec

SimpleWebTokenHandler.cs you need to fix the casing of the following values:
From
const string BinarySecurityToken = "binarySecurityToken";
const string ValueType = "valueType";

To
const string BinarySecurityToken = "BinarySecurityToken";
const string ValueType = "ValueType";

CustomIssuerTokenResolver.cs you need to fix the key that is created as it's initalized with a UTF8 bytes, but it should actually get initialized with decoded Base64 bytes:
From
key = new InMemorySymmetricSecurityKey(UTF8Encoding.UTF8.FromBase64String(base64Key));

To
key = new InMemorySymmetricSecurityKey(System.Convert.FromBase64String(base64Key));

After you've fixed all this, everything sits in place. The authenticators and authorizators are getting called and voilà, suddenly you have a WCF Service exposed as REST endpoint and all the claims etc. are also working.

A: I think your issue may be with the SWTTokenHandler in this sample: http://code.msdn.microsoft.com/vstudio/Custom-Token-ddce2f55
In CanReadToken(), it checks to see if the token is a BinarySecurityToken of type SWT:
if ( reader.IsStartElement( BinarySecurityToken )
&& ( reader.GetAttribute( ValueType ) == SimpleWebTokenConstants.ValueTypeUri ) )

But the constant BinarySecurityToken is defined as:
const string BinarySecurityToken = "binarySecurityToken";

Note the lower-case "b". XML elements are case sensitive, and the actual element is "BinarySecurityToken" with a capital B. This will cause the handler to return false in CanReadToken(), causing WIF to believe it doesn't have a handler registered for this token type.


text:
Q: Different used disk space with du and quota If I run quota I get:
Disk quotas for user XXXXXX (uid xxxx):
 Filesystem  blocks   quota   limit   grace   files   quota   limit   grace
   /dev/md2 1119132* 1048576 2097152    none       6       0       0
   /dev/md3 6816256       0 10485760            4529       0       0

The first is a temp directory and can be ignored. Home is on the second disk (md3). If I run du -sh inside my home directory I get:
3.3G    .
3.3G    total

I've run du without switches and the numbers all seem to coincide with what I should get (not listing for the sake of privacy).
So, why is quota showing ~6.8GB used while du is showing 3.3GB used? I am on a shared server and have a pretty small allowed storage space, of which about 33% seems to be missing!
I checked for "deleted" files that might be held open by a process:
lsof | grep "$USER" | grep deleted

Nothing. I ran a list of open files but nothing seemed out of the ordinary (though it might have been and I didn't realize it):
lsof | grep "$USER" > list.txt

I'm not sure of what else to try.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Without a solution this has become kind of moot as I got to a superuser and had them eliminate my quota and then reinstate it a day later. My quota now is showing LESS than du. So it might be worth investigating but I can live with the ability to use approx. 1 GB MORE space then my quota!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is Ham($S^2$) homeomorphic to SO(3)? Is it true that Ham($S^2$,\omega), the group of Hamiltonian diffeomorphisms of the sphere $S^2$ with its standard symplectic structure $\omega$, is homeomorphic to SO(3)?

A: The correct statement is:

Claim. The group $Ham(S^2)=Ham(S^2,\omega)$ of Hamiltonian diffeomorphisms of the $2$-sphere $S^2$ (endowed with the standard symplectic structure $\omega$) is homotopy equivalent to the group of rotations $SO(3)$.

Notice that, while $SO(3)$ is a finite-dimensional Lie group, the group $Ham(S^2)$ (i.e. the time-$1$ maps of Hamiltonian flows) is an infinite dimensional topological manifold with the $\mathcal{C}^\infty$ topology, i.e. that of "uniform convergence of all derivatives".
Probably you can reconstruct a complete proof of the above claim by looking at the details in the following references (which I just found online by a google search):

*

*In general, there are inclusions
$$Ham(M,\omega)\subseteq Symp_0(M,\omega)\subseteq Symp(M,\omega)\subseteq Diff^{+}(M)$$
with notations as in this short survey by Dusa McDuff.1 On page 2 it's stated that, if $H^1(M,\mathbb{R})=0$ (which is the case of $S^2$) then $Ham(M,\omega)=Symp_0(M,\omega)$.

*In the same survey, on page 3, it's stated that in dimension 2 "Moser's argument" implies that $Symp_0(M,\omega)$ is homotopy equivalent to $Diff^+(M)$.

*Theorem (Smale):  The group of orientation preserving diffeomorphisms of $S^2$ deformation-retracts onto $SO(3)$, so it's homotopy equivalent to the latter.
1McDuff, Dusa, A survey of the topological properties of symplectomorphism groups, Tillmann, Ulrike (ed.), Topology, geometry and quantum field theory. Proceedings of the 2002 Oxford symposium in honour of the 60th birthday of Graeme Segal, Oxford, UK, June 24–29, 2002. Cambridge: Cambridge University Press (ISBN 0-521-54049-6/pbk). London Mathematical Society Lecture Note Series 308, 173-193 (2004). arXiv:math/0404340, ZBL1102.57013, MR2079375.


text:
Q: Probability Question- rolling dice and the number "5" You are given with three dices, two normal and one fake.
The fake dice possess two "5" faces and no "4" faces.
You choose one dice out of the three and roll it twice.

*

*What is the probability that in the first two rolls, the dice will fall on "5"  ?

*If one knows that in the second roll the dice fell on "5", what is the probability that in the first roll the dice fell on a "4"?

*If one knows the chosen dice fell twice on "5", and then we choose one dice out of the other two and roll it. What is the probability the dice will fall on a "5"?
In question 1, my calculation was:
$\frac{2}{3} \frac{1}{6} \frac{1}{6} + \frac{1}{3} \frac{1}{3} \frac{1}{3} $ . The first term corresponds to choosing a normal dice and the second term corresponds to choosing a fake dice. The answer is $\frac{1}{18}$  (I think that the two consecutive rolls are independent, so I can just multiply the probabilities for intersection).
In question 2, my calculation was $\frac{2}{3} \frac{1}{6^2} = \frac{1}{54} $ .
My problem is with the third part of the question. How can I calculate this part using conditional probability ? The denominator should be $\frac{1}{18} $ , but when calculating the numerator I get a number bigger than $\frac{1}{18}$ . Will you please help me understand the calculation ?
Thanks in advance

A: The answer to your first question is correct.
For the second question you should use that for the probability of an event $A$ given the event B can be calculated by:
$$\mathbb{P}(A\ |\ B) = \frac{\mathbb{P}(A\cap B)}{\mathbb{P}(B)}.$$
If you now define $A:=$ "the first roll gives a 4" and $B:=$ "the second roll gives a five" you find your answer. If I'm correct this is $1/12$.
COMPUTATION:
$$\mathbb{P}(A\ |\ B) = \frac{\frac{2}{3}\frac{1}{6}\frac{1}{6}+\frac{1}{3}0\frac{1}{3}}{\frac{2}{3}\frac{1}{6}+\frac{1}{3}\frac{1}{3}}=\frac{1}{12}.$$
Similar for the third question, but now $A:=$ "the third roll gives a 5" and $B:=$ "the first two rolls give a 5". $\mathbb{P}(B)$ was already calculated in the first question.
COMPUTATION:
$$\mathbb{P}(A\ |\ B) = \frac{\frac{2}{3}\left(\frac{1}{6}\right)^2\left(\frac{1}{2}\frac{1}{6}+\frac{1}{2}\frac{1}{3}\right)+\frac{1}{3}\left(\frac{1}{3}\right)^2\left(1\cdot\frac{1}{6}\right)}{\frac{1}{18}} = \frac{7}{36}.$$
In the numerator de terms between brackets give the probability of choosing a third dice and rolling a 5, the squared numbers give the probability of throwing a 5 twice with the first dice and the remaining numbers give the probability of choosing the first dice.
Hope this is clear and the arithmetics are correct.

A: Im not so sure but maybe:

*

*a) The distributed probability for 2 consecutive 5 (choosing one dice between 3 where 2 are normal and 1 is fake) is $\frac{1}{6^2}\frac{2}{3}$ on normal dice and $\frac{1}{3^2}\frac{1}{3}$ on the fake dice, so you have $P_n=\frac{\frac{1}{6^2}\frac{2}{3}}{\frac{1}{6^2}\frac{2}{3}+\frac{1}{3^2}\frac{1}{3}}=\frac{1}{3}$ probability that the rolled dice was normal instead of fake and $P_f=1-P_n=\frac{2}{3}$ probability that the rolled dice was fake instead of normal
(where n is for "normal" and f is for "fake").

*b) If the rolled dice was the fake then the probability to take a 5 choosing one of the others dice is $P_p(5)=\frac{1}{6}$, because these two have the same probability on 5 (p is of "pure").

*c) If the rolled dice was a normal one then the probability to take a 5 choosing one of the others is $\frac{1}{6}\ or\ \frac{1}{3}\ i.e.\ P_m(5)=\frac{1}{3}\frac{1}{2}+\frac{1}{6}\frac{1}{2}=\frac{1}{4}$ (the m is for "mixed").

*d) Combining you knowledge from a) then the probability to take a 5 in the described circumstances is
$P(5)=P_p*P_f+P_m*P_n=\frac{1}{6}\frac{2}{3}+\frac{1}{4}\frac{1}{3}=\frac{7}{36}\approx 19.4\%$
I hope this maybe correct/useful for you.
EDIT: forget to distribute the probabilities of the first roll, now seems correct.


text:
Q: AlertDialog does not display when used with a button I would like to display an alert when my "save" button is pressed if the textview fields are left blank.  However, I can not get an AlertDialog box to appear within my save button.  The same code works for the AlertDialog if it is outside of the button.  Thanks in advance for any help you can provide.  I read several similar questions for none of the solutions are solving my problem.  My code is below:
public class MyActivity extends Activity{

...
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

...
Button saveButton = (Button) findViewById(R.id.data_save);

new AlertDialog.Builder(MyActivity.this)
        .setMessage("This is a test")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }})
         .show();

saveButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
                  builder.setMessage("This is a test 2 ")
                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {
                                 dialog.cancel();
                             }
                          })
                          .show();

        }
        );

A: This code works fine for me. If you are getting any sort of exception post it. Try Clean-ing the project and try again.


text:
Q: Boost Spirit: How to serialize qi::grammar and qi::rule objects? I'm using Boost library version 1.55.
1st Question
I have the following object myRule:
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

typedef qi::rule<std::string::iterator, qi::blank_type>     Rule;

Rule myRule %= qi::string("Hello world");

How can I serialize it as a string object?
2nd Question
I have the following object myGrammar:
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

typedef qi::rule<std::string::iterator, qi::blank_type>     Rule;
typedef qi::grammar<std::string::iterator, qi::blank_type>  Grammar;

class MyGrammar : Grammar
{
     // Constructor/Destructor
     MyGrammar()::base_type(myRule)
     {
         myRule %= qi::string("Hello world");
     }
     ~MyGrammar() { }

     // Attributes
     Rule myRule;
};

MyGrammar myGrammar;

How can I serialize it as a string object?


text:
Q: Store DataTables API Instance in Object On a webpage I have the following table:
<table id="table1" class="dynamicTable">
...
...
</table>

In a JavaScript file added to all of my pages I had the following:
$(".dynamicTable").DataTable({ ... });

which worked fine. Now, on each page I need to access the DataTables API (initializing DataTables and calling its API are done in different places). I thought it would be a good idea to store the API instance in a property of the table itself, so I changed to this:
$(".dynamicTable").each(function () {
    $(this).api = $(this).DataTable({ ... });
});

and tried to access it on my page with:
$("#table1").api.rows()....

but it doesn't work. I tried many other things such as (inside .each() function):
$(this).get(0).api = $(this).DataTable({ ... });

and:
var datatable = {};
datatable.api = $(this).DataTable({ ... });
$.extend($(this), datatable);

and so on. Please tell me, how I can store the API instance inside the table itself for future use.

A: You can do it using .data():
$(this).data("api",$(this).DataTable({ ... }));

Working Example


text:
Q: How To Use Go local package In terminal How can I link my local cmd go package on my computer? In npm we use npm link on the root of the package and a symlink will be created for the package to be used on the terminal how to do that with Go?

A: For example in macOS, your package is app, put your app folder in go/src/app cd in your app folder and type export GOPATH=$HOME/go enter, and export PATH=$PATH:$GOPATH/bin enter, then run your package. just type app and enter


text:
Q: Semantically 'correct' method of styling a label using the CSS :checked property Working on a form that has some custom radio button styling and wanted to check the way I normally do this.
To avoid Javascript, I typically have a radio input wrapped inside a label and a div following the input. I then style the div depending on the checked state.
This is some example markup:

label input:checked ~ span {
    background: red;
}
<label for="10000">
        <input type="radio" id="10000" name="coveramount" value="10000">
        <span>£10,000</span>
    </label>

(there's normally classes on the elements)
Is the span inside a label correct? Is there a better way of doing this with another tag or similar for accessibility?

A: The HTML in your question is fine.  This is a very simple and reliable way of styling radio and checkbox elements.
There are some potential accessibility issues to watch out for, more to do with the CSS than the HTML.
Will the <input> element itself be visible, in your design?  It's common to hide the actual radio/checkbox input, and use CSS background images to provide fancy-looking versions of the checked and unchecked states.  If you do this, remember to:

*

*Provide focus styles for sighted keyboard users, using something like label input:focus ~ span

*Avoid using display:none, visibility:hidden, or the HTML hidden attribute to hide the real radio/checkbox.  These will all prevent the input from being operable by keyboard-only users, and screen reader users (pointer users can click on the <label> element).  That's because they all cause the input to be removed from the keyboard tabbing order, and removed from the accessibility tree which is sent to assistive tech.  If you need to hide the real input element, use an approach like Bootstrap's .sr-only class or HTML5Boilerplate's .visuallyhidden class. For more detail about this, see:

*

*this real-world bug report for the Eleven  Drupal admin theme

*Short note on the accessibility of styled form controls, which includes code demonstrations of styling radios.

Another potential issue is with use of colour.  Don't rely on a change of colour alone to indicate a checked control, that's a WCAG failure.  Native radios and checkboxes involve a shape change (i.e. the bullet which fills the circle).  Be aware that CSS colours get overridden when a Windows High Contrast theme is in use.  If background: red is the only clue to a checked (or focused) radio option, Windows High-Contrast users won't know what's going on.

A: Refer : After Pseudo Element
Use ::after or ::before pseudo-elements, and adjust content accordingly.

label input:after {
  content: '10,000';
  font-size: 20px;
  height: 1em;
  position: relative;
  left: 20px;
}
label input:checked::after {
  background-color: red;
}
<label for="10000">
    <input type="radio" id="10000" name="coveramount" value="10000">
</label>

Update :

*

*Not a good and proper solution as using a pseudo element on an input element won't render anything in Firefox or Edge


text:
Q: Python type comparision Ok, so I have a list of tuples containing a three values (code, value, unit)
when I'm to use this I need to check if a value is an str, a list or a matrix. (or check if list and then check if list again)
My question is simply should I do like this, or is there some better way?
for code, value, unit in tuples:
    if isinstance(value, str):
        # Do for this item
    elif isinstance(value, collections.Iterable):
        # Do for each item
        for x in value:
             if isinstance(x, str):
                  # Do for this item
             elif isinstance(x, collections.Iterable):
                  # Do for each item
                  for x in value:
                      # ...
             else:
                  raise Exception
    else:
        raise Exception

A: The best solution is to avoid mixing types like this, but if you're stuck with it then what you've written is fine except I'd only check for the str instance. If it isn't a string or an iterable then you'll get a more appropriate exception anyway so no need to do it yourself.
for (code,value,unit) in tuples:
    if isinstance(value,str):
        #Do for this item
    else:
        #Do for each item
        for x in value:
             if isinstance(value,str):
                  #Do for this item
             else:
                  #Do for each item
                  for x in value:

A: This works but every time you call isinstance, you should ask yourself "can I add a method to value instead?" That would change the code into:
for (code,value,unit) in tuples:
    value.doSomething(code, unit)

For this to work, you'll have to wrap types like str and lists in helper types that implement doSomething()

A: An alternative to your approach is to factor out this code into a more general generator function (assuming Python 2.x):
def flatten(x):
    if isinstance(x, basestring):
        yield x
    else:
        for y in x:
            for z in flatten(y):
                yield y

(This also incorporates the simplifications suggested and explained in Duncan's answer.)
Now, your code becomes very simple and readable:
for code, value, unit in tuples:
    for v in flatten(value):
        # whatever

Factoring the code out also helps to deal with this data structure at several places in the code.

A: Just use the tuples and catch any exceptions. Don't look before you jump :)

A: Recursion will help.
def processvalue(value):
  if isinstance(value, list): # string is type Iterable (thanks @sven)
    for x in value:
      processvalue(value)
  else:
    # Do your processing of string or matrices or whatever.

# Test each the value in each tuple.
for (code, value, unit) in tuples:
  processvalue(value)

This is a neater way of dealing with nested structures, and will also give you the ability to process abitrary depths.


text:
Q: compiler returns: "'value' is defined but never used" when I used it I want to get in the api with function value and return USD instead of making a lot of functions without value I'm trying this code but compiler returns 'value' is defined but never used
any ideas?
  data(){
      return {
        posts: [],
      }
  },
  methods: {
    changeCurrency: function (value) {
      axios.get('http://data.fixer.io/api/latest?access_key=509c9d50c1e92a712be9c8f1f964cf67')
      .then(response => {
        this.currency = response.data.rates.value
      })
    },
  }

    <button @click="changeCurrency(USD)">
      USD
    </button>

A:   data(){
      return {
        posts: [],
      }
  },
  methods: {
    changeCurrency: function () { // removed unused variable "value" here
      axios.get('http://data.fixer.io/api/latest?access_key=xxxxxx')
      .then(response => {
        this.currency = response.data.rates.value
      })
    },
  }

A: The parameter value is passed to the changeCurrency function but it is never used in the function itself. Your Linter complains about it due to no-unused-vars rule.
  data(){
      return {
        posts: [],
      }
  },
  methods: {
    changeCurrency: function () { // <-- removed `value` from here. Should pass the linter
      axios.get('http://data.fixer.io/api/latest?access_key=xxxxxx')
      .then(response => {
        this.currency = response.data.rates.value
      })
    },
  }


text:
Q: How do I perform a function similar to Windows' Easy Transfer? You know how Windows has the thing where you can plug in a male-male cable into two computers, and then transfer stuff from one system to the other? Is there a way to do that in Linux?

A: In theory, using avahi you shoud get IP auto setup.
The relevant packages are:
avahi-autoipd
avahi-daemon
samba

After all of that is installed, you should be able to share a folder in the server computer and find it in the network browser in the client computer.


text:
Q: Apache-tomcat-8.5.29 overrides the content of the exploded folder? I am doing an upgrade from older version of tomcat to 8.5.29
I have a tomcat server with WAR file and exploded folder
tomcat8/webapps/xerox.war and tomcat8/webapps/xerox
The exploded folder contains patches that doesn't exist in the WAR
I would like tomcat to use only  the exploded folder and ignore the WAR file.
So in server.xml, on the Host section I set the unpackWARs to true, and autoDeploy to false,
It seems like its not working ok, and stuff in the exploded folder gets overridden / deleted after restart.
  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="false">

What am I doing wrong?

A: Tomcat creates a META-INF/war-tracker empty file in the unpacked WAR folder (tomcat8/webapps/xerox). If the modification time in milliseconds (cf. stat, since I assume you are under *nix) is exactly the same for both he WAR file and the tracker the directory is left alone. Otherwise Tomcat deletes the directory and unpacks the WAR file again.
The autoDeploy="false" setting does not influence this behavior, unless you also set deployOnStartup="false", in which case both the WAR file and the expanded directory will be ignored by Tomcat. This is not what you want.
You have two solutions:

*

*stop Tomcat and delete the WAR file,

*keep them both, but check if something (e.g. a backup system) is not modifying the timestamps of the WAR file and tracker file.

A: Using the first answer about war-tracker that I didn't know exist...
I ended up finding this method, it seems like its working fine
touch ./tomcat8_NEW/webapps/xerox/META-INF/war-tracker -r ./tomcat001_old/webapps/xerox.war

This creates a new  war-tracker file in the META-INF directory and clone the WAR timestamp
So tomcat thinks that there are no changes to the WAR and doesn't do anything to the exploded dir.
Thank you @Piotr P. Karwasz for your answer, I will accept it.


text:
Q: No alive nodes found in your cluster I'm using a centos 7 server where I've installed nginx, php, mysql, elsaticsearch and ceated a magento setup.
In the magento admin  > stores > Configuration > catalog > Catalog > Catalog Search I'm getting No alive nodes found in your cluster
Although the indexing is running properly and I can see it in Elasticsearch log.
Please let me know what I'm doing wrong over here.
Please have a look at the below given admin configuration.

When I'm calling from terminal this is what I'm getting

Below is the indexer result.

A: Did anyone have success fixing this error?
I have the same error, indexing via cli is working but the Storefront and Admin have the error "No alive nodes found in your cluster"
Update:
I resolved my error - issue was CentOS SELinux and permissions set to Enforcing.
Changing SELinux permissions to Permissive resolved the issue for me.
setenforce 0

Note: I faced the same issue where Indexing worked correct via command line, but not on front/back end admin. This has fixed my issue.. good luck.

A: Check the configuration
First let's check if your configuration is correct:
Update your host and port: '[host]:[port]'. E.g.: localhost:9200 in Stores > Settings > Configuration > Catalog > Catalog > Catalog Search or if you are you are using Elastic Suite in Stores > Configuration > ElasticSuit > Basic configuration as per your setting.
Update your indices alias name and indices name pattern in admin configuration same as above.
Clear cache by going to System > Cache Management or using this command (on your server in Magento installation folder):
php bin/magento cache:clean

Reindex by visiting System > Index Management or running command below:
Update catalog search
php bin/magento indexer:reindex catalogsearch_fulltext

Or reindex all indexers
php bin/magento indexer:reindex

Check Elasticsearch
If the error still stands, it might be the issue with the elasticsearch service on your server. To solve this follow the steps below:
Log into your Magento instance.
Check if the elasticsearch is running:
sudo /etc/init.d/elasticsearch status
Try to start it if it's not running, or restart it if it's running:
Start elasticsearch
sudo systemctl start elasticsearch

Or restart elasticsearch
sudo systemctl restart elasticsearch

You've found the issue if you encounter an error here and your elasticsearch doesn't start. Solve the issue first. Continue when the elasticsearch starts.
Navigate to your Magento installation folder
Reindex all indexers
php bin/magento indexer:reindex

Clear the cache
php bin/magento cache:flush

Your problem should have been solved by now.

A: If you are using Magento and getting 'No alive nodes found in your cluster' error while reindexing.
Make sure you have updated following :
Your Host and port : '[host]:[port]'. Eg: 'es-node1.fqdn:9200, es-node2.fqdn:9200' or 'localhost:9200' in Admin -> Store -> Configuration -> Catalog -> Catalog -> Catalog Search.
Update your indices alias name and indices name pattern in admin configuration same as above.
Try this, and clear cache and reindex. It will solve your issue.
If you are using Magento and getting 'No alive nodes found in your cluster' error while reindexing.
Make sure you have updated following :
Your Host and port : '[host]:[port]'. Eg: 'es-node1.fqdn:9200, es-node2.fqdn:9200' or 'localhost:9200' in Admin -> Store -> Configuration -> Catalog -> Catalog -> Catalog Search.
Update your indices alias name and indices name pattern in admin configuration same as above.
Try this, and clear cache and reindex. It will solve your issue.

A: Please check if you are closing the Elasticsearch cmd panel. Don't close that window. So that Elasticsearch will be on otherwise it will disable.
After that run these commands:
php bin/magento setup:upgrade
php bin/magento setup:di:compile


text:
Q: Error al intentar acceder a una lista anidada Tengo un problema al intentar acceder a los elementos de una lista anidada.
Tengo estos datos de entrada:
string = list("Wizard")
string2 = list("Magical")
lista = [string, string2]

Y tengo este código:
for a in range(0, len(lista)):
    for b in range(0, len(lista[a])):
        if b % 2 == 0:
            print(lista[a[b]])

Como pueden ver, mi idea es imprimir los caracteres de lista[a[b]] siguiendo la siguiente condición: Si el índice de lista[a[b]] es par, imprima el contenido de lista[a[b]]. Sin embargo, me este error: TypeError: 'int' object is not subscriptable.. ¿Cuál es el problema?

A: Ejecutando el codigo veo que el error que te aparece es una excepción TypeError: 'int' object is not subscriptable.
El problema que tienes en el codigo es que estás intentando indexar a[b] siendo que a corresponde a un int del iterador range. La sintaxis correcta para indexar una lista de listas sería, en este caso, lista[a][b]. Por lo tanto, la solución correcta debería ser:
for a in range(0, len(lista)):
    for b in range(0, len(lista[a])):
        if b % 2 == 0:
            print(lista[a][b])


text:
Q: Why can't you square both sides of an equation? Why can't you square both sides of an equation?
I've been asked this many times and can never quite give a good, clear, concise answer (for beginning algebra students) in plain language. I just searched the web and still couldn't find a simple-to-understand answer for why squaring both sides gives you extraneous solutions.

A: If two things are equal, then so long as you do the same thing to both, they will remain equal. There is nothing wrong with taking the square of both sides of an equation. However, you have to be careful if you want to take the square root of both sides, because the square root is not a normal function: it has two values $\pm \sqrt x$. By convention, the positive square root is chosen, and that is what people mean when they say "the square root". But equations don't care about our conventions. The fact that $(-1)^2 = 1^2$ certainly doesn't imply that $-1 = 1$.
In other words, if $x^2 = y^2$, then taking the square root (using the stated convention) of both sides results in $|x| = |y|$, not in $x=y$.
For these reasons, if you have an equation containing an unknown, then squaring both sides of it can introduce new solutions, so you have to be careful. For instance, the equation $x=1$ obviously has only one solution (namely $x=1$!) but squaring both sides of it yields the equation $x^2=1$ which has the two solutions $x=\pm 1$.

A: When you "solve" an equation, all you are doing is finding an expression that is equivalent to the original equation. By "equivalent", I mean that one is true if and only if the other is true. For example. $x - 5 = 2$ and $x = 7$ are equivalent, but $x - 5 = 2$ and $x > 0$ are not.
For any expressions $a$ and $b$, and function $f$, we know that $a = b \implies f(a) = f(b)$, because functions have one output for each input. But this might not go the other way. Some examples where $f(a) = f(b)$ does not imply $a = b$:

*

*$f(x) = \sin{x}, \ \sin{0} = \sin{2 \pi}$

*$f(x) = 0x, \ 0 \cdot 5 = 0 \cdot 11$

*$f(x) = x^2, \ 1^2 = (-1)^2$

So if we apply these functions to both sides of an equation, we don't get something equivalent to the original, and extraneous solutions show up.
When do we get something equivalent? Our functions have to be injective, so that there exists a right-inverse. Then we have:
$$ f(a) = f(b) \implies f^{-1}(f(a)) = f^{-1}(f(b)) \implies a = b$$
so we have both directions of implication, and therefore equivalent statements. That's why we don't have to worry about making extra solutions when we add, subtract, multiply (except by zero), or divide, because these functions are injective.
In particular, squaring isn't injective. So you can go from $a = b$ to $a^2 = b^2$, but you can't go backwards, so it's not equivalent.

A: The short answer is that when you square something, you lose the sign that it started with.
The long answer (is actually the same as the short answer). This is almost word-for-word the explanation that I now use in class (if a student asks -- otherwise I just tell them to follow the directions):
Suppose you wanted to solve the equation $x=-2$. Nevermind for now that it is its own solution (that is, $x$ equals $-2$ is the solution).
Start by squaring both sides to get $x^2=4$.
Bu now you know how to solve this. We take the square root of both sides (don't forget the plus-or-minus symbol)
$$\sqrt{x^2} = \pm \sqrt{4} \\
x = -2 \text{ or } 2$$
We get two answers, one of which is clearly wrong (it is called extraneous). When we squared, we lost the sign information.
My Original Answer (this example is not as clear to students): Suppose you wanted to solve (call this Example 1 -- and never mind that it is its own solution) $$\sqrt x = -3.$$
You start by squaring both sides. You get $$x = 9.$$
Now, that $9$ on the right side might have come from $3^2$, or it might have come from $(-3)^2$. The equation no longer indicates what it came from. Note that $x=9$ does not solve the original equation (that is, $\sqrt 9 = 3 \ne -3$).
Now say you were want to solve the equation (Example 2) $$\sqrt x = 3.$$
Once again, you start by squaring both sides, and you get $$x = 9.$$
Notice that the step after squaring is the same for both examples. That's because the $9$ on the right hand side could have come from squaring a $3$ or from squaring a $-3$.
So, when you square both sides of an equation, you can get extraneous answers because you are losing the negative sign. That is, you don't know which one of the two square roots of the right hand side was there before you squared it.

A: Start with a false proposition
e.g.: $-2 = +2$
square both sides
$(-2)^2 = (+2)^2$
and it becomes true (!?)
$+4 = +4$
So the operation turns (some) false statements into true statements.

A: I've had to teach this to beginning algebra students (in the context of adult ed), so I thought I would put my two cents in.
When you square an equation the result doesn't remember what the signs of the numbers were before hand. A squared equation is really two equations put into one, the original equation you wanted to solve and a "buddy" equation that has an extra negative sign. The extraneous solutions are  solutions of the corresponding buddy equation.
At this point I generally provide a specific example writing down an equation and its buddy (which has an extra negative sign) one above the other and then draw arrows going from both to the common squared equation.
Sometimes I either lead or wrap up the discussion by talking about different arithmetic operations they have learned and point out that if you know a number was obtained by performing addition, multiplication, division, etc. you can always tell me the original number by reversing the process but when we square a number we have no way of knowing the original sign by looking at the result. Often it is helpful to draw diagrams showing the flow of the arithmetic and make them reverse some aritmetic.
For instance you could say that we got 15 when we multiplied a number by 2 and added 1. Then (not emphasizing symbolic algebra but just the arithmatic) the student should be able to reverse the process by subtracting 1 (which gives 14) and dividing by 2 (which gives 7) obtaining the original number.
If your course is anything like mine their first instinct may be to convert the above inversion process into an equation ("rewrite the sentence as an algebraic equation and solve for the unknown"). I think it is very important to not let them do this, more likely than not they'll get caught up in trying to "solve for x" and probably forget why we are doing this in the first place. The point of the exercise is to teach them the ideas of invertible and non-invertible operations not to see if they can shuffle letters around on a page.
This should be wrapped up by giving a similar problem but now involving a non-invertible operation. For instance, 25 was obtained by squaring a number. What was the number? They should be able to recognize that this question is flawed because there are two numbers which square to 25.

A: Others have addressed why new solutions are introduced so I won't repeat that.  But I do want to constructively comment on a more fundamental source for this issue.
$$x + y = c \tag{Step 1}$$
$$(x + y)^2 = c^2 \tag{Step 2}$$
This isn't necessarily a problem, as long as the student understands that you can't assume $\text{Step 1} \iff \text{Step 2}$. It should be $\text{Step 1} \rightarrow \text{Step 2}$.
$\text{Step 1} \leftarrow \text{Step 2}$ can lose solutions to a problem.
$\text{Step 1} \iff \text{Step 2}$ keeps the same solutions to a problem.
$\text{Step 1} \rightarrow \text{Step 2}$ can introduce new values which are not solutions to the original problem.

By the way, I strongly discourage the terminology "can do to an equation".  It reeks of students just trying to figure out what they have to do to make the teacher happy.  A teacher especially should be very careful to avoid that phrase and use more appropriate phrases:
"Presents an equation that is exactly as true as the last one." ($\iff$ case)
"Has the same solutions." ($\iff$ case)
"Has the same solutions, maybe with some extra." ($\rightarrow$ case)
"Implies that the next equation must be true." ($\rightarrow$ case)
"Is true if the next equation is true." ($\leftarrow$ case)
"Is also true (if the first equation was)." ($\rightarrow$ case)
"Makes an equivalent equation." ($\iff$ case)
"Makes a logically equivalent equation." ($\iff$ case)
If I was instructing students in algebra, I'd require them to write arrows between their steps from early on.

A: You can.
However, you must be careful that you could have introduced extraneous solutions. Hence, you have to check that your solutions of the squared equation do actually satisfy the original equation.
Case in point: Solve $x -1 = 1$.
If we square both sides, we get $x^2 - 2x + 1 = 1^2$, or that $0 = x^2 - 2x = x(x-2)$. This has solutions $x=0, 2$. We then have to check back if they satisfy the original equation.

A: Actually you can, but you cannot assume that if $x^2 = y^2$ then $x=y$
Thus we lose the definitive sign after squaring both sides, we might get more result answers for $x$,$y$ that satisfies $x^2 = y^2$ then $x = y$

A: The fundamental problem is that when novice students (and even some non-novices ones) manipulate equations, they get the false impression that anything implied by their original expression will also imply their original expression.
To take an intentionally absurd example (absurd because we actually have the solution written down to start with), they reason like this:
$$x = 1$$
"square both sides"
$$x^2 = 1^2 = 1$$
The solutions of this are $1$ and $-1$ (true) and therefore (invalid deduction) the solutions of the original equation are $1$ and $-1$ (false conclusion).
If they were more careful they would write:
$x = 1 \implies x^2 = 1 \implies (x = 1) \vee (x = -1)$
So we know that nothing other than $1$ and $-1$ can be solutions, but we still don't know which (if any) is really a solution.
It's entirely analogous to reasoning:
$$x < 1$$
therefore since $1 < 3$ and $<$ is transitive:
$$x < 3$$
Now, $2 < 3$ therefore (invalid deduction) $2$ is a solution to the original inequality (false conclusion). And this is indeed a mistake people sometimes make when solving inequalities.
Or consider:
$$x^2 = -1$$
therefore
$$x^4 = 1$$
Now, in the integers or real numbers this also implies $x = 1 \vee x = -1$. But actually there are no solutions for $x^2 = -1$ in the real numbers. We can (in standard logic) actually deduce anything we like from $x \in \mathbb{R} \wedge x^2 = -1$, because it's false. One-way implications do not necessarily lead to solutions.
The problem stems from being taught various mechanisms for manipulating (in)equalities, but losing track of what these manipulations actually mean in terms of correct deductions about the values involved. If the operation applied to both sides is an injection then of course it's reversible and so we have two-way implication, and in that case the deduction would be valid.
In short: you can square both sides, of course. This tells you a true fact about $x$, but not everything true of $x$ in the squared equation is necessarily true of $x$ in the original. In this case $x = 1 \Rightarrow x \in \{1, -1\}$ but  $x \in \{1, -1\} \not \Rightarrow x = 1$

A: Essentially the problem comes from the fact the squaring function is not an injective function (also known as one-to-one). A common way to observe whether a function is injective (especially in an elementary algebra class) is to look at the the graph of the function and use the horizontal line test (which is only useful in certain contexts).
One thing that might add clarity is to notice the "problems" that occur with squaring (adding extra solutions) is not unique to squaring, so it is not special, it just points to some larger principle. For example "cos" both sides, or multiplying both sides by zero both lead to the same problem, in fact unlike squaring both of the examples given can add infinitely many solutions, not just one. $x=1$ has one solutions, but $0 \cdot x = 0 \cdot 1$ has every number as a solution.

A: You start with $$a=b$$
When you square both sides, you get
$$a^2 = b^2 \Leftrightarrow a^2 - b^2 = 0 \Leftrightarrow (a-b)(a+b) = 0 \Leftrightarrow a = b \; \text{    or    } \; a = -b$$
The $a = -b$ part is where the extraneous solutions come from.

A: There's nothing wrong with squaring both sides of an equation, as long as you check that the solutions work. You're only going to gain extra solutions, you definitely won't lose any.

A: If you say $x=-2 \implies x^2=4 \implies x=2 \text{ or } x=-2$ you have not made an error as it is true in general that $P \implies P \lor Q$.
The error would be says that $2$ was a solution to $x=-2$, which would require you to reverse the implications.  In particular $x=-2 \not \Leftarrow x^2=4$.
This is why you need to check your solutions in the original expression.

A: The simples answer based on an e.g is probably  this.
what is $2 * 2$ its $2^2$ its $4$
what is $-2 * -2$ its $(-2)^2$ its also $4$
so you see why you just can't square $4$ without taking in advise that it may be $2$ or $-2$
so if you take care of $± $ you can say: $x = ±y \Leftrightarrow x^2 \Leftrightarrow y^2$


text:
Q: Calculating the value of $\frac {1}{D^2+a^2} \sin ax$ where the operator $D = \frac {d}{dx}$. Error in Method $1$? Calculating the value of $\dfrac {1}{D^2+a^2} \sin ax$ where the operator $D = \dfrac {d}{dx}$
I have tried calculating using two different methods and both of them yield different results. Could someone please pinpoint any error in Method $1$ which I might be making. My textbook uses method $2$. Thanks a lot for your help
$1$**">
$2$**">

A: These solutions are equivalent. Their difference is a solution of the homogeneous equation, so both are suitable particular solutions. None of them are special in the sense that both value and first derivative at zero are zero.


text:
Q: Nodemailer status code 500 using createTestAccount() I'm using default code from Nodemailer page (console added by me):
nodemailer.createTestAccount((err, account) => {
    console.log(err);
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
            user: account.user, // generated ethereal user
            pass: account.pass  // generated ethereal password
        }
    });
});

It returns me the following error:
Error: Invalid status code 500
    at ClientRequest.<anonymous> (/Users/angelodias/GIT/bootcamp/04-iniciando-back-end/node_modules/nodemailer/lib/fetch/index.js:221:23)
    at ClientRequest.emit (events.js:223:5)
    at ClientRequest.EventEmitter.emit (domain.js:475:20)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
    at TLSSocket.socketOnData (_http_client.js:456:22)
    at TLSSocket.emit (events.js:223:5)
    at TLSSocket.EventEmitter.emit (domain.js:475:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:290:11) {
  type: 'FETCH',
  sourceUrl: 'https://api.nodemailer.com/user'
}

What am I doing wrong? Is there any bug?
I tried with .then().catch() and it catches the same error.
Running Node v12.14.1 and Nodemailer 6.4.6


text:
Q: DataTables won't work in a modal I have a table, where on row click a modal window is opened. Thanks to this:
th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'"

openPoolModal.js looks like:
function openPoolModal(id){

$.ajax({
    url: "/" + id,
    success: function(data){
    $("#PoolModalHolder").html(data);
    $("#personalModal").modal();
    $("#personalModal").modal('show');
}
});
}

PoolModalHolder is just an empty div on my main.html file, where the first table is rendered. personalModal is a fragment of code that opens on a modal dialog.
A modal dialog is then filled with personalModal:

            <button type="button" class="close" data-dismiss="modal">×</button>

Network Id

                        Pool name
                        Date from
                        Hashrate

                         Sample data
                        Maven Street 10, Glasgow
                        999-999-999

I can't get the DataTables to work on the table inside personalModal window.
The standard DataTables initialization doesn't work and that is:
$(document).ready( function () {
$('#poolTable').DataTable();
} );

I have also tried this, but with same result:
$( "#personalModal" ).focus(function() {
$('#poolTable').DataTable();
});

I have header links added and those are: jQuery, Bootstrap, DataTables.js.
I have also tried with table-responsive example, but again, doesn't work. Data is generated correctly through Spring controller method. I just need to apply sorting & pagination to the table.


text:
Q: Customizing WPF DataGrid I am new to C# WPF, and customizing DataGrid in C# WPF, I have created subclass a below :-
namespace DataGridFiltter
    public class FilteringDataGrid : Microsoft.Windows.Controls.DataGrid
    {
    .......
    }
}

and in xaml file i am using this class as below :-
<UserControl x:Class="formGroup"
 xmlns:dataGridFiltter="clr-namespace:DataGridFiltter">

<dataGridFiltter:FilteringDataGrid  IsFilteringCaseSensitive="False" x:Name="groupTable"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" FontSize="16" AutoGenerateColumns="False" ItemsSource="{Binding DataCollection, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" SelectionChanged="groupTable_SelectionChanged" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Grid.IsSharedSizeScope="True" AlternatingRowBackground="#FFD6D1D1" CanUserAddRows="false" CanUserDeleteRows="False" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserResizeRows="False" IsReadOnly="True" Margin="0,0,-8,0"  >
                <DataGrid.ItemBindingGroup>
                    <BindingGroup/>
                </DataGrid.ItemBindingGroup>
                <DataGrid.Columns>
                    <DataGridTextColumn Header="RecordNumber" Width="100" Visibility="Hidden" />
                    <DataGridTextColumn Header="NAME" Width="200" Binding="{Binding GroupName}" />
                    <DataGridTextColumn Header="Group Name" Width="144" Binding="{Binding ParentGroupName}" />
                    <DataGridTextColumn Header="Creation Time" Width="200" Binding="{Binding CreationTime}" />
                    <DataGridTextColumn Header="Modification Time" Width="200" Binding="{Binding ModificationTIME}" />
                    <DataGridTextColumn Header="User" Width="100" Binding="{Binding PeopleName}" />

                </DataGrid.Columns>

            </dataGridFiltter:FilteringDataGrid>

As i have used style as below :-
<ResourceDictionary
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"
   xmlns:dataGridFiltter="clr-namespace:DataGridFiltter">

    <dataGridFiltter:HeaderFilterConverter x:Key="headerConverter"/>

    <Style TargetType="{x:Type my:DataGridColumnHeader}">
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type my:DataGridColumnHeader}">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="ShowFilterControl">
                            <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterTextBox" Storyboard.TargetProperty="(UIElement.Visibility)">
                                <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Visibility.Visible}"/>
                                <DiscreteObjectKeyFrame KeyTime="00:00:00.5000000" Value="{x:Static Visibility.Visible}"/>
                            </ObjectAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterTextBox" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                                <SplineColorKeyFrame KeyTime="00:00:00" Value="Transparent"/>
                                <SplineColorKeyFrame KeyTime="00:00:00.5000000" Value="White"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        <Storyboard x:Key="HideFilterControl">
                            <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterTextBox" Storyboard.TargetProperty="(UIElement.Visibility)">
                                <DiscreteObjectKeyFrame KeyTime="00:00:00.4000000" Value="{x:Static Visibility.Collapsed}"/>
                            </ObjectAnimationUsingKeyFrames>
                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterTextBox" Storyboard.TargetProperty="(UIElement.OpacityMask).(SolidColorBrush.Color)">
                                <SplineColorKeyFrame KeyTime="00:00:00" Value="Black"/>
                                <SplineColorKeyFrame KeyTime="00:00:00.4000000" Value="#00000000"/>
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <my:DataGridHeaderBorder x:Name="dataGridHeaderBorder" Margin="0" VerticalAlignment="Top" Height="61" IsClickable="{TemplateBinding CanUserSort}" IsHovered="{TemplateBinding IsMouseOver}"  IsPressed="{TemplateBinding IsPressed}" SeparatorBrush="{TemplateBinding SeparatorBrush}" SeparatorVisibility="{TemplateBinding SeparatorVisibility}" SortDirection="{TemplateBinding SortDirection}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.ColumnSpan="1">
                        <Grid>
                              <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                <RowDefinition Height="*" />
                            </Grid.RowDefinitions>
                            <Grid x:Name="grid" Width="Auto" Grid.Row="0" Height="Auto" RenderTransformOrigin="0.5,0.5">
                                <Grid.RenderTransform>
                                    <TransformGroup>
                                        <ScaleTransform/>
                                        <SkewTransform/>
                                        <RotateTransform/>
                                        <TranslateTransform/>
                                    </TransformGroup>
                                </Grid.RenderTransform>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                             <!--   <Grid.RowDefinitions>
                                    <RowDefinition Height="10" />
                                <RowDefinition Height="10" />
                            </Grid.RowDefinitions> -->
                                <ContentPresenter x:Name="contentPresenter"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                    ContentStringFormat="{TemplateBinding ContentStringFormat}"
                                    ContentTemplate="{TemplateBinding ContentTemplate}">
                                <ContentPresenter.Content>
                                        <MultiBinding Converter="{StaticResource headerConverter}">
                                            <MultiBinding.Bindings>
                                                <Binding ElementName="filterTextBox" Path="Text" />
                                                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Content" />
                                            </MultiBinding.Bindings>
                                        </MultiBinding>
                                </ContentPresenter.Content>
                            </ContentPresenter>
                            </Grid>
                            <Grid Grid.Row="1">
                                <TextBox x:Name="filterTextBox" HorizontalAlignment="Right" MinWidth="25" Height="Auto" OpacityMask="Black" Visibility="Visible" Text="" TextWrapping="Wrap"  Grid.ColumnSpan="1"/>

                            </Grid>
                        </Grid>
                    </my:DataGridHeaderBorder>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                        <!--    <Trigger.EnterActions>
                                <BeginStoryboard x:Name="ShowFilterControl_BeginStoryboard" Storyboard="{StaticResource ShowFilterControl}"/>
                                <StopStoryboard BeginStoryboardName="HideFilterControl_BeginShowFilterControl"/>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <BeginStoryboard x:Name="HideFilterControl_BeginShowFilterControl" Storyboard="{StaticResource HideFilterControl}"/>
                                <StopStoryboard BeginStoryboardName="ShowFilterControl_BeginStoryboard"/>
                            </Trigger.ExitActions> -->
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

I am getting compile time error  (Error :- Event Expected ) for DataGrid.ItemBindingGroup ,DataGrid.Columns and DataGridTextColumn
Can someone please help me what is the right way use above tags as i have created subclass of DataGrid.


text:
Q: Durandal and Knockout: do a css binding to body element I am trying to make the body element of a Durandal app (a SPA framework which employs Knockout) by checking a module's state (which account type users are logged in as). In the viewmodel of the app's shell, I have the following code:
function bindingComplete() {
  viewhelper.accountVisualTreatment();
}

And accountVisualTreatment is defined in the viewhelper module as such:
if (typeof(appsecurity.userInfo()) == 'undefined') {
  $("body").addClass("notloggedin");
  $(".container").addClass("notloggedin");
} else {
  if (appsecurity.isUserInRole(['Account Manager']) && !appsecurity.isUserInRole(['Administrator'])) {
    $("body").addClass("accountmanager");
    $("nav").addClass("hidden");
  } else {
    $("body").removeClass();
    $(".container").removeClass("notloggedin");
    $("nav").removeClass("hidden");
  }
}

Everything works fine if I refresh the pages when logged in as the diff account types. But as a SPA framework, there's no page refreshes while being used. Hence, the classes are not being applied as I want it to. How do I make it so the body, container, and nav elements' classes are being bound as I want?
Edit: I have tried to call viewhelper.accountVisualTreatment() in viewmodels of the landing page of the different account types but to not avail. Still needs page refresh.
Edit: I ugly-ly fixed it by applying a css binding to the container div in my shell.html
<div class="container" data-bind="css: viewhelper.accountVisualTreatment()"> ... </div>

A: Because you want to do this in the body (so globally). So my assumption is you want to update the css classes as soon the accountinfo changes. You could create a singleton observable with the accountinfo. When it changes you just subscribe to the observable.
The only problem is with elements which aren't in the dom. (like between loading pages). Because you use Durandal you have different hooks to change the dom with jQuery.
To do this in the viewmodels you should use attached() or compositionComplete() see: http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks.html. This is the callback you get from durandal when the dom is completly attached to the viewmodel and all the observables.
I would say you don't want to do this in every viewmodel. So I would suggest to hook on the router:navigation:composition-complete event on the router, see: http://durandaljs.com/documentation/api.html#class/Router/event/router:navigation:composition-complete. This will make sure you will get the callback for every new hash navigation.
You can register to the global event in the data-main where the app is started:
app.on('router:navigation:composition-complete').then(viewhelper.accountVisualTreatment());

I hope this helped.


text:
Q: How to require/read the JSON files from aws-sdk apis folder I am trying to fetch all the instance types for EC2 from EC2 SDK JSON
const instanceEnums = require('aws-sdk/apis/ec2-2016-11-15.normal.json');

function getAllTypes(property) {
   return instanceEnums.shapes[property].enum;
}
getAllTypes('InstanceType')

But It throws an error that

cannot find module aws-sdk/apis/ec2-2016-11-15.normal.json

I realized that the installed SDK/module does not include the .normal.json file but only .min.js file.
Is there any other way to access the files from apis folder same as we can access clients folder just by requiring SDK and AWS.EC2 and all(as sdk exports the clients folder's files from index.js.)
I need to use something like explained as in this answer https://stackoverflow.com/a/42494509/9381809

A: You can download ec2-2016-11-15.normal.json directly from github (on the application startup for example) and use it like as follows:
const axios = require('axios');

const url = 'https://raw.githubusercontent.com/aws/aws-sdk-js/master/apis/ec2-2016-11-15.normal.json';

const getAllTypes = (() => {
  const loadApi = axios.get(url);
  return (property) => loadApi.then(response => {
    return response.data.shapes[property].enum
  })
})();

getAllTypes('InstanceType').then((types) => {
  console.log(types);
});

A: The code below works for me.
const instanceEnums = require('aws-sdk/apis/ec2-2016-11-15.min.json');
console.log(instanceEnums.shapes);


text:
Q: how to prevent division by 0 in this case? How can i prevent divison by 0 in this case?
round(
(sum(case when e.nome = 'ERRO' then 1 else 0 end) / sum(case when e.nome = 'SUCESSO' then 1 else 0 end))*100,2) as porcent_error

i tried this way but don't work

A: The simplest method is to leave out the else in the denominator:
round( sum(case when e.nome = 'ERRO' then 1 else 0 end) * 100 /
       sum(case when e.nome = 'SUCESSO' then 1 end)), 2
      ) as porcent_error

That way, if nothing matches, it returns NULL rather than 0 -- and the division is safe.


text:
Q: Matplotlib, Google Fonts: how to use fonts in vscode jupyter notebook I've searched for a while, trying to use Chinese font in my matplotlib histogram. Instead of installing the font locally, I tried to follow the post to use the raw TTF file from Github. However, I got In FT2Font: Can not load face.  Unknown file format. message. Here is my code:
from tempfile import NamedTemporaryFile
import urllib3
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

https = urllib3.PoolManager()
github_url = 'https://github.com/google/fonts/tree/main/ofl/notosanssc/NotoSansSC[wght].ttf'

url = github_url + '?raw=true' # will trigger the download

response = https.request('GET', url)
# print(response.data) # to confirm the successful response with data
f = NamedTemporaryFile(delete=False, suffix='.ttf')
f.write(response.data)
f.close()
f.name # C:\\Users\\<username>\\AppData\\Local\\Temp\\tmp9i1czwm1.ttf'

fig, ax = plt.subplots()
ax.plot([1, 2, 3])

prop = fm.FontProperties(fname=f.name)
ax.set_title('this is a special font:\n%s' % github_url, fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

Reinstalling matplotlib and removing cache gave me no luck. What could be the issue? Thanks.

A: I've figured it out using another way instead of Github Google font. There's also a post regarding using Chinese font with Mac. However, I am using Windows 10, which cannot replicate Mac's solution.
On Windows 10 (or 11), open Settings, Personalization, then fonts. Here you can confirm the installed fonts and available Chinese fonts. Next, go to matplotlib font cache, which could be C:\Users\<username>\.matplotlib. There's a file called fontlist-<version>.json, storing available fonts.
The format is:
{
  "_version": 330,
  "_FontManager__default_weight": "normal",
  "default_size": null,
  "defaultFamily": {
    "ttf": "DejaVu Sans",
    "afm": "Helvetica"
  },
  ttflist: [
    {
      "fname": "C:\\Windows\\Fonts\\FRABKIT.TTF",
      "name": "Franklin Gothic Book",
      "style": "italic",
      "variant": "normal",
      "weight": 400,
      "stretch": "normal",
      "size": "scalable",
      "__class__": "FontEntry"
    },
    "__class__": "FontManager"
  ]
}

Finally, you can set the font family with the name field. Below is the snippet:
fig, ax = plt.subplots()

fontP = matplotlib.font_manager.FontProperties()
fontP.set_family('DFKai-SB')

ax.set_title('職缺頻率計算', fontproperties=fontP)
plt.show()


text:
Q: Как убрать ограничение на загрузку больших файлов на сервер ASP.NET MVC? У меня загружаются на сервер только маленькие файлы.
Где можно убрать это ограничение?
Я ставил в web.config, но, даже, если ставлю большие цифры- файлы,скажем 100-200 метров на закачиваются.
Делал, как здесь
<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" maxRequestLength="2147483647" executionTimeout="1600" requestLengthDiskThreshold="2147483647" />
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647" />
      </requestFiltering>
    </security>
    ...
</system.web>

Хотя, причина, возможно, в клиенте...
Я не браузером отправляю, а программой с WebClient. Может здесь как-то надо прописать на больший объём?
    dynamic dyn = JObject.Parse(Params.Data);
    dynamic dat = new JObject();

    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    using (var fileStream = File.OpenRead(dyn.FullPath.ToString()))
    {
       HttpContent fileStreamContent = new StreamContent(fileStream);
       var filename = Path.GetFileName(dyn.FullPath.ToString());
       formData.Add(fileStreamContent, "upload", filename);// загрузка
       var response = client.PostAsync("http://localhost:2613/siteapi/postfile?code="+ dyn.Code.ToString(), formData).Result; //Отправка
   }

A: В ответе по ссылке - ошибка (и об этом сказано в комметариях)
httpRuntime и security должны лежать в разных секциях - system.web и system.webServer соответственно:
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5"
            maxRequestLength="2147483647"
            executionTimeout="1600"
            requestLengthDiskThreshold="2147483647" />
    </system.web>
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="2147483647" />
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

И еще - maxRequestLength указывается в килобайтах; maxAllowedContentLength и requestLengthDiskThreshold - в байтах, так что подгоните под одинаковые значения. requestLengthDiskThreshold при этом не обязательно задирать до maxAllowedContentLength.
И вообще - стоит выставить лимиты на основе реально необходимых значений, а не просто "все по 2 гига" :)


text:
Q: How to get matrix elements based on names and indexes As a result of an apply function to matrix (df) columns, I get a list or dataframe "m" with the indexes that match the criteria of my function. How do I get the actual elements based on that?
So for a matrix (df) like this:
      col1     col2     col3
[1,]  match1  no        match5
[2,]  no      match3    no
[3,]  no      match4    no
[4,]  match2  no        match6

I get this result "m" from the apply function using grep for the word "match":
      col1 col2 col3
[1,]    1    2    1
[2,]    4    3    4

I ended up getting the right results by changing "value=TRUE" when using grep in the original apply function that returns "m".
However, if I used df[m] it returned all results based on col1 from df. So I am still wondering how to get the actual elements of "df" based on "m" results.
Thank you!


text:
Q: How to develop a metro template using bootstrap framework I would like to develop a metro template using Bootstrap framework. I cant get any proper reference link or tutorial. I hope its possible to design a metro template using bootstrap framework.if so send me some reference link.

A: You can try these links.
http://metroui.org.ua/
http://bootswatch.com/ and go Cosmo or Yeti themes
http://aozora.github.io/bootmetro/
http://talkslab.com/metro-bootstrap/index.html
http://www.jquery4u.com/bootstraps/metro-bootstraps/

A: there are many templates using bootstrap with the metro style.
https://wrapbootstrap.com/theme/metro-mania-no.1-metro-bootstrap-theme-WB07F9G8L
take a look this link: http://www.jquery4u.com/bootstraps/metro-bootstraps/

A: Metro UI Bootstrap Based. It's better to reuse the stuff, rather than building a new one.
Click Here


text:
Q: Spring restTemplate .postForObject() mapping cannot access element Im trying to use the restTemplate.postForObject(URL, Session.class) method and map the response to a POJO. This works partially, however when i try to access an element with a name like "name-with-dashes" I cannot find the element.
The JSON I am extracting from the method call:
{"age":60,"expire":12345,"name-with-dashes":"This name has dashes?!"...}

Here is the POJO im using to extract this data:
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class Session {
        private int age;
        private long expire;
        //will not grab name-with-dashes... returns null
        private String nameWithDashes;
}

A: You should annotate your fields, especially the ones that do not comply to bean naming conventions, with the @JsonProperty annotation as follows:
@JsonProperty("name-with-dashes")
private String nameWithDashes;

A: You can annotate the property
@SerializedName("name-with-dashes")
private String nameWithDashes;

using Gson


text:
Q: Automapper complex mapping How can I map the following:
public abstract class PersonBase
{
   public Address Address { get; set; }
}

public class Address
{
  public string AddressHome { get; set; }
  public int PostalNumber { get; set; }
}

public class PersonEditVM : PersonBase
{
   public int PersonId { get; set; }
}

public PersonEntity
{
  public int PersonId { get; set; }
  public string AddressHome { get; set; }
  public int PostalNumber { get; set; }
}

I would like to map PersonEntity to PersonEditVM.
EDIT: Solved after a cup of coffee but it would be nice if it's a cleaner solution?.
Mapper.CreateMap<PersonEntity, PersonEditVM >()
                .ForMember(d=>d.Address, s=>s.MapFrom(p=> new Address{
                    AddressHome = p.AddressHome,
                    PostalNumber = p.PostalNumber
                    }));

A: Here's one way to do it, which would split your Adress (which is correctly spelled Address by the way) mapping into another CreateMap call:
Mapper.CreateMap<PersonEntity, PersonEditVM>()
    .ForMember(dest => dest.Adress, opt => opt.MapFrom(src => src));

Mapper.CreateMap<PersonEntity, Adress>()
    .ForMember(dest => dest.AdressHome, opt => opt.MapFrom(src => src.AdressHome))
    .ForMember(dest => dest.PostalNumber, opt => opt.MapFrom(src => src.PostalNumber));


text:
Q: What is the VC dimension of a Single-Layered Perceptron (SLP) with N inputs? What is the VC dimension of a non-linear Multi-Layered Perceptron (MLP) with N inputs and M hidden units?

A: VC dimension of SLP is N+1 and VC dimension of MLP is 2(N+1)M(1+log(M))
Thanks


text:
Q: If $a,b,c \in \mathbb{Z}$ with $gcd(a,b)=1$ where $ab=c^n$, then $\exists d,e\in \mathbb{N}$, such that $a=d^n$ and $b=e^n$ If $a,b,c \in \mathbb{Z}$ with $gcd(a,b)=1$ where $ab=c^n$, then $\exists d,e\in \mathbb{N}$, such that $a=d^n$ and $b=e^n$
I was not exactly sure how to start, but I decided to write out prime factorizations to complete the proof. I think my proof does not make much sense but this is what I have so far. Would appreciate some input.
Proof: Since $a$ and $b$ are relatively prime, they have have unique disjoint prime factorizations:
$$a=p_1^{a_1} \cdot p_2^{a_2}\cdots p_s^{a_s}\\
b=q_1^{b_1} \cdot q_2^{b_2} \cdots q_t^{b_t}$$
Now, let us assume that $a\cdot b=c^n$, that is,
$$ab=\left(p_1^{a_1} \cdot p_2^{a_2}\cdots p_s^{a_s}\right)\left(q_1^{b_1} \cdot q_2^{b_2} \cdots q_t^{b_t} \right)=c^n$$
Since the sets $\{p_1,\ldots,p_s\}$ and $\{q_1,\ldots,q_t\}$ are disjoint, it must be the case that:
$$ab=\underbrace{\left(p_1^{a_1} \cdot p_2^{a_2}\cdots p_s^{a_s}\right)}_{d^n}
\underbrace{\left(q_1^{b_1} \cdot q_2^{b_2} \cdots q_t^{b_t} \right)}_{e^n}=c^n$$
Hence, $a=d^n$ and $b=e^n$.

A: Yes, the proof is correct.
Let $c=\Pi_{i=1}^k {r_i}^{e_i}$ (prime factorization of c)
Then, think of ${r_i}$ for all integers $i$  ($1 \le i \le k$)
Note that $\gcd(a,b)=1$.
So,note that if $r_i | a$ then $\gcd(b,r_i)=1$, and vice versa. ...(1)
$a \times b = c^n = \Pi_{i=1}^k {r_i}^{n \times e_i}$
Let $P= \{ p_i|1 \le i \le s, i \in \boldsymbol Z \}$,
$Q= \{ q_i|1 \le i \le t, i \in \boldsymbol Z \}$,
$R= \{ r_i|1 \le i \le k, i \in \boldsymbol Z \}$
then, $P \cup Q = R$ and $ P \cap Q = \varnothing$
Let $v_p(n)$ be the exponent of the largest power of p that divides n.
Then, $n|v_{r_i}(c^n)$ for all integers $i$  ($1 \le i \le k$) ...(2)
by (1),(2),
$n|v_{p_i}(a)$ for all integers $i$  ($1 \le i \le s$) and
$n|v_{q_i}(b)$ for all integers $i$  ($1 \le i \le t$)
So the proof is correct.


text:
Q: Python/Tkinter Button and Entry on the same window I'm a beginner in Python (2.7.5). So here is a basic question
I'm trying to create a window with both a Button and some Entry but for some reason it doesn't work.
If I try to make a window with only entries or only a button it works but not with both the button and the entry at the same time.
so the question is basically: How to create a window with both a button and an entry ?
Below is some script:
from Tkinter import*

def super_function():
    fen1.quit

fen1 = Tk()
entr = []
for i in range(10):
    entr.append(Entry(fen1))
    entr[i].grid(row=i)
Button(fen1,text='store everything in a list',command=fen1.quit).pack(side=BOTTOM)
fen1.mainloop()

Thank you !

A: The problem is that you are using pack and grid at the same time.  Instead, you should use only one:
from Tkinter import *

def super_function():
    fen1.quit

fen1 = Tk()
entr = []
for i in xrange(10):
    entr.append(Entry(fen1))
    entr[i].grid(row=i)
# Use grid instead of pack here
Button(fen1,text='store everything in a list',command=super_function).grid()
fen1.mainloop()


text:
Q: Remove differences between two video frames Im trying to remove the differences between two frames and keep the non-chaning graphics. Would probably repeat the same process with more frames to get more accurate results. My idea is to simplify the frames removing things that won't need to simplify the rest of the process that will do after.
The different frames are coming from the same video so no need to deal with different sizes, orientation, etc. If the same graphic its in another frame but with a different orientation or scale, I would like to also remove it. For example:
Image 1

Image 2

Result (more or less, I suppose that will be uglier but containing a similar information)

One of the problems of this idea is that the source video, even if they are computer generated graphics, is compressed so its not that easy to identify if a change on the tonality of a pixel its actually a change or not.
Im ideally not looking at a pixel level and given the differences in saturation applied by the compression probably is not possible. Im looking for unchaged "objects" in the image. I want to extract the information layer shown on top of whats happening behind it.
During the last couple of days I have tried to achieve it in a Python script by using OpenCV with all kinds of combinations of absdiffs, subtracts, thresholds, equalizeHists, canny but so far haven't found the right implementation and would appreciate any guidance. How would you achieve it?

A:
Im ideally not looking at a pixel level and given the differences in saturation applied by the compression probably is not possible. Im looking for unchaged "objects" in the image. I want to extract the information layer shown on top of whats happening behind it.

This will be extremely hard. You would need to employ proper CV and if you're not an expert in that field, you'll have really hard time.
How about this, forgetting about tooling and libs, you have two images, ie. two equally sized sequences of RGB pixels. Image A and Image B, and the output image R. Allocate output image R of the same size as A or B.
Run a single loop for every pixel, read pixel a and from A and pixel b from B. You get a 3-element (RGB) vector. Find distance between the two vectors, eg. magnitude of a vector (b-a), if this is less than some tolerance, write either a or b to the same offset into result image R. If not, write some default (background) color to R.
You can most likely do this with some HW accelerated way using OpenCV or some other library, but that's up to you to find a tool that does what you want.


text:
Q: Seperate styling for 3 alternate li's Im working on a project and im using ul and li's.
I have to change background for 3 alternate li's. since list item is coming from backend I won't be knowing about number of list item.
I tried with css3 child classes but couldn't able to achieve.. Is there any way i can achieve this with css or jquery?

.list-item li
{
  width:30%;
  display:inline-block;
 }

list item 1

list item 2

list item 3

list item 4

list item 5

list item 6

list item 7

list item 8

list item 9

same background color for list 1,2,3,7,8 and 9 and different background color for list 4,5 and 6.

As you can see in image, Here I am using table and   I am achieving this using nth-child(even)/(odd) property.because of few restrictions I can't use table here. So need to achieve this using li's.

A: I assume you want to achieve this?
To change styling for every third item use :nth-child() with i.e. 3n+0 as an argument. If you solve that equation when counting n from 0 upwards you will get the indexes of the items which will be addressed.
Btw:
2n+0 in other words is even
2n+1 in other words is odd
edit:
I added a JS function for achieving something like alternating rows like in the picture which was added in the question later. Have a look at the fiddle!

var alternate = (function() {

  var count = 0;
  var flipAt = 3;
  var condition = false;

  function init(num) {
    flipAt = num;
  }

  function process() {
    if(count === flipAt) {
      condition = condition ? false : true;
      count = 0;
    }
    count++;
    return condition ? true : false;
  }

  return {
    init : init,
    process : process
  }
})()

$('li').each(function(index, el) {
  if (alternate.process()) {
    $(el).css('background', 'blue');
  }
});
li:nth-child(3n+0) {
    background: red;
}

li:nth-child(3n+1) {
    border: 2px solid green;
}

1

2

3

4

5

6

7

8

9

10

11

12

14

A: Yo can use following CSS
li:nth-child(3n+0) {
    background: red;
}
li:nth-child(3n+1) {
    background: green;
}
li:nth-child(3n+2) {
    background: blue;
}

for working example Click here

A: You need to style 6nth, 6n-1th and 6n-2th items:

.list-item li
{
  width:30%;
  display:inline-block;
  background: #cfc;
 }
.list-item li:nth-child(6n-2),
.list-item li:nth-child(6n-1),
.list-item li:nth-child(6n){
  background: #ccf;
}

list item 1

list item 2

list item 3

list item 4

list item 5

list item 6

list item 7

list item 8

list item 9

list item 10

list item 11

list item 12

list item 13

list item 14

list item 15

list item 16

list item 17

list item 18


text:
Q: Writing results of a python script to CSV I'm using this Amazon reviews scraper I found on Github: https://github.com/philipperemy/amazon-reviews-scraper
        for review in reviews_list:
             rating = review.find(attrs={'data-hook': 'review-star-rating'}).attrs['class'][2].split('-')[-1]
             body = review.find(attrs={'data-hook': 'review-body'}).text
             date = review.find(attrs={'data-hook': 'review-date'}).text
             title = review.find(attrs={'data-hook': 'review-title'}).text

             logging.info('***********************************************')
             logging.info(title)
             logging.info(date)
             logging.info(rating)
             logging.info(body)
             logging.info('***********************************************\n')
             reviews.append({'title': title,
                             'rating': rating,
                             'body': body,
                             'product_id': product_id
                            })

              return reviews

I want those results to be sent to a CSV file. But I'm just a beginner with Python so I'm not entirely sure. I'm using Python on Windows.
With the help of Akshat I've got this, but I'm not sure it's correct:
        for review in reviews_list:
            rating = review.find(attrs={'data-hook': 'review-star-rating'}).attrs['class'][2].split('-')[-1]
            body = review.find(attrs={'data-hook': 'review-body'}).text
            date = review.find(attrs={'data-hook': 'review-date'}).text
            title = review.find(attrs={'data-hook': 'review-title'}).text

from csv import DictWriter

with open('results.csv', 'w') as csvfile:
    fieldnames = ['title', 'date', 'rating', 'body']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()

    for review in reviews:
        writer.writerow(review)

A: Your problem is here:
    writer.writerow(title, date, rating, body)

writerow expects a sequence. Do this instead:
    writer.writerow([title, date, rating, body])

That line needs to be inside a loop through reviews.

A: Apart from the error pointed out by @BoarGules. I would suggest you to explore DictWriter from CSV module
from csv import DictWriter

with open('results.csv', 'w') as csvfile:
    fieldnames = ['title', 'date', 'rating', 'body']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()

    for review in reviews:
        writer.writerow(review)


text:
Q: Sending multipart/form-data from .net app to php server I've taken a simple example of the httpClient as per this answer https://stackoverflow.com/a/19983672
I'm trying to get this working, but on my server side (I'm logging the requests) it's empty.
c#
    async public void postTest(string theAddress)
    {
        HttpClient httpClient = new HttpClient();
        MultipartFormDataContent form = new MultipartFormDataContent();

        form.Add(new StringContent("abc"), "test");
        HttpResponseMessage response = await httpClient.PostAsync(theAddress, form);

        response.EnsureSuccessStatusCode();
        httpClient.Dispose();
        string sd = response.Content.ReadAsStringAsync().Result;
    }

And on the server side, I'm logging like this
php
    $log='';
    $log .= $_SERVER['REQUEST_METHOD']."\n";
    $log .= "Request array \n";
    $log .= print_r($_REQUEST,true);
    $log .= "Post array \n";
    $log .= print_r($_POST,true);

    $fp= fopen('log.txt', 'a+');
    fwrite($fp, $log."\n\n");
    fclose($fp);

My log after running the c# app looks like this
GET
Request array
Array
(
)
Post array
Array
(
)

A: This turned out to be something rather stupid.
I decided to open up fiddler (forgot about this lovely tool) and check the request.
The issue was that I was posting to a non www. address and the web server was setup to do a 301 redirect to the www. equivalent. The post was request was lost as the redirect was GET.


text:
Q: How to move part of git branch to different repo? Let assume that i have a git repo with commits:
H - add stuff
G - add stuff
F - add stuff
E - remove big files
D - add stuff
C - add big files
B - add stuff
A - initial commit

I want to move this branch which is master to different repo from commit F to H without the stuff from A to E. Basically the new repo would contain squashed commits from A to E plus commits F,G and H.
Update:
Based on comments i tried the following, but it ended up in merge conflicts:
git checkout A
git checkout -b cleanup
git checkout master
git rebase -i cleanup

pick A
squash B
squash C
squash D
squash E
pick F
pick G
pick H

A: Git internally is just a folder that contains objects that represent snapshots of the state of your files.
So the first step in the process is to copy your entire project including the .git folder (this is crucial you may not see it if it hidden, but it will be okay if you just copy the all project folder).
The next step is to operate the git rebase command in the copied folder like this:
git rebase -i <A hash in this exmple ce0e2fd>

You'll be presented with an interactive window like this:
ce0e2fd pick A initial commit
72ab3c4 pick B add stuff
8150939 pick C add big files
301c1e1 pick D add stuff
ab123c4 pick E remove big files
342d191 pick F add stuff
12ce3d7 pick G add stuff
23fd457 pick H add stuff

...

If you're using the default vim editor, you may need to learn how to use it, too.
My recommendation is to use vscode, use this tutorial to change it to your default editor.
Interactive rebase provides instructions for your scenario, so you should change "pick" to "squash" for A till E:
ce0e2fd squash A initial commit
72ab3c4 squash B add stuff
8150939 squash C add big files
301c1e1 squash D add stuff
ab123c4 squash E remove big files
342d191 pick F add stuff
12ce3d7 pick G add stuff
23fd457 pick H add stuff

This will squash A till E into a single commit, allowing you to change the commit message.
If you're happy to use the commit message of A, you can use "fixup" instead of "squash" and you won't be prompted to update the commit message.
In case you want to make sure that the commits A to E are completely removed and no longer accessible, please check
this answer on how to prune dangling commits.
update:
Base on the comments and our discussion, it seems you will maybe face some conflicts.
As well said @mat:

"but it ended up in merge conflicts" Why did it end? Merge conflicts only end things if you stop when you get them. Don't. The correct response to merge conflicts is to resolve them. Remember, merge conflicts are not bad. They are not an error condition. They are not a problem. They merely indicate that what's happened is beyond Git's capacity to perform automatic merge. Merge conflicts are a good thing: they greatly reduce the chances that Git will do something wrong while merging for you.

A: This is pretty straightforward. Assuming the following history:
4103511 (HEAD -> master) H - add stuff
7946283 G - add stuff
f78ffc7 F - add stuff
ced1bdc E - remove big files
1234ee9 D - add stuff
b9fd6c6 C - add big files
af5a768 B - add stuff
a1436d0 A - Initial commit

then you can:

*

*Create a new branch from F:
$ git checkout -b newbranch f78ffc7

*Squash all commits into one on newbranch (thanks to this answer for the tip):
$ git reset $(git commit-tree HEAD^{tree} -m "F - add stuff")

*Cherry-pick commits G and H from master:
$ git cherry-pick 7946283
$ git cherry-pick 4103511
you'll end up with a new branch newbranch which contains the desired history:
1fafbe7 (HEAD -> newbranch) H - add stuff
4e9d879 G - add stuff
7bc7b56 F - add stuff


text:
Q: force download microsoft outlook (.msg) file in IE 11 hyperlink Objective:
we want to have a hyperlink  Download  in IE 11. But it opens the file on the browser itself displaying some special characters. We want force the file to download. It is working fine in Chrome.
What we tried:
I tried with both absolute url and relative url inside href. But no luck

Any help please.

A: read the last answer in This
i guess there is no way to download it with IE .


text:
Q: C++: Error with MergeSort implementation with arrays: malloc(): memory corruption (fast): for I'm working on an implementation of Merge Sort in C++, and I'm getting the following error when I run my MergeSort function:

*** glibc detected *** ./p1: malloc(): memory corruption (fast): 0x0000000001a250d0 ***
======= Backtrace: =========
/lib64/libc.so.6[0x386ce75e5e]
/lib64/libc.so.6[0x386ce7a528]
/lib64/libc.so.6(__libc_malloc+0x5c)[0x386ce7ab1c]
/usr/lib64/libstdc++.so.6(_Znwm+0x1d)[0x343febd0cd]
/usr/lib64/libstdc++.so.6(_ZNSs4_Rep9_S_createEmmRKSaIcE+0x59)[0x343fe9c3c9]
/usr/lib64/libstdc++.so.6(_ZNSs4_Rep8_M_cloneERKSaIcEm+0x2b)[0x343fe9d19b]
/usr/lib64/libstdc++.so.6(_ZNSs7reserveEm+0x3c)[0x343fe9d5ec]
/usr/lib64/libstdc++.so.6(_ZNSs6appendERKSs+0x4f)[0x343fe9dabf]
./p1[0x403b35]
./p1[0x401ef9]
/lib64/libc.so.6(__libc_start_main+0x100)[0x386ce1ed20]
./p1[0x401879]
======= Memory map: ========
00400000-00406000 r-xp 00000000 fd:00 12322163                           /home/hmp54/p1b/p1
00605000-00606000 rw-p 00005000 fd:00 12322163                           /home/hmp54/p1b/p1
01a25000-01a46000 rw-p 00000000 00:00 0                                  [heap]
343fe00000-343fee8000 r-xp 00000000 fd:00 1062181                        /usr/lib64/libstdc++.so.6.0.13
343fee8000-34400e8000 ---p 000e8000 fd:00 1062181                        /usr/lib64/libstdc++.so.6.0.13
34400e8000-34400ef000 r--p 000e8000 fd:00 1062181                        /usr/lib64/libstdc++.so.6.0.13
34400ef000-34400f1000 rw-p 000ef000 fd:00 1062181                        /usr/lib64/libstdc++.so.6.0.13
34400f1000-3440106000 rw-p 00000000 00:00 0
386ca00000-386ca20000 r-xp 00000000 fd:00 6815797                        /lib64/ld-2.12.so
386cc20000-386cc21000 r--p 00020000 fd:00 6815797                        /lib64/ld-2.12.so
386cc21000-386cc22000 rw-p 00021000 fd:00 6815797                        /lib64/ld-2.12.so
386cc22000-386cc23000 rw-p 00000000 00:00 0
386ce00000-386cf8b000 r-xp 00000000 fd:00 6815808                        /lib64/libc-2.12.so
386cf8b000-386d18a000 ---p 0018b000 fd:00 6815808                        /lib64/libc-2.12.so
386d18a000-386d18e000 r--p 0018a000 fd:00 6815808                        /lib64/libc-2.12.so
386d18e000-386d190000 rw-p 0018e000 fd:00 6815808                        /lib64/libc-2.12.so
386d190000-386d194000 rw-p 00000000 00:00 0
386d200000-386d283000 r-xp 00000000 fd:00 6816160                        /lib64/libm-2.12.so
386d283000-386d482000 ---p 00083000 fd:00 6816160                        /lib64/libm-2.12.so
386d482000-386d483000 r--p 00082000 fd:00 6816160                        /lib64/libm-2.12.so
386d483000-386d484000 rw-p 00083000 fd:00 6816160                        /lib64/libm-2.12.so
3995800000-3995816000 r-xp 00000000 fd:00 6815780                        /lib64/libgcc_s-4.4.7-20120601.so.1
3995816000-3995a15000 ---p 00016000 fd:00 6815780                        /lib64/libgcc_s-4.4.7-20120601.so.1
3995a15000-3995a16000 rw-p 00015000 fd:00 6815780                        /lib64/libgcc_s-4.4.7-20120601.so.1
7f4654000000-7f4654021000 rw-p 00000000 00:00 0
7f4654021000-7f4658000000 ---p 00000000 00:00 0
7f465a4d0000-7f465a4d5000 rw-p 00000000 00:00 0
7f465a4e2000-7f465a4e5000 rw-p 00000000 00:00 0
7ffeca062000-7ffeca077000 rw-p 00000000 00:00 0                          [stack]
7ffeca13c000-7ffeca13d000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
(OrderedList) After mergeSort: Aborted (core dumped)

I've declared the functions within an OrderedList object, and myArray from the following chunk of code is what I'm sorting:
(myArray is an int*)
OrderedList::OrderedList(int size){
    theArraySize = size;
    myArray = new int[size];
}

'MergeSort()':
void OrderedList::mergeSort(int first, int last){
    int middle;

    if(first < last){
        int middle = ((first + last) / 2);
        mergeSort(first, middle);
        mergeSort(middle + 1, last);
        merge(first, middle, last);
    }
}

Here is my 'Merge()' Function:

void OrderedList::merge(int first, int middle, int last){
    int tempArray[last];
    int i = first, j = middle + 1;
    int index = first;

    while((i <= middle) && (j <=last)){

        if(myArray[i] < myArray[j]){
            tempArray[index] = myArray[i];
            i++;
        } else {
            tempArray[index] = myArray[j];
            j++;
        }
        index++;
        theTraversalCount++;
    }

    if(i > middle){
        while(j <= last){
            tempArray[index] = myArray[j];
            j++;
            index++;
            theTraversalCount++;
        }
    } else{
        while(i <= middle){
            tempArray[index] = myArray[i];
            i++;
            index++;
            theTraversalCount++;
        }
    }

    for(int k = first; k < index; k++){
        myArray[k] = tempArray[k];
        theTraversalCount++;

    }
}

I'm still new to using pointers (I've really only worked with java before c++, so pointers still aren't that intuitive to me) so I'm wondering if I might have done something wrong with my array declarations/array pointer declarations?