How to import a variable from django into vue.js instance

Question: I want to import a variable from a django generated html page into my App.vue component.
My goal is to pass a String, which represent the user AuthGroup, eg. 'milkman', 'hairdresser' or 'supplier'
The error Message looks like this:

Module parse failed: Unexpected token (1:1)
You may need an appropriate loader to handle this file type, currently no loaders are configured to > process this file. See https://webpack.js.org/concepts#loaders
{% extends 'base.html' %}
| {% load render_bundle from webpack_loader %}
| {% load navtag %}

frontend.html
{% extends 'base.html' %}
{% load render_bundle from webpack_loader %}
{% load navtag %}

{% block head %}
<title>title</title>

{% endblock %}

[...]
{% block content_vue %}

         <app></app>

    {% render_bundle 'app' %}
{% endblock %}

I can't figure out how to modify webpack or find a way to import the variable from django into the vue project. FYI: The vue project is a small part of a large Django environment.
Answer: for now I use the user session and get the data via window into the vue environment:
// frontend.html

// 1. App.vue
async created() {
  store.dispatch('store/setTest')
}
// 2. in store
actions: {
  setTest({commit}) {
    commit('setToken')
  }
}
// 3. trigger mutation
mutations: {
  setToken(state) {
    state.token = testToken
  }
}
// 4. state
state: {
  token: '' // String from django is here
}

is there a better solution?


Split a group of people in half based on preference

Question: I'm a 3d Animation Tutor with very basic Python knowledge and have been bashing my head against a wall trying to code what I think could be a VERY beneficial script..
Any help would, including a simple point in the right direction would be very much appreciated. Thanks in advance.
Here is my scenario:
My class of 18 students is about to enter into the "group project" module.
This year I would like to split the class in half to keep the projects more manageable and also to encourage healthy competition.
The students have already filled out surveys in which they annotated their preference for working with all the other students by giving each a number between 0 and 5.
My idea is that I can use these surveys to mathematically calculate the best possible split in terms of preference.
Now I've made a very basic start in CodeSkulptor - a browser based python emulator.
In this prototype version I am starting with just 4 sample "students" - A, B, C and D.
Each student has given their opinions of the others and to keep things simple, their opinion of themselves is all set at 0, (though this could just as easily be any value, since you can't NOT work with yourself..)
Here is my psuedocode:

Create empty set "students" that will contain all students, i.e. [A,B,C,D]
Create an empty set "combinations" that will be filled with all of the possible combinations, i.e [((A,B),(C,D)),((A,C),(B,D)),((A,D)(B,C))]
define a class containing preference information for each student, once all the possible combinations have been determined, this information will be used to calculate the combination with the overall highest "Happiness"/"Morale"..
Create a function that cycles through all the possible combinations, returning them as lists of lists which get added to the combinations set.
( Not added yet ) Create a function that cycles through all the combinations in the set "combinations", and calculates overall "happiness" based off the preferences stored in the student class.
( Not added yet ) Create a function that prints the combinations with the highest happiness.

In this case it should print:
print"A,B/C,D = 7"

print"A,C/B,D = 10"

print"A,D/B,C = 15"

print"Highest possible split is A,D/B,C with overall happiness of 15!"

I'm kind of embarrassed to show the WIP.. but here it is:
http://www.codeskulptor.org/#user17_EEvOfHGg7AAZt1w_1.py
Or for those that would rather stay on this page:
people = set([])
combinations = set([])

class person:
    def __init__(self, name, A = 3, B = 3, C = 3, D = 3):
        self.name = name
        self.A = A
        self.B = B
        self.C = C
        self.D = D

    def get_name(self):
        return self.name

    def get_A(self):
        return self.A

    def get_B(self):
        return self.B

    def get_C(self):
        return self.C

    def get_D(self):
        return self.D

# make all the possible combinations
#def combine(people):
#combine any 2 given people into a new group

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

####[A,B,C,D]
people.add(person("A", 0, 1, 2, 4))
people.add(person("B", 3, 0, 3, 4))
people.add(person("C", 1, 5, 0, 2))
people.add(person("D", 3, 3, 2, 0))

combinations(people,2)

The combinations function - I actually lifted straight off the itertools documentation page, but I'm not exactly sure if it's working or even if this is the best way to split the groups.
I can't import itertools directly as CodeSkulptor only supports a few modules (math, random, time etc.).
I tried using actual python but it functions a whole lot differently than I'm used to.
I have learned many things in my research, such as that calculating something like this may take years for the computer to go through the 24310 different split possibilities..
Another option would be for the code to just generate 100 random split possibilities at a time and I could keep track of the highest result each runthrough.
All in all, it's been a fun script to try and figure out - actually a little too fun.
I can't physically tear myself away from it, even though I've stopped making actual progress.
So please, if someone could hint/show me where to go from here I would very much appreciate the help.
Cheers,

Eli
Comment: Are you actually splitting the class in half (with groups of 9), or are you splitting the class into groups of two?
Comment: In half ( two groups of 9 ) This was mentioned in the second paragraph. and, no - ( (A,),(B,C,D) ) would be invalid
Comment: I suggest looking at a builtin module called itertools is a very helpful tool. I think you may find [itertools.combinations](http://docs.python.org/2/library/itertools.html#itertools.combinations) in specific to be very helpful
Comment: I'd really recommend using the standard Python implementation. Doing it on CodeSkulptor will result in learning bad habits and duplicating a lot of standard library code. Just look at that big, confusing `combinations` function that could have been replaced with `from itertools import combinations`.
Comment: I agree, and have been attempting to transition into regular python. I have looked at itertools and was hoping to work out the underlying mechanics of itertools.combinations for myself before relying on it and perhaps taking it for granted. I can't say that I have figured it out just yet however...
Comment: Brute-forcing 24310 possibilities is entirely feasible. Unless CodeSkulptor is orders of magnitude slower than CPython, you shouldn't have a problem with that.
Answer: Completed
from itertools import combinations
import numpy as np
import string

    def get_maxhappiness(results):
        max_happiness = max(results)
        index = results.index(max_happiness)

        #Printing the result! (There may be more than one best result, but this will only show 1)
        print "Optimal Groups: Point value of",max_happiness,"\n",groups[index],"\n", anti_groups[index]
        results[index] = 0
        return results

def calculateHappiness(points,group):
    happiness = 0
    for i in range(len(group)):
        person_prefs = points[group[i]]
        others = group[i:] + group[:i]
        for other in others:
            happiness += person_prefs[other]
    return happiness

if __name__ == "__main__":
    people = string.letters[26:44]
    groups = list(combinations(people,9))
    anti_groups = [tuple(set(people).difference(set(x))) for x in groups]

    #Making fake results
    survey_results = dict()
    for person in people:
        results = dict(zip(people,np.random.randint(0,10,size=(len(people)))))
        results[person] = 0
        survey_results[person] = results

    #Printing Survey Results
    for name,values in survey_results.items():
        print "Student:", name, "has preferences:", values

    #Calculating happiness for every group
    results = []
    for i in range(len(groups)):
        results.append(calculateHappiness(survey_results,groups[i])+calculateHappiness(survey_results,anti_groups[i]))
    #Finding the largest happiness value
    top_n = 5
    while top_n > 0:
        results = get_maxhappiness(results)
        top_n -= 1

Yields:
...

Student: N has preferences: {'A': 5, 'C': 5, 'B': 0, 'E': 0, 'D': 3, 'G': 6, 'F'
: 8, 'I': 8, 'H': 3, 'K': 1, 'J': 4, 'M': 4, 'L': 9, 'O': 0, 'N': 0, 'Q': 3, 'P'
: 2, 'R': 2}
Student: Q has preferences: {'A': 9, 'C': 0, 'B': 3, 'E': 4, 'D': 3, 'G': 2, 'F'
: 2, 'I': 7, 'H': 5, 'K': 2, 'J': 3, 'M': 0, 'L': 9, 'O': 2, 'N': 5, 'Q': 0, 'P'
: 2, 'R': 0}
Student: P has preferences: {'A': 2, 'C': 3, 'B': 0, 'E': 9, 'D': 3, 'G': 6, 'F'
: 7, 'I': 1, 'H': 7, 'K': 9, 'J': 7, 'M': 4, 'L': 8, 'O': 2, 'N': 6, 'Q': 5, 'P'
: 0, 'R': 7}
Student: R has preferences: {'A': 5, 'C': 3, 'B': 7, 'E': 1, 'D': 5, 'G': 6, 'F'
: 1, 'I': 6, 'H': 9, 'K': 9, 'J': 3, 'M': 6, 'L': 8, 'O': 8, 'N': 5, 'Q': 1, 'P'
: 3, 'R': 0}
Optimal Groups: Point value of 709
('A', 'B', 'F', 'G', 'J', 'K', 'O', 'Q', 'R')
('C', 'E', 'D', 'I', 'H', 'M', 'L', 'N', 'P')
(x4)

Comment: Nice, this is a very efficient start. I had wondered about using dictionaries over defining a class. Good to know it's how others would do it. so this gets me all the way up to step 4. I will attempt to push on past here into the "possible combinations" step later on when I have access to proper python ( not codeskulptor )
Comment: So, I think the code in my post now works, but I would welcome people to test it out for accuracy because I haven't.
Comment: Wow! Thanks heaps :D I managed to get Python 2.7.5 up and running on my work computer without admin rights, but unfortunately it doesn't come packaged with numpy. Just working on getting that installed now.
Comment: Tested it, works perfect thanks! This is exactly what I needed. I'll test it tomorrow with my actual survey results.
Comment: Great. If you have any further questions about the code, don't hesitate to ask.
Comment: Just wondering how hard it would be to make it print several results? Lets say the 5 highest and their total happiness scores
Comment: could "max_happiness" instead .pop from max(results), and then I could continue to do this for the next best and so on?
Comment: What you can do is get the highest value index. change that to 0 after you grab it and then redo finding the max. The way I'm finding it uses the fact that the indices are matching the group indices. Not popping them out of hte list would be optimal.
Comment: @EliTucker I made the edit to print out several results in order of value, but I haven't tested it.
Comment: I'm getting an error every time. "*** can't assign to function call(C:/Users/Eli/Desktop/groupSplitter2.py, line 11)"

which refers to the line:

    results(index) = 0

I think I know what it's trying to do here, but it doesn't seem to want to change the value of max_happiness for some reason I can't quite figure out.
Comment: Oh sorry, that's my fault. Indexing in python is with []'s not ()s. ()s are normally function calls.
Comment: awesome :) Works perfectly thanks! One last question and then I'll leave you alone ( probably... ): If I have a split already in mind, would there be a way of pushing that backwards through the script to find out the total happiness?
Comment: Run it through calculateHappiness (both the group and antigroup). calculateHappiness(survey_results,group) + calculateHappiness(survey_results, antigroup)
Comment: One year later, I have decided to try this process again, but this time I want to split the class into 3 groups. I looked back over the script, but due to the "anti_group" section, I'm certain it cannot do this in it's current state.. I'm going to try rebuilding it myself, but any suggestions would be very much appreciated. Cheers,


Why is RAM usage so high on an idle server?

Question: I'm investigating a server used for scientific data analysis. It's running RHEL 6.4 It has almost 200GB of RAM. It's been running very slowly for users via SSH, and after some poking around I quickly noticed that the RAM usage was sky-high. What's odd is that even in an idle state it's still using a ton of RAM:

I also looked via htop and I can't see that any running process is using more than 0.1% of the RAM. So I wonder what's going on? Right now the only user-initiated process running is an rsync between two NFS-mounted shares.
I tried rebooting the server and it was much more responsive for a few minutes, but then memory usage shot up again.
Is there any way I can pinpoint why memory usage is so high?
Comment: http://www.linuxatemyram.com/
Answer: It's high because that saves effort. It takes effort to make memory free. And if you do that, it just takes effort to make it used again. So, to save effort, modern operating systems only make memory free if they have absolutely no other choice.
If you're thinking "I want memory free now so I can use it later", banish that thought from your mind. Memory does not have to be free now to use it later. It can be used now and also be used later. So there's no painful tradeoff here. Using memory is a pure win.
Whatever your problem is, high memory usage is not it. That's a sign of a normally functioning system.
Comment: I should already know this. I guess I was confused because my other servers don't exhibit this pattern. :) Thank you for the helpful and patient answer!
Answer: About 190G of your memory is being used by the filesystem cache, which normally isn't really a problem.
Look at the cached field in top.
Answer: you can also run
echo 3 /proc/sys/vm/drop_caches

if you feel antsy ;)


AVAudioPlayer intermittently wont play sound

Question: I have a music player app on ipad. I download m4a files from a server and save them to doc dir. I also use Core Data to save the playlist info. I have over 1000 songs and my table loads perfectly and plays perfectly. I can play the playlists thru with no problems. BUT... every once in a while one song does not play. NO SOUND! I can press the cell to play the song or goto the next song and everything works again. So this problem is random and intermittent. It's never the same song that gets stuck. I cant give you any debug statements, cus like I said, it's so random and intermittent that it's hard to duplicate. I'm wondering if it's an ARC problem. Please help, as this app is going to production very soon.
Relative code:
<code>// setup music session
NSError *error = nil;
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &error];
[[AVAudioSession sharedInstance] setActive: YES error: &error];

NSLog(@"error AVAudioSession:%@", [error description]);

AVAudioPlayer *player = [[AVAudioPlayer alloc] init];
NSString *fullPath = fullPath = [self.docDirPath stringByAppendingPathComponent:filename];
NSURL *musicFileURL = [[NSURL alloc] initFileURLWithPath:fullPath];

// getting song from docDir
    NSData *songData = [[NSData alloc] initWithContentsOfURL:musicFileURL];
    player = [player initWithData:songData error:&error];
    NSLog(@"error player reg:%@", [error description]);

//NSLog(@"playing %@ at index:%d", musicFileURL, index);

    self.appPlayer = player;

    [self.appPlayer prepareToPlay];
    [self.appPlayer setEnableRate: YES];
    [self.appPlayer setDelegate: self];
    [self.appPlayer play];
</code>
Answer: If you use ARC a good point to start to solve your problem is to watch the reference counting in Instruments. I had the problem as well. None of my files were playing. I've seen in Instruments that the AVAudioPlayer instance was released BEFORE the sound started to play. At least it looked like it was released. After i've stored the reference of AVAudioPlayer in the core data model the bug was fixed! In another project without ARC the same code did work without storing the reference.
Comment: Thank you for answering my Q after so long. Indeed my problem was related to releasing before it was supposed to.
Answer: or you can try to use strong instead of retain in the property declaration
@property(nonatomic, strong) AVAudioPlayer *player;


Drush Error: no database record could be found after failed attempt of sql-sync

Question: I was pushing our latest version of the site from our development environment to our live site (located on the same server). But unfortunately our web server ran into memory issues which prevented the move. We opened up access to more space but now SQL-sync refuse to function.
I assumed that we had issues with the database being corrupt so I replaced the database with our backup. But this did not help.
The development environment seem to work really well but I am very poor with Drush/SQL so I got a hard time understanding the error messages I get when testing the alias and site config. The Dev site work well while the live site is down and I would appreciate any advice on likely sources of the error.
The Dev alias that work well
sigvard@server1:~$ drush @mysite.dev status
 Drupal version                :  7.26
 Site URI                      :  dev.mysite.org
 Database driver               :  mysql
 Database hostname             :  localhost
 Database username             :  mysite_dev
 Database name                 :  website_mysite_dev
 Database                      :  Connected
 Drupal bootstrap              :  Successful
 Drupal user                   :  Anonymous
 Default theme                 :  mysite
 Administration theme          :  seven
 PHP configuration             :  /etc/php5/cli/php.ini
 Drush version                 :  4.5
 Drush configuration           :
 Drush alias files             :  /usr/share/drush/includes/../aliases/mysite.
                                  aliases.drushrc.php
                                  /home/sigvard/.drush/aliases.drushrc.php
 Drupal root                   :  /var/www/mysite_dev
 Site path                     :  sites/default
 File directory path           :  sites/default/files
 Private file directory path   :

Alias of the live site
sigvard@server1:~$ drush @mysite.live status
include_once(/var/www/mysite/sites/default/settings.php): failed to [warning]
open stream: Permission denied in drupal_settings_initialize() (line
717 of /var/www/mysite/includes/bootstrap.inc).
include_once(): Failed opening                                       [warning]
'/var/www/mysite/sites/default/settings.php' for inclusion
(include_path='.:/usr/share/php:/usr/share/pear') in
drupal_settings_initialize() (line 717 of
/var/www/mysite/includes/bootstrap.inc).
 Drupal version         :  7.26
 Site URI               :  mysite.org
 Default theme          :  garland
 Administration theme   :  garland
 PHP configuration      :  /etc/php5/cli/php.ini
 Drush version          :  4.5
 Drush configuration    :
 Drush alias files      :  /usr/share/drush/includes/../aliases/mysite.aliases
                           .drushrc.php /home/sigvard/.drush/aliases.drushrc.php
 Drupal root            :  /var/www/mysite
 Site path              :  sites/default
 File directory path    :  sites/default/files

sql-conf of the dev site
sigvard@server1:~$ drush @mysite.dev sql-conf
Array
(
    [database] => website_mysite_dev
    [username] => mysite_dev
    [host] => localhost
    [port] =>
    [driver] => mysql
    [prefix] =>
)

sql-conf attempt on the live site
sigvard@server1:~$ drush @mysite.live sql-conf
include_once(/var/www/mysite/sites/default/settings.php): failed to [warning]
open stream: Permission denied in drupal_settings_initialize() (line
717 of /var/www/mysite/includes/bootstrap.inc).
include_once(): Failed opening                                       [warning]
'/var/www/mysite/sites/default/settings.php' for inclusion
(include_path='.:/usr/share/php:/usr/share/pear') in
drupal_settings_initialize() (line 717 of
/var/www/mysite/includes/bootstrap.inc).

Answer: I wonder if it's a file system permission on your live site. Are you sure /var/www/mysite/sites/default/settings.php on the live site is readable by your web server?
(Also, unrelated to this but Drush 4.5 is getting pretty old so if possible you might want to update it.)
Comment: Yeah, Drush probably needs to be updated as well, looks like it doesn't get updated together with other modules. But settings.php should be readable.
Comment: I was hoping that updating Drush would solve the issue but:
Install location /usr/share/drush already exists. Do you want to overwrite it? (y/n): y
Project drush (7.x-1.x-dev) downloaded to /usr/share/drush.                                                   [success]
Drush successfully updated to version 7.x-1.x-dev.                                         Project drush contains 8 modules: drush_pm, drush_pm_svn, drush_pm_wget, drush_sql, drush_pm_cvs, drush_simpletest, drush_tools, drush.
mylogin$ drush site-alias
E: Could not locate a Drupal installation directory. Aborting. @Mark G
Answer: The initial error was caused by a server error filling the allocated memory and crashing the sync.
The corrupt server was a nightmare so in the end I just wiped the database and recreated the site from a backup using Drush.


Exporting SWT Image into PDF using Java iText API

Question: I have a an SWT image I want to export this image into a pdf file using iText API.
I have tried saving this image on the disk and then using the path of image to export
it to the pdf, this takes lots of time to generate the pdf.
I have also tried converting the SWT image into AWT image and then exporting it into the
pdf, this approach takes even more time to generate pdf.
Another approach I have been trying is to convert the raw data of image into
jpeg byteArrayOutputStream using ImageLoader Object as shown below :
ImageLoader tempLoader = new ImageLoader();
tempLoader.data = new ImageData[] {
    image.getImageData()
};
ByteArrayOutputStream bos = new ByteArrayOutputStream();
tempLoader.save(bos, SWT.IMAGE_JPEG);

Now I am using this ByteArrayOutputStream as input to
OutputStream outStream = new FileOutputStream(selectedPathAndName);
Document document = new Document();
document.setMargins(0,0,0,0);
document.setPageSize(new Rectangle(0,0,width,height));
PdfWriter.getInstance(document, outStream);
document.open();
com.itextpdf.text.Image pdfImage = com.itextpdf.text.Image.getInstance(bos.toByteArray());
document.add(pdfImage);
document.close();

This generates pdf files with the width and height I have set, but the page seems to be empty.
Any suggestions or any other approach is most welcome.
Thank you,
Answer: It looks your page sizes are zero, try setting them to something like A4 in the constructor.
Document document = new Document(PageSize.A4, 50, 50, 50, 50);


Como corrigir "dancinha" (flicker) de webfont de ícones ao fazer reload da página?

Question: Ao fazer reload da página os ícones de um webfont são carregados somente depois do carregamento do CSS e isso ocasiona uma "dancinha" no texto.
Veja abaixo o comportamento indesejado do ícone quando se faz reload da página:

O código fonte do meu CSS:
@font-face {
    font-family:"icons";
    src:url("../fonts/icons.eot");
    src:url("../fonts/icons.eot?#iefix") format("embedded-opentype"),
        url("../fonts/icons.woff") format("woff"),
        url("../fonts/icons.ttf") format("truetype");
    font-weight:normal;
    font-style:normal;
}

.i {
    font-family:"icons";
    display:inline-block;
    vertical-align:middle;
    line-height:1;
    font-weight:normal;
    font-style:normal;
    speak:none;
    text-decoration:inherit;
    text-transform:none;
    text-rendering:auto;
    -webkit-font-smoothing:antialiased;
    -moz-osx-font-smoothing:grayscale;
}

.i--menu:before {
    content:"\f117";
}

Comment: Esse problema é chamado de `flicker` normalmente. O Paul Irish fez um post sobre o assunto: [`Fighting the @font-face FOUT`](http://www.paulirish.com/2009/fighting-the-font-face-fout/) Dá uma olhada também no seguinte material: [`Introduction to the Google WebFont Loader`](http://www.position-absolute.com/articles/introduction-to-the-google-webfont-loader-and-how-to-avoid-font-face-text-flickering-with-it/)
Comment: Bruno, qual é a fonte que você está carregando nesse exemplo?
Comment: @Romulo é um custom utilizando o grunt-webfont.
Answer: Este flick acontece porque a sua fonte ainda não carregou, nas minhas aplicações em costumo usar um pre-loading, assim esses "problemas" não ficam visiveis para o usuário final.
Se o pre-loading não for uma opção você também pode deixar o tamanho deste elemento fixo (width, height), assim mesmo que a imagem não tenha sido carregada o elemento ocupara o espaço definido para ele.
Answer: Você pode tentar uma destas opções <link> com prefetch dentro de :
<!doctype html>

        <link rel="prefetch" href="(url)">

Então sendo as fontes CSS você deverá adicionar assim no prefetch:
<!doctype html>

        <link rel="prefetch" href="fonts/icons.eot">
        <link rel="prefetch" href="fonts/icons.eot?#iefix">
        <link rel="prefetch" href="fonts/icons.woff">
        <link rel="prefetch" href="fonts/icons.ttf">

Eu adicionei o fonts/icons.eot?#iefix pois o sinal de ? faz a url ser considerada outra.

Diferenças
Existe um método chamado prerender e isto confunde algumas pessoas, segue as diferenças:

prefetch (pré carregar):
Isto é usado para buscar e fazer cache dos "resources" para que depois possa ser usado na navegação especificação HTML5, talvez este já atenda o caso do uso das fontes.

Nota: Aparentemente não é suportado pelo Safari (Mac OSX) ainda
Lista de navegadores com suporte:

Internet Explorer 11+
Edge 12+
Chrome 8+ e Opera 15+ (coloquei junto pois usam a mesma tecnologia, o Chromium)
Firefox 2+

prerender (pré renderizar):
É usado para pré-renderizar uma página completa que provavelmente será usada em uma próxima navegação.

Nota: O problema do prerender é que ele ainda não é suportado pelo Firefox e Safari
Lista de navegadores com suporte:

Internet Explorer 11+
Edge 12+
Chrome 49+ e Opera 15+ (coloquei junto pois usam a mesma tecnologia, o Chromium)

Suporte atual:
Através dos seguintes links acompanhe as atualizações do navegadores:

http://caniuse.com/#feat=link-rel-prefetch
http://caniuse.com/#feat=link-rel-prerender


Generalized Modal Matrix of a square matrix

Question: How to find the generalized eigen vectors and canonical basis for the following matrix A?
\begin{bmatrix}
0 & 4 & 2\\
-3 & 8 & 3\\
4&-8& -2
\end{bmatrix}
The eigen value is 2 with algebraic multiplicity 3 and geometric multiplicity is 2. How to find generalized eigen vector in this case? I have solved problems where algebraic multiplicity 3 and geometric multiplicity is 1, but in this question I am stuck due to the geometric multiplicity which is two.
Comment: What do you mean by "modal matrix" ?
Comment: A nonsingular matrix whose columns are Eigenvectors
Answer: In fact Jordan Canonical Form (JCF) gives the "pseudo diagonalization" you are looking for under the form :
$$A=VJV^{-1}$$
where
$$V=\pmatrix{-2&1&1\\-3&0&0\\4&0&1}$$
(whose columns are the eigenvectors you are looking for) and
$$J=\left(\begin{array}{cc|c}2&1&0\\0&2&0\\ \hline 0&0&2 \end{array}\right)$$
(please note the $2$s on the diagonal and the two "Jordan blocks" on the diagonal, one $2 \times 2$, the other $1 \times 1$).
I have used a software (MATLAB) for obtaining this decomposition but it can be done by hand.
For a hand calculation, see this similar example : How to order the basis vectors that put a matrix in jordan canonical form


why java regex pattern error comes in windows but not in solaris environment

Question: Why does this string problem occur only in windows?
How do I replace the file seperator?
Both of the below methods are not working for me.
The error is:

java.util.regex.PatternSyntaxException: Unexpected internal error near
  index 1.

String s ="pathoffile";

if(File.separator.equals("\\"))
   s= s.replaceAll(File.separator,"/");

if(File.separator.equals("\\"))
   s= s.replaceAll("\\","/");

Comment: You can also use forward slashes everywhere, the JVM on windows gets it right. Life is easier that way.
Answer: You need to escape a backslash in a regular expression twice:
 s= s.replaceAll("\\\\","/");

Once, to put a backslash into a String.
Twice, because regular expressions have special character classes, like \d, and those start with a backslash, so a literal backslash is \\.
But what you should probably really do is not use a regular expression at all to just replace single characters:
s = s.replace('\\', '/');

Comment: @sunleo just by seeing your profile, don't forget to mark this post as an answer by clicking on the check next to the text (and do the same for your other questions). There is a wait time of 15 minutes to mark the post as answer.
Comment: sorry am new so i didn't do that now i did that is this ok ? Please help me.
Comment: @sunleo don't worry, we were new once upon a time and learned in the way.


What is the number of Latin rectangles given the number of reduced Latin rectangles?

Question: My PhD supervisor called the following result something along the lines: "The theorem in the theory of Latin squares with the most incorrect proofs" (then, to my embarrassment, proceeded to point out an error in my "proof" at the time).  I'll pose proving it as a problem.
Definition:  A $k \times n$ *Latin rectangle* is a $k \times n$ matrix with symbols from $\{1,2,\ldots,n\}$ for which each symbol occurs exactly once in each row and at most once in each column.  For example:
1 2 4 3
2 3 1 4
4 1 3 2

is a $3 \times 4$ Latin rectangle.
Definition:  A Latin rectangle is called reduced if the first row is $(1,2,\ldots,n)$ and the first column is $(1,2,\ldots,k)^T$.
The above Latin rectangle is not reduced, but this one is:
1 2 3 4
2 3 4 1
3 4 1 2

Let $L_{k,n}$ be the number of $k \times n$ Latin rectangles.  Let $R_{k,n}$ be the number of reduced $k \times n$ Latin rectangles.
Theorem:  For all $1 \leq k \leq n$, \[L_{k,n}=\frac{n!(n-1)!}{(n-k)!}R_{k,n}.\]

Problem:  Prove it (and double-check your proof).
Answer: Consider the following reduction algorithm:

Move the unique column in which $1$ is the first element to the left (extract it and put it as the first column).
Apply the unique injection that maps the $j$th element in the first column to $j$.
Apply the unique permutation on the $n-1$ columns to the right of the first column which makes the first row $1\ldots n$.

Taking our steps in reverse to unscramble a reduced form, we have $(n-1)!$ choices in the third step, $(n-1)^{\underline{k-1}} = (n-1)!/(n-k)!$ choices in the second step, and $n$ choices in the first step, to a total of $$(n-1)!\frac{(n-1)!}{(n-k)!}n = \frac{n!(n-1)!}{(n-k)!}.$$
More formally, we could define

$A_{k,n}$ as the number of Latin rectangles whose upper left value is $1$.
$B_{k,n}$ as the number of Latin rectangles whose left-most column is reduced.

Then we show the following:
$$\begin{align*} L_{k,n} &= n A_{k,n}, \\ A_{k,n} &= \frac{(n-1)!}{(n-k)!} B_{k,n}, \\ B_{k,n} &= (n-1)R_{k,n}. \end{align*}$$
Comment: Oh, I think you've got it!  Some small points:  Step 2 might be better phrased as "Apply one of the (n-k)! symbol permutations that maps the j-th element of the first column to j" (it's not unique when k<=n-2) and $B_{k,n}=(n-1)! R_{k,n}$.
Comment: By the way, the standard trap is to go straight from $L_{k,n}$ to $R_{k,n}$ ignoring the possibility of autotopisms (permuting rows/columns/symbols so as to return the original Latin rectangle).  But, you establish three equalities here that each individually avoid that trap.
Answer: So I'll give the proof I'm used to.  It relies on what (I've been led to believe) Brendan McKay coined the "switching principle":  Suppose you have a bipartite multi-graph, with parts $A$ and $B$.  Suppose every vertex in $A$ has degree $c$ and every vertex in $B$ has degree $d$.  Then $Ac=Bd$.
We say a Latin rectangle is normalised if the first row is $(1,2,\ldots,n)$.  Let $K_{k,n}$ be the number of $k \times n$ normalised Latin rectangles.  By permuting the columns of a $k \times n$ Latin rectangle, we generate $n!$ distinct Latin rectangles of which exactly one is normalised.  Hence $L_{k,n}=n! K_{k,n}$.
We will now prove the identity $K_{k,n}=\frac{(n-1)!}{(n-k)!} R_{k,n}$.
We take A to be the set of all normalised $k \times n$ Latin rectangles and take B to be the set of all reduced $k \times n$ Latin rectangles.  [Actually, B is a subset of A, so this is strictly speaking a bit suspect, but this can be overcome this problem by labelling (I won't do this here, as it's a bit messy).]
Let $G$ be the group of permutations of $\{1,2,\ldots,n\}$ that fix 1.  Given any reduced Latin rectangle $L \in B$ and $\alpha \in G$ we can construct a normalised Latin rectangle by: starting from $L$, permute the columns by $\alpha$, then permute the symbols by $\alpha$.  Call this Latin square $L_\alpha$.
We construct the bipartite multigraph by: for every $L \in B$ add an edge from $L$ to $L_\alpha$ for all $\alpha \in G$.  Since $L_\alpha$ might equal $L_\beta$, the graph might not be simple.
Every vertex in $B$ has degree $(n-1)!$.  So it is sufficient to show that every vertex in $A$ has degree $(n-k)!$.  There is an edge between $L=(l_{ij}) \in A$ and some vertex in $B$ for each permutation $\alpha \in G$ satisfying $\alpha(i)=l_{i1}$ for all $1 \leq i \leq k$.  There are $(n-k)!$ such permutations, and hence every vertex in $A$ has degree $(n-k)!$.


Implementing a staircase within a C program

Question: I just started with C programming and have some difficulty implementing a program which is giving a staircase with 'Height' amount of steps.
#include <cs50.h>
#include <stdio.h>

int main(void)

{
  int height;

    do
    {
        height = get_int("Height: ");
    }
    while(height > 8 || height == 0 || height < 0);

  int width = 0;
  int length = height;

  while(width < height)
  {
    printf(" ");
    printf("@");
    for(width = 0; width < height; width++)
      {
        printf("\n");
      }

  }
}

The first lines with the Height are working, but I have difficulties with actually writing a staircase. I wanted something like this or similar to this.
Height: 3
@
 @
  @

I just want to learn how to implement something like this if I face a problem like this in the future. If somebody could help me further I would really appreciate it!
Comment: The duplicated question linked here (How do I check out a remote Git branch?) does not match up with @Hyakkimaru's question?
Comment: Stop vandalizing your own question.   You have done this twice now.
Answer: #include <stdio.h>

int main(void)
{
    int height = 5;
    for(int i=0; i<height; printf("%*s\n", ++i, "@"));
}

Output:
Success #stdin #stdout 0s 5572KB
@
 @
  @
   @
    @

Comment: It's a homework question... it's probably better to not just solve it for OP but guide them.
Comment: @einpoklum it's not really a homework question, but more like an extra question if you want to learn more. I won't copy it, but just want to know how it's  done. So don't worry :)
Comment: @abelenky Just curious, what does "%s\n" do. I know that \n is to write a new line, but what about %s.
Comment: @Hyakkimaru: You should read about what `printf()` [actually does](https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm). You're using it in a degenerate form, and could really just replace your uses of it with `puts()` calls.
Answer: I see three issues here:

You're printing newlines (\n) instead of spaces ( ).
Why print the single space character?
You're printing the "@" before (what should be) the spaces.
Print a newline after the spaces and the @.

Also... the staircase's width is always equal to its height; it's just the line you're printing that's advancing... that's a bit confusing.
Answer: This works:
#include <stdio.h>

int main() {
    // gets height input - replace with your get_int method
    int height;
    printf("Height: ");
    scanf("%i",&height);
    // loop over all the steps: 0 - height
    for (int i = 0; i < height; i++) {
        // add a space i number of times (where i is our current step number and so equal to width)
        // notice that if we take top left as (0,0), we go 1 down and 1 right each time = current step
        for (int j = 0; j < i; j++) {
            printf(" ");
        }
        // finally, after the spaces add the character and newline
        printf("@\n");
    }
    return 0;
}

Comment: Just curious what does the 'scanf 'function do and what is meant with '%d'
Comment: It is just grabbing the input. Declaring a variable, then passing its address to the function. This reads the standard inputs and passes its value into the variable at the given address (height in this case). %d is just stating the data type (decimal). I changed it now to %i which is integer


Select de duas tabelas sem repetir dados

Question: Tenho duas tabelas, uma de utilizadores e outra de fotos onde cada linha contem o id de utilizador da respetiva foto.
Quero selecionar os dados de utilizador e pegar as fotos pelo id de utilizador da tabela fotos.
Desta maneira ele retorna me os dados duplicados da tabela utilizador porque o utilizador contém varias fotos na tabela fotos.
Como poderei apenas pegar uma vez os dados do utilizador(tabela user) e  todas as fotos a que ele pertencem da fotos(tabela photo), que o utilizador(user_id) contém na tabela photos?
$sql = "SELECT  u.id, u.username, u.genero, u.idade, u.local, u.descricao, p.user_id, p.location

FROM user AS u

INNER JOIN photos AS p

ON u.id=p.user_id

";

Comment: David você já tentou usar o "select distinct"
Comment: já sim,mas o retorno é o mesmo
Comment: Mas você quer as fotos, certo? Se você quer as fotos e precisa do local delas `p.local` então ao fazer o join você vai ter que ter o dados do usuário para cada linha. Pensa no mundo real, cada foto tem um user, logo, cada linha do SQL vem uma foto diferente e cada uma delas tem um user, só que no seu caso o user é o mesmo...
Comment: Eu entendi que ele não queria as fotos, mas a quantidade. Entendi isso por essa frase retirada da pergunta: "e a totalidade das fotos(tabela photo) que o utilizador(user_id) contém na tabela photos".
Comment: @cantoni, eu percebi isso também, mas também vi o `p.local` ali, aí resolvi deixar o comentário para ver qual das duas coisas ele precisa na verdade. No caso a totalidade que ele quis dizer pode ser todas as fotos e não um count... Como você já tinha colocado o count na resposta eu só falei do caso do `p.local`
Comment: @Ricardo queria apenas a informação do utilizador e todas as fotos do próprio utilizador. So as fotos se podem repetir porque o utilizador pode ter várias fotos.
Comment: David, você quer o total de foto apenas, tipo, utilizador david tem 50 fotos ou quer os detalhes de todas as fotos?
Comment: o `p.location` é o diretorio das fotos, não tem problema. elas sao exibidas com a query q eu tenho. so que para cada linha de foto ele duplica os dados do utilizador
Comment: @ricardo quero receber as informações do utilizador e todas as fotos que pertencem a ele. Essa query, retorna as informações do utilizador duplicados porque ele tem 2 fotos, por exemplo. Se o utilizador tiver 4 fotos, vêm as 4 fotos mais 4x o username, por ex.
Answer: Se o que você deseja saber são os dados do utilizador e a quantidade de fotos que existe pra cada um, então esse SQL deve resolver:
SELECT  u.id, u.username, u.genero, u.idade, u.local, u.descricao, count(*)
FROM user AS u
INNER JOIN photos AS p
ON u.id=p.user_id
GROUP BY u.id, u.username, u.genero, u.idade, u.local, u.descricao

Answer: Estou colocando uma resposta porque no comentário vai ficar muito ruim fazer a tabela que quero colocar de exemplo.
O que você está dizendo que é um problema na verdade é o "certo". Vamos a um exemplo pratico:
Utilizador Ricardo tem 5 fotos:
Ao fazer o SQL o retorno é:
u.id   u.username   p.user_id   p.location
1      Ricardo      1           (local foto1)
1      Ricardo      1           (local foto2)
1      Ricardo      1           (local foto3)
1      Ricardo      1           (local foto4)
1      Ricardo      1           (local foto5)

Isso é o resultado atual:
O que você está pedindo é para ficar assim:
u.id   u.username   p.user_id   p.location
1      Ricardo      1           (local foto1)
null   null         1           (local foto2)
null   null         1           (local foto3)
null   null         1           (local foto4)
null   null         1           (local foto5)

Isso não seria o correto.
Se você quiser somente os dados das fotos faz um SQL direto nas fotos:
select * from photos where user_id = 1

Não é errado ele retornar os dados duplicados se você faz o join das duas tabelas.
Entendeu?
Comment: Ok, isso esta certo. Mas eu também quero receber a informação do utilizador.

selecionar o utilizador id=1 e receber todas as fotos que existem do utilizador na tabela photos($user_id=1).
Comment: O seu SQL da pergunta fazer exatamente o que você está dizendo, traz tudo do utilizador e pegar todas as fotos dele, e vem no formado da primeira tabela dessa resposta, que você acabou de dizer (Ok, isso esta certo). Concorda?
Comment: Sim, o SQL da minha pergunta retorna tudo. As informações do utilizador e as fotos todas que pertencem ao utilizador. Como no seu primeiro exemplo. Ele tem 5 fotos e repete 5x o username
Comment: Então, entendeu que o que você tem é o correto?
Comment: Para ele não repetir eu teria que fazer uma query so para a saida do utilizador e então fazer uma outra query para selecionar as photos do utilizador que saiu na primeira query?
Comment: Isso mesmo. Agora, quanto ao certo ou errado de fazer duas consultas ou uma só como está vai de cada um.
Answer: use o select distinct.
$sql = "SELECT DISTINCT u.id, u.username, u.genero, u.idade, u.local,u.descricao, p.user_id, p.location

FROM user AS u

INNER JOIN photos AS p

ON u.id=p.user_id

";


Create image from ArrayBuffer in Nodejs

Question: I'm trying to create an image file from chunks of ArrayBuffers.
all= fs.createWriteStream("out."+imgtype);

for(i=0; i<end; i++){
    all.write(picarray[i]);
}

all.end();

where picarray contains ArrayBuffer chunks. However, I get the error  TypeError: Invalid non-string/buffer chunk.
How can I convert ArrayBuffer chunks into an image?
Comment: Possible duplicate of [How to write a file from an ArrayBuffer in JS](http://stackoverflow.com/questions/31581254/how-to-write-a-file-from-an-arraybuffer-in-js)
Answer: Have you tried first converting it into a node.js. Buffer? (this is the native node.js Buffer interface, whereas ArrayBuffer is the interface for the browser and not completely supported for node.js write operations).
Something along the line of this should help:
all= fs.createWriteStream("out."+imgtype);

for(i=0; i<end; i++){
    var buffer = new Buffer( new Uint8Array(picarray[i]) );
    all.write(buffer);
}
all.end();

Answer: after spending some time i got this, it worked for me perfectly.
as mentioned by @Nick you will have to convert buffer array you recieved from browser in to nodejs Buffer.
var readWriteFile = function (req) {
    var fs = require('fs');
        var data =  new Buffer(req);
        fs.writeFile('fileName.png', data, 'binary', function (err) {
            if (err) {
                console.log("There was an error writing the image")
            }
            else {
                console.log("The sheel file was written")
            }
        });
    });
};

Comment: Thanks to answer. One addition, Buffer is deprecated now, use Buffer.from() instead.
Answer: Array Buffer is browser supported which will be unsupportable for writing file, we need to convert to Buffer native api of NodeJs runtime engine.
This few lines of code will create image.
const fs = require('fs');
let data = arrayBuffer // you image stored on arrayBuffer variable;
data = Buffer.from(data);
fs.writeFile(`Assets/test.png`, data, err => { // Assets is a folder present in your root directory
      if (err) {
         console.log(err);
      } else {
         console.log('File created successfully!');
      }
});

Create image from ArrayBuffer in Nodejs


Drupal CSS broken in Internet Explorer 7/8, but works as static page

Question: The CSS layout on my Drupal site was suddenly found to be broken in IE 7 & 8. No idea what happened to cause this, but the strange thing is, if I save the source/files, then upload and test as a static page, it works fine (well, good enough for Internet Explorer). I'm using Adobe BrowswerLab to test.
I've turned off caching in performance and boost. I have also turned gzip compression off on the server, and added 10 second delay to browserlab load-time. Nothing seems to make the CSS work straight from the actual site.
I haven't found any threads about this specifically. Does anybody know what might be going on?
I am using Drupal 6.24.
Comment: Well, could you give us something concrete, like code or a website URL? I don't want to break into your house to debug this...
Comment: Oops yes: www.worldyoganetwork.com
Answer: Do you have CSS and Javascript caching enables? IE7 & IE8 can only load a certain amount of external files and you maybe exceeding the limit. Retry with CSS and JS caching enabled.
Answer: I had this issue too in a Drupal Commons 6x24 site: On a quick step I did toggle the CSS-aggregation, and switched it off.
Just have a closer look at this, here: Your lack of styles on the site is due to inadequate file permissions on your server. Your site is unable to save the auto-generated compressed CSS file, thus there is no style information to be displayed.
Installing a different theme would do nothing to fix this situation. If you cannot manage to get the proper files permissions set up, you may try disabling CSS aggregation by navigating to Administration -> Site Configuration -> Performance, and toggling off the CSS aggregation setting, then clicking the save button.
Answer: Looking at your source code and the number of modules noted in your jquery settings, it does look this is the IE CSS loader limit issue. IE will load 32 css files and only 32 -- any more than that and it just quits and refuses to load any. Here is a good testbed of this issue:
http://john.albin.net/ie-css-limits/993-style-test.html
When developing for IE, you will need to temporarily turn off css aggregation (which is on in your site) to get the styles to load. Another option (for Drupal 6.x) is to install the unlimted css loader module:
http://drupal.org/project/unlimited_css
Which offers another option around this.
Comment: hi there - many thx for the  great answer! Good job!
Answer: Also you could open the css file in another tab and check if IE found it or if return a error or something like that.
Sometime this happened to me when the css file had another encoding.


Loop through SQL query result and compare against table values?

Question: I have a table (Client_Programs) which contains a list of clients and a government program they're enrolled in.  Each client is identified by a unique ClientULink and programs have a ProgramULink. Each entry contains a StartDate and EndDate.  So the data may look like this:
ClientULink                             ProgramULink                            StartDate                    EndDate
b0afd171-28d0-48a3-989f-f2b0583c0fxx    46dcdf26-4916-4966-ac81-eaf57c7a26xx    2/2/2017 6:00:00 AM 5/2/2017 6:00:00 AM

A client can be in this table multiple times for the same (or different) programs. I'm being asked to create a query (report) of any client that has NOT re-enrolled into a program.  My thinking is to initially start off by running a query to return entries from the Client_Program table between two EndDates (which would be an input parameter in my final stored procedure for this report).  For example:
SELECT ClientULink, ProgramULink, StartDate, EndDate FROM Client_Program cp WHERE cast(cp.EndDate as date) BETWEEN '2017-05-01' AND '2017-05-30'

However, I would like to place these into a temp table or memory so that I can then loop through them and check all of these results against the main Client_Program table to see if these clients have any "newer" entries that shows they are re-enrolled or not.
SELECT ClientULink, ProgramULink, StartDate, EndDate FROM Client_Program cp WHERE ClientULink = 'b0afd171-28d0-48a3-989f-f2b0583c0fxx' AND cp.ProgramULink = '46dcdf26-4916-4966-ac81-eaf57c7a26xx' AND CAST(cp.StartDate as DATE) > '2017-05-30'

My question is how do I loop through my first results query?  Basically, I'm trying to find any client who has not re-enrolled (doesn't have an entry with a newer StartDate for a program - or specific program as shown in my query) than the EndDate range specified.
Any help in showing this in a stored procedure or query would be very much appreciated and helpful.  Thank you for your time!
Comment: I don't get it.  Your query has a date range but nothing in the question suggests that a date range is needed.
Comment: It is a bit confusing to me.  They are asking to know any client who has not re-enrolled in a program (i.e. let existing program lapse).  So they EndDate is required, but am I using it correctly?  I felt that I'd allow the user to choose a date range (like last month) and then find ONLY those clients who had a program ending during that time.  THEN find if they re-enrolled or not.  This limited me to using the results from the date range query and not the entire Client_Program table - which is huge!  Make sense?  Thanks again.
Comment: If EndDate is required, why not use IS NOT NULL instead of a range? If you are only looking for re-enrollments and not new enrollments.
Answer: You could use a cursor to do loops, but that is a poorly performaning option compared to a set based operation.
Using not exists() to return all clients in programs that ended in May, that have not re-enrolled:
select
    ClientULink
  , ProgramULink
  , StartDate
  , EndDate
from Client_Program cp
where cp.EndDate >= '20170501'
  and cp.EndDate <  '20170601'
  and not exists (
    select 1
    from Client_Program i
    where i.ClientULink = cp.ClientULink
      and i.ProgramULink = cp.ProgramULink
      and i.StartDate >= cp.EndDate
      )

Notes:

Bad habits to kick : mis-handling date / range queries - Aaron Bertrand
What do between and the devil have in common? - Aaron Bertrand
Should I use not in(), outer apply(), left outer join, except, or not exists()? - Aaron Bertrand
The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn] - Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

test setup:
create table Client_Program (ClientULink uniqueidentifier, ProgramULink uniqueidentifier, StartDate datetime, EndDate datetime)
insert into Client_Program values
 ('00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000','2017-02-02T06:00:00','2017-05-02T06:00:00')
,('11111111-1111-1111-1111-111111111111','11111111-1111-1111-1111-111111111111','2017-02-02T06:00:00','2017-05-02T06:00:00')
,('11111111-1111-1111-1111-111111111111','11111111-1111-1111-1111-111111111111','2017-05-02T06:00:00','2017-08-02T06:00:00')
select
    ClientULink
  , ProgramULink
  , StartDate = convert(char(10),StartDate,120)
  , EndDate   = convert(char(10),EndDate,120)
from Client_Program cp
where cp.EndDate >= '20170501'
  and cp.EndDate <  '20170601'
  and not exists (
    select 1
    from Client_Program i
    where i.ClientULink = cp.ClientULink
      and i.ProgramULink = cp.ProgramULink
      and i.StartDate >= cp.EndDate
      )

rextester demo: http://rextester.com/LYE54567
returns:
+--------------------------------------+--------------------------------------+------------+------------+
|             ClientULink              |             ProgramULink             | StartDate  |  EndDate   |
+--------------------------------------+--------------------------------------+------------+------------+
| 00000000-0000-0000-0000-000000000000 | 00000000-0000-0000-0000-000000000000 | 2017-02-02 | 2017-05-02 |
+--------------------------------------+--------------------------------------+------------+------------+

You could also use aggregation and filter in the having clause where max(EndDate) is between some date range (If they re-enrolled, then their max(EndDate) would not be in the date range):
select
    ClientULink
  , ProgramULink
from Client_Program cp
group by
    ClientULink
  , ProgramULink
having max(EndDate)>= '20170501'
   and max(EndDate) < '20170601'

returns:
+--------------------------------------+--------------------------------------+
|             ClientULink              |             ProgramULink             |
+--------------------------------------+--------------------------------------+
| 00000000-0000-0000-0000-000000000000 | 00000000-0000-0000-0000-000000000000 |
+--------------------------------------+--------------------------------------+

Comment: Are you sure your not Aaron Bertrand in disguise?  You're definitely well read on his material; and quick to site it! :P
Comment: @xQbert I've never even been to Rhode Island.Though working for SentryOne would probably be awesome, considering the pub. https://www.sentryone.com/company/about-us#prettyPhoto
Comment: @xQbert Oh, here is another article that is slightly related to my answer: - [Should I use `not in()`, `outer apply()`, `left outer join`, `except`, or `not exists()`? - Aaron Bertrand](https://sqlperformance.com/2012/12/t-sql-queries/left-anti-semi-join)
Comment: I need to loosen up a bit... pub anyone?  Set that SQL mind free...  and read some more ---- below
Comment: @xQbert Here is a good index of some of his bad habits articles: https://blogs.sentryone.com/aaronbertrand/bad-habits-revival/.
Comment: Hi Aaron... nice to meet you. :P  soo much good quality content to read.
Comment: @xQbert Good to meet... ahh you almost got me.
Comment: ohhhh.... you're just trying to distract me from answering more SO questions aren't you.
Comment: Thank you! If I understand this query, it is providing me the clients that have indeed re-enrolled into a program again.  Is there a way to provide which ones have NOT re-enrolled.  In other words - they do NOT have a StartDate >= EndDate?
Comment: @DataCrypt This returns clients that have not re-enrolled in programs where the enrollment that ends within the date range. I have added a demo to my answer to illustrate.
Comment: @SqlZim - Thank you very much!  I was able to use your query with a small change to the date handling and got it to work.  I appreciate your time and assistance in helping me with this.  Kindest regards.
Answer: In general, if you are looping in SQL, you're probably doing it wrong. You can use EXCEPT to achieve this.
SELECT ClientULink
FROM Client_Program
WHERE CAST(EndDate as date) BETWEEN '2017-05-01' AND '2017-05-30'
EXCEPT
SELECT ClientULink
FROM Client_Program
WHERE CAST(StartDate as date) > '2017-05-01'

Edit: If a client Starts and Ends within the DateRange they will be wrongly excluded from the result.
Comment: If somebody was only once enrolled at e.g. '2017-05-05`, your query will not provide his name. It includes the name in the first part, but deletes it in the EXCEPT query. Or I'm missing something?
Answer: Are you certain you are not over-thinking this? Not re-enrolled appears to be the set of IDs (client, program) that have a count of 1. E.g.,
select cp.ClientULink, cp.ProgramULink from dbo.Client_Program as cp
group by cp.ClientULink, cp.ProgramULink
having count(*) = 1
order by cp.ClientULink, cp.ProgramULink ;

What else do you need?
Comment: No, but I see what you mean.  Not being enrolled means they're not currently in a program (which lasts between a StartDate and EndDate).  So, a client can be in a program from say 2/1/2016 through 2/1/2017.  They are sent a notice that it's expiring and to re-enroll about a month ahead of time.  If they do, they'd get a new record showing something like 3/1/2017 through 3/1/2018.  However, now they are asking me for a query to know who didn't re-enroll. So they don't have anymore records after their most recent program expired.
Answer: If you need the date filter, try something like this:
select ClientULink, ProgramULink, StartDate, EndDate
from Client_Program cp
inner join
(
    select ClientULink, ProgramULink, count(*) as Count
    from Client_Program cp2
    group by ClientULink, ProgramULink
    having count(*) = 1
) cp2
on cp.ClientULink = cp2.ClientULink
and cp.ProgramULink = cp2.ProgramULink
where cast(cp.EndDate as date) between '2017-05-01' and '2017-05-30'


How to set Checkbox value into a array android

Question: I got an ArrayList:
ArrayList<CheckBox> swmsInfo = new ArrayList<CheckBox>();
and some checkboxes:
checkBoxCompany = createCheckBox(R.id.checkBoxCompany);

checkBoxName = createCheckBox(R.id.checkBoxName);
checkBoxPhone = createCheckBox(R.id.checkBoxPhone);

checkBoxAdress = createCheckBox(R.id.checkBoxAdress);

I want to get their values 0 or 1 if some of the checkboxes are checked or not , and when i got their values i want to put them into a array. My checkboxes are inside a array
ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
Comment: could you add the code where you use this?
Comment: my code is very long.I use this array to send him to a API. The array must content boolean values of all checkboxes.
Comment: I'm lost with what you are asking you need to improve your question some more
Answer: You can loop through the arraylist and get the value. Something like
for (int i = 0; i<boxes.size(); i++){
    CheckBox cb = boxes.get(i);
    if (cb.isChecked()){
      System.out.println("checked");
      //from here you can populate you array
    }else{
      System.out.println("not checked");
      //from here you can populate you array
    }
}

======= Edit after the comment =======
public class CheckBoxStatus{

    CheckBox cb;
    boolean blnIsChecked;

    public CheckBoxStatus(CheckBox cb, boolean blnIsChecked){
      this.cb = cb;
      this.blnIsChecked = blnIsChecked;
    }

    public CheckBox getCheckbox(){
       return this.cb;
    }

    public boolean getStatus(){
       return this.blnIsChecked;
    }

    public boolean setStatus(boolean blnIsChecked){
        this.blnIsChecked = blnIsChecked;
    }

}

//Now in your code instead of ArrayList<CheckBox>, use ArrayList<CheckBoxStatus>

ArrayList<CheckBoxStatus> alCBS = new ArrayList<CheckBoxStatus>();
CheckBoxStatus cbs = new CheckBoxStatus(<checkbox instance>, false); //pass false as default value;
alCBS.add(cbs);

//Modified loop
for (int i = 0; i<boxes.size(); i++){
  CheckBox cb = boxes.get(i);
  CheckBoxStatus cbs = new CheckBoxStatus(cb, cb.isChecked());
  boxes.set(i, cbs);
}

Comment: yea but i want to get there boolean values and put them in the same array.I use this array to send it to a API with all boolean values of my checkboxes :)
Comment: then you need to create a POJO class. Let me update my answer and give you some hint.


Capturar dados até o espaço, regex

Question: Estou usando esta expressão regular para capturar dados entre asteriscos:
\*(.+)\*

contudo ela captura de forma errônea quando o texto se enche de asteriscos, por exemplo em:
oi pessoas *lindas* e pessoas *lindos*

ela entende apenas os asteriscos mais de fora capturando todo o lindas* e pessoas *lindos sendo que era para capturar apenas lindas e lindos separadamente.
Existe alguma forma de adapta-la para que ela pegue de forma separada? Usando alguma condição com espaço ou algo assim..?
Answer: você pode utilizar o \w+ para indicar que existem apenas letras entre os asteriscos:
a expressão: \*(\w+)\*
veja funcionando no Regex101
Comment: @user3163662 Sim. Basta adicionar `^` dentro dos colchetes.
Comment: https://regexr.com/3kvab para o caso de tudo (números e letras)
Comment: teria como ao invés de especificar o que eu quero, especificar o que eu não gostaria? Tipo deixar tudo menos espaço

Capturar dados até o espaço, regex


for any ring $A$ the matrix ring $M_n(A)$ is simple if and only if $A$ is simple

Question: Let integer $n\geq 1$. I have obtained that for any field $k$, the matrix ring $M_n(k)$ is simple, i.e., $M_n(k)$ contains no nonzero proper two sided ideals. Now I want to prove that: for any ring $A$ (not necessarily commutative), the matrix ring $M_n(A)$ is simple if and only if $A$ is simple.
How to prove?
Answer: All ideals below are two-sided ideals. I also assume $A$ has a unit.

If $I$ is an ideal of $A$, then $J=M_n(I)$ is an ideal of $M_n(A)$.
This is easy to prove from the definition of matrix addition and multiplication.
If $J$ is an ideal of $M_n(A)$, then $J=M_n(I)$ for some $I$ is an ideal of $A$.
Take $I$ to be the set of all $a \in A$ such that there is $M\in J$ having $a$ in one entry. Then $I$ is an ideal of $A$ and $J=M_n(I)$ because you can pre- and post- multiply matrices in $J$ by elementary matrices $E_{ij}$ to move entries to any desired place. ($E_{ij}$ is the matrix will all zeros except for the entry $ij$ which is $1$.)
Comment: And what about the case, when $R$ is not unital? There are two-sided ideals not of the form $M_n(I)$. But is the following result: $R$ is simple iff $M_n(R)$ is simple valid?


How can I get an entityform attached to an order in drupal commerce?

Question: I'm trying to append an entityform to an order in Drupal commerce. I included the several attempts in my code snippet. Version 1 just throws the following error:
Fatal error: Cannot use object of type EntityValueWrapper as array in /sites/all/modules/kalamuna/tb_commerce_panes/tb_commerce_panes.module on line 374

I tried two other attempts. Version 2 and 3 show up in $order, but when I get to the checkout page and var_dump $order it isn't there. Any ideas why?
function commerce_panes_custom_submit($form, &$form_state, $checkout_pane, $order) {
  // Strip out the entityform type.
  $values = $form_state['values'];
  $entityform_type_name = $values['entityform_bundle'];

  // Create a new entityform from the remaining fields.
  global $user;
  $form = new Entityform(
    array(
      'type'     => $entityform_type_name,
      'created'  => time(),
      'changed'  => time(),
      'language' => LANGUAGE_NONE,
      'uid'      => 2
    )
  );

  // The process the rest entityform fields.
  foreach ($values as $k => $v) {
    if (strstr($k, 'field_')) {
      $form->$k = $v;
    }
  }

  //Version 1 - Original
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->field_tb_registration_forms[] = $form;
  $order_wrapper->save();

  //Version 2 - Modified Original
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $node = $order_wrapper->values();
  $node->field_tb_registration_forms[] = $form;
  $order_wrapper->save();

  //Version 3 - modify $order and save it
  $order->field_tb_registration_forms = $form;
  commerce_order_save($order);

}

Comment: What type of field is >field_tb_registration_forms?
Comment: That was it! it was a text field. I ended up just storing the entityform_id in that field and changed calls to the form with:

    $reg_form_id = $order_wrapper->field_tb_registration_forms->value();
    $tb_registration_forms = entityform_load($reg_form_id);
Answer: Have you tried first checking to make sure $order is set? If not then load cart from $user->id first and then wrap it.
Comment: Yes, I checked before and after adding forms. I even tried reloading the $order using commerce_order_load().


Doesn't show the needed info from auth.log file when using grep

Question: I want to get all info about user from auth.log file, but when I use grep user /var/log/auth.log but instead of giving me all the information with user mentioned, it just writes to me Binary file /var/log/auth.log matches. It used to pick up the sentences with mentioned user, but now it doesn't.
Comment: try `grep -a user /var/log/auth.log`  it may help you.  `-a, --text`
              Process a binary file as if it were text; this is equivalent to the --binary-files=text option.
Answer: Sounds like your auth.log has some garbage in it that is making grep believe it is binary, perhaps some UTF-8 encoded data.
Either way, grep has a switch to make it treat it as text anyway
grep -a pattern /var/log/auth.log


Can acceptable trills be played on an old M1 with unweighted synth action?

Question: So I have a Korg T3 (basically an M1 with some extra ROM samples).
I am deeply deeply unsatisfied with my trills because they just don't have that smooth, singing, "trilly" quality.
They are on time and everything, but they sound... bad.
I am beginning to suspect that the synth's unweighted action and limited sound capabilities place an upper limit on how good can my trills sound - and that, in particular, if the keys would "bounce back" like they are supposed to, everything would sound better.
Can anybody confirm or deny such a possibility?
Has anybody managed to produce good trills on a synth action keyboard?
Am I wasting my time, here?
(Obviously, I don't have access to a piano for the ultimate test.)
Thank you.
Comment: I know what a piano teacher would say.  But I think the old quote about a workman blaming his tools would also apply.
Comment: Based on dim & distant memory, the M1 had a decent keyboard for a sprung mechanism [never owned a T3] I'd say, make sure you hit the bottom of each key-travel to get some feel from it, I do recall it had a reasonable 'stop point' to work with.
Comment: There's no piano store near where you live? You could try it there.
Comment: That's quite an old keyboard, isn't it ? Is it possible the return springs have streteched and so the keys aren't bouncing back as they should ? Either way the best bet would be to try it on another sythn/keyboard - anythign woudl do- to see if it feels different. I disagree with @DarrenRinger's comment: If your tools are genuinely shot (f'nar), then you're fighting a losing battle. I'm a guitarist so an analogy is: playing a guitar with v high action makes it a real handful. Playing a well set up guitar makes it a dream. Sometimes it IS the tools - but also .. sometimes not ;-)
Answer: Having just done an acid test, for me, trills using a proper piano action are easier to execute than doing them on an 'organ' type 'board. This may be because I play a lot more on pianos than keyboards, though. The bounce back seems to help the control. Having said that, there are lots of trill type bits in Bach's organ works, so it is quite possible to do it well. It is probably a harder technique than on a piano to master, as control is far more in the finger muscles when the keys respond in the way they do on a keyboard.


Higher Moment in Gaussian

Question: Prove that for $X$ a Gaussian random variable, all moments after the third are zero, that is
$$
\mathbb{E}[X^n] = \int_{-\infty}^\infty x^n P_X(x)dx = 0,\qquad n\geq 3
$$
Comment: In one word: Antisymmetry.
Comment: This is only true for odd $n$'s. http://www.wolframalpha.com/input/?i=integrate+1%2FSqrt%5B2+Pi%5Dx%5E4+e%5E%7B-x%5E2%2F2%7D%2C+%7Bx%2C-infty%2C+infty%7D
Comment: Maybe James meant cumulants: http://en.wikipedia.org/wiki/Cumulant#Cumulants_of_some_continuous_probability_distributions
Answer: They are not zero. If it is zero mean then the odds moments will be zero, but the even ones are not.
Answer: In its current formulation, this statement is $\textbf{false}$.
If we look at the case $n = 4$, we basically have to integrate the function $x \mapsto x^{4} e^{- \frac{x^{2}}{2}}$, which a stricly positive function on the entire $\mathbb{R}$-axis.
However, if we suppose that the gaussian is $\textbf{centered}$ (meaning its mean is $0$), we can look at the case n odd, $n > 3$. We have to integrate a function of the form $f : x \mapsto x^{2n + 1} e^{- \frac{x^{2}}{2}}$. As this function is an odd function ($f (- x) = f (x)$), the integral $\int f (x) \, dx$ shrinks down to $0$. So that, in conclusion, for every odd $n \geq 3$, the moments of a centered Gaussian distribution are $0$.
Answer: If $X$ is normally distributed, $n$ is odd and $E[X]=0$ then $X^n$ and $-X^n$ have the same distribution, so $E[X^n]=-E[X^n]$ wich leads to $E[X^n]=0$.
In general the statement in your question is not true.

Higher Moment in Gaussian


How to characterize conditional entropy given uniform distributions

Question: I'm trying to derive conclusions on how uniform distributions with different alphabet lengths influence the information measured from any other random variable (not neccesarily uniformly distributed). Overall we measure the reduction in the uncertainty of the RV $X$ given $Y$ is observed by means of:
$$H(X|Y) = H(X,Y)-H(Y).$$
Now suppose two random variables $Y$ and $Z$ are uniformly distributed, with $|\mathcal{Y}|<|\mathcal{Z}|$ (and with $|\mathcal{Y}|$ and $|\mathcal{Z}|$ the alphabet sizes). So what is the relationship between  $H(X|Y)$ and $H(X|Z)$?
I initially supposed that given $H(Y)=\log|\mathcal{Y}|<\log|\mathcal{Z}|=H(Z)$ then $H(X|Y) > H(X|Z)$, but I cannot figure out how actually this relationship is influenced by $H(X,\cdot)$ as $|\mathcal{Y}|<|\mathcal{Z}|$.
Thanks for your help.
Answer: Without further specifying any condition on the joint distribution with $X$, it'll be difficult to derive the type of general relationship you're looking for.
Take for example the case when $X = Y$ and $X$ is independent of $Z$.  Then $H(X|Y) = 0 < H(X|Z) = H(X)$.  Alternatively, we can take $X = Z$ and $X$ independent of $Y$ to get the inequality in the other direction


Internal Server Error Wordpress

Question: I've uploaded wordpress file in my panel. But I can't configure my wordpress site with database. When i browse my site as ************.us, it shows 500 Internal Server Error error. So, i've deleted all uploaded files and uploaded again. But i'm facing this problem again and again.
So, i'm seeking a better solution.
Comment: Try to enable PHP's debug flags: http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php
Comment: Check all the file permissions. 644 for files and 755 for folders
Comment: http://**********.us/cgi-bin/  this also  shows INTERNAL ERROR
Answer: Check files and folder permissions as follows:
public_html folder should have 750 and chown it to cpaneluser:nobody
files inside public_html/ should have 644 permissions
folders inside public_html/ should have 755 permissions
Check if there is any .htaccess file inside your public_html folder. If there are any rules inside that file those could lead to the error
If you do not need the rules or the file, you can just delete it.
Answer: to increase php post limit
128M And also upgrade your current version.
for support click heenter link description herere
Comment: This doesn't answer the question.

Internal Server Error Wordpress


How to run multiple SQL queries?

Question: I have a create table query, an update query ,and then drop table query. I need to run these three queries in one shot. What is the best way to do this?
Example
1st Query: Create table A.
2nd Query: Update value in table A
3rd Query: Drop table A.

Instead of running these three queries one by one, I want to run them in on go either by PLSQL or some other way. Please help.
Comment: Sometimes you don't need the (temporary) staging table at all e.g. can use a CTE instead. But isn't the net result of running all three (create A, update A, drop A) exactly nothing?
Comment: I did it in TOAD IDE. WE can run multiple queries at a time by pressing F5 I think(Done long back)
Comment: Write the queries in a file (script) and then run the script: http://www.techonthenet.com/oracle/questions/script.php
Comment: Also see this: http://download.oracle.com/docs/cd/B10501_01/server.920/a90842/ch6.htm
Comment: Creating and dropping tables in a single Unit Of Work is a code smell.  It might be necessary in some other databases, but it is not necessary in Oracle: there are always better ways, depending on precisely what it is you need to do.
Answer: Put the 3 queries following each other separated by a semi-colon:
SELECT *
FROM table_to_be_selected;
DROP TABLE the table_to_be_dropped;
TRUNCATE TABLE table_to_be_truncated;

You can concatenate these queries in a string and execute that string.
Answer: Why not create a PROCEDURE?
E.g.
CREATE OR REPLACE PROCEDURE foo
IS
BEGIN
  -- The create sentence goes here. For example:
  -- EXECUTE IMMEDIATE
  -- 'CREATE TABLE bar (...)';

  -- The update sentence goes here
  -- EXECUTE IMMEDIATE
  -- 'UPDATE bar SET ...';

  -- The drop/delete sentence goes here.
  -- EXECUTE IMMEDIATE
  -- 'DROP TABLE bar;'
END;

You can test it with:
SET serveroutput ON;
exec foo;

The PROCEDURE is stored on the database, so you can use it later on.
Hope this helps.
Comment: don't forget about execute immediate for DDL statements here
Comment: Thanks for pointing that out. I learned something new today! :)
Answer: Simply put three queries one after the other in a .sql file, with semi-colons after each statement, then execute it as a script (either on a SQL*Plus prompt using @scriptname.sql or in TOAD/SQL Developer [or equivalent] using its script execution function).

How to run multiple SQL queries?


Cisco PIX 8.0.4, static address mapping not working?

Question: upgrading a working Pix running 5.3.1 to 8.0.4. The memory/IOS upgrade went fine, but the 8.0.4 configuration is not quite working 100%. The 5.3.1 config on which it was based is working fine.
Basically, I have three networks (inside, outside, dmz) with some addresses on the dmz statically mapped to outside addresses. The problem seems to be that those addresses can't send or receive traffic from the outside (Internet.) Stuff on the DMZ that does not have a static mapping seems to work fine. So, basically:
Inside -> outside: works
Inside -> DMZ: works
DMZ -> inside: works, where the rules allow it
DMZ (non-static) -> outside: works
But:
DMZ (static) -> outside: fails
Outside -> DMZ: fails (So, say, udp 1194 traffic to .102, http to .104)
I suspect there's something I'm missing with the nat/global section of the config, but can't for the life of me figure out what. Help, anyone?
The complete configuration is below. Thanks for any thoughts!

!
PIX Version 8.0(4)
!
hostname firewall
domain-name asasdkpaskdspakdpoak.com
enable password xxxxxxxx encrypted
passwd xxxxxxxx encrypted
names
!
interface Ethernet0
 nameif outside
 security-level 0
 ip address XX.XX.XX.100 255.255.255.224
!
interface Ethernet1
 nameif inside
 security-level 100
 ip address 192.168.68.1 255.255.255.0
!
interface Ethernet2
 nameif dmz
 security-level 10
 ip address 192.168.69.1 255.255.255.0
!
boot system flash:/image.bin
ftp mode passive
dns server-group DefaultDNS
 domain-name asasdkpaskdspakdpoak.com
access-list acl_out extended permit udp any host XX.XX.XX.102 eq 1194
access-list acl_out extended permit tcp any host XX.XX.XX.104 eq www
access-list acl_dmz extended permit tcp host 192.168.69.10 host 192.168.68.17 eq ssh
access-list acl_dmz extended permit tcp 10.71.83.0 255.255.255.0 192.168.68.0 255.255.255.0 eq ssh
access-list acl_dmz extended permit tcp 10.71.83.0 255.255.255.0 192.168.68.0 255.255.255.0 eq 5901
access-list acl_dmz extended permit udp host 192.168.69.103 any eq ntp
access-list acl_dmz extended permit udp host 192.168.69.103 any eq domain
access-list acl_dmz extended permit tcp host 192.168.69.103 any eq www
access-list acl_dmz extended permit tcp host 192.168.69.100 host 192.168.68.101 eq 3306
access-list acl_dmz extended permit tcp host 192.168.69.100 host 192.168.68.102 eq 3306
access-list acl_dmz extended permit tcp host 192.168.69.101 host 192.168.68.101 eq 3306
access-list acl_dmz extended permit tcp host 192.168.69.101 host 192.168.68.102 eq 3306
access-list acl_dmz extended permit tcp 10.71.83.0 255.255.255.0 host 192.168.68.101 eq 3306
access-list acl_dmz extended permit tcp 10.71.83.0 255.255.255.0 host 192.168.68.102 eq 3306
access-list acl_dmz extended permit tcp host 192.168.69.104 host 192.168.68.101 eq 3306
access-list acl_dmz extended permit tcp host 192.168.69.104 host 192.168.68.102 eq 3306
access-list acl_dmz extended permit tcp 10.71.83.0 255.255.255.0 host 192.168.69.104 eq 8080
access-list acl_dmz extended permit tcp 10.71.83.0 255.255.255.0 host 192.168.69.104 eq 8099
access-list acl_dmz extended permit tcp host 192.168.69.105 any eq www
access-list acl_dmz extended permit tcp host 192.168.69.103 any eq smtp
access-list acl_dmz extended permit tcp host 192.168.69.105 host 192.168.68.103 eq ssh
access-list acl_dmz extended permit tcp host 192.168.69.104 any eq www
access-list acl_dmz extended permit tcp host 192.168.69.100 any eq www
access-list acl_dmz extended permit tcp host 192.168.69.100 any eq https
pager lines 24
mtu outside 1500
mtu inside 1500
mtu dmz 1500
icmp unreachable rate-limit 1 burst-size 1
no asdm history enable
arp timeout 14400
global (outside) 1 interface
nat (inside) 1 0.0.0.0 0.0.0.0
nat (dmz) 1 0.0.0.0 0.0.0.0
static (dmz,outside) XX.XX.XX.103 192.168.69.11 netmask 255.255.255.255
static (inside,dmz) 192.168.68.17 192.168.68.17 netmask 255.255.255.255
static (inside,dmz) 192.168.68.100 192.168.68.100 netmask 255.255.255.255
static (inside,dmz) 192.168.68.101 192.168.68.101 netmask 255.255.255.255
static (inside,dmz) 192.168.68.102 192.168.68.102 netmask 255.255.255.255
static (inside,dmz) 192.168.68.103 192.168.68.103 netmask 255.255.255.255
static (dmz,outside) XX.XX.XX.104 192.168.69.100 netmask 255.255.255.255
static (dmz,outside) XX.XX.XX.105 192.168.69.105 netmask 255.255.255.255
static (dmz,outside) XX.XX.XX.102 192.168.69.10 netmask 255.255.255.255
access-group acl_out in interface outside
access-group acl_dmz in interface dmz
route outside 0.0.0.0 0.0.0.0 XX.XX.XX.97 1
route dmz 10.71.83.0 255.255.255.0 192.168.69.10 1
timeout xlate 3:00:00
timeout conn 1:00:00 half-closed 0:10:00 udp 0:02:00 icmp 0:00:02
timeout sunrpc 0:10:00 h323 0:05:00 h225 1:00:00 mgcp 0:05:00 mgcp-pat 0:05:00
timeout sip 0:30:00 sip_media 0:02:00 sip-invite 0:03:00 sip-disconnect 0:02:00
timeout sip-provisional-media 0:02:00 uauth 0:05:00 absolute
dynamic-access-policy-record DfltAccessPolicy
no snmp-server location
no snmp-server contact
snmp-server enable traps snmp authentication linkup linkdown coldstart
crypto ipsec security-association lifetime seconds 28800
crypto ipsec security-association lifetime kilobytes 4608000
telnet 192.168.68.17 255.255.255.255 inside
telnet timeout 5
ssh timeout 5
console timeout 0
threat-detection basic-threat
threat-detection statistics access-list
no threat-detection statistics tcp-intercept
!
class-map inspection_default
 match default-inspection-traffic
!
!
policy-map type inspect dns preset_dns_map
 parameters
  message-length maximum 512
policy-map global_policy
 class inspection_default
  inspect dns preset_dns_map
  inspect ftp
  inspect h323 h225
  inspect h323 ras
  inspect netbios
  inspect rsh
  inspect rtsp
  inspect skinny
  inspect esmtp
  inspect sqlnet
  inspect sunrpc
  inspect tftp
  inspect sip
  inspect xdmcp
!
service-policy global_policy global
prompt hostname context
Cryptochecksum:2d1bb2dee2d7a3e45db63a489102d7de
Answer: You have to specify the interface which points toward the DNS server
dns domain-lookup outside
Answer: All your NAT rules are from lower-security interfaces to higher-security interfaces; this is not the normal way to do things.
static (if1,if2) ip1 ip2 presents ip1 on if2 as ip2 on if1; the NAT-ed to interface is the first mentioned, and the source interface is the second.
Taking your first static rule:
static (dmz,outside) XX.XX.XX.103 192.168.69.11 netmask 255.255.255.255
This maps the external address xx.xx.xx.103 on the outside interface to the internal address 220.127.116.11 on the inside interface.
Normally, you would configure the exact opposite: map the internal IP 192.168.69.11 on the inside interface to the external IP xx.xx.xx.103 on the outside interface; this presents the xx.xx.xx.103 interface to the outside world, allowing external hosts to connect to that IP and reach your DMZ host:
static (outside,dmz) 192.168.69.11 XX.XX.XX.103 netmask 255.255.255.255
The reason you are seeing it "working" on the other interface combinations is simply because those all fall through to the global nat rules you have set previously.
I think you should start with reversing those statics, and set up global pools for everything that is not static; do not rely on blank 0:0 NATs !


Skewness of log-normal distribution only depending on variance?

Question: Wikipedia says that the skewness of the log-normal distribution only depends on the variance of the underlying normal distribution.
Skewness:
However, from my point of view the skewness increases as the mean of the underlying normal distribution increases (described here).
Can anyone show which point is valid?
Answer: I believe the ambiguity comes from how you define skewness.  Wikipedia uses
$$
  \mathrm{E}\left(\frac{X - \mu}{\sigma}\right)^3, \text{ with }
  \mu=\mathrm{E}X \text{ and } \sigma^2=\mathrm{E}(X-\mu)^2.
$$
If you compute this for $X\sim \text{log-normal}(\mu,\sigma^2)$, you arrive at the given formula.  During the calculation, the dependency on $\mu$ is normalized out when you divide by $\sigma^3$.  To check this, write $X = \exp(\mu+\sigma Z)$ for
$Z\sim\text{Normal}(0,1)$ and try calculating the moments.
Alternatively, the third moment, $\mathrm{E}X^3$, and the third central moment, $\mathrm{E}(X-\mathrm{E}X)^3$ certainly do depend on $\mu$.  Your cited web page doesn't define skewness, but I assume they are referring to the third central (unnormalized) moment.


find linear polynomial g that is closest to f, where $f(x) = e^x$ and the distance between the two

Question: In the real linear space [-1,1] with inner product $\int^1_{-1} f(x)g(x)\,dx$. Find the linear polynomial $g$ nearest to $f$ and find $||g -f||^2$ for this $g$.
My problem is that I simply don't know how to do this. All the examples that involve projections (maybe even Graham-Schmidt here?) were all vectors. So I don't know how to do this.
Comment: The set of continuous functions on [-1, 1] is a vector space, so these are all "vectors" too. Just write $g(x) = ax + b$, compute $\langle g-f, g-g \rangle$, and you'll get an expression involving $a$ and $b$. Now minimize it by varying $a$ and $b$.
Answer: This is an easy question to answer once we have an orthonormal basis for the functions we're using to approximate $e^x$.  In this case, we are approximating $e^x$ using linear polynomials.
That is, we'd like an orthonormal basis for the subspace (of all real functions on $[-1,1]$) spanned by $\{1,x\}$.  Let's use the Graham-Schmidt process:
$$
\|1\|_2 = \sqrt{\langle 1,1 \rangle} = \sqrt{\int_{-1}^1 (1)^2\,dx} = \sqrt{2}\\
u_1 = \frac{1}{\|1\|_2} = \frac 1{\sqrt 2}
\\
\langle x, u_1 \rangle =
\int_{-1}^1 x \cdot \frac{1}{\sqrt 2} dx = 0
\\
v_2 = x - \langle x, u_1 \rangle u_1 = \cdots
$$
Can you take it from there?  You should find $u_2 = x$, so that $\{\frac{1}{\sqrt 2}, \sqrt{\frac{3}{2}}x\}$ is an orthonormal basis.  From there, we have
$$
e^x \approx
\langle e^x, u_1\rangle u_1 +
\langle e^x, u_2\rangle u_2
$$
Comment: where are you getting {1,x}?
Comment: What do we mean by "linear polynomial"?  That's where I'm getting $\{1,x\}$
Comment: I still don't know what {1,x} means.
Comment: how does e^x not play a factor in any of your calculations?
Comment: $\{1,x\}$ is the basis consisting of the functions $f(x) = 1$ (represented by "$1$"), and the function $g(x) = x$ (represented by "$x$").  The space of linear polynomials is the subspace spanned by the two functions (remember that functions are the vectors of our vector space) $f(x)$ and $g(x)$.  That is, $\{f(x),g(x)\}$ forms a basis of our subspace.
Comment: explain the first line (the first one with an integral)? where are you getting <1,1>? I think I got except for that point.
Comment: That's the inner product of $f(x)$ with $f(x)$, where $f(x) = 1$.  If $\langle \cdot,\cdot \rangle$ is an inner product, then the norm derived from that inner product is $\|f\| = \sqrt{\langle f,f \rangle}$
Comment: f(x) = e^x. So how can you define it to be = to 1?
Comment: I forgot that we had already used $f$ and $g$.  The letters aren't terribly important though.  If it helps, pretend that I said $p(x) = 1$ and $q(x) = x$, and make replacements accordingly.
Comment: why didn't you normalize $v_2$?
Comment: Try it.  Check that $\|v_2\| = 1$
Comment: No. If $v_2$ = $x$, then $ = \int_{-1}^1 x^2$ = $(2/3)$
Comment: Oh, whoops, my mistake.


Where does the t.GUID value come from in my RegisterFunction(Type t)

Question: Where does t.GUID value come from on Type t. If I set the GUID in Visual Studio 2017, under the Project menu, Solution Properties, Application tab, Assembly Information, does that get associated with the t.GUID?
Comment: P.S.  I borrowed this code from another persons code, and am not familiar with the Register and Unregister code.
Comment: P.P.S Or is it one of the GUIDs from the sln file?
Comment: P.P.P.S. Maybe someone can help me Understand where and how all the GUIDs are used in the Visual Studio Environment.
Answer: From the .NET "Type" reference:

A GUID is associated with a type using the GuidAttribute attribute.

Where the GuidAttribute is applied to your class as follows:
[GuidAttribute("EE2BFDAD-CB79-494F-978E-1171B1FA131F")]
public class MyClass
{
}

The docs also say:

Supplies an explicit Guid when an automatic GUID is undesirable.

So if no GUID is assigned then one is automatically assigned.
The GUID in your assembly information is for identifying your assembly as opposed to an individual Type.


When can changing key sound good?

Question: Most songs stick to one key, but I've noticed that switching keys is sometimes barely noticeable (to listeners) while playing guitar.
In which circumstance would changing your key mid-song sound alright?
Comment: You're asking about "modulation," when a composer changes key mid-composition. This is different from "going out of key," which suggests someone being unable to perform the work. Going out of key almost never sounds good; modulation often sounds great!
Comment: It sounds good when you resolve the dissonance properly, which is a very subjective statement and depends entirely on the genre.  In tonal harmony like to use Pivot Chords and Secondary Dominants or Leading Tone Chords to achieve relatively consonant sounding modulation... Or in jazz you could walk down the circle of fifths by landing on the dominant seventh every time => `G7 - C7 - F7 - Bb7 - Eb7` etc. They call this the `V of V of V of V etc.`
Comment: I've played songs that change to a similar key in a new section of a song like changing from the key of G to the key of C in a bridge or instrumental.
Answer: There are various techniques in theory for when key changes sound good (look at circle of fifths for example) but in reality you can make almost any key change sound good in context.
The simple examples are those you get in pop songs - where a final chorus or verse shifts up a step or two (the so called Truck Driver Gear Shift) but you do see some fine examples where it works really well (there are various collections of these - have a listen.)
It all depends what you are trying to do at the time - so my advice to you is to just experiment. Sometimes it will work, and sometimes it won't, but you'll learn a lot about context along the way.
Answer: It's really just like anything else in music.  Some things "sound right" and others don't.  Furthermore, things that "sound right" to some people sound very wrong to others.  So, what's important is that they sound right to you.  If some people like what you're doing and others hate it, it's probably pretty good.  (If everyone hates it, either you're a genius who's years ahead of his time or you have work to do.)
Modulation between closely related keys (keys a fifth apart, relative major and minor, for example) are pretty common, because they are pretty easy to do.  You just play a chord common to both keys and move on as if you were in the new key. Try playing these chords: Am, E7, Am, Dm, F, G7, C. That moves very smoothly from Am to C, Am's relative major.
This Elton John piece has a pretty striking modulation, from Eb minor to G major, which is a pretty distant key (six flats to one sharp, or a half step above the relative major). But it works, to my mind. (To get a sense of the original key, start at 2:00. The actual modulation begins at 2:18.)

Finally, here is a nice introduction to various kinds of modulations, with some examples.
Answer: There's generally not time within a pop/rock song to do much with structural key contrasts.  It's fairly common to jump to a remote chord to begin the 'middle 8', but it's often only to give a platform from which to immediately work your way back home, maybe through a 'cycle of 5ths' progression.
Note that my answer is full of hedge words - 'generally', 'fairly', 'often'.  There's the 'three chord trick'. There are mini-symphonies.  And there's everything in-between.
When a change is 'barely noticable', we could question whether there's really a modulation at all.  But we could argue all day over what's a modulation, what's a brief excursion, what's just a chromatic chord or two.  Recognise what's happening, don't worry too much about categorising it!
Answer: I think a key change can often work well if the lyric has a change in energy or a strong change in the point of view. The key change should align with the lyric change, though. If you want to amp up energy, you will probably want to either go upwards in pitch, or cycle upwards on the circle of fifths. Relaxation in energy would be the opposite direction, usually. Large changes in key signature (many accidentals changing) are more likely to give a sense that you've gone somewhere pretty far from where you were, and small changes seem nearer by. These are just some general guidelines. Have to use your ear and feel the implication of the sounds, if that makes any sense.

When can changing key sound good?


NuGet "Failed to generate binding redirects for My Project" with error "Object reference not set to an instance of an object."

Question: On several different packages like SquishIt and DotNetOpenAuth i get an error saying:

Failed to generate binding redirects for 'MyProject'. Object reference not set to an instance of an object.

I've seen a lot of post about other people having problems with "binding redirects" but not found a single reference to this problem combined with "Object reference not set to an instance of an object.".
What exactly is NuGet trying to do at this stage? Does it try to update the binding redirects in Web.Config? Could i have some issue with my Web.Config? How can i go about debugging this?
I shall say that this does not happen in a "clean" project.
Comment: As you suspected, the NuGet extension will attempt to add/update the web.config to add a binding redirect to the newest version of the library you're adding. Is your web.config file under source control? If it is not checked out properly (e.g. still marked read-only) it will cause the update to fail.
Answer: I had the same issue mucking around with MVC versions in one project.  I think it could happen for any NuGet package that tries to add Binding Redirects to your config file.
I ended up renaming "Web.config" to "Web.Temp.Config", then installing the package.
I then I manually merged the changes that the package put into my config file into the temp one, then deleted it and renamed my original back to web.config.
This resolved the issue for me - hopefully it helps you.
Comment: Yeah good idea @Nootn. I tried something similar by changing the Default Project and let it do its thing there. No 'object reference' error, and then copied the config.file changes back into my main one. After that I use UnInstall-Package [package] –RemoveDependencies to revert.
Answer: In my case, update NuGet Package Manager solves the problem.
Comment: how we can do that ?


How to handle boolean attributes with groovy templates?

Question: Given the following groovy template element:
select(class: 'form-control input-sm',
       disabled: isDisabled)

I just wan't to disable the select if isDisabled is true. The problem is that HTML considers the presence of disabled as enough to disable the element.
Answer: Interesting problem, I have no better idea than to simply do something like this:
isDisabled ? select(class: 'form-control input-sm', disabled:'disabled') : select(class: 'form-control input-sm')

[updated] or this:
def selectAttrs = [class: 'form-control input-sm']
if (isDisabled) selectAttrs += [disabled:'disabled']
select(selectAttrs)

Full test script:
import groovy.text.markup.MarkupTemplateEngine
import groovy.text.markup.TemplateConfiguration

model = [isDisabled:true]

def config = new TemplateConfiguration()
MarkupTemplateEngine engine = new MarkupTemplateEngine(config)
def template = engine.createTemplate '''
html {
body {
      isDisabled ? select(class: 'form-control input-sm', disabled:'disabled') : select(class: 'form-control input-sm')

      def selectAttrs = [class: 'form-control input-sm']
      if (isDisabled) selectAttrs += [disabled:'disabled']
      select(selectAttrs)
}
}
'''

StringWriter rendered = new StringWriter()
template.make(model).writeTo(rendered)

print rendered

Answer: I'm not familiar with Groovy templates, but is it something you could use with a ternary expression? Possibly changing the expression to:
select(class: 'form-control input-sm' ${isDisabled?", disabled":""})

This would only include the disabled attribute if isDisabled is true.
Comment: Groovy templates are plain old groovy scripts (at least as far as my understanding goes), but they use a very nifty groovy builders API to make they look similar to some popular templating engines like Jade. So in OP's example we can see a call to a method named `select`, passing a map with two key-value pairs as a parameter. Something like [this](http://pastebin.com/hhSBJxcL), basically. Your proposed solution is not a valid groovy, unfortunately.


Python on linux: Can't contact LDAP server

Question: I'm trying to extract some information from Active Directory using a python script:
<code>SERVER='LDAP://my.domain.com'
ldapobject=ldap.initialize(SERVER)
ldapobject.protocol_version = ldap.VERSION3
ldapobject.set_option(ldap.OPT_REFERRALS, 0)
dn = 'my_dn'
ldapobject.simple_bind_s(dn, PASSWORD)
</code>
Here I receive the error "Can't contact LDAP server".
This worked for me, but now I receive that error without making any modification. Also the server is untouched.
I searched for a solution but nothing resolved my problem.
Do you have any idea about this?
Thanks.
Comment: Can you ping the server? Can you open a raw connection on the LDAP port with `nc`?
Comment: The server is available, I have an application which connects to AD with success.
Answer: It seems that the problem is solved if I'm using:
    SERVER='LDAP://server_name.my.domain.com'
but I want that the server_name to be automatically found in the domain.


Running python on client side

Question: I want to run python code on client-side in my web technology project. The objective is that there will be some input from the user, taken via JavaScript, is then fed to .py files which will produce some output to be displayed on the website at the same time.
Please suggest a suitable way like brython or skulpt. A brief explanation or quick links will be very generous.
I'll be using turtle, numpy, manim, matplotlib and such libraries is that is the concern.
Comment: You did not asked any question, please read [how to ask](https://stackoverflow.com/help/how-to-ask), before posting. In any case [Flask](http://flask.pocoo.org/) can be use for your request..
Comment: You might have to send the user's input to a backend server to be processed by the Python script.
Comment: @DavidDR I'm sorry, I was just asking about what to use. Can you tell me what brython or skulpt can do? I read that they are used for client side python.
Comment: @NikhilJagtap I don't any info about brython and skulp... as mentioned in my opinion its better to use python as server side. Flask is one of the best option you have on doing that...
Answer: You may be able to build and compile some application to run on the client machine, but modern web browsers do not have the ability to run python files. As mentioned in the comments, you'd have to get user input and then process it server side.

Running python on client side