PNG file looks completely different inside of Unity

Question: I purchased the "Set Builder: Back street Manhattan"  with came with some png textures such as this one.
When I open the file in the browser or any editing program, it looks completely transparent except for the windows.   When I drag the image into Unity, it is completely opaque bricks (which is what I want)  If I duplicate the image and drag that image into Unity, it is again completely opaque bricks.  If I save a copy of the image with photoshop or another application, the information that contained the bricks is lost and it is now mostly transparent, except it has some blotchy white textures which also aren't seen in the photoshop interpretation.  Every texture in this folder is doing this same behavior.  Are these files corrupted or compressed?  How do I retain the brick information into an image editing program besides taking a screenshot within Unity ? Here is an example : of dragging images onto cubes in Unity. Left is a Photoshop copy. Right is attached image
The developer has not replied to my direct questions.
Comment: did you find a solution, same problem here with bought asset xd
Answer: I found a solution in Photoshop.
Layer>layer mask>from transparency. Then right click on the layer to disable the transparency.
Answer: it can be your texture import format
try changing its format to true color
Comment: I appreciate you taking the time to respond.  This seems to be a misleading problem to explain.  Unity is importing the PNG in the way that I want. I have made work with this PNG inside of Unity.  My problem lies with the interpretation of this png *outside* of Unity.   I want to edit this png in photoshop, but the information does not exist in any other program except for Unity.   The PNG that I have attached has baffled several colleagues and professors.  I am seeking an explanation so that this can be avoided in the creation of future assets.


Using the DropdownButton value

Question: I built a beautiful DropdownButton in my flutter app, but have had a hard time finding out how to actually use it.
How can I extract the selected value?
I want to use it to update the settings for my search bar. When a user selects '1' the search bar should search a specific column in my Sqlite database, when they select '2' it should search other columns. After I extract the value is it best to make my if/else statement above the search bar or in the part of my code that tells how to search the database?
Answer: Try this:
search_page.dart
class SearchingPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MyBeautifulDropdownPage(
      myIfElseFunction: (value) {
        print('selected value is $value');
        if(value =='1'){
          _searchASpecificColumnInMySqliteDb();
        }else if (value == '2'){
          _searchTheOtherColumnInMySqliteDb();
        }
      },,
    );
  }
}

my_beautiful_dropdown.dart
class MyBeautifulDropdownPage extends StatelessWidget {
  final Function(String) myIfElseFunction;

  const MyBeautifulDropdownPage({Key key, this.myIfElseFunction}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return new DropdownButton<String>(
      items: <String>['1', '2'].map((String value) {
        return new DropdownMenuItem<String>(
          value: value,
          child: new Text(value),
        );
      }).toList(),
      onChanged: myIfElseFunction
    ),
  }
}

In dropdown, you can get the value of the selected column with the onChanged property. In there you can put your if statement
Comment: @BillWatts sure that is possible. check my edited answer
Comment: I wrote the dropdown menu on a separate page and inserted it as a widget. Is there a way to write something in onChanged so that on my searching page I can use the value and write my if/else there?

Using the DropdownButton value


SoapUI java API, the TestCase.setPropertyValue operation with a long value blocks the java program

Question: I'm using SoapUI API version 5.5.0 to execute SoapUI tests from a java test program. I want to pass the service endpoint to test and the input parameters changing the properties of the SoapUI testcase.
This is the dependence on my pom.xml:
  <dependencies>
    <dependency>
        <groupId>com.smartbear.soapui</groupId>
        <artifactId>soapui-maven-plugin</artifactId>
        <version>5.5.0</version>
    </dependency>

The program is blocked at execution time when I use a long value for one parameter.
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.StandaloneSoapUICore;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.model.support.PropertiesMap;
import com.eviware.soapui.model.testsuite.*;

private static void PutTestCaseProperties(TestCase testCase){

   // Get keys of all properties of this TC
   Map <String, TestProperty> propertiesTC = testCase.getProperties();
   List<String> lKeys = new ArrayList<String>();
   for(Map.Entry<String, TestProperty> entry : propertiesTC.entrySet()) {
      lKeys.add(entry.getKey());
   }

   for(String keyTC : lKeys) {
      String keyValue = "pppppp ppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppppppppp ppppppppppppppppp ppppppppppppppppppppppppppppp pppp pppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp";

      //String keyValue = "short";

      testCase.setPropertyValue(keyTC, keyValue);
  }

}
If I use the "short" value for the keys, the SoapUI test is completely executed,
but if I use the long value the program is blocked after that.
Is there any length limit in the custom properties of a soapUI test case? I would like to use the parameters to write whole XML files (all built in a text line).
The soapUI program allows to load the custom properties of a test case from a external file. Is it also possible to do it from the soapUI java API?
Answer: I have found the following solution:
Based on this response I can load long parameters without errors. Only with the following variation in my groovy to use a properties file which path I configure with a parameter of the Test Case (and I configure this parameter from my Java code using the SoapUI API):
def props = new Properties()
//replace the path with your file name below. use / instead of \ as path separator even on windows platform.
new File(context.expand('${#TestCase#propertiesFile}')).withInputStream { s ->
  props.load(s)
}
props.each {
    context.testCase.setPropertyValue(it.key, it.value)
}


Tox set default values for missing environment variables

Question: I'd like to set default values to environment variables that are missing within tox but only if they're missing.
Answer: This works via the env substitution. An example for either using TOX_WORKDIR or the default:
tox.ini
[tox]
envlist = py
skipsdist = true

[testenv]
setenv = TOX_WORKDIR = {env:TOX_WORKDIR:.tox}
commands = python ./envecho.py

envecho.py
#!/usr/bin/env python
import os

print(os.getenv("TOX_WORKDIR"))

output without env set:
$ tox

py create: /home/oliver/Dropbox/projects/tox/lab/mini/.tox/py
py installed: appdirs==1.4.3,packaging==16.8,pyparsing==2.2.0,six==1.10.0
py runtests: PYTHONHASHSEED='2704413679'
py runtests: commands[0] | python ./envecho.py
.tox
______________________________ summary ______________________________
  py: commands succeeded
  congratulations :)

output with env set:
$ TOX_WORKDIR=/tmp/ tox

py installed: appdirs==1.4.3,packaging==16.8,pyparsing==2.2.0,six==1.10.0
py runtests: PYTHONHASHSEED='30398946'
py runtests: commands[0] | python ./envecho.py
/tmp/
______________________________ summary ______________________________
  py: commands succeeded
  congratulations :)


Intersection of subgroup and normal subgroup

Question: I know the standard result that " let G be group and let H be subgroup and N be normal subgroup of G then H ∩ N is normal subgroup of H"
   but is,  H ∩ N is the normal subgroup of G? if no, then is, there is counter example? I am unable to find such examples. I had tried for S3, as {(1), (1,3)} is subgroup of S3 and A3 is normal subgroup of S3 and this gives A3 ∩ {(1),(13)} = {(1)} and this is normal subgroup of S3. so I am unable to find counter example.
Answer: No, it is not true.
In particular, it's not true that if $A$ is normal in $B$ and $B$ is normal in $G$ then $A$ is normal in $G$. For instance, look at $G = S_4$ and its subgroups $A = \langle (12)(34) \rangle$ and $B=\{(12)(34),(13)(42),(23)(41),e \}$. $A$ is normal in $B$, $B$ is normal in $S_4$, but $A$ is not normal in $G$ (And in particular, $A \cap B = A$). $\diamondsuit$
Comment: still I don't get, my question is " if H is subgroup of G and N is normal subgroup of G then H ∩ N is normal subgroup of " G. "
Comment: I think he answered to your question. Take $G=S_4$, $H=A$ and $N=B$. Then $N\unlhd G$, $H\leq G$ but $H\cap N=H$ which is nonnormal in $G$.


Confidence level of a sample of count data

Question: I have a sample of count data (N = 226) representing a parameter of a population. The sample contains many zero values and a few non-zero values. How can I best estimate the level of confidence that the population is being truly represented by this sample?
The 226 0.1 acre plots are distributed across a 3000 acre study area. On these plots, snags over a certain size were counted. Eight plots had one snag, and one plot had two. I need to estimate the total number of snags on the study area.
Comment: "Level of confidence that the population is truly represented by the sample" -- you can't really know that, unless you know something more about the population than you do about your sample.  You can look at the bootstrapped distributions of statistics of your sample, but they only generate confidence intervals for their population counterparts in the case of random sampling.  And with few non-zero data points, it may be that none fall in your sample.
Answer: You won't be able to find the answer analytically, but I'd suggest that you look at how you sampled numbers.  What was the mechanism by which you got the data?  Is it reasonable that the population yields these values?  If not, then I think it's very likely that there was an error somewhere with your sampling process and you might want to find another way to sample.


Email for domain vs subdomain at two different locations

Question: I would like to know if I have a domain foo.bar and want to host the main email server at other provider, such as by google, simultaneously having another email server subdomain.foo.bar locally.
In other words, emails to firstname.lastname@example.com will be handled by external host while emails to firstname.lastname@example.com will be handled by a local email server. Both cater to global clients.
Is it a usual practice to do so?
Answer: The email service implementation won't treat a domain and subdomain differently.  So you will simply need to add relevant MX records for both the domain and subdomain, matching your target mail servers.
Comment: I am slightly confused. Is it 'won't treat completely' or will treat completely differently?
Comment: No difference at all.
Answer: This is a common setup.  Large organizations often use subdomains for non-personal mail types.  Servers sending you mail will look for the MX record for the fully qualified domain receiving the mail.  Your domain and subdomain are different fully fully qualified domains.
You can point your MX record(s) to any hosts that are configured to receive mail for your domain.  Ensure your mail server is configured to accept mail for your subdomain.  It is common for mail servers to be configured to send and receive as the organization's domain.  You may need to reconfigure so that it is configured to send and receive mail for your subdomain.
Answer: This is a common setup for large organisation and for orgranisation which has country wide branch office. All you need to do register your main domain and subdomain separately, and have MX record separately. Even you can host different mail server for each domain on this scenario.


The Chords in this progression sound great but don't belong together - so why do they work?

Question: I am a songwriter and compose my own music to go with my lyrics.  Most of my chord progressions follow common patterns like using a I V IV or I IV V with an occasional ii or iii or vi chord thrown in for good measure.  But I am always looking for new ways to make my chord progressions more interesting and unusual.  But I want them to be effective and satisfying.  So when I see something outside the norm that sounds good, I like to try to figure out what makes it work.
The sound file below is an example of a popular song (some may recognize it but the title isn't important) that uses a very strange chord progression.  My arrangement is transposed from the original composition but these chords absolutely work in this song.  Yet the chords don't seem to fit properly into any key.  I'll take a wild guess and say it's in the key of G.
So the intro is G to E (G = G major and E = E major).  Then the verses chords are G B7 C A   G B7 C A then the chorus is G Em  G Em  G A G E (major this time).  Then there is a bridge that goes G D C  -  G D C   -    G D C then F D7 then back to the verse.  Song ends on E (major) after repeating the intro.
My question is how can these chords go together?  There is an Em and E major?  I know the G C D & Em fit in the key of G major.  But why does an A major and E major work if this song is in the key of G?  What about the B7 (a B major will work in the song also). I realize the bridge might modulate to a different key?  But in the verse there is a G and B7 and A and C   If I can understand what functions these seemingly out of place chords have and what makes them work in this progression, perhaps I can use the same logic to compose some fresh new melodies for my own original songs.
The sound file is me playing the chord progression on acoustic guitar while calling out the chord names in case my sloppy playing does not make them clear.
Comment: "If it sounds good, it is good." In other words, if they sound great, they **do** belong together. The theory serves the sound, not the other way around. Personally I think theory has a lot more hand waving in it than theorists want to admit. Why do some things sound good and others don't? What makes a hit song a hit? I believe we don't actually know, and that's the wonderful mystery of music. If it actually were a science, it wouldn't be an art.
Comment: The idea that "fitting into a key" is some kind of rule that needs to be adhered to is one of the most common misconceptions in music theory, and one that I think points to a real problem in how theory is taught (and, indeed, how music is notated). There are many wondrous harmonies to be discovered outside if the diatonic scale, even if you stay within the bounds of the 12-tone scale.
Comment: The first part is very reminiscent of Dock of the Bay https://www.youtube.com/watch?v=rTVjnBo96Ug
Comment: Note that in the original version of the song there's no Em, just E.
Answer: Intro: G to E
This could work chromatically. It doesn't really belong to any scale. You play G and by chromatically changing G to G# you go to E. Beatles had a similar progression on the verse of their song 'Honey Don't':

They start with an E major chord that is followed by a C major chord. It creates a nice sound because it has the G# that chromatically goes to G (natural) and then back to G# etc.
Verse: G B7 C A G B7 C A
This could work on the G major scale. Let's take a look:
G->F#->G->A
B->B ->C->C#
D->D#->E->E
This is how the first four chords can sound good together. They move semitones/tones away, so the chords don't sound that far off, even though they don't belong in the scale per se. It is common to play the III as a major, where it was supposed to be minor. Again, from C to A, you move chromatically by changing C to C#.
I know that these are not the voicings you have used, but to simplify the explanation I used them.
In Jazz, it is common to play a vi ii V I progression all in dominant chords (or simply major ones): VI7 II7 V7 IM7 (or VI II V I).
B7 is also the dominant of E (both major and minor; let's take the minor one here). After V, instead of I you can use VI, which is the case here. In the E natural minor scale the VI is the C major chord. So, you can assume that this might be going on here.
Chorus: G Em G Em G A G E
This works on the E natural minor scale. You start with its III (G) and go to i (Em) twice. The fact that it ends on E major and not E minor, could be a Picardy Third. To quote wikipedia:

It refers to the use of a major chord of the tonic at the end of a musical section that is either modal or in a minor key.

Which is exactly what happens above.
Bridge: G D C - G D C - G D C then F D7
Now this bridge is simply in G major; I V IV- I V IV - I V IV. I'm not sure I understand what the role of F is there , but D7 is the dominant of G, so it is there to take you back to G.
So, from what I understand, the song revolves around the G major chord. Sometimes it is used as the I in the G major scale and sometimes in its relative minor, the E minor scale.
Comment: Just some additional notes: The first move from G to E, and the Beatles example from E to C, are called chromatic mediant relationships. Two chords of the same quality whose roots are a third apart. There will always be one common tone, on chromatic alteration, and one stepwise change. I also agree with your way of hearing the B7–C. It's called a deceptive resolution of a secondary dominant if you want to look up more examples @RockinCowboy
Comment: If the bridge IS in G major (which seems logical) then the F could function as the flattened seven chord which can substitute for the 7 diminished as explained in great detail in the answers to this question [http://music.stackexchange.com/q/29817/16897 ]  And thans for fixing the sound cloud link.
Comment: @RockinCowboy that totally slipped my mind! yes, that could be the explanation for the `F`
Comment: @RockinCowboy: The F is taken from G mixolydian, adds a bluesy feel to it.
Comment: The F can be interpreted as a [temporary tonic](https://en.wikipedia.org/wiki/Tonicization) to which the C resolves as a dominant.  It also provides a nice bridge to the D7 (F -> F#), which is in turn the dominant to the following G.
Comment: From what I've understood, the Picardy third is used when you want to end a section hopefully. A song in a minor scale might sound unhopeful or sad or whatever, but if you end it in the major tonic, you would leave the listener with some hope
Comment: @Shevliaskovic - that's the point of a Picardy third - it moves the TONIC from minor to major. However, in this example, it's not the tonic that gets changed.
Comment: The video linked is dead.
Answer: B7 is the dominant of Em (the relative minor of G), so the first two chords appear to be preparing a cadence to Em. Instead, there is a C chord, which is 'almost' Em - either IV in G or VI in Em. The A chord has a similar function as the B - it can be taken as a secondary dominant, leading to D (which isn't played). It also is IV of Em - a major subdominant.
Look at the movement of the notes in G and B - they both have a B, D ascends D# and G descends to F#. Also look at the notes in C and A (especially A7): E and G are common and the C ascends to C#. These sequences increase tension.
The closing E major can be seen as a Picardy third, if the key is indeed E minor, a decoration dating from a few hundred years ago.
I don't know what song this is but The Beatles were very fond of such progressions, especially the major fourth in a minor key (here, A if the key is Em) and the minor fourth in a major key (not applicable here).
Answer: Theory is coming up with a plausible reason why something works. There is one about using chords from the parallel key. Thus, in a song, in G, any chords from G minor will also fit quite well, within reason. Move to the relative minor of G - E minor, and take the parallel major from that. E major. This gives a whole new set of chords to play with, which, again, within reason, will fit quite well.
So, now, there are four sets of chords which can fit together. All of the chords in this song can be found using this formula. Of course, not all have been used - some were docked from the list.
Answer: Ok, I will throw my two cents into the bucket.
The intro; G to E (both major) is an example of the basic 'rule'(description of common practice) that music commonly modulates to the parallel major of the relative minor. This progression is quite is quite common.
A B7 chord commonly occurs in the key of G major. It is the dominant of e minor. Often the B7 is followed by an e- chord. In this case, it is followed by C. As noted in one of the answers above, e- and C are related. All diatonic triads whose roots are a third apart, share to two notes in common.
I would say that the C actually represents a modulation to C major. This explains the A chord. The C and the A are the exact same relationship as the G and the E. (parallel major of the relative minor)
Now to the chorus. The G and e- is the basic I and vi. The A sounds like a modulation to me. Definitely out of key. What key? What key has both a G major and an A major chord? D major! This is a example of the 'rule' (description of common practice); modulation to a closely related key i.e. a key with only one sharp or one flat difference. G major - 1 sharp, D major - 2 sharps.
This song is interesting, the implied modulation never actually resolves with the tonic of the new key. The B7 does not go to e-. The A in the chorus does not go to D.
Now the bridge. G D C, obviously I V IV now what about the F and the D7? What key that is related to G major has an F and a D7? I say, g minor. VII V7 in g minor. I would also say that both the F and the D7 function as dominants to G. The F chord is a bVII this is a modal 'dominant' and D7 is the real thing, pulling us back to G.


Calculate Font baseline in WinRT

Question: I'd like to find out the baseline of a font in WinRT.
I've also calculated the size of text for a particular font by creating a dummy TextBlock, but I'm not sure how to calculate the baseline. Is this even possible in WinRT?
Answer: Unfortunately, what you are looking for is FormattedText [MSDN: 1 2 ] that exists in WPF and doesn't exist in WinRT (i don't even think it's even in silverlight yet).
It will probably be included in a future version because it seems to be a very sought after feature, is sorely missed and the team is aware of it omission. See here: http://social.msdn.microsoft.com.
If you are interested or are really, really in need of a way to measure the specifics of a type face you can try writing a wrapper for DirectWrite which to my knowledge is inside the WinRT available technology stack, however it is only accessible via C++
here is a couple of jumping off points for you, if you want to try:

these guys seem to actually be using DirectWrite in a WinRT app
this is a wrapper for C++ making DX available, DirectWrite would be
much of the same

hope this helps, good luck -ck
update
I thought about this for a bit and remembered that TextBlocks have the oft forgotten property BaselineOffset which gives you the baseline drop from the top of the box for the selected type face!  So you can use the same hack everyone is using to replace MeasureString to replace a loss of FormattedText.  Here the sauce:
    private double GetBaselineOffset(double size, FontFamily family = null, FontWeight? weight = null, FontStyle? style = null, FontStretch? stretch = null)
    {
        var temp = new TextBlock();
        temp.FontSize = size;
        temp.FontFamily = family ?? temp.FontFamily;
        temp.FontStretch = stretch ?? temp.FontStretch;
        temp.FontStyle = style ?? temp.FontStyle;
        temp.FontWeight = weight ?? temp.FontWeight;

        var _size = new Size(10000, 10000);
        var location = new Point(0, 0);

        temp.Measure(_size);
        temp.Arrange(new Rect(location, _size));

        return temp.BaselineOffset;
    }

and i used that to do this:

perfect! right? hope this helps -ck
Comment: Wow, yes that is perfect!
I had seen that property when searching for this problem, but for some reason had dismissed it... But it works exactly right.

Calculate Font baseline in WinRT


Return 1 if multiple columns are true, return 0 if only one column is true

Question: I have a table that looks like the following:

id
bucket_1
bucket_2
bucket_3
bucket_4

7689
1
1
0
1

3456
1
0
1
1

4567
0
0
1
1

5677
1
0
0
0

4567
1
0
0
0

What I need to do is to write SQK code that looks at bucket 1 to 4 and if more than one of these columns have a value of 1, then mark it as 1 or true, and otherwise mark it as 0 or false.
Here is the table that I am trying to make:

id
bucket_1
bucket_2
bucket_3
bucket_4
result

7689
1
1
0
1
1

3456
1
0
1
1
1

4567
0
0
1
1
1

5677
1
0
0
0
0

4567
1
0
0
0
0

Could you help how this can be achieved? I am not sure how it can be done with the case clause.
Comment: Tag your question with the database you are using.
Answer: You can use a case expression:
select t.*,
       (case when bucket_1 + bucket_2 + bucket_3 + bucket_4 > 1
             then 1 else 0
        end) as result
from t;

Answer: You could directly do:
select t.*,
          +(bucket_1 + bucket_2 + bucket_3 + bucket_4 > 1) result
from t


How to add HTML5 attribute "autocomplete" to form fields?

Question: According to an accessibility test, I have to add the HTML5 attribute "autocomplete" an the proper tags to all form fields on my website where the user fills in his/ her personal data.
E.g. "Your E-Mail" > autocomplete="email", "Your Family Name" > autocomplete="family-name", etc. (The proper tags are listet in the WHATWG HTML standard https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill)
Some of the fields are in Drupal core (like the user registration form), others are webforms (like an event registration).
What is the best way to achieve this in Drupal 8?
Comment: I think there is no general way to do it for all fields, you will have to do it with custom code for example with  `hook_form_alter` something like `$form['your_field']['#attributes']['autocomplete'] = 'your_autocomplete_value';`
Comment: This post has some good info for webforms that might be helpful:  http://www.codeexpertz.com/blog/drupal/drupal-8-webform-alter-change-fields-labels-hiding-fields-custom-validate-and-submit
Comment: Just wanted to note that Webform module now has support for adding autocomplete tags per HTML 5.2 spec: https://www.drupal.org/project/webform/issues/3113160#comment-13464333
Answer: I think it's possible to add this attribute to all input fields using a bit of JS, something like this should work:
(function($, Drupal) {
  Drupal.behaviors.autocompleteFieldBehavior = {
    attach: function (context) {
      $(context).find('input').each(function () {
        var name = $(this).attr('name');
        if ($(this).attr('autocomplete').length === 0) {
          if (name) {
            $(this).attr('autocomplete', name);
          }
          else {
            $(this).attr('autocomplete', 'Default autocomplete value.');
          }
        }
      });
    }
  };
})(jQuery, Drupal);

The other solution would be alter all forms using hook_form_alter, see @berramou's comment.


where do the uploaded files using multipart forms gets saved?

Question: I wanted to know that where will the files uploaded by clients gets saved,if i am using multipart forms and also will these files be saved permanently and if 2 or more users are trying to upload files at the same time so will both of there files be saved or overwrite??
My cgi script is a .py script
Tnx in advance
Answer: I don't think uploaded files get saved "automagically". Your script needs to process the request and save them.
Answer: These files will be saved in a temporary directory, you will need to save them manually.
You can control the files using PERL, something like this:
<code>require "cgi-lib.pl";
$uploadDirectory = "YOUR_DIRECTORY";
open (OUTPUT_FILE, ">$upload_dir\/$in{'file'}") || & Die("Could not open file: $!");
undef $Buffer;
while (read($in{'file'},$Buffer,1024)) {
     print OUTPUT_FILE $Buffer;
}
close(OUTPUT_FILE);
</code>
To handle multiple uploads you can make sure you give them separate names (eg. including the user_id, or random).
Comment: kkz,,,I save them manually but if 2 or more users are trying to upload their files at the same time with same name let say hello.html so will these files be saved as differnt or will they be overwritten
Comment: Again, this is a manual process. You can verify a file with the same name exist and save with a different name eg Name_1, Name_2 and so on. Best practice would be to save the file as a random encrypt and store the text in a database, if you use the name provided in the front you are exposing to path traversal attacks (see the owasp.com website for more details about webapps security).
Comment: And i have no knowledge of db or mysql so is this possible that 2 users files of same names get saved differnetly??
Comment: yes, you check if the filename exists and if it doesn't you add a suffix to it. best practice would be not to save a file with the provided name.


How to prove that the inverse of a persymmetric matrix is also persymmetric?

Question: An exercise in a textbook I'm using to brush up on my linear algebra asks to prove that the inverse of a persymmetric matrix is also persymmetric. I have a colleague's old notes in front of me with a solution, but I can't understand his reasoning. It states:

Let $A_S$ denote the persymmetric matrix. Then $A = SA_S = A_SS$, where $A$ is the anti-diagonal identity matrix (i.e.: the identity matrix rotated 90°).
$$(SA_S)^{-1} = A_S^{-1}S^{-1}$$
In a previous question, we have proven that $A = A^{-1}$ ($A^2 = I$, where $I$ is the identity matrix, and thus $A^2 = AA = I$, and so multiplying both sides by the inverse $A^{-1}$ we have $A = A^{-1}$). Thus:
$$(SA_S)^{-1} = A_S^{-1}S^{-1} = A_S^{-1}S$$
Therefore we need only prove $A_S^{-1}$ is symmetric. In a previous question we proved the transpose of the inverse of a matrix is equivalent to the inverse of its transpose, so $(A_S^{-1})^T = (A_S^T)^{-1}$. Since we know $A_S^T = A_S$, $(A_S^T)^{-1} = A_S^{-1}$, therefore $A_S^{-1}$ is symmetric. QED.

I can't follow several bits of reasoning in this answer.

First of all, I don't see how the second equation follows from the setup--how does $A = A^{-1}$ tell us that $A_S^{-1}S^{-1} = A_S^{-1}S$?
Why is proving $A_S^{-1}$ to be symmetric sufficient to prove $A_S^{-1}$ is persymmetric?
The author claims $A_S^T = A_S$, which would be true for a symmetric matrix, but not a persymmetric one (it is true that the transpose of a persymmetric matrix is also persymmetric). What is the basis for this claim?

It's also possible that my colleague's answer is incorrect. I have an idea that perhaps using the facts that $A$ rotated by 90° is $I$ and $A_S$ rotated by 90° is a symmetric matrix in order to tackle the proof, but I'm stuck on the specifics.
Can someone either explain my colleague's answer, give me a hint on how to prove this statement, or provide a proof of their own?
Comment: Yes, I think the answer has some typos in which $A_S$ is replaced by $A$. But the general idea might work.
Comment: For reference to others (http://en.wikipedia.org/wiki/Persymmetric_matrix). And because Wikipedia lists two different definitions, from the given proof it is clear here it is about the first definition.
Comment: Let us look at the computation of the inverse using the minors. Since the matrix is symmetric with respect to the antidiagonal, the minors of two components that are symmetric with respect to the antidiagonal should be the same. Therefore the matrix of the cofactors is persymmetric too. Now we divide by the determinant everywhere. This preserves persymmetry. Finally we transpose. But if a matrix symmetric with respect to the antidiagonal is transposed, the symmetry with respect to the antidiagonal is preserved.
Comment: Another Wikipedia article, [Exchange matrix](https://en.wikipedia.org/wiki/Exchange_matrix), denotes the identity matrix rotated $90^\circ$ with the symbol $J$. Then it says persymmetry of $X$ is equivalent with $XJ=JX^T$. This is persymmetry in the sense that $x_{i,j} = x_{n+1-j,n+1-i}$ for all $i$ and $j$, which is the same as defining a matrix $X$ as persymmetric iff it is the rotation by $90^\circ$ of a symmetric matrix. On the other hand, $XJ=JX$ (without transpose) is stated to be equivalent with $X$ being centrosymmetric, not persymmetric.
Answer: Let $A$ be a nonsingular persymmetric matrix, and let $J$ be the exchange matrix.  The condition of persymmetry, under the usual definition (see, e.g., Horn and Johnson's Matrix Analysis or Golub and Van Loan's Matrix Computations), can be expressed as $A=JA^TJ$.  Consequently, we have that
$A^{-1}=J^{-1}(A^T)^{-1}J^{-1}=J(A^{-1})^TJ$
where we've used basic facts about the inverse of a nonsingular matrix product, the fact that $J$ is involutory (i.e., is its own inverse), and that $(A^T)^{-1}=(A^{-1})^T$.  This shows that $A^{-1}$ is persymmetric.


When does $x^T (xy^T) y = x^T (x^Ty) y$?

Question: $x$ and $y$ are column vectors. When does $x^T (xy^T)  y = x^T (x^Ty) y$?
After a few trial and errors, I found that if at least one of $x$ and $y$ is a zero matrix then the equality is true. The equation is also true if $x$ = $y$.
I'm interested in knowing if there's a way to solving this problem, rather than plugging in numbers, to see if I'm missing values.
Comment: I don't think there is any easy answer to your question, unless the vector space is $\mathbb R^n$.
Comment: The key is to notice that $a^T b = a\cdot b$.
Answer: So you have, in summation convention,
$$ x_i (xy^T)_{ij} y_j = x_i x_i y_j y_j = \lVert x \rVert^2 \lVert y \rVert^2, $$
and
$$ x_i (x_j y_j ) y_i = (x \cdot y)^2. $$
This is just the case of equality in the Cauchy-Schwarz inequality,
$$ (x \cdot y)^2 \leqslant \lVert x \rVert^2 \lVert y \rVert^2; $$
one checks by examining the discriminant of the quadratic $\lVert x-\lambda y \rVert^2$ that equality can only occur when $x$ is a scalar multiple of $y$.
Answer: Strictly speaking your second expression makes no sense. The middle factor $x^Ty$ is a $1\times1$ matrix, which (assuming you are not working in dimension$~1$) you cannot multiply to the right of the $1$-row matrix $x^T$, nor to the left of the $1$-column matrix$~y$. So the only way to make sense of the expression $x^T(x^Ty)y$ is to treat the middle $x^Ty$ is a scalar, and move it out of the way, to give $x^Ty(x^Ty)$. Also I assume you are working in $\Bbb R^n$, since in $\Bbb C^n$ products like $x^Ty$ are not related to any inner product.
Note that matrix multiplication is associative, so on the left you have $x^T(xy^T)y=(x^Tx)(y^Ty)$ which is a $1\times1$ matrix with entry $(x\mid x)(y\mid y)$; on the right $x^Ty(x^Ty)$ is a $1\times1$ matrix with entry $(x\mid y)^2$. So those entries are the numbers occurring in the Cauchy-Schwarz inequality, whose statement tells you when you have equality; this answers your question.


Programmatically fill the "Publish On" date field value provided by the Scheduler Module

Question: I'm using the Scheduler Module to schedule the publishing date of the content in my Drupal 8 site. I would like to programmatically fill the value of the Publish On date field provided by the scheduler module.
In Drupal 7, I used the following code
function hook_form_alter (&$form, $form_state) {
     $date_format = (_scheduler_use_date_popup()) ? SCHEDULER_DATE_FORMAT : variable_get('scheduler_date_format', SCHEDULER_DATE_FORMAT);

      $form['scheduler_settings']['publish_on']['#default_value'] = format_date($querydate, 'custom', $date_format);
}

This code doesn't work in Drupal 8, since the _scheduler_use_date_popup() function and the SCHEDULER_DATE_FORMAT constant are not available.
I'm using the following code in Drupal 8 which doesn't work:
function hook_form_id_alter(&$form, FormStateInterface $form_state) {
    $form['scheduler_settings']['publish_on']['#default_value'] = \Drupal::service('date.formatter')->format($contest_start_date, 'custom', 'Y-m-d H:i:s');
}

Answer: You should be able to provide a default value using a hook_field_widget_form_alter() to modify the #value_callback of the TimestampDatetimeNoDefaultWidget that scheduler uses to a custom one, and this is how you can pass custom logic for a default value. Here's some sample code that could go in your custom module, you could add/modify conditions and logic as needed, but this should at least get things moving in the right direction:
<?php

/**
 * @file
 * Publish On Default module file.
 *
 * This module provides a default value for the "Publish On" value
 * for nodes.
 */

use Drupal\Core\Datetime\Element\Datetime;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\scheduler\Plugin\Field\FieldWidget\TimestampDatetimeNoDefaultWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_datetime_timestamp_no_default_form_alter(&$element, FormStateInterface $form_state, $context) {
  // Only alter the callback for the "Publish On" instance of the `datetime_timestamp_no_default` widget.
  if (isset($element['#title'])) {
    if ($element['#title']->__toString() == "Publish on") {
      $element['value']['#value_callback'] = 'mymodule_publish_on_default_value_callback';
    }
  }
}

/**
 * Callback function to add default time to the publish on widget.
 */
function mymodule_publish_on_default_value_callback(&$element, $input, $form_state) {
  // If no default value, set the default to the current date/time.
  if (empty($element['#default_value'])) {
    $date_format = $element['#date_date_format'];
    $time_format = $element['#date_time_format'];
    $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
    $date_time_format = trim($date_format . ' ' . $time_format);
    $date_time_input = date('Y-m-d H:i:s');
    $date = DrupalDateTime::createFromFormat($date_time_format, $date_time_input, $timezone);
    $element['#default_value'] = $date;
    $input = FALSE;
    return Datetime::valueCallback($element, $input, $form_state);
  }
  // Fallback to the original valueCallback() method.
  else {
    return TimestampDatetimeNoDefaultWidget::valueCallback($element, $input, $form_state);
  }
}


How to clone an SVG Map Using xpath

Question: I need to copy the svg map come from other website.
Here is the website for example where i'm going to copy the svg map:
https://www.alexa.com/siteinfo/google.com
Here is the xpath location from the website:
//*[@id="visitsMap"]
What I need?
I'd like to copy the result/post of that xpath into my page.
Something like this:

        <svg></svg>

Thanks
Comment: You probably need to read the Alexa T&Cs, as well as read up on intellectual property, copyright infringement, etc. But back to the technical issue, you are going to face an issue with cross-origin requests. So you'll have to go through a server to fetch the information.
Comment: This for e.g only...! but im not going to use alexa. for it... :) some advice me just to use iframe...
Comment: You can indeed use an iframe, but you won't be able to style it, manipulate it, add event handlers to different parts of the map, etc. It'll just be a "black box".
Comment: correct... thats why i need some bet soln...in it
Comment: Well, that map is actually drawn by amCharts, so you're probably better off calling amCharts yourself and just get the original data from the Alexa page (search for `ALEXA.viewsHelpers.map.areas` in that page to find the data). But as cross-origin requests are not allowed for that page, you'll need to go through a server to get that data into your page.
Comment: So the only way to gopy that if they provide some kind of access eg api...something??\
Answer: uSING AMCHARTS..

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

To View a Demo: http://webbatlas.com/google.com

How to clone an SVG Map Using xpath


Consider hyperboloid $z^2 = x^2 − 4y^2 + 5$. Find an equation of the line which belongs to this hyperboloid and the point $(0, 1, 1)$.

Question: Consider hyperboloid $z^2 = x^2 − 4y^2 + 5$. Find an equation of the line which belongs to this hyperboloid and the point $(0, 1, 1)$.
This is what I have so far:
$I(s) = OP + sv$
Letting $v = (a, b, c) $
$I(s) = (0, 1, 1) + s(a, b, c)$
$x = as,  y = bs + 1, z = cs + 1$
I then plugged the parameterization into the equation $z^2 = x^2 − 4y^2 + 5$, giving me $s^2(a^2-4b^2-c^2)-2s(4b+c)=0$.
However, how do I proceed from here to find $(a, b, c)$?
Comment: you need both $a^2 - 4 b^2 - c^2 = 0$  along with $4b+c=0.$  Note that the thing is homogeneous, you get one free value, for example choose $b = -1$
Answer: We'll assume $s \neq 0$ to simplify things since we know $I(0) = (0,1,1)$. Notice then that
\begin{align*}
(cs+1)^2=(as)^2 -4(bs+1)^2+5  &\implies s \left(sa^2  - 4 b^2 s - 8 b - c^2 s - 2 c\right) = 0\\
& \implies s\left(a^2 -4b^2 -c^2\right) = 8b+2c \tag{1}
\end{align*}
From here, since it should hold that $I(s)$ is in the hyperboloid for any $s$, choosing some arbitrary $s_1, s_2 \in \mathbb{R} \setminus \{0\}$ we get that
$$
(s_1-s_2) \left(a^2 -4b^2 -c^2\right) = 0
$$
but since $s_1$ need not be equal to $s_2$, to guarantee that the above equation holds in general it must be the case that
$a^2 -4b^2 -c^2 = 0$. Plugging the previous condition in $(1)$ we get $c = - 4b$. So combining the last two conditions we get that
\begin{align}
a^2 = 4\left(- \frac{c}{4} \right)^2 +c^2 \implies c = \pm \frac{2a}{\sqrt{5}}\\
a^2 = 4b^2 +(-4b)^2 \implies b = \mp \frac{a}{2\sqrt{5}}\\
\end{align}
noticing that $c = - 4b$ imposes $b$ and $c$ to have different signs. So your line has a free parameter $a$, and choosing $a=1$ for simplicity you get your solutions to be
$$
\boxed{I(s) = (0,1,1) + s\left(1, \pm \frac{1}{2\sqrt{5}}, \mp \frac{2}{\sqrt{5}}\right)}
$$
Here's a graph of how the solutions look like:

where the dotted line is the solution with the $y$ coordinate $+ \frac{1}{2\sqrt{5}}$ and the filled-out line is the solution with the $y$ coordinate $- \frac{1}{2\sqrt{5}}$.
Comment: You have a typo in the direction vectors of the line I think: $+1$ in second and third components should not be there.
Comment: @MathLover, you're right. Thank you for pointing it out!
Answer: Here is how I would approach it - use the fact that the line is in hyperbola and hence it must also be  perpendicular to the normal vector to the tangent plane at $(0, 1, 1)$.
Hyperbola surface $S: -x^2 + 4y^2 + z^2 - 5 = 0$
Equation of line through point $(0, 1, 1)$ is $(0, 1, 1) + s(a, b, c)$
Taking partial derivatives, gradient vector is $(-2x, 8y, 2z)$. At point $(0, 1, 1)$, the gradient vector is $(0, 8, 2)$ or $(0, 4, 1)$.
As the direction vector of the line is $(a, b, c)$, we have $(a, b, c) \cdot (0, 4, 1) = 0$. That gives us $c = - 4b$
As the line is in the hyperbola, the points on the line must satisfy the equation of hyperbola. So as you rightly said,
$s^2(a^2-4b^2-c^2)-2s(4b+c)=0 \implies a^2 = 20b^2, a = \pm2 \sqrt5 \ b$
So equation of line is $(0, 1, 1) + s (\pm2\sqrt5, 1, -4)$


Why does semantic-release backmerge fail with HEAD -> develop (non-fast-forward)?

Question: I'm using semantic-release with saitho/semantic-release-backmerge.
The branch structure looks like this: release <- beta <- alpha The branches alpha, beta are pre-release branches and release is the stable branch.
The usual flow works fine:

commits are merged into alpha
alpha is merged into beta
beta is merged into release

The problem occurs when merging a hotfix into release. In that case, semantic-release-backmerge should:

rebase the beta branch onto release (so that hotfix is also in beta)
rebase the alpha branch onto beta  (so that hotfix is also in alpha)

The backmerge plug-in only works if all branches are already on the same commit and I make a commit on the release branch. But it doesn't work in the following example:

All branches are on same commit
Make commit on alpha
Make commit on beta (e.g. a hotfix)
Backmerge fails with error:

! [rejected]        HEAD -> alpha (non-fast-forward)
error: failed to push some refs to 'https://github.com/<REMOVED>'
Updates were rejected because the tip of your current branch is behind
its remote counterpart. Integrate the remote changes (e.g.
'git pull ...') before pushing again.

How is it possible that a simple use-case like this doesn't work with the backmerge plug-in? How can I resolve that in the context of semantic-release-backmerge?
Answer: Fundamentally, rebase works by copying some old commits (which are not necessarily bad but are now outdated) to new and improved commits:
             F1--F2--F3   <-- feature
            /
...--o--o--o   [shared point]
            \
             o--o--o   <-- mainline

becomes:
             F1--F2--F3   [abandoned]
            /
...--o--o--o
            \
             o--o--o   <-- mainline
                    \
                     F1'-F2'-F3'  <-- feature

where the 3 F commits are the ones that make up the feature branch.  Note that the original commits are still in the repository: we just no longer use them, since we have Git find a commit by starting from a name like mainline or feature and then working backwards.
That's just your repository
This happens successfully in the repository in which you run git rebase: the old commits are now ejected off the tip of the branch, and the new and improved commits make up the new tip of the branch . But if and when you want to git push these new-and-improved commits, they automatically mean the receiving Git will see you as "behind". You are "behind": you discarded the old commits F1-F2-F3 in order to put the new and improved commits on.
So, in the repository to which you're running git push, they might now have:
             F1--F2--F3   <-- feature
            /
...--o--o--o
            \
             o--o--o   <-- mainline

They receive the three replacements and see that you'd like to have them move their name feature to point to F3'.  They immediately object: Hey, if I do that, I'll lose someone's valuable commits F1-F2-F3 off the end of my branch.  You probably want to get those commits from me and merge them in first, right?  Right?!?
You don't, of course: you threw out the three feature commits in favor of the new and improved ones.  But they don't know that.
Note that it's possible that they now have:
             F1--F2--F3--F4   <-- feature
            /
...--o--o--o
            \
             o--o--o   <-- mainline

in their repository, if some third person added a new commit F4 to the feature branch and used git push to (successfully) send it back to the repository you are all using to communicate with each other over on GitHub.1
Now, if that didn't happen—and most of the time it indeed did not happen—then you might want to "force" this communications-repository (on GitHub) to take the same change to its feature branch.  To do that, you can use git push --force-with-lease.  This uses your own Git repository's memory of their Git repository's feature, stored in your origin/feature, to know that the last time you polled the sharing repo, F3 was the last commit on feature.  This means F3' should be the last commit, as it is in your rebase.  If they are still in that state at the time you run git push --force-with-lease, you will tell them that, yes, you really would like them to eject their F1-F2-F3 chain off the end of their feature branch please, because F1'-F2'-F3' is your shiny new improved replacement chain.
If they did acquire a new F4 on the end, your git push --force-with-lease will find that, no, they don't end at F3 any more, and won't force them to toss F4 off the end of their feature.  Your git push --force-with-lease will fail.
The tricky part here is that this might not be the only reason your git push --force-with-lease could fail.  (Perhaps, for instance, your Robotic Rebaser lost its push access somehow: perhaps some admin messed up a permissions change.)  But if the failure is because F4 appeared, you should obtain the new F4 commit and put your feature back over to the new F4 and have the robot try again, this time copying F4 to new and improved F4'.

1I say "on GitHub" here because you mentioned:

failed to push some refs to 'https://github.com/<REMOVED>'

It doesn't actually matter where this meeting-point repository is, though: what matters is the potential for losing a commit like F4, which occurs whenever there's a race between whatever is doing this rebase, and some additional person making additional commits.

Making it all work under all conditions is hard
In a previous $workplace someone borrowed an existing Robotic Replacer and adapted it for our own needs.  Some bugs cropped up (I forget which ones) and we worked on them and got around the usual case and had something usable for our purposes.  It still wasn't perfect but it did what we wanted, most of the time, and didn't spiral into an infinite loop of repeated failed rebases in bad situations.
Overall this is a hard problem, made harder by the lack of an "evolve" concept in Git (this concept exists in Mercurial, but as an extension, and it also depends on the fact that Mercurial commits aren't wholly immutable, unlike Git commits).  But the most common case is pretty easy: you just have to know how to automate it.
When doing this on GitHub, remember that GitHub actions by default have shallow clones these days; you'll need one deep enough to complete the rebase correctly (how deep that will be depends on many factors and the only really safe way to do it is the expensive full-clone way).
Comment: Your git answers are just legendary, thanks


Discrete random variable with $f(x)=c(2x-1)$

Question: I feel really stupid because I don't understand this example at the start of my textbook. The chapter is discrete random variables and it starts out with this example with no explanation. I understand the rule that $\sum f(x)=1$ so I can see why there is a $1$ at the front of this equation. I don't understand how the equation went from $\sum (2x-1)$ to $2\sum x-12$. And the step after that - are they following a formula there? I'm having trouble finding information on the internet that explains this type of problem. Thank you in advance.
$$f(x)=c(2x-1) \text{ for } x=1,2,\dots,12$$
$$1=c\sum_{x=1}^{12} (2x-1)=c\left[2\sum_{x=1}^{12} x-12\right]=c\left[\frac{2(12)(13)}{2}-12\right]=c(12)^2$$
Answer: Thanks, I found the rules:
$ \displaystyle{ \sum_{i=1}^{n} c  } = cn$
$ \displaystyle{ \sum_{i=1}^{n} i
= { n(n+1) \over 2 } } $
So, $\displaystyle c\sum_{x=1}^{12} (2x-1)=c[2\sum_{x=1}^{12} x-\sum_{x=1}^{12}1]=c[2\sum_{x=1}^{12} x-(1)(12)]$
(by the first rule)
And the rest is easy following the second rule.
Answer: $$\displaystyle 1=c\sum_{x=1}^{12} (2x-1)=c[2\sum_{x=1}^{12} x-12]=c[\frac{2(12)(13)}{2}-12]=c(12)^2$$
Your question is why is $$\sum_{x=1}^{12}1=12$$  This is simply adding 1 - 12 times.  On the other and $$\sum_{x=1}^{12} x$$ is sum of x taking the values 1 to 12 = $1+2+3+\cdots+12$ which utilizes the sum of an n consecutive integers $1+2+3+\cdots+n$ = n(n+1)/2.
Comment: The (2x-1) I would have factorized to 2(x-1/2) and then removed the 2 to the outside leaving (x-.5) after sigma. Is that incorrect?
Comment: Thanks for the second part - the n(n+1)/2 formula makes perfect sense.
Comment: You are welcome


Ionic 3: No response on REST API call

Question: here's my issue:
I have this endpoint (GET) which gives me a JSON object as a result:
'localhost:3305/v1/patients'
I use Ionic 3 with the provider 'RestProvider'.
My rest.js looks like this:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';

@Injectable()
export class RestProvider {
    apiUrl = 'localhost:3305/v1';
    constructor(public http: HttpClient) {
        console.log('Hello RestProvider Provider');
    }

    getPatients() {
        return new Promise(resolve => {
            this.http.get(this.apiUrl+'/patients').subscribe(data => {
                resolve(data);
                console.log(data);
            }, err => {
                console.log(err);
            });
        });
    }
}

home.ts:
import { Component } from '@angular/core';
import { RestProvider } from '../../providers/rest/rest';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {
    patients: any;
  constructor (public restProvider: RestProvider) {
     this.getPatients();
    }

    getPatients() {
        this.restProvider.getPatients()
        .then(data => {
            this.patients = data;
            console.log(this.patients);
        });
    }
}

home.html:
<ion-content>
  <ion-navbar>
    <ion-title>My patients</ion-title>
  </ion-navbar>
  <ion-list>
    <ion-list-header>My patients</ion-list-header>
  </ion-list>
  <ion-list inset>
    <ion-item *ngFor="let patient of patients">

{{patient}}

    </ion-item>
  </ion-list>
</ion-content>

Problem: There's no error, but there's nothing shown in the view.
console.log(data); of rest.js shows: [object Object].
Does anyone know where the mistake is?
Thanks in regard!
Comment: Dows it return any data when you try in postman or curl?
Comment: yes, the endpoint works fine. I already tested it via Postman.
Comment: You should not have to use Promises in Angular as HttpClient uses observables. Try removing the promise funcion
Answer: Need to rewrite  getPatients() code in following way:
getPatients() {
    return this.http.get(this.apiUrl+'/patients', {
      headers: new HttpHeaders().set('Content-Type', 'application/json'),
    })
   .toPromise()
}

And Getting data in home.ts
getPatients() {
    this.restProvider.getPatients().then((res => {
        this.patients = data;
    }, (err) => {
       console.log("rejected");
    })
}

Answer: Since you are using modern Angular you should use http methods in accordance with docs:
In your service:
getPatients() {
            return this.http.get(this.apiUrl+'/patients')
}

In your component:
getPatients() {
        this.restProvider.getPatients()
        .subscribe(data => {
            this.patients = data;
            console.log(this.patients);
        });
    }

Basically leverage observables as pointed out in comments
Answer: Don't forget to parse te response from the json, like this way, or the way you prefer.
getPatients() {
    return new Promise((resolve, reject) => {
        this.http.get(`${this.apiUrl}/patients`).subscribe(data => {
            try {
               response = response.json();
               resolve(response);
            } catch (error) {
               console.log('[api-153]', response);
               reject(response);
            }
            console.log(data);
            resolve(data);
        }, err => {
            console.log(err);
        });
    });
}

Ionic 3: No response on REST API call


Live search with Jquery, PHP, and MySQL break with certain results, how to avoid?

Question: I'm trying to do a live search with JQuery, PHP, and MySQL. I'm no expert but I know and understand enough to be dangerous. At any rate, everything seems to be working except for when any of my search results contain single or double quotes. For example, my search results may contain:
Contact, door 3/4" recessed
Motion, detector 35' x 50'
And so on and so on.
My code is:

and
<?php
if(isset($_POST['queryString'])) {
    $queryString = $_POST['queryString'];
    if(strlen($queryString) >0) {
        $query = "SELECT short_desc
                  FROM equipment
                  WHERE short_desc
                  LIKE '$queryString%'
                  ORDER BY short_desc
                  ASC LIMIT 10";
        $result = mysql_query($query) or die("There is an error in database");
        while($row = mysql_fetch_array($result)){
            $escaped_desc_html = htmlentities($row['short_desc']);
            $escaped_desc_escape = addslashes($row['short_desc']);
            echo
            "
".$escaped_desc_html."
";
        };
    };
};
?>

I've tried storing the data in MYSQL like this:
Contact, door 3/4\" recessed
Motion, detector 35\' x 50\'
But then it comes out on the page looking just like that.
I've tried addslashes(), htmlentities(), combinations of both, and it keeps breaking. I tried escape() in the javascript too but then I don't get any formatting and the list is a continuous block of jumbled text.
My problem is when the results of my search are passed back to Jquery, that quote or double quotes makes it think that the command if over and I get an error about a missing ).
Is there a way to make Jquery ignore any html, slashes, or quotes that come back as data? Maybe have it treat it like an object instead of commands. Even with htmlentities() the &quo still breaks the code. It's driving me crazy! The problem always breaks in these two places:
$('#autoSuggestionsList').html(data);
and
$("#inputString").val(thisValue);
Comment: Upvote for "know and understand enough to be dangerous" ;-)
Answer: I had a similar problem. As my problem was only with double quotes i converted them to " on input using:
$OUTPUT = str_replace("\"",""",$INPUT);
If this causes a problem for you javascript you could use the same code to replace the " with a "-" or something.
When you do get to the user input stage be sure to protect yourself from injection attacks like others have mentioned!
Sorry just seen the date on this one!! hope this helps someone though
Answer: You should use mysql_real_escape_string for escaping variable in MySQL queries. More importantly, though, you need to be very careful to properly escape both content you put in your database and also content that you render to the user... you should never trust input provided by the user, because if you do, you will come across at least one malicious hacker who exploits such a vulnerability.
The best way to avoid this is to:

Unit test each component, and exercise validation in unit tests (make sure that there is proper validation / escaping code in place and that it actually works, at each component).
Use fuzzers to automatically generate inputs to try to find these issues. For example, could a user generate an input such that it can delete your entire database?
Comment: Yeah, I will. I just haven't got that far yet. At any rate, it's only for an internal work inventory database that myself and one other computer illiterate person are going to use. Thanks though.
Comment: I changed it to
$queryString = mysql_real_escape_string($_POST['queryString']);
Answer: You leave yourself WIDE OPEN to SQL injection attacks with the code above. You need to call mysql_real_escape_string() on the value before you execute the SQL statement.
Comment: Yeah, I will. I just haven't got that far yet. At any rate, it only for an internal work inventory database that myself and one other computer illiterate person are going to use. Thanks though.
Comment: mysql_real_escape_string will also prevent the issue you are having with the quote marks. The quote marks literally end the query prematurely and allow a malicious user to write their own SQL that will be evaluated by the database... So you actually kill two birds with one stone if you fix the problem now.
Comment: I changed it to
$queryString = mysql_real_escape_string($_POST['queryString']);
Comment: Okay, I've added the real_escape, what should I do to the data already in my database? Example: Contact, 3/4" recessed -- Should I update everything to Contact, 3/4\" recessed ?
Comment: I'm not entirely sure about that. Not sure whether it needs to be escaped once it is in the database. I think the escape will be converted back to the character once it actually reaches the data layer. Test and see what happens when you try and search now - if it doesn't work you will need to do a one time update of your database records.
Comment: I updated my database so that everything is escaped as it's stored. It works more than not now, but it still breaks with some results. Do I have to escape parenttheses as well? If I gave you a temporary link, would you look at it for me and maybe offer a suggestion?


Renew letsencrypt certificate SSL - AMI Linux Amazon

Question: I trying to renew an SSL certificate on EC2 with AMI Linux Amazon but I am receiving the error below:
[ec2-user@ip-xxx-xx-xx-xx letsencrypt]$ ./letsencrypt-auto renew

Error: couldn't get currently installed version for /home/ec2-user/.local/share/letsencrypt/bin/letsencrypt:
Traceback (most recent call last):
File "/home/ec2-user/.local/share/letsencrypt/bin/letsencrypt", line 7, in <module>
from certbot.main import main
File "/home/ec2-user/.local/share/letsencrypt/local/lib/python2.7/dist-packages/certbot/main.py", line 12, in <module>
import zope.component
File "/home/ec2-user/.local/share/letsencrypt/local/lib/python2.7/dist-packages/zope/component/__init__.py", line 16, in <module>
from zope.interface import Interface
ImportError: No module named interface

Any idea how to solve?
Answer: I was getting the same issues with an Amazon Linux instance that was originally set up with cert-bot and worked fine. I tried to fix some other issues by following another post and this is the result I came too
In the end, I had to do the following
rm -rf /opt/eff.org/*

It will probably fail on this one but setups a clean virtual environment
./certbot-auto --debug

cd /opt/eff.org/certbot/venv/lib64/python2.7

mv site-packages site-packages.sav

ln -s dist-packages/ site-packages

You're now ready to run certbot-auto again
./certbot-auto --debug

Answer: Someone had the same problem as you, check the community forum from Let's Encrypt.
One solution from that thread was:

Basically, I reinstalled it from scratch:
cd $HOME/.local/share
rm -fr letsencrypt
unset PYTHON_INSTALL_LAYOUT
./certbot-auto -d DOMAIN certonly --webroot -w DOCUMENT_ROOT --debug


Xamarin.iOS - How to change the label font size dynamically?

Question: I am trying to change the font size based on the iPhone Screen size.
I am setting a font size that looks good on iPhone 6 Plus and once I detect the iPhone and it is not iPhone 6 Plus, I change its size.
I am trying it on the ViewDidLoad event:
lblLogin.Font.WithSize(17f);

But it is not updating the FontSize, I guess "Font.WithSize" is not the path to achieve it, any ideas?
Answer: WithSize() returns a font reference, it does not modify the existing font
lblLogin.Font = lblLogin.Font.WithSize(17f);

Also, see this Xamarin recipe
Answer: If you want to change the font size of a UILabel, try to use those code, like:
//1 Just change size
customLabel.Font = UIFont.SystemFontOfSize (18);
//2 Set the font name and size:
customLabel.Font = UIFont.FromName("Helvetica-Bold", 20f);

Hope it can help you.


Extending TInterpolationType in Delphi's TAnimation

Question: I am working on a Delphi application using the FMX framework and I am trying to extend the TAnimation class to add my own custom interpolation algorithms. The TAnimation class uses an enumerated type TInterpolationType to allow users to select the interpolation algorithm they wish to use:
TInterpolationType = (Linear, Quadratic, Cubic, Quartic, Quintic, Sinusoidal, Exponential, Circular, Elastic, Back, Bounce);

This can be set via the Interpolation property:
property Interpolation: TInterpolationType read FInterpolation write FInterpolation default TInterpolationType.Linear;

There are many other interpolation algorithms available (e.g., Accelerate interpolator, Decelerate interpolator, Anticipate interpolator, Hesitate interpolator, Spring interpolator, etc.), and I would like to update the TAnimation class so that I can define and use my own interpolation algorithm.
By what can I replace (or extend) the Interpolation property so that I can also include my own custom interpolation algorithms?
Right now I think to add "Custom" in TInterpolationType = (Linear, Quadratic, Cubic, Quartic, Quintic, Sinusoidal, Exponential, Circular, Elastic, Back, Bounce, CUSTOM); and add an event OnCustomInterpolation but Would like to know if their is not a more elegant solution?
Comment: Any way if you do decide to go and rewrite `TAnimation` I'm guessing that just adding ability for us to specify custom Interpolation method would be best solution since then you can write nay interpolation method you need. But it seems that original authors of `TAnimation` class never expected anyone to try and extend this class by adding other Interpolations. I long for days of Delphi 6 when extending any of the code that shipped with Delphi was simple as making class derivation. Nowadays you are often forced into using RTTL hacks to do what could be done by simple class derivation.
Comment: The way how TAnimation is currently codded I'm afraid you won't have an easy time extending it. Why? If you look at its source code you will see that the only place where `FInterpolation` field is used is in [TAnimation.GetNormalizedTime](https://docwiki.embarcadero.com/Libraries/Alexandria/en/FMX.Ani.TAnimation.GetNormalizedTime) protected method. The said method has just one case statement which then calls appropriate Interpolation methods based on InterpolationType. So no easy way of changing this without rewriting the existing `TAnimation` class. ...
Comment: ... On the other hand since `GetNormalizedTime` is getter method for [NormalizedTime](https://docwiki.embarcadero.com/Libraries/Alexandria/en/FMX.Ani.TAnimation.NormalizedTime) you might be able to redeclare same named property that would use your custom getter method.
Answer: Finally I decided to add "Custom" in TInterpolationType = (Linear, Quadratic, Cubic, Quartic, Quintic, Sinusoidal, Exponential, Circular, Elastic, Back, Bounce, CUSTOM); and add an event OnCustomInterpolation
The code is visible at https://github.com/MagicFoundation/Alcinoe
Interpolated Animation
The TALAnimation component is a refined iteration of Delphi's foundational TAnimation object, meticulously tailored for mobile platforms. By forgoing the traditional Timer mechanism and instead adopting platform-specific technologies, this component offers a vastly improved animation experience for mobile users. On Android, animations are seamlessly integrated with the Choreographer, ensuring they sync perfectly with the device's refresh rate. Meanwhile, on iOS, the precision of DisplayLink is harnessed, leading to optimized and fluid animation rendering. Beyond these foundational changes, one of the most notable enhancements is the capability to support custom interpolation algorithms. This offers developers the flexibility to design unique and intricate animation patterns, moving beyond the traditional ease-in or ease-out sequences.

SpringForce Animation
Inspired by Android's SpringForce, the TALSpringForceAnimation Component brings the intrigue of physics-based animations to the Delphi platform. This component captures the real-world dynamism of objects influenced by spring mechanics. The resulting animations are ones that stretch, bounce, and settle, mirroring real-world behaviors and offering a tangible sense of realism to users. Developers have the added advantage of being able to adjust various physical properties of the spring, such as its stiffness and damping ratio. This ensures that a broad spectrum of animation behaviors can be realized, catering to the specific nuances of different applications.


Which hands to use for Für Elise by Beethoven?

Question: In Für Elise by Beethoven, in many variations found on the net, starting from bar 13, and as I have seen in many videos playing this part, both hands are used consecutively while most to all of them can be easily played with just the right hand. Is there any special reason why this happens (something like making it look pretty)? Is it written by Beethoven himself or have later editors made these changes? Is it wrong or considered rude (because great pianists have not done so) if I play it with only one hand?

PE: My problem is not where E has different octaves, but those D# & Es and continuous moving from the bottom staff to the top staff starting from bar 13, is my main problem, and yes about those Es: although that E to E travel could be done using both hands differently, for example it's much easier for me to play the starting E in bar 13 with my left pinky, the second E with my left thumb and the rest with my right hand, and the highest E with my right hand.
Comment: Regarding your update: finger legato is why you start the octaves 5-5-1 instead of 5-1, because it sets you up to play the phrase legato after that first jump. And the minor seconds (d#-e) are all the same two notes, in treble clef. They are easy to play with one hand but easier to count with two, plus the first left hand beat gives you time to bring your right hand back from the high E.
Comment: One note is that a composers can use this type of clef separation to indicate which "voice" is intended to be playing those notes. (especially in a more polyphonic piece as was popular in Beethoven's day) E.g. it could indicate that in a duet you should switch between the two instruments for what, in this example, is the bass and treble clef.
Comment: please limit your posts to one question. I have edited this for you - your other question is already covered on this site anyway. See the related sidebar to the right.
Comment: Although these two question may be about one piece of music of BT, I thought the topic would be different, so I asked them in two different places, though one of them contains more questions. Sorry if it violates SE rules cause I wasn't aware...
Comment: AF - I deleted your thank you post as well. it's worth reading our [about] page to understand how this site is different from online discussion forums - we don't use thank you posts at all. Simply upvote good answers, and accept the one you think is best. When you have more rep you can also add bounties etc...
Comment: Of course, but in my opinion, when it comes to only one instrument it is more interesting and a little bit challenging...
Answer: Fingering suggestions, including handedness, are always just suggestions. You can play it how you like. That said, there are a few reasons to use both hands in this passage:

The octaves are much easier to play smoothly and evenly when you play with both hands.
Using both hands, you can play the octaves with finger legato, which is good technique even when using the pedal.
Alternating hands helps less with technique for the minor seconds, but it helps a lot with counting the minor seconds to keep time, especially because the length of that phrase varies throughout the piece.

These reasons are a bit more compelling for beginning and intermediate players, which is usually when you learn this piece, and once you have learned it, there is little reason to change the technique.
Comment: Yes, and it's such a big deal in learning classical and romantic piano like this, along with the touch and evenness that you mention. This is a great piece for developing that technique!
Comment: @AF by writing that E in the lower staff, Beethoven has suggested that it be played by the left hand.   If you play it with the right, it doesn't mean you're playing the piece wrong.   If using the right hand causes you to break the legato phrase, though, it does mean you're playing it badly.
Comment: Yes. The old 'finger legato'. The most desireable thing in piano music.
Comment: Which _hand_ to use is a suggestion. But the _clef_ is not a suggestion, it defines the pitch as much as the lines do. Make sure you are not confusing _clef_ with _staff_ as they mean different things.
Comment: And this advice is for piano – guitars have different issues.
Comment: @AF The question mentions "those D# & Es and continuous moving from bass to treble clef in bar 14," and elsewhere you also appear to use "bass clef" to refer to the lower staff. That terminology is incorrect and confusing. There is no bass clef in bar 14; both staves are in treble in that measure. If you read the lower staff as bass clef, you'll play the wrong notes.
Comment: The fingerings are always just suggestions. That includes which hand to use, as I state in my answer. That said, unless you are working with a teacher who can guide you personally, I recommend sticking to the recommendations until you have enough skill and understanding to realize why the editor made those suggestions. You won't offend anyone, but they're there to help you learn.
Comment: "Fingering suggestions, including handedness, are always just suggestions", by saying this part, does this suggestion only apply to numbering notes for fingers (which is written above notes and is common in many instruments such as Piano, Guitar etc), or writing each note on the treble or bass clef is also a part of suggestions? I mean, there might be a piece of music written by a composer, arranged for piano for example, without knowing the techniques of the piano, and that is just a write-down of melody he/she has in his/her mind. There, we can change the way we play it?
Comment: Yes, clearly I know what clef is!! I mean there might be some situations like this part of Fur Elise, which we can play with both hands (and clearly can be written on each staff sometimes by using ledger lines... I mean writing on one staff while being able to write it on the other equals to making us use one hand or another, or even they are suggestions. For example bar 13, bass clef, third note (E). In other words, if one bass line must only be played by left hand even if one note written on that is possible to play by right hand in an easier way?
Comment: @BraddSzonye this is where my question is, I know the clef sign is changed to G just before bar 14, but my question was: in a grand staff, regardless of which clef we are reading notes from, is always the top staff for right hand and the bottom for the left hand? But after reading the answers now, there are mostly suggestions while at the same time in most cases the best suggestion...
Answer: For me, I would use the combination of both hands for two main reasons:

The less "jumping around" on the piano, the better. Fewer fast movements (such as going from that upper E to the D# 8vb) usually equates to fewer mistakes (or chances for mistakes). If we can make the movements easier by spreading it over both hands, why not?
It's very much about 'touch'. To get those E octaves, most people will need to play the lower with their thumb and the upper with their pinky finger. The lower octave E is repeated, and doing this with the thumb (which is the shortest and strongest of human fingers) can result in an excessive, 'harsh' tone on the repeated note. It's a subtle thing, but by using different fingers on the same note, we have more control; not just over tone, but also at fast tempos with rhythmic "even-ness".

Is it "wrong" to play with only one hand? No. But I would suggest that that is not the best method of performing this piece. It may get the job done, but as you say, "great pianists" use both hands, for the reasons above.
Comment: Also, that technique of switching fingers for the same note is helpful for the bass in the C section of the piece. I find that it is _much_ easier to play an even pulse on the bass when I play it 3-2-1-3-2-1 instead of 1-1-1 or 2-2-2.
Comment: Totally agree about _touch,_ which is what I was getting at talking about smoothness & evenness in my own answer.


Prove $\sup(AB) = \sup(A)\sup(B)$

Question: I know $\sup(AB) = \sup(A)\sup(B)$ if $A$ and $B$ are nonnegative, but what if the assumption is dropped that $A$ and $B$ are nonnegative. Does this change the answer?
Answer: Consider $A=[0,1]$, $B=\{-1\}$, $Sup(AB)=0$, $Sup(A)Sup(B)=-1$
Answer: Yes it does. Consider the set $$A=B=\{-1/n : n\in \mathbb{N}\}.$$
Then $\sup(AB)=sup\{ab: a\in A, b\in B\}=1$ but $sup(A)=sup(B)=0$

Prove $\sup(AB) = \sup(A)\sup(B)$


Can a unitary matrix $U$ be factorized $U=\overline{R}R^{-1}$ for a non-singular matrix $R$?

Question: Suppose $U$ is a unitary matrix. Does there exist a non-singular matrix $R$ such that
$$
 U=\bar{R}R^{-1}?
$$
The bar denotes the complex conjugation of each entry of the matrix $R$.
Remarks: 1) It is obviously true for $1\times 1$. 2) If $U$ admits the decomposition $U=VDV^{T}$, where $V$ is orthonormal and $D$ diagonal with diagonal entries of unit modulus, then $R:=VD^{-1/2}V^{T}$.
Answer: The required $R$ exists if and only if $U$ is complex symmetric.
If $U=\overline{R}R^{-1}$, then $UR=\overline{R}$. Hence $U\overline{UR}=U\overline{\overline{R}}=UR=\overline{R}$. In turn, $U\overline{U}=I$ and $\overline{U}=U^\ast$. Hence $U=U^T$.
Conversely, if $U$ is complex symmetric, it admits a special form of singular value decomposition $V\Sigma V^T$, known as Takagi factorisation. Since $U$ is unitary, its singular values are all equal to $1$. Hence $\Sigma=I$ and $U=VV^T$. Now take $R=\overline{V}$ and we are done.


Why does "vagrant ssh -c 'cabal build'" yield an empty binary?

Question: I'm using Vagrant to build my Haskell Cabal project on Linux. When I cabal build in the Vagrant VM, the binary that's produced is fine. When I try to script the build from the host machine using vagrant ssh -c 'cabal build' a binary of zero size is produced. The compile clearly works but I think as soon as the linker kicks in, the Vagrant shell is closed and terminates the linking. Why would this be happening?
After some Googling I could only find one SO question that looked similar.
With some help from IRC, we were able to determine this works:
ssh firstname.lastname@example.com -p 2222 -i .vagrant.d/insecure_private_key 'cabal build'
Here's the ssh command vagrant ssh dumps in debug mode which doesn't work:
["email@example.com", "-p", "2222", "-o", "Compression=yes", "-o", "DSAAuthentication=yes", "-o", "LogLevel=FATAL", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "IdentitiesOnly=yes", "-i", ".vagrant.d/insecure_private_key", "-t", "bash -l -c 'pwd'"]
Using deduction I've found that the ssh -t is causing the problem. From the docs:

 -t      Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services.
         Multiple -t options force tty allocation, even if ssh has no local tty.

So now the question is why does -t cause cabal build to fail?
Running cabal build -v3 bails out with the error /usr/bin/ghc returned ExitFailure 9 which I think means out of memory.
Answer: The OOM is killing GHC when running out of memory. The ssh -t flag was apparently just enough to put it over the threshold. Confirmed with /var/log/syslog. The solution is to simply allocate more memory to the VM. Thanks to tibber and teukka on Freenode.


How to query table1 first and make second query with results+table2 at the same time

Question: SELECT LOGS.UserID, LOGS.UserName, LOGS.TransactionTime FROM LOGS
WHERE LOGS.TransactionTime BETWEEN DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T06:00:00') AND DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T08:00:00')

This is my first query. I get results of when workers start working from my LOGS table.
I have another table named Workers which includes all workers in it.
I want to compare myfirstquery.UserID with Workers.UserID and that query should show me who is not in myfirstquery (which means who is not working that day) but I need to do it in one query.
Answer: You could use the not exists operator:
SELECT *
FROM   workers w
WHERE  NOT EXISTS (SELECT *
                   FROM   logs l
                   WHERE  w.UserId = l.UserId AND
                          l.TransactionTime BETWEEN
                          DATEADD(day, DATEDIFF(day, '20010101', GETDATE()), '2001-01-01T06:00:00') AND
                          DATEADD(day, DATEDIFF(day, '20010101', GETDATE()), '2001-01-01T08:00:00')

Comment: The same can be achieved using the `NOT IN` Operator too


Is it easy to learn how to use an American pool cue if you're a snooker player?

Question: The only cue sports I have good experience of are Snooker and British pool. For these cue sports one usually play with a 9mm tip. Even though American pool balls are slightly bigger and heavier than the balls used on British tables, I still think that I might struggle to get used to a 13mm tip (this seems by far the most common option when buying an American pool cue; other sizes like 12 or 11.75 mm are quite rare, so I presume they are not as common as the 13mm tips among players?). An American cue might feel very different from what I'm used to, almost like I'd be playing with a broomstick rather than a cue. Furthermore, I'm afraid that the amount of spin (or "English" if you prefer) that I can put on a ball with a 13mm tip is far less than what I could do with a snooker cue, thus increasing my sense of frustration.
Has anybody undergone a similar experience? Of if you have used a 13mm tip, are my fears not grounded at all?
Answer: I've been through exactly that experience. I expected to find it weird, but did not - proportionally, it's almost the same. In fact, what does feel strange is playing with a 9mm snooker cue, hitting US pool sized balls. It's easier (for me, anyway) to put unwanted side on the ball with a small tip.
Dr Dave Alciatore's page on cue tips gives more information than you could ever imagine.
Answer: My experience disagrees with @timseal's answer, for two reasons.

Control: cue sports are all about cue ball control, and I feel that the snooker cue gives me far more control over its movement and in consequence of the table. This is perhaps because I come from a snooker background and am more "used to" micromanaging the exact spot on the cue ball that I want to strike. The much larger pool cue tip feels to me like a behemoth compared to the snooker tip.
Deep screw: don't get me wrong, many pool players are able to perform a deep screw with a usual pool cue. However, I find that this requires far more effort with a large tip than with a snooker cue since you can keep the shaft much closer to the table while maintaining a parallel position. I was able to pull off close to jaw-dropping deep screws on a full-sized pool table that would have required a lot more effort with a pool cue.
Laser view: one habit I developed playing snooker is the refined view you get when you align your shaft with the potting line. This creates a sort of "laser view" that you don't get with a huge pool cue as it does not allow to refine your line of aim.

Again, note that these are only my points of view and others might of course find that a pool cue is more adapted to the game and should be used as such. Experience should be your guide and the general rule of "whatever feels best for you" should be applied here.
Finally, I would like to note that Jimmy White famously refused to play pool with a pool cue, and always bought his snooker cue to pool tournaments. Think of this what you will.


Autofac with MEF integration

Question: I need help. I create Windows Service with Autofac container.
And I use MEF Integration service for create  several alternative components for my service.
For example:
Module 1
<code>  [Export(typeof(IClass1))]
  public class Class1 : IClass1
  {
        public void Show()
        {
              Console.WriteLine("Hallo from Class1");
        }
  }
</code>
Module 2
<code>  [Export(typeof(IClass2))]
  public class Class2 : IClass2
  {
        public void Show()
        {
              Console.WriteLine("Hallo from Class2");
        }
  }
</code>
Basic class for modules integration - example
<code>  class Program
  {
        private static IContainer Container { get; set; }

        static void Main(string[] args)
        {

              // Create your builder.
              var builder = new ContainerBuilder();

              /** find all modules in selected folder */
              var catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\modules", "*Module.dll");

              /** register finded modules */
              builder.RegisterComposablePartCatalog(catalog);

              builder.RegisterType<MyClass>().As<IMyClass>().SingleInstance();

              Container = builder.Build();

              var cls = Container.Resolve<IMyClass>();

              cls.Show();

              Console.WriteLine("Class ready. Press Enter");
              Console.ReadKey(true);
        }
  }

  class MyClass: IMyClass
  {
        private readonly IClass1 _class1;
        private readonly IClass1 _class3;

        private readonly IClass2 _class2;
        private readonly IClass2 _class4;

        public MyClass(IClass1 class1, IClass2 class2)
        {
              _class1 = class1;
              _class2 = class2;

              _class3 = class1;
              _class4 = class2;
        }

        public void Show()
        {
              _class1.Show();

              Console.WriteLine("Class1 ready. Press Enter");
              Console.ReadKey(true);

              _class2.Show();

              Console.WriteLine("Class1 ready. Press Enter");
              Console.ReadKey(true);
        }
  }

  internal interface IMyClass
  {
        void Show();
  }
</code>
In this example all work fine.This principle I use in my service. For test start and debug my service I use Service.Helper from Nuget packages repository.
Everithyng work fine too.
But. If i create install package in Advance installer and install my service in system (Windows 8.1 x64) service do not start.
Logging exception from service write System.ArgumentNullException in system Event log. Exception most likely in this line
builder.RegisterComposablePartCatalog(catalog);
Service do not load any modules from start folder. Access denied from service to his subfolder. Help please. Thanks.
Answer: Try Assembly.GetEntryAssembly().Location insted of Assembly.GetExecutingAssembly().Location

Autofac with MEF integration


Matrix semi-definite positive

Question: I have to show that given $G = A^{T}A$ and $E = B^{T}B$. the matrix $G$ or $E$ is semi-definite positive and also $G + E$.
Do you think this is correct?
Because the dot product is a definite positive bilinear form, we can show that:
$$\langle v,Gv\rangle = \langle v,A^{T}Av\rangle = \langle Av,Av\rangle \geq 0$$
And for $E + G$ we have using the formula above:
$$\langle (G+E)v,v\rangle = \langle Gv+Ev,v\rangle = \langle Gv,v\rangle + \langle Ev,v\rangle \geq 0$$
Answer: It's correct . To show that E+G is positive semidefinite you can also use the easy to show fact that the sum of two positive semidefinite matrices is also positive semidefinite .
When dealing with finite dimensional spaces , using the matrix notation $<u,v> == u^{T}v$ can make things a bit more clear.
Comment: Using the properly-typeset matrix notation $\langle u, v\rangle = u^T v$ will make things even more clear than that.
Comment: Well maybe is geographical question, but here, in switzerland, we use to use "brackets" notation and in mechanics the dot. Even if we understand the other ones, is easier for me to read it as I did.
Comment: Misha Lavrov - if you bake me some cookies , I will write as you please :)).

Matrix semi-definite positive


Selecting lag order for VAR and VECM

Question: I want to estimate two models, Vector Autoregression (VAR) and Vector Error Correction Model (VECM).
What is the correct way to choose lag length / lag order?
For the VAR model, I have selected the lag ($p=4$) using:

variables at first difference
statistical criterion  AIC
no evidence of autocorrelation or  heteroscedasticity in the residuals.

For the VECM model, I have selected the lag ($p=1$) using:

VAR with variables at level,
statistical criterion of AIC,
no evidence of autocorrelation or  heteroscedasticity in the residuals of VAR,
lag of VECM equal lag of VAR in level minus 1, VECM(0).

Is this methodology correct or in error?
Comment: See also [Optimal lag length in VECM using vars R package](http://stats.stackexchange.com/questions/81133/optimal-lag-length-in-vecm-using-vars-r-package?rq=1).
Answer: Your methodology seems fine.

From a theoretical perspective, it broadly agrees with recommendations in time series textbooks.
From an empirical perspective, your models have well-behaved residuals, so they are decent approximations of the data.

More generally, there is no methodology that is universally the best. Model selection should depend on the intended use of the model.

If you intend to do forecasting, a sensible lag order selection criterion is AIC. AIC tends to select the model (from the pool of candidate models) that yields the smallest squared forecast error 1 step ahead.
If you want to recover the true model (from a pool of candidate models that includes the true model), a sensible lag order selection criterion is BIC. Asymptotically it should select the true model with probability 1. However, the assumption that the true model is in the candidate pool may be very restrictive, especially when working with real world applications where models are approximations of the (very) complex reality.
Well-behaved residuals are desirable, but they do not necessarily suggest you have picked a good model for the underlying data generating process. It is always possible to construct a rich, flexible model that fits the data sufficiently well to produce well-behaved residuals. However, this does not make the model likely to be a good approximation of the data generating process. It fits well in sample but may not fit well out of sample, and it is normally the latter that we care about (either by intending to forecast it or to test some hypothesis about it).

(But of course, residual diagnostics should not be neglected; a particular pattern in ill-behaved residuals may indicate how the model could be changed for the better. Also, for hypothesis testing you need to account for autocorrelation or heteroskedasticity if it is present, e.g. by using HAC standard errors.)

Selecting lag order for VAR and VECM


Simplification of the exponential integral to a closed form

Question: Can the following integral be simplified to a closed form expression?
$$f = e^{yE}\int_{-z}^{z} \frac{e^{\Gamma \beta}}{\beta A + E} \,d\beta - e^{-yE}\int_{-z}^{z} \frac{e^{\xi \beta}}{\beta A + E}\, d\beta$$
I have tried solving the problem and I am getting solution in term of the exponential integral: $\int e^t/t\,dt = \operatorname{Ei}(t)$. Further, I tried approximating the exponential integral using the Taylor series expansion of $e^t/t$. However, the solution is quite cumbersome.
Is there a solution to the original integration or an approximation without using the $\operatorname{Ei}(t)$?
Comment: Are you supposed to know about exponential integrals ?
Comment: @ClaudeLeibovici Thank you for the solution you have provided below. I was looking for a closed form solution without the exponential integrals. Or any approximation of closed of exponential integrals.
Comment: Have a look to my edit.
Answer: Consider
$$I=\int \frac {e^{ax}} {bx+c}\,dx$$
Let $$bx+c=t\implies x=\frac{t-c}{b}\implies dx=\frac{dt}{b}$$ which makes
$$I=\frac{e^{-\frac{a c}{b}}}{b}\int \frac{e^{\frac{a t}{b}}}{t}\,dt$$ Make now $\frac{a t}{b}=y$ to end with something like
$$\int \frac {e^y} y \,dy=\text{Ei}(y)$$ Back to $x$,
$$I=\frac{e^{-\frac{a c}{b}} }{b}\,\text{Ei}\left(\frac{a c}{b}+a x\right)$$
Edit
In terms of approximation, for large values of $y$, you could use
$$\text{Ei}(y)=\frac{e^y}y\sum_{n=0}^\infty \frac {n!}{y^n}$$ and truncate it.
Similarly, for small values of $y$,
$$\text{Ei}(y)=\gamma+\log(y)+\sum_{n=1}^\infty \frac {y^n} {n \,n!}$$ which, I suppose, is what you used
Comment: @whn. Yes. Make that a Taylor series to $O(y^p)$ summing from $n=1$ to $n=p-1$.
Comment: By "and truncate it", do you mean truncate the summation?  For example, are you simply saying that one should just choose a max value of $n$ to sum over? As a native English speaker, the subject of "truncate" is not clear.
Comment: How do I figure out when to stop on the divergent series (large value approximation)?  If max n is too high  you'll overshoot the value.
Comment: @whn. For large or small values of $y$ ?
Comment: large values of $y$, the first one after **Edit**.
Comment: Okay, I think I figured it out.  The divergent series: $$\text{Ei}(y)=\frac{e^y}y\sum_{n=0}^\infty \frac {n!}{y^n}$$ follows a curve with the difference from value y based on N iterations (checked in code, and shown on wikipedia).  I can figure out when the difference switches from getting smaller to getting larger, and that allows me to figure out the most "optimal" place to stop iterating automatically. see https://en.wikipedia.org/wiki/Asymptotic_expansion#:~:text=In%20mathematics%2C%20an%20asymptotic%20expansion,the%20function%20tends%20towards%20a