Q:

Are inverted scales a thing?

Inverted chords are a thing.
But are inverted scales a thing?
What do I mean with that?
A scale is defined by a certain set of notes where one of them is the root key. Playing the root key feels like coming home and most melodies in that scale start with that note.
So let's say in a song I'm using the notes of a certain scale. However, the note that it feels like coming home to and I often start a melody with, is another note than the root key of the scale I'm using.
Could you say I'm using an inverted version of that scale? Is there any other name for it?
Or doesn't it really matter and I'm still using the same scale? If that is the case, wouldn't that mean that C Major and A Minor are not two different scales with the same set of notes, but actually the same scale which just has two different names?
An example:
For now, let's just assume C Major wouldn't exist as a named scale. Yes, weird, but bear with me. However I'm making a song in a scale that would be C Major. Since it has the same notes and I want to be able to communicate what scale I'm using, I'm would say that my song is in A Minor - second inversion.
Of course, it's a bit weird that I'm using a major scale and I'm calling it a minor scale, but I think you understand my point.

A:

We call these rotations (or modes) of a scale. We can rotate any scale such that any member of that scale can be a tonic.
The most common rotations are the seven diatonic church modes (see also this question), where we rotate the major scale to begin on each of its seven pitches.
But you can rotate every scale out there, and there's likely a name for it. Rotating the harmonic minor scale to begin on the fifth scale degree, for instance, creates the Phrygian dominant scale, something very common in Klezmer music.

A:

There are seven of them. They're called modes. They use exactly the same notes as the 'standard major scale', but are rooted on each of the scale notes. And, there are many tunes which use them.
Let's take C major. CDEFGAB. As it stands, it's the C major scale. But if we reconfigure that abd go from , say D to D, it beecomes D Dorian. the root is  now D, and the sound is minor. The scale now is DEFGABCD.
That same idea carries through with each 'root note'.

A:

You have a lot of questions in your “question“ so I will try and hit on them in order.
So let's say in a song I'm using the notes of a certain scale. However, the note that feels like coming home to and I often start a melody with, is another note than the root key of the scale I'm using. Could you say I'm using an inverted version of that scale? Is there any other name for it? Or doesn't it really matter and I'm still using the same scale?
OK, 3 at a time, here goes: If your home key or tonality is the root of the particular major scale then you are playing just that scale and not an inverted scale. There is no rule stating that melodies have to originate or end on any specific note within a scale. If you are in C major and playing E to E you are still using a C major scale.
There is a name for what you are more or less describing, explore “modes”, which is the process of creating 7 different scales from one scale, say a C major scale, by using the 7 different starting notes, i.e. D to D, E to E, etc. In each of these cases though the starting note becomes the new tonality. There are MANY answered questions about modes on this site or you can do an independent search about them.
If that is the case, wouldn't that mean that C Major and A Minor are not two different scales with the same set of notes, but actually the same scale which just has two different names?
C major and A minor are two different scales which contain the exact same notes BUT they have different root notes and are also constructed very differently.
An example: For now, let's just assume C Major wouldn't exist as a named scale...
As for your example, C would be the 3rd inversion of the Am scale, not the 2nd (B is the second) if they were called inversions but this is really about what I mentioned before, “modes”. Actually the A minor scale (Aeolian mode) is built on the 6th degree of the C major scale (Ionian mode) Explore modes and I think you will see things more clearly. Here’s a wiki article to get you started:
https://en.wikipedia.org/wiki/Mode_(music)


Q:

Hide iOS/mobile address bar in galleria fullscreen mode

I'm putting together a responsive galleria slideshow on a drupal site with the galleria module and the galleria 'twelve' theme, using omega as my drupal base theme. Everything is working very well, except that when I enter fullscreen on my iPod I can't get rid of the address bar. I'd also like to make the bottom toolbar go away if possible. Together they take up quite a bit of space.
Any suggestions? I've seen a few methods to accomplish this (in a more general way, not specific to galleria) with some javascript, but that's not my strong suit, and I wouldn't know how to implement those solutions.

A:

To hide the address bar on iOS you just need to scroll the page a little
window.onload = function() {
    // x/y coordinates, "1" will cause the address bar to hide
    window.scrollTo(0, 1);
};

The bottom bar can't be hidden while in the browser. However, you can add the website to the home screen which will make hiding the address bar and bottom toolbar possible by adding a meta tag:
<meta name="apple-mobile-web-app-capable" content="yes">


Q:

Trim the contents of a String array in C#

    String []lines = System.IO.File.ReadAllLines(path);
    foreach (String line in lines)
    {
        line.Trim();
    }

Obviously this doesn't work because String.Trim returns the Trimmed version as a new String. And you can't do line = line.Trim(). So is the only way to do this an old-school for loop?
    for(int i=0;i<lines.Length;++i)
    {
        lines[i] = lines[i].Trim();
    }

Note I am restricted to Visual Studio 2005 i.e. .Net 2.0

A:

lines.Select(l => l.Trim()).ToArray();

Alternatively, for .NET 2.0:
static IEnumerable<string> GetTrimmed(IEnumerable<string> array)
{
    foreach (var s in array)
        yield return s.Trim();
}

Used through:
lines = new List<string>(GetTrimmed(lines)).ToArray();


Q:

Building RegEx Regular Expression

I'm new to regular expressions and struggling to get my head around them!
What I'm trying to do is strip the EASW_ID value from the following text which gets treated as a string.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:widget="http://www.netvibes.com/ns/" xmlns:wpp="http://www.easportsworld.com/wpp/1.0">
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>Fifa Ultimate Team</title>
  <script type="text/javascript">
     var HOST_DOMAIN = 'http://www.easports.com/';
     var EASW_ID = '123456789';
     var BUILD_CL = '123456';
     var BASE_FUT_URL = 'https://utas.fut.ea.com';
     var STATIC_ASSET_URL = '//www.easports.com/iframe/fut16';
     var CONTENT_URL = 'https://fifa15.content.easports.com';

The Id will be between 10-13 digits and the position that it is returned in the string can also change.
Am I correct in thinking that using a regular expression is the correct way to achieve this in ColdFusion? And, if so, how do I go about building a regular expression that'll meet my requirements?
Thanks

A:

Do you want to delete this value from string? Then you can use:
REReplace("YourString","var EASW_ID = '[\d]*'; *","","ALL")

Result string:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:widget="http://www.netvibes.com/ns/" xmlns:wpp="http://www.easportsworld.com/wpp/1.0"> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>Fifa Ultimate Team</title> <script type="text/javascript"> var HOST_DOMAIN = 'http://www.easports.com/'; var BUILD_CL = '123456'; var BASE_FUT_URL = 'https://utas.fut.ea.com'; var STATIC_ASSET_URL = '//www.easports.com/iframe/fut16'; var CONTENT_URL = 'https://fifa15.content.easports.com';

if you want to grab digits:
REMatch("var EASW_ID = '([\d]*)", "YourString")

or
REMatch("var EASW_ID = '([\d]{9,13})", "YourString")

to specify number of digits. Parentheses - to specify captured text. \d means any digit. And * means that char can occur from 0 to any times. {9,13} Means from 9 to 13 times. Other characters treated as is.


Q:

RAID 10 or RAID 1 x 2 for Hyper-V with AD, EXCHANGE on Windows 2008 R2

We have 2 servers which have 6 SATA 7200 disks inside (each). We want to configure both servers so that they will have Window Server 2008 R2 Enterprise installed and on top of it Exchange 2010 x2 (for 300 people) as one virtual machine and AD x2 as another virtual machine and maybe some additional VM's (but not that much.
Now we are asking ourselves if it's better to create 3 RAID groups RAID 1 or (RAID 1 and RAID 10 scenario). We're looking for performance and protection. Of course SATA drives were choose because of costs and there's no real option to choose something else.
Idea 1:

Raid A -> 2 x 1TB (RAID 1) -> C partition for system + D partition for Exchange logs
Raid B -> 2 x 1TB (RAID 1) -> E partition - all virtual machines
RAID C -> 2 x 1TB (RAID 1) -> F partition - exchange database

Idea 2:

Raid A -> 2 x 1TB (RAID 1) -> C system partition + exchange logs
Raid B -> 4 x 1TB (RAID 10) -> all virtual machines, exchange db

Idea 3:

Raid A -> 6 x 1TB (RAID10) -> system, all vm's, exchange db, exchange logs

Idea 4:

?

Which of the option is the best? Will having RAID 10 on 4 drives mitigate the problem of putting multiple stuff on one big drive so access speed may be slower if all things at once hit the same target?

A:

Just use one bit 6-way RAID10 array per server, it's kind of pointless doing anything else as you're using such slow drives and you'll lose some IO performance due to virtualisation anyway (you didn't mention hypervisor or disk access method by the way).


Q:

JavaScript: don't unload document until HttpRequest is complete

I need to make sure that when someone reloads or closes my page, their progress is saved. To save progress, I do a POST via XMLHttpRequest(), sending the data to server.
I'm triggering this saveData() function inside a window.onbeforeunload event.
The problem is, that saveData() does some calculations, and then calls a sendData(content) to finally actually POST the data.
And if the data I'm processing&sending is large (>100kB), the window seems to close before all the data gets through to the server. (I'm sending an image, and some times I only get half of it on the other side)
The http request is synchronous, xhr.open("POST", url, false), but that doesn't seem to cut it.
So my question is, how can I keep the onbeforeunload function from terminating, UNTIL xhr.readyState == 4? How do I make it wait for that event?
Oh, and setTimeout() will not work. The window will close before the "Time" comes.
This won't work:
if (!jQuery) {
    setTimeout(attachCode, 100);
    return;
} else {
    // continue and close
}

Thanks for any insight!
PS: this shouldn't be "bad practice" since it only takes a few of seconds and I don't want the user to have to save manually. Also, saving while he works (as in, before he closes window), would slow down the app so I can't do that.
[EDIT] As a temporary measure, I resorted to using this trick to auto save the data if the user decides to stay on the page. However, I'd really like to not need to use any alert messages. :(

A:

Disallowing the browser to do it's normal behaviour is normally a bad idea. And with onbeforeunload you can't pause the unload, you can only let the user know, that he/she is leaving the page and then let them decide, whether or not to leave the page - and thus the data unsaved.
So i your case, i would suggest an draft autosave, like you see in Google documents + a warning when the user leaves the page with unsaved data.


Q:

Solve a vector equation?

$$\vec{a} + \vec{b} \times \vec{x} = \lambda\vec{x}$$

$\vec{a}, \vec{b}$ are known vectors and $\lambda$ is a known scalar. How can i solve that equation ($\times$ between $\vec{b}$ and $\vec{x}$ is a vector product)?

A:

$\vec{a} + \vec{b} \times \vec{x} = \lambda\vec{x}$
If you write it using the definition of cross product you get:
$a_1\vec{i} + a_2\vec{j} + a_3\vec{k} + (b_2x_3-b_3x_2)\vec{i} - (b_1x_3-b_3x_1)\vec{j}+(b_1x_2-b_2x_1)\vec{k}=\lambda(x_1\vec{i}+x_2\vec{j}+x_3\vec{k})$
Now use the definition of equality of vectors and you`re left with three equations in three unknowns and sure you know how to handle this linear system of equations.

A:

First, assume that $a$ and $b$ are linearly independent (not parallel). Then, $a,\ b,\ a\times b$ is a basis of the space, and write
$$x=\alpha a+\beta b+\gamma(a\times b)$$
Then we have to solve
$$a-\alpha(a\times b)+\gamma\cdot b\times (a\times b) = \lambda \alpha a+\lambda\beta b+ \lambda\gamma(a\times b) \\
a+\gamma\cdot((b\cdot a)b-(b\cdot b)a)-\alpha(a\times b)= \lambda \alpha a+\lambda\beta b+ \lambda\gamma(a\times b) \\
(1-(b\cdot b))a+(\gamma(b\cdot a))b-\alpha(a\times b)= \lambda \alpha a+\lambda\beta b+ \lambda\gamma(a\times b)
$$
By the uniqueness of coordinates, we thus have $1-(b\cdot b)=\lambda\alpha$, $\ \gamma(b\cdot a)=\lambda\beta$ and $\ -\alpha=\lambda\gamma$.
So, providing $\lambda\ne 0$, we have $\alpha=\frac{1-(b\cdot b)}{\lambda}$, $\ \gamma=-\frac{\alpha}{\lambda}\ $ and $\ \beta=\frac{\gamma(b\cdot a)}{\lambda}$.


Q:

I want to add a view that will persist through out the application?

I want to add a view that will persist through out the application?
How can i achieve this?
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 430, 320, 50)];
    myView.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
    [self.window addSubview:myView];

This is not working.
Thanks in advance...

A:

There are several ways in achieving that. It's not clear if you want a view like that be in each view controller, or you want the same instance in each view controller.
Since I don't see any reason to have one shared instance (basing on your description), my approach would be to subclass UIViewController, let's call it SOMyViewController, and then inherit all view controllers in your app from SOMyViewController.
Then, I'd override the 'viewDidLoad' method of SOMyViewController as follows:
- (void) viewDidLoad {
    [super viewDidLoad];

    if ([self addMyCustomView]) {
        UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 430, 320, 50)];
        myView.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
        [self.window addSubview:myView];
    }
}

/**
 Override this in all your subclasses to decide whether to display the custom view or not
 */
- (BOOL) addMyCustomView {
    return YES;
}

If instead you want the same instance shared among view controllers, I would change the above code as follows:
static UIView *mySharedView;

+ (void) initialize {
    mySharedView = [[UIView alloc]initWithFrame:CGRectMake(0, 430, 320, 50)];
    mySharedView.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
}

- (void) viewDidLoad {
    [super viewDidLoad];

    if ([self addMyCustomView]) {
        [self.window addSubview:mySharedView];
    }
}

/**
 Override this in all your subclasses to decide whether to display the custom view or not
 */
- (BOOL) addMyCustomView {
    return YES;
}


Q:

Event triggers by itself

I have no idea why function wich should run only when button is pressed runs by herself.
Here is my button declaration:
var oButton = new sap.m.Button({
    id: "buttonId",
    text: "Yes",
    press: this.fnB()
});

My controller looks like follows:
sap.ui.controller("<controller-name>", {

    fnA: function(){<button_declaration_here>},

    fnB: function(){console.log("Hello from fnB!");}

});

When I run the app I get:

Hello from fnB!
Uncaught TypeError: Cannot read property '0' of undefined

No buttons pressed yet, so why do I get the hello message?
I use SAP WEB IDE if it matters...

A:

This:
press: this.fnB()

calls this.fnB() and uses its return value to initialize the press property, exactly the way x = foo() calls foo and assigns its return value to x.
You probably wanted
press: this.fnB

or
press: this.fnB.bind(this)

so that you were assigning a reference to the function to press, not calling it and using its return value.
That second example probably needs some explaining: If we used just
press: this.fnB

that would assign the function to press, but when it was run, the this during the call to fnB wouldn't be the same as the this in the code above, because in JavaScript, the value of this within a function is usually determined by how the function was called.
Using Function#bind:
press: this.fnB.bind(this)

...creates a new function that, when called, will call the original function with the this value we give to bind.


Q:

changing alpha value in SDL_SetRenderDrawColor doesn't effect anything. SDL2

This code shows just a simple window with a color:
#include<SDL.h>
SDL_Window* g_pWindow = 0;
SDL_Renderer* g_pRenderer = 0;
int main(int argc, char* args[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) >= 0)
    {
        g_pWindow = SDL_CreateWindow("Chapter 1: Setting up SDL",
            SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
            640, 480,
            SDL_WINDOW_SHOWN);
        if (g_pWindow != 0)
        {
            g_pRenderer = SDL_CreateRenderer(g_pWindow, -1, 0);
        }
    }
    else
    {
        return 1; // sdl could not initialize
    }
    SDL_SetRenderDrawColor(g_pRenderer, 80, 80, 253, 0);
    // clear the window to black
    SDL_RenderClear(g_pRenderer);
    // show the window
    SDL_RenderPresent(g_pRenderer);
    // set a delay before quitting
    SDL_Delay(2000);
    // clean up SDL
    SDL_Quit();
    return 0;
}

I'm testing to see what happens when I change the alpha factor in SDL_SetRenderDrawColor(g_pRenderer, 80, 80, 253, 0). When I change the alpha value from 0 to 255 it doesn't effect anything.
What's the problem here?

A:

First of all, you haven't enabled blending (e.g. SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);).
But anyway, it makes no sense for clear operation to use blending, and I bet SDL_RenderClear ignores it.
If you want fullscreen blend, you should draw fullscreen rectangle with SDL_RenderFillRect.


Q:

Ошибка при компиляции, Си

Не получается скомпилировать данный код.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE *file =  fopen("c:\test.txt", "w");
    int wordNumbers;
    printf("please add an amount of words into the dictionary ");
    scanf("%i", &wordNumbers);

    for (int i=0; i< wordNumbers; i++)
    {
        char word[30] = {0};
        printf("add a word into the dictionary please\n");
        scanf("%s", &word);
        fprintf(file, "%s", word);
    }
    fclose(file);
    return 0;
}

Указывает на ошибки в строке
for (int i=0; i< wordNumbers; i++)

Пишет: "синтаксическая ошибка", и о не объявлении переменной і.
Подскажите, пожалуйста, где здесь ошибка. Сама программа, по идее, должна в файл записывать некоторые слова, которые в последующем я использую в качестве словаря.

A:

Возможно ваш компилятор не поддерживает стандарт C99 и требует, чтобы все переменные были объявлены в начале блока.
Поэтому объявите переменную i в начале функции. Например,
int main()
{
    FILE *file =  fopen("c:\test.txt", "w");
    int wordNumbers;
    int i;
    ^^^^^
    printf("please add an amount of words into the dictionary ");
    scanf("%i", &wordNumbers);

    for ( i=0; i< wordNumbers; i++)
    {
        //...

A:

Ошибка скорее всего в том, что программа компилируется в режиме C90 или в более ранних стандартах. Там действительно запрещено объявлять переменные таким образом. Пример:
int main( void )
{
  for( int i = 0; i < 1; i++ ) {}
  return 0;
}

1)
$ gcc -ansi 1.c
1.c: In function ‘main’:
1.c:7:3: error: ‘for’ loop initial declarations are only allowed in C99 or C11 mode
   for( int i = 0; i < 1; i++ ) {}
   ^
1.c:7:3: note: use option -std=c99, -std=gnu99, -std=c11 or -std=gnu11 to compile your code

2)
$ gcc -std=c90 1.c
1.c: In function ‘main’:
1.c:7:3: error: ‘for’ loop initial declarations are only allowed in C99 or C11 mode
   for( int i = 0; i < 1; i++ ) {}
   ^
1.c:7:3: note: use option -std=c99, -std=gnu99, -std=c11 or -std=gnu11 to compile your code

3)
$ gcc -std=c99 1.c && echo "$?"
0

В двух первых случаях C-код должен выглядеть так:
int main( void )
{
  int i;
  for( i = 0; i < 1; i++ ) {}
  return 0;
}

Или меняйте стандарт в опциях компилятора/IDE.
P.S. А работа с файлами тут вообще не при чём. Поменяйте заголовок чтобы никого не сбивать с толку.
P.P.S. а, нет, при чём :) Но это уже совсем другой вопрос (подсказка: ошибка в "c:\test.txt")


Q:

Problem populating a Jlist based on two Jcomboboxes connected to a PostgreSQL database

Good afternoon
I'm working on a project in witch I have to calculate the performance of a pump for certain parameters like rotation, number of stages, diameter and viscosity. At first I created a database using PostgreSQL with several commercial pumps. The database contains schemas as the companies that manufacture the pumps, in each schema there are tables representing the different series of pumps and the tables have several pumps organized as lines. The lines contains coefficients that represent the pumps and that are necessary to calculate the performance.
I tried to code the application in C++, but was too hard to connect with Postgre, so I ended working with Java and Netbeans (I think it's easier to newcomers). The application is running quite good so far, but I have found two problems that I cannot solve.
To select the pump to make the calculations I had to use two Jcomboboxes and a Jlist. The first Jcombobox is for selecting the manufacturer, the second to select the serie. Finally, the Jlist displays all the pumps in that serie so the user can select one.
I was able to populate the first Jcombobox with the schemas of the database (thanks to you guys, actually), the second with the tables of the schema selected in the first and the Jlist with the names of the pumps.
The first problem is that I cannot clear the second Jcombobox (the series one) after changing the selected manufacturer in the first Jcombobox, it will add more itens every time that I change the first Jcombobox, even if I re-select an item that was already selected. I tried using the command  "removeAllItems()", but then it displays just one table and stop filling the Jcombobox.
The second problem is that, when I select a serie in the second Jcombobox, it doesn't immediately display the pumps in the Jlist, the Jlist starts displaing after I select another serie. So, I have to select one and then change to another so the pumps start appearing in the Jlist.
I'm sorry for the long text and the english errors, I hope its enough for you guys to understand. I know the code is not pretty, that's because I'm not so good at this yet and I'm in a bit of a hurry to deliver it.
Here is the code, without all the generated code that Netbeans does.
public final class LabPump extends javax.swing.JFrame {

Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;

public LabPump() {
    initComponents();

    con = ConnectPump.connect();

    FillSelectFabricante();

}

public void FillSelectFabricante(){

    try {
        rs = con.getMetaData().getSchemas();

        while(rs.next()){
            String schemas = rs.getString("TABLE_SCHEM");

            if(schemas.equals("information_schema") || schemas.equals("pg_catalog")){
            }
            else{
                selectFabricante.addItem(schemas);
            }
        }
    }
    catch(SQLException error){
        JOptionPane.showMessageDialog (null,error);
    }

}

public void FillSelectSerie(String fabricante){

    //selectSerie.removeAllItems();

    try {
        String[] sql = {"TABLE"};
        rs = con.getMetaData().getTables(null, fabricante, "%", sql);

        while(rs.next()){
            String tables = rs.getString(3);

            selectSerie.addItem(tables);
        }
    }
    catch(SQLException error){
        JOptionPane.showMessageDialog (null,error);
    }

}

public void FillListBomba(String fabricante, String serie){

    DefaultListModel dlm = new DefaultListModel();
    dlm.removeAllElements();

    try{
        String sql = "select * from " + fabricante + "." + serie;
        pst = con.prepareStatement(sql);
        rs = pst.executeQuery();

        while(rs.next()){
            String bomba = rs.getString("bomba");
            dlm.addElement(bomba);
        }
    listBomba.setModel(dlm);
    }
    catch(SQLException error){
        JOptionPane.showMessageDialog (null,error);
    }

}

    private void selectSerieActionPerformed(java.awt.event.ActionEvent evt) {

    selectSerie.addActionListener((ActionEvent e) -> {
        String fabricante = selectFabricante.getSelectedItem().toString();
        String serie = selectSerie.getSelectedItem().toString();

        FillListBomba(fabricante, serie);

    });
}

private void selectFabricanteActionPerformed(java.awt.event.ActionEvent evt) {

    String fabricante = selectFabricante.getSelectedItem().toString();

    FillSelectSerie(fabricante);

}

Thank you all.

A:

I managed to solve the problem just now. When the selectSerie.removeAllItems() line was uncommented the program returned a NullPointerException error.
To solve the problem I used the DefaultComboBoxModel class and then used the RemoveAllElements() method. I'm not quite sure why the other method didn't work though.
Thanks for your time and help Peter.
public void FillSelectSerie(String fabricante) {

    DefaultComboBoxModel box;
    box = new DefaultComboBoxModel();
    box.removeAllElements();

    try {
        String[] sql = {"TABLE"};
        rs = con.getMetaData().getTables(null, fabricante, "%", sql);
        box.addElement("-");

        while (rs.next()) {
            String tables = rs.getString(3);
            box.addElement(tables);
        }
        selectSerie.setModel(box);
    } catch (SQLException error) {
        //JOptionPane.showMessageDialog (null,error);
    }
}


Q:

apex detail page is blank

I am trying to display detail of a custom object by using apex:detail. But i am getting no a blank page without any details i try it with Account but it was not working.
 <apex:page standardController="CustomObjectA__c">
   <apex:detail subject="{!CustomObjectA__c.id}" relatedList="true" title="false"/>
 </apex:page>

please help me to get it solved.

A:

With a standard controller, <apex:detail /> without a subject should be sufficient, but you must  pass an id to the page, e.g., http://c.naX.visual.force.com/apex/detailTest?id=a03E00000082KUi.


Q:

external link not working javascript

I have some basic javascript that was originally in the html file but then I have put it in an external file and it is not working, I am not sure why. I have put the script just before the closing body tag.
Here is my code:
http://jsfiddle.net/2fuxR/
HTML

JAVASCRIPT
 function display(imgElement){
   document.getElementById('displayimg').setAttribute('src',imgElement.getAttribute('src'));

A:

you forgot the } at end of jscript function
and try adding a slash to your js src


Q:

How to substitute a point in line equation using sympy

from sympy import *

Rfinal = dict()
Bfinal = dict()
x, y = symbols('x y')

Red= [(1,1),(2,1),(4,2),(2,4), (-1,4)]
Blue= [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines=["(1*x)+(1*y)+0","(1*x)-(1*y)+0","(1*x)+(0*y)-3","(0*x)+(1*y)-0.5"]

for exp in Lines:
    for a,b in Red:
        d = exp.subs(x,a).subs(y,b)
        if d > 0:
            Rfinal['(a,b)'] = positivepoint
        elif d == 0:
            Rfinal['(a,b)'] = pointontheline
        else:
            Rfinal['(a,b)'] = negativepoint

for exp in Lines:
    for p,q in Blue:
        d = exp.subs(x,a).subs(y,b)
        if d > 0:
            Bfinal['(p,q)'] = positivepoint
        elif d == 0:
            Bfinal['(p,q)'] = pointontheline
        else:
            Bfinal['(p,q)'] = negativepoint

error 'str' object has no attribute 'subs'*

A:

IIUC
from sympy import *

Rfinal = dict()
Bfinal = dict()
x, y = symbols('x y')

Red = [(1,1),(2,1),(4,2),(2,4), (-1,4)]
Blue = [(-2,-1),(-1,-2),(-3,-2),(-3,-1),(1,-3)]
Lines = [x+y, x-y, x+y-3, x+y-0.5]

for exp in Lines:
    Rfinal[exp]={}
    Bfinal[exp]={}

    for point in Red:
        d = exp.subs(x,point[0]).subs(y,point[1])
        if d > 0:
            Rfinal[exp][point] = 'positivepoint'
        elif d == 0:
            Rfinal[exp][point] = 'pointontheline'
        else:
            Rfinal[exp][point] = 'negativepoint'

    for point in Blue:
        d = exp.subs(x,point[0]).subs(y,point[1])
        if d > 0:
            Bfinal[exp][point] = 'positivepoint'
        elif d == 0:
            Bfinal[exp][point] = 'pointontheline'
        else:
            Bfinal[exp][point] = 'negativepoint'

Bfinal
{x + y: {
  (-2, -1): 'negativepoint',
  (-1, -2): 'negativepoint',
  (-3, -2): 'negativepoint',
  (-3, -1): 'negativepoint',
  (1, -3): 'negativepoint'},
 x - y: {
  (-2, -1): 'negativepoint',
  (-1, -2): 'positivepoint',
  (-3, -2): 'negativepoint',
  (-3, -1): 'negativepoint',
  (1, -3): 'positivepoint'},
 x + y - 3: {
  (-2, -1): 'negativepoint',
  (-1, -2): 'negativepoint',
  (-3, -2): 'negativepoint',
  (-3, -1): 'negativepoint',
  (1, -3): 'negativepoint'},
 x + y - 0.5: {
  (-2, -1): 'negativepoint',
  (-1, -2): 'negativepoint',
  (-3, -2): 'negativepoint',
  (-3, -1): 'negativepoint',
  (1, -3): 'negativepoint'}}


Q:

Pop up the file to be download on clicking the link

I am trying to make the .txt, .xml,.sql files be downloadable in the same page just like .zip,.docx files which are pop up and ask "do you want to download this file?".
I have researched and found that the windows default option for these files are open in new browser but I just want to be download in the same page. I have attached the image just like that I need to pop up when clicking those .txt,.xml,.sql files.
How can this be done? Anyone have idea for this.

A:

        I have corrected by my own. Just putting the code below will successfully pop up any files to ask whether to download or not. This is my new code.
    The download.php contains the code below:

        <?php
        $filename = $_GET["file"];
        $contenttype = "application/force-download";
        header("Content-Type: " . $contenttype);
        header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
        if($_GET['path'] == 'new_uploads')
        readfile($_SERVER['DOCUMENT_ROOT']."50dl/admin_panel_new/assets/plupload/new_uploads/".$filename);
        else
        readfile($_SERVER['DOCUMENT_ROOT']."50dl/admin_panel_new/assets/plupload/assessment_uploads/".$filename);
        exit();
        ?>

And the file.php contains this code:

<img src="<?php echo base_url();?>assets/plupload/assessment_uploads/<?php echo $files->file_name?>" title="DOWNLOAD IMAGE" height="100" width="100" onClick="window.location.href='<?php echo base_url();?>logos/download?file=<?php echo $files->file_name?>&path=assessment_uploads'" class="download"/>

This will correctly sort out the current issue.


Q:

How to merge content of enduser defined to DataTemplate in WPF, some like change DataTemplate content at runtime

I want to change DataTemplate's content at runtime, the content is designed by enduser, and saved in a file as xaml format.
the DataTemplate is defined like this:
<DataTemplate x:Key="DataTemplate1">
    <Grid>
        <Canvas x:Name="canvas1" />
    </Grid>
</DataTemplate>

and the content designed by enduser like this:
<Canvas x:Name="canvas1">
    <Label ...>
    ...
</Canvas>

I want to meger the content designed by enduser to the datatemplate using code:
DataTemplate templateObj = FindResource("DataTemplate1");

and now I don't know how to change the templateObj to merge the content, at last the templateObj will like this:
    <DataTemplate x:Key="DataTemplate1">
        <Grid>
            <Canvas x:Name="canvas1">
                <Label ...>
                ...
            </Canvas>
        </Grid>
    </DataTemplate>

A:

Actually I don't think you can marge two DataTemplates. Try create one parent template and one child  which base on parent template. Change template use:
DataTemplate summary = this.FindResource("SimpleTemplate") as DataTemplate;
YourControl.ItemTemplate = summary;


Q:

Calculating time difference between two db values for multiple rows

I have a database which holds two timestamps (date_ticket_reported, date_ticket_resolved), I want to caluclate the average time difference between these times for each resolved_by user_id.
Each row has a (resolved_by) column which corresponds to a user_id.
There will be multiple rows, for each user_id.
I have tried various approaches including the following.
ticket_model.php code
public function get_resolved_time_by_user($user_id){
    $query1 =    $this->db->select('resolved_date')->from('tickets')->where('resolved_by',$user_id)->get();
    $resolved1 =  $query1->row();
    $query2 = $this->db->select('ticket_date_reported')->from('tickets')->where('resolved_by',$user_id)->get();
    $reported1 = $query2->row();

    $resolved2 = $resolved1->resolved_date;
    $reported2 = $reported1->ticket_date_reported;
    foreach($resolved2 as $row){
    //Convert them to timestamps
    $reported_dateTimestamp = strtotime($resolved2);
    $resolved_dateTimestamp = strtotime($reported2);

    $diff = $resolved_dateTimestamp - $reported_dateTimestamp;
    return $diff;

    }

}

Ticket view code
<p> Average Resolve Times  <?php echo $this->ticket_model->get_resolved_time_by_user($user_id); ?> </p>

So to summarise; I want to display the average time between  date_ticket_reported, date_ticket_resolved. For each user_id specified.
Any help would be awesome!
I have tried Malkhazi Dartsmelidze answer,
$this->db->query("SELECT
AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as     timediff,
    resolved_by as user
FROM tickets
GROUP BY resolved_by");

I get an error saying Object of class CI_DB_mysqli_result could not be converted to string
Where you say resolved_by as user. Should "user" be the user_id? ie should it say "resolved_by as user_id"?

A:

You Can run only One Query With Myqsl:
SELECT
    AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as timediff,
    resolved_by as user
FROM tickets
GROUP BY resolved_by

This returns Average Time Difference in Seconds for Each User


Q:

How does the naive Bayes classifier handle missing data in testing?

Assume that a classier has been trained already (no missing training data), but a prediction has been requested based on an observation that does not include every feature. How can we handle this missing feature?

A:

In evaluation (test) phase, when data point $x_n$ has $d$ missing features at indices $M=\{m_1,...,m_d\}$, corresponding terms $P(x_i|C_k),i \in M$ are simply removed from the classifier. That is, classifier
$$C(x_n) = \underset{k \in \{1,..,K\}}{\mbox{argmax }}P(C_k)\prod_{i}P(x_i=x_{n,i}|C_k)$$
is replaced with
$$C(x_n) = \underset{k \in \{1,..,K\}}{\mbox{argmax }}P(C_k)\prod_{\color{blue}{i:i \notin  M}}P(x_i=x_{n,i}|C_k)$$
where $i$ iterates over features, $x_{n,i}$ denotes the $i$-th feature of data point $n$, and there is $K$ classes in total.


Q:

Can't change State from child component even after passing a function from parent component

Currently making a to-do app that has a welcome screen at first, but when clicked the button enter, it'll setState welcome from true to false. triggering the actual todo list component.
For some reason even after passing down the function to WelcomePage, React still wont render to the other component when I press enter.
Thank you,
function Router(props) {
    if (props.welcome) {
        return <WelcomePage onEnter={props.onEnter}/> //if home is true, there will be home page rendered
    } else {
        return <ToDoPage/> //if home is false, that means you've entered
    }
}

class ToDo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {welcome: true};
        this.onEnter = this.onEnter.bind(this);
    }

    onEnter(e) {
        this.setState({welcome: false});
    }

    render() {
        return (

                    <Router welcome={this.state.welcome} onEnter={this.onEnter}/>

            )
    }
}

class WelcomePage extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

 Welcome

 Who does this list beong to?

                <input placeholder="your name"/>
                <input type="button" value="enter" onSubmit={this.props.onEnter}/>

            )
    }
}

A:

Try changing onSubmit to onClick as input:button does not emit submit events:
class WelcomePage extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

 Welcome

 Who does this list beong to?

                <input placeholder="your name"/>
                <input type="button" value="enter" onClick={this.props.onEnter}/>

            )
    }
}


Q:

Compared to mod_wsgi, how does mod_python "work"?

It seems most of the blog posts the web relating to mod_python & mod_wsgi concentrate on telling me how mod_wsgi is better and what a WSGI application looks like. This is fine, but what I'd really want to know -- to have complete knowledge of the subject -- is:
How do they differ in running a script?
With CGI the server simply sets up the environment and runs a simple .py. WSGI wraps the application in an object, but the concept is still pretty much the same: run a .py file.
How does mod_python do it?
I'm also really interested in learning how anything mod_ works, so, really, feel free to point me to anything interesting on the subject.
Thanks!

A:

You could start by reading:
http://blog.dscpl.com.au/2009/03/python-interpreter-is-not-created-for.html
The basic principle of when/how sub interpreters are created and used is the same in mod_wsgi as well.
The question is why you would want to use mod_python as a basis for learning how it works as mod_python is no longer being developed and has been moved to the attic by the Apache software foundation. The mod_wsgi module also fixes various things mod_python gets wrong with thread handling if your intention is to go down to that level.

A:

See the official mod_python documentation, namely:

So what exactly does mod_python do?
Multiple interpreters

In practice, please note that there usually is no need to run Apache at all when working with python and web as there are many, many ways of serving the pages from python directly
Standard library:

http.server
wsgiref

External web servers:

Green Unicorn
Twisted web
...and many others

External Web frameworks:

CherryPy
WerkZeug
numerous others


Q:

Axios VueJs Response Map Unique

I am trying to retrieve car manufacturer ID's using AXIOS within VueJs front-end and Spring back-end.
In the code provided below I have achieved that, however some of the ID's repeat(this is meant to happen), the question is how is it possible to filter out the duplicate ID's?
My getMethod below.
   getMethod () {
            AXIOS.get(`/url/`)

                .then(response => {
                        if (response.status == 200) {

this.response = response.data
                            this.myTest = response.data.map(mesg => mesg.carManufacterId)
                            console.log(this.myTest)

                        }
                    },
                    (err) => {

                       if (err.response.status == 500) {

                            console.log('turned off')
                        }
                        else if (err.response.status == 404) {
                                console.log('Could not retrieve)
                        }
                    })

        },

A:

You achieve that by looping through your response data array and check in each iteration if the new item is already in myTest array based on carManufacterId:
this.myTest = []
response.data.forEach(item => {

  if (!this.myTest.some(rec => {
      return item.carManufacterId === rec.carManufacterId
    })) {
    this.myTest.push(item);
  }
});


Q:

NHibernate 3.3 or Entity Framework 4.3 for Oracle 11g and ASP.NET MVC 3.0?

I have to choose between last versions of NHibernate (3.3) and Entity Framework (4.3) to work with Oracle 11g; a very special issue with our architecture is: we have to execute a lot of stored procedures to keep balance with others old systems.
We're gonna use ASP.NET MVC 3 for user interface. so, can you help to choose which is more convenient for our architecture between NHibernate and Entity Framework?
I have read that Oracle driver for Entity Framework is very new, so, I can't decide yet.

A:

MS is very committed to EF but they are not developing provider for Oracle! Is Oracle committed to EF as well?
The best way to make decision is to create a short POC (proof of concept) where you evaluate both tools on some easy and intermediate problems (you can also try a hard problem) you will have to solve in the real project. This will help you understand challenges in both tools on your real problems not only in some imaginary discussion. It will also help you understand difficulties in adopting a new technology and integrating it with your existing environment.


Q:

Renaming a Word document and saving its filename with its first 10 letters

I have recovered some Word documents from a corrupted hard drive using a piece of software called photorec. The problem is that the documents' names can't be recovered; they are all renamed by a sequence of numbers. There are over 2000 documents to sort through and I was wondering if I could rename them using some automated process.
Is there a script I could use to find the first 10 letters in the document and rename it with that? It would have to be able to cope with multiple documents having the same first 10 letters and so not write over documents with the same name. Also, it would have to avoid renaming the document with illegal characters (such as '?', '*', '/', etc.)
I only have a little bit of experience with Python, C, and even less with bash programming in Linux, so bear with me if I don't know exactly what I'm doing if I have to write a new script.

A:

How about VBScript? Here is a sketch:
FolderName = "C:\Docs\"
Set fs = CreateObject("Scripting.FileSystemObject")

Set fldr = fs.GetFolder(Foldername)

Set ws = CreateObject("Word.Application")

For Each f In fldr.Files
    If Left(f.name,2)<>"~$" Then
        If InStr(f.Type, "Microsoft Word") Then

        MsgBox f.Name

        Set doc = ws.Documents.Open(Foldername & f.Name)
        s = vbNullString
        i = 1
        Do While Trim(s) = vbNullString And i <= doc.Paragraphs.Count
            s = doc.Paragraphs(i)
            s = CleanString(Left(s, 10))
            i = i + 1
        Loop

        doc.Close False

        If s = "" Then s = "NoParas"
        s1 = s
        i = 1
        Do While fs.FileExists(s1)
            s1 = s & i
            i = i + 1
        Loop

        MsgBox "Name " & Foldername & f.Name & " As " & Foldername & s1 _
            & Right(f.Name, InStrRev(f.Name, "."))
        '' This uses copy, because it seems safer

            f.Copy Foldername & s1 & Right(f.Name, InStrRev(f.Name, ".")), False

            '' MoveFile will copy the file:
        '' fs.MoveFile Foldername & f.Name, Foldername & s1 _
        ''  & Right(f.Name, InStrRev(f.Name, "."))

        End If
    End If
Next

msgbox "Done"
ws.Quit
Set ws = Nothing
Set fs = Nothing

Function CleanString(StringToClean)
''http://msdn.microsoft.com/en-us/library/ms974570.aspx
Dim objRegEx
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True

''Find anything not a-z, 0-9
objRegEx.Pattern = "[^a-z0-9]"

CleanString = objRegEx.Replace(StringToClean, "")
End Function


Q:

c# - create thread in for loop (arguement out of range exception)

I don't know how to describe this problem precisely. Let's look at my code.
for (int i = 0; i < myMT.Keys[key_indexer].Count; i++)
{
     threads.Add(new Thread(
         () =>
         {
             sounds[myMT.Keys[key_indexer][i]].PlayLooping();
         }
     ));
     threads[threads.Count - 1].Start();
}

Note: sounds is a list of SoundPlayers
The initialization of threads and myMT:
List<Thread> threads = null;
MusicTransfer myMT=null;

and in the constructor:
threads = new List<Thread>();
myMT = new MusicTransfer(bubblePanel);

The variable Keys in myMT is with type of List<List<int>>. It is initialized with the same way of myMT and threads. Imagine a matrix, the outer list is a list of rows and the inner one is for each cell.
When I run the program, I set myMT.Keys[key_indexer].Count to 1. So, normally, the for loop should stop when i reach 1.
However, it throws an exception of ArgumentOutOfRange at the line of sounds[myMT.Keys[key_indexer][i]].PlayLooping(). So, I used debugger to check the value of each variable.
What I found are:

If I use "step over" check step by step, which means time is consumed quite much after the new thread runs, for loop will stop when i reaches 1, which is the way it should be.
If I click "continue" after the breakpoint triggered, the for loop is still processing after i equals 1.
the break point should always be set at the line of threads.Add(new Thread(. If it is set at the line of sounds[myMT.Keys[key_indexer][i]].PlayLooping();, the exception will be triggered even after "step over"

I guess the problem is about thread, but have no idea how to solve it.
Thanks for any help!

A:

There is so many things wrong with your post, however maybe this will help you out a bit
Note : Make your code readable, trust me it does wonders
// List of threads
var threads = new List<Thread>();

// Lets stop indexing everything and make it easy for ourselves
var someList = myMT.Keys[key_indexer];

for (var i = 0; i < someList.Count; i++)
{
    // we need to create a reference to the indexed value
    // in the someList, otherwise there is no gaurentee
    // the thread will have the right index when it needs it
    // (thank me later)
    var someSound = someList[i];

    // create a thread and your callback
    var thread = new Thread(() => someSound.PlayLooping());

    // add thread to the list
    threads.Add(thread);
}

// now lets start the treads in a nice orderly fashion
foreach (var thread in threads)
{
    thread.Start();
}

Another way to do this with Tasks
var tasks = new List<Task>();

var someList = myMT.Keys[key_indexer];
for (var i = 0; i < someList.Count; i++)
{
    var someSound = someList[1];
    var task = new Task(() => someSound.PlayLooping());
    tasks.Add(task);
    task.Start();
}

Task.WaitAll(tasks.ToArray());

Disclaimer : i take no responsibility for your other logic problems, this was for pure morbid academic purposes


Q:

How to print the confidence level of a predicted image

I trained a logistic regression model on the mnist data set, these are the important variables...
# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes

# set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# construct model
logits = tf.matmul(x, W) + b
pred = tf.nn.softmax(logits)  # Softmax

# minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=1))

# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(cost)

Now what I did is I created an array called adversarial of slightly altered images that I feed back into the model so that it can make a prediction.
If I do the following...
classification_adversarial = sess.run(tf.argmax(pred, 1), feed_dict={x:adversarial})
print(classification_adversarial)

>> [6, 6, 6, 6, 6, 6, 6, 6, 6, 6]

I get an output of the model's prediction. This is the intended output, the model thinks that the images are 6s.
Anyways, for each of these images, I would like an accuracy to be displayed. So if I feed one image such as adversarial.reshape((1, 784)), I want the model to tell me how accurate, percentage-wise, is its prediction.
I tried to implement something like the following to get the total accuracy...
# list of booleans to determine the correct predictions
correct_prediction = tf.equal(tf.argmax(pred, 1), np.array([6]*10))
print(correct_prediction.eval({x:adversarial}))

>> [True, True ... , True, True]

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: adversarial}))

>> Accuracy: 1.0

I am getting an accuracy of 1.0. What does this mean, my model is 100% accurate? If this is so, I must be doing something wrong.

A:

To print confidence of each image, you have to print "pred" which is softmax of logits.
In your case, accuracy is measured only for 10 images and model is correct in all 10 cases. So, accuracy is 1.0

Does that makes sense ?? Comment if you need more information.


Q:

Understanding bindings in IIS on Azure VM

I have a VM in Azure with IIS running and hosting a website.  This site was originally written and hosted by another company and they recently moved it to this VM for us.  The binding still shows as the old website name (as hosted on the other company's site) and we still access it by going to the original website URL name in our browser.  The developer mentioned to me that I'd need to eventually change the binding to reflect something hosted by my company.
My question is what is my next step?  I know how to change the binding, but I'm having trouble knowing what to change it to?  Ideally, I'd like to have the site hosted in Azure - the url name does not matter to me, as long as I can change it from the old original one.  I created a new Web App in Azure and am trying to point the website to that new url but it's not working.  Not sure that's the best route anyway.

A:

If I understood your question correctly, Original website may have a domain name associated with it. You will have to update the DNS records with PIP (static-public IP) of Azure VM (site is now running on IIS on Azure VM).
Trust this helps.


Q:

why does if statement not work in actionlistener

enter.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            User = input.getText();

            if (User == "hello") {
                Console = "Hi User!";
            }

            output.setText("User: " + User + "\n" + "Console: " + Console);
        }
    });

When I run it, it displays the text on the GUI.
But why is it that the console doesn't respond.
I did a system.out.prinln on User when I wrote "hello"
Thats exactly hat it said, why is this if statement not working?

A:

You need to compare String using .equals method not ==, so try to change you code to something like:
if (User.equals("hello")) {
    Console = "Hi User!";
}

Read more about How to Compare String in java


Q:

Python - functions being called inside list bracket. How does it work?

I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'.
I found this piece of code, which works:
 list = ['X' if coord == '0' else coord for coord in printready]

What I would like to know is exactly why this works (I understand the logic in the code, just not why the compiler accepts this.)
I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').
This is probably thoroughly documented, but I have no idea on what this thing is called.

A:

This construction is called a list comprehension. These look similar to generator expressions but are slightly different. List comprehensions create a new list up front, while generator expressions create each new element as needed. List comprehensions must be finite; generators may be "infinite".

A:

I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').

If you're going to substitute multiple variables, I would use a dictionary instead of an "elif".  This makes your code easier to read, and it's easy to add/remove substitutions.
d = {'0':'X', '1':'Y', '2':'Z'}
lst = [d[coord] if coord in d else coord for coord in printready]


Q:

Is it possible to check if certain layer is empty? CS6 Script

I want function which checks if certain layer has all pixels with 0% transparency, in other words, layer is just empty.
function isLayerEmptyCheck(layer) {
   //code
}

Unfortunately, I couldn't find any information in documentation (Photoshop CS6 Scripting Guide, Photoshop CS6 JavaScript Ref) of any artlayer property of this kind.

A:

There is only need to check of property of artlayer bounds to find out, if all values of its arrays are equal to "0 px". When all of them are "0 px", then it means that layer is empty.
Below I created function which checks if input layer is unfilled.
#target photoshop

var doc = app.activeDocument;
var certainLayer = doc.artLayers[0];

var isLayerEmpty = isLayerEmptyCheck(certainLayer);

alert(isLayerEmpty);

function isLayerEmptyCheck(layer) {

    var isLayerEmpty = new Boolean;

    var LayerBounds = layer.bounds;
    if (LayerBounds[0] === "0 px" && LayerBounds[1] === "0 px" && LayerBounds[2] === "0 px" && LayerBounds[3] === "0 px") {
        return isLayerEmpty = true;
    } else {
        return isLayerEmpty = false;
    }

}


Q:

Concise induction step for proving $\sum_{i=1}^n i^3 = \left( \sum_{i=1}^ni\right)^2$

I recently got a book on number theory and am working through some of the basic proofs. I was able to prove that $$\sum_{i=1}^n i^3 = \left( \sum_{i=1}^ni\right)^2$$ with the help of the identity $$\sum_{i=1}^ni = \frac{n(n+1)}{2}$$ My proof of the induction step goes as follows (supposing equality holds for all $k \in \{1,2,\dots n \})$: $$\sum_{i=1}^{n+1} i^3 = \sum_{i=1}^{n} i^3+(n+1)^3 \\ =  \left( \sum_{i=1}^ni\right)^2+(n+1)^3 \\ =  \left( \frac{n(n+1)}{2}\right)^2 + (n+1)^3 \\ =  \frac{n^2(n+1)^2}{4}+\frac{4(n+1)^3}{4} \\ = \frac{n^4+2n^3+n^2}{4}+\frac{4n^3+12n^2+12n+4}{4} \\ = \frac{n^4+6n^3+13n^2+12n+4}{4} \\ = \frac{(n^2+3n+2)^2}{4} \\ = \frac{[(n+1)(n+2)]^2}{4} \\ = \left(\frac{(n+1)(n+2)}{2}\right)^2 \\ =  \left(\sum_{i=1}^{n+1}i\right)^2$$ I was a little disappointed in my proof because the algebra got really hairy. It took me a long while to see that I could twice unfoil the polynomial $n^4+6n^3+13n^2+12n+4$ and all in all the solution seems pretty inelegant. Does anyone have a smoother way to prove the induction step or bypass the algebra? I feel like their must be some concise way to get the same result.

A:

An idea for your fourth line:
$$\frac{n^2(n+1)^2}{4}+\frac{4(n+1)^3}{4}=\frac{(n+1)^2}4\left(n^2+4n+4\right)=\frac{(n+1)^2}4(n+2)^2$$


Q:

Can this iteration be written in a tidy functional way

data has a column named description of type character() and a column id of type integer() that is set by row_number().
data_map has a column name desc_map of type character() and a column id of type integer() that is set by row_number().
data and data_map do have other columns used in further processing after joining.
The idea of the code below is to use data_map$desc_map as a pattern in str_detect to match data$description. On a match it would add a row to another tibble, using data$id and data_map$id. The resulting matches allows joining together of data and data_map.
library(tidyverse)

data = tribble(
  ~description,
  "19ABB123456",
  "19BCC123456",
  "19CDD123456",
  "19DEE123456",
  "19EFF456789",
  "19FF0056789",
  "19A0A123456",
) %>% mutate(id = row_number())

data_map = tribble(
  ~desc_map,
  "AA",
  "BB",
  "CC",
  "DD",
  "EE",
  "FF",
  "00",
) %>% mutate(id = row_number())

seq_along_rows <- function(.data) {
  seq_len(nrow(.data))
}

matches <- data %>% (function (tbl) {
  m <- tibble(
    row_id = integer(),
    map_id = integer()
  )

  for (i in seq_along_rows(tbl)) {
    row <- tbl[i, ]
    key <- row[["description"]]
    found <- FALSE

    for (j in seq_along_rows(data_map)) {
      map_row <- data_map[j, ]
      pattern <- map_row[["desc_map"]]

      if (str_detect(key, pattern)) {
        m <- add_row(m, row_id = row[["id"]], map_id = map_row[["id"]])
        found <- TRUE
        # allow for finding more than one match
      }
    }

    if (!found) {
      m <- add_row(m, row_id = row[["id"]], map_id = NA)
    }
  }

  return(m)
})

not_unique <- matches %>%
  group_by(row_id) %>%
  filter(n() > 1) %>%
  ungroup() %>%
  inner_join(data, by = c("row_id" = "id")) %>%
  inner_join(data_map, by = c("map_id" = "id"))

head(not_unique)
#> # A tibble: 2 x 4
#>   row_id map_id description desc_map
#>    <int>  <int> <chr>       <chr>
#> 1      6      6 19FF0056789 FF
#> 2      6      7 19FF0056789 00

matches_not_found <- matches %>%
  filter(is.na(map_id)) %>%
  select(-map_id) %>%
  inner_join(data, by = c("row_id" = "id"))

head(matches_not_found)
#> # A tibble: 1 x 2
#>   row_id description
#>    <int> <chr>
#> 1      7 19A0A123456

matches_found <- matches %>%
  filter(!is.na(map_id)) %>%
  inner_join(data, by = c("row_id" = "id")) %>%
  inner_join(data_map, by = c("map_id" = "id"))

head(matches_found)
#> # A tibble: 6 x 4
#>   row_id map_id description desc_map
#>    <int>  <int> <chr>       <chr>
#> 1      1      2 19ABB123456 BB
#> 2      2      3 19BCC123456 CC
#> 3      3      4 19CDD123456 DD
#> 4      4      5 19DEE123456 EE
#> 5      5      6 19EFF456789 FF
#> 6      6      6 19FF0056789 FF

My question is, can this code be written in a more tidy functional way and what that would look like? If it cannot be done in such a way, what would the reason be?

A:

Update
Based on your updated question here is an updated version of my answer.
This time I just used your inputs as is and did not create a named function. Instead I put everything in one pipe. The column found should indicate how many times a pattern was found, so you should not need different objects as not_unique, matched_not_found, matches_found.
I picked up the idea from GenesRus (in the comments of your question) to create a list-column and unnnest it, but I did not take the approach further using spread/pivot-wider and instead chose map2 to loop over the description and desc_map columns.
library(tidyverse)

data %>%
  mutate(pattern = list(data_map)) %>%
  unnest %>%
  rename(row_id = "id", map_id = "id1") %>%
  mutate(v = map2_lgl(description, desc_map,
                  ~ str_detect(.x, .y))) %>%
  group_by(row_id) %>%
  mutate(found = sum(v),
         desc_map = ifelse(found == F, NA, desc_map),
         map_id = ifelse(found == F, NA, map_id)) %>%
  filter(v == T | (v == F & found == 0)) %>%
  distinct %>%
  select(-v)

Old answer
Below is a more tidyverse-based approach which should yield the same result. 'Should' because I can only guess how your input data and expected result looks like. A few notes: (1) I choose normal character vectors as inputs. Row ids are generated on-the-fly. (2) I put your approach into a function called match_tbl. (3) I used tidyverse functions in combination with the pipe-operator. This makes the whole approach easy to read and the appearance seems to be 'tidyverse-ish'. However, when you look into actual functions of tidyverse packages you will see that authors usually refrain from using the pipe operator inside functions, since it can easily throw errors. Use the RStudio debugger on a pipe operation and try to dig deeper into whats going on and you will see it is pretty messy. Therefore, if you want to make a real stable function out of it, drop the pipes and use intermediate variables instead.
Data and packages
library(tidyverse)

# some description data (not a dataframe but a normal char vector)
description <- c("This is a text description",
                "Some words that won't match",
                "Some random text goes here",
                "and some more explanation here")

# patterns that we want to find (not a dataframe but a normal char vector)
pattern <- c("explanation","description", "text")

A function generating the desired output: a match table
# a function which replaces your nested for loop
match_tbl <- function(.string, .pattern) {

  res <- imap(.pattern,
               ~ stringr::str_detect(.string, .x) %>%
                     tibble::enframe(name = "row_id") %>%
                     dplyr::mutate(map_id = .y) %>%
                     dplyr::filter(value == T) %>%
                     dplyr::select(-"value"))

  string_tbl <- .string %>%
             tibble::enframe(name = "id") %>%
             dplyr::select("id")

  dplyr::bind_rows(res) %>%
    dplyr::right_join(string_tbl, by = c("row_id" = "id"))

}

Function call and output
match_tbl(description, pattern)
>   row_id map_id
>    <int>  <int>
> 1      1      2
> 2      1      3
> 3      2     NA
> 4      3      3
> 5      4      1


Q:

Where can I get DirectX headers for Mingw?

I have downloaded the latest Mingw toolchain from mingw.org, but it seems DirectX headers are missing. Where can I get those?
I assume there are open source compatibility headers out there, in particular for ddraw.h, which is deprecated by Microsoft.

A:

The MAME development site recommends using these headers from WINE; the particular zip they link is from a year ago, so you may be able to extract more recent (and presumably, somehow better) headers from WINE itself.


Q:

dotnet restore unable to resolve Telerik.UI.for.AspNet on macOS

I'm trying to get a dotnet project working on macOS but I'm getting stuck when I run dotnet restore. All packages install fine except for my Telerik package:
Unable to resolve 'Telerik.UI.for.AspNet.Core (>= 2016.3.1118)' for '.NETFramework,Version=v4.5.2'.
It's not a very descriptive error message so I'm not sure where to go from here.
Some things I've tried:

Running nuget restore (results in error saying The project file... .xproj was not found. - even though it's there)
Adding the package to NuGet.Config:

<add key="Telerik.UI.for.AspNet.Core.2016.3.1118" value="/Users/me/.nuget/packages/Telerik.UI.for.AspNet.Core/2016.3.1118" />
What the package looks like in my nuget packages directory

A:

Well that's not the name of a Nuget package any more, as far as I can tell. I believe you want the KendoUICore.
Based on the versions of that - which include 2016.3.1118 - I suspect that temporarily had the name "Telerik.UI.for.AspNet.Core" before someone noticed that was a bizarre NuGet package name.
There's also Kendo.Mvc which has the description "Telerik UI for ASP.NET MVC Core 1.0.0", but that doesn't have a version matching your expected version number.


Q:

How to customize UIRefreshControl with different image and position?

I have been looking around but couldn't find anything good about this.
I would like to customize the default UIRefeshControl with different loader, etc. So far I can only change tintColor & attributedTitle properties and most code I found are just basically creating a new "pulltorefresh" effect but what I want is to just use the UIRefreshControl and customize it a bit.
Is this possible?

A:

You can't add different loader without accessing private APIs, but you can add background image:
UIImageView *rcImageView =
    [[UIImageView alloc] initWithImage:
        [UIImage imageNamed: @"refreshControl.png"]];
[self.refreshControl insertSubview:rcImageView atIndex:0];

assuming self is an instance of UITableViewController subclass.
Image size you need is 320x43px (@2x 640x86px), the middle area (approximately 35px) will be covered by the loader animation.
I show application logo there...


Q:

Secure and SEO friendly method to return to the previous working page after login in PHP

What is the Secure and SEO friendly method for redirecting a user to the previous page he was working in PHP.
I have seen people using GET variables to pass url, and I also know that sessions or $_SERVER['HTTP_REFERER'], can be used. But one of my friend told that $_SERVER['HTTP_REFERER'] is not safe
If it is not safe how can we get the previous page URL

A:

Your Friend is right . $_SERVER['HTTP_REFERER'] is not guarantied to return previous page accurately. My recommendation is to use session and cookie to store the last page. Upon the login check for stored page URL and forward to your desired page and expire the cookie.


Q:

Show that $f(z)= \frac{-1}{z}$ maps each circle of the form $|z+ti| = (t^2-1)^{1/2}$ onto itself.

Show that $f(z)= \frac{-1}{z}$ maps each circle of the form $|z+ti| = (t^2-1)^{1/2}$ onto itself

A:

Let $C(0,-t)$ be the center of a circle in question, and let $T$ be either point of intersection of the variable circle and the Unit Circle; then,
$$|OC|^2 = t^2 = \left(t^2-1\right) + 1 = |CT|^2 + |OT|^2$$
so that $\triangle OTC$ is a right triangle with right angle at $T$: radius $OT$ is tangent to the variable circle. (Since radius $CT$ of the variable circle is likewise tangent to the Unit Circle, the circles are orthogonal. Depending on what you know about Möbius transformations, this (along with an observation about the location of $f(T)$) more-or-less ends the proof. However, I'll continue with an elementary geometric argument.)
Let $P := p \; \exp(i\theta)$ and $Q := q\; \exp(i\theta)$ be the two (possibly-coincident) points with argument $\theta$ that lie on the variable circle. By the Power of a Point Theorem, because $OT$ is tangent to the variable circle,
$$p q = |OP|\cdot|OQ| = |OT|^2 = 1$$
Now, note that
$$f(P) = -\frac{1}{p\exp(i\theta)} = -\frac{1}{p}\exp(-i\theta) = q\;\exp(i\pi-i\theta) = q\;\exp\left(i(\pi-\theta)\right)$$
This says that $f(P)$ is the reflection of $Q$ across the $y$-axis. As the $y$-axis runs through the center of the variable circle, and $Q$ lies on that circle, this reflected point must lie on that circle, as well. QED


Q:

Magento Customer Email Activiation

Trying to import customers from an old site to new, the idea behind the migration is to not cause any down time and have the site work exactly as before so i need the customers that were email activated to be so on the new site.
I've looked in customer_entity_int and in the customer_attribute table but too no avail, could someone tell me what magento does behind the scenes when a customer clicks the link in the email activation?

A:

In the customer entity is_active is set to 1. There is also an attribute confirmation for customers that is set to null.
Check Mage_Customer_AccountController::confirmAction and you can see what Magento actually does when the link is clicked.
On line 600 the following is done
try {
   $customer->setConfirmation(null);
   $customer->save();
}

the setConfirmation part translates to the attribute confirmation which is stored in the table customer_entity_varchar.


Q:

ASP.NET trigger CallbackPanel callback from javascript every 10 seconds

Im trying to trigger callback of CallbackPanel with javascript in my WebFormUserControl every 10 seconds.
Im able to trigger it with ASPxButton and ClientSideEvents, but my goal is to start it automatically every 10 seconds.
My UserControl code:
<dxcb:ASPxCallbackPanel ID="panel" runat="server" ClientInstanceName="panel" OnCallback="ASPxCallbackPanel1_Callback" Width="200px">
            <PanelCollection>
                <dxcb:PanelContent runat="server">
                    <dxcb:ASPxImage ID="ASPxImage1" runat="server" ImageUrl="~/Images/Image1.png" ShowLoadingImage="true"></dxcb:ASPxImage>
                </dxcb:PanelContent>
            </PanelCollection>
</dxcb:ASPxCallbackPanel>
 <dxcb:ASPxButton ID="ASPxButton1" runat="server" AutoPostBack="false" Text="ASPxButton">
            <ClientSideEvents Click="function(s, e) { panel.PerformCallback();  }" />
 </dxcb:ASPxButton>

I tried to fire it ever 10 seconds like this:
<script type='text/javascript'>
setInterval(function () { panel.PerformCallback(); }, 10000);
</script>

Is is possible to achieve my goal?
If so, please provide some useful code.
Thanks :)

A:

You can use __doPostBack while passing the id of your CallBackPanel. Like this:
<script type='text/javascript'>
    setInterval(function () {
        __doPostBack("<%= panel.ClientID %>", "PanelCalledBack");
    }, 10000);
</script>

Then check against your passed PanelCalledBack argument in your panel's OnLoad event (if it has one) or in the Page_Load event:
if (Request.Params.Get("__EVENTARGUMENT")?.Trim().IndexOf("PanelCalledBack") != -1)
{
    ASPxCallbackPanel1_Callback(panel, null);
}


Q:

Label attribute table column

I simply want to label a column in the attributes table as: "line 1", "line 2", "line 3" etc. I am sure there's an easy fix but couldn't find the exact solution from other posts.
(using QGIS 2.18.7)
Each row represents a different line feature (GPS track)

A:

the simpelst form I can think of is:

Open field calculator and update the field with:
concat( 'line ',  $id)

the result would be "line 1", "line 2" and so on
if you need to start at 1 use:
concat( 'line ',  $id +1)


Q:

Read more button dont work with  element

I have this code below that consist of a HTML Tab I have printed out multiple DOM Elements inside the tab with a Read More Button the function works fine when its just a paragraph but when i add  tags inside the paragraph the button doesn't appear anymore does anyone know why this is happening any suggestion / help would be greatly appreciated thanks!
The issue can be seen in the first description of John Doe which has some
 in the text

var personArr = [];
var person = {["first-Name"]:"John", ["last-Name"]:"Doe", ["age"]:21, ["person-desc"]:"
Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky
boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim
sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin
 picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong
 ham hock tenderloin shank brisket.
"};
var person2 = {["first-Name"]:"Paul", ["last-Name"]:"Logan", ["age"]:22, ["person-desc"]:"Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket."};
var person3 = {["first-Name"]:"Sean", ["last-Name"]:"Kim", ["age"]:32, ["person-desc"]:"Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket."};
var person4 = {["first-Name"]:"Ken", ["last-Name"]:"Chow", ["age"]:12, ["person-desc"]:"Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket."};

personArr.push(person, person2, person3, person4);

var parent = document.getElementsByClassName('line1')[0];
var frag = document.createDocumentFragment();

personArr.forEach((person,i) => {
   var name = document.createElement('h4');
   var desc = document.createElement('p');
   var button = document.createElement('div');

   desc.className = "more";
   name.innerHTML = ` ${person['first-Name']} ${person['last-Name']}`;
   desc.innerHTML = ` ${person['person-desc']}`;
   frag.appendChild(name);
   frag.appendChild(desc);

});
parent.appendChild(frag);
//<---------------------------------------------- READ MORE FUNCTION ------------------------------------------------------->
$(document).ready(function() {
 var showChar = 300;
 var ellipsestext = "...";
 var moretext = "Read More";
 var lesstext = "Read Less";
 $('.more').each(function() {
  var content = $(this).html();

  if(content.length > showChar) {
   var c = content.substr(0, showChar);
   var h = content.substr(showChar-1, content.length - showChar);
   var html = c + ''+ellipsestext+' ' + h + '  '+moretext+'';
   $(this).html(html);
  }
 });
 $(".morelink").click(function(){
  if($(this).hasClass("less")) {
   $(this).removeClass("less");
   $(this).html(moretext);
  } else {
   $(this).addClass("less");
   $(this).html(lesstext);
  }
  $(this).parent().prev().toggle();
  $(this).prev().toggle();
  return false;
 });
});
//<---------------------------------------------- READ MORE FUNCTION ------------------------------------------------------->

//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
body {font-family: Arial;}

/* Style the tab */
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
.line1{
display:inline-block;
}
.size{
width:50%;
}
a.morelink {
 text-decoration:none;
 outline: none;
}
.morecontent span {
 display: none;

}
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

  <button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People</button>

A:

Your substring cuts on <br:
<br  Read More

In this case you can save by not chopping the last char, which is wrong anyway - as you can see on the other persons, the last full stop is missing
var c = content.substr(0, showChar); // showChar is NOT included
var h = content.substr(showChar, content.length - showChar); // so include it here

But you really need to check the chopping is not ON a BR
I also translated your DOM to jQuery - I may have broken something in the tab handling - I added a data attribute

var personArr = [];
var person = {
  ["first-Name"]: "John",
  ["last-Name"]: "Doe",
  ["age"]: 21,
  ["person-desc"]: "
Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky
boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim
sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin
 picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong
 ham hock tenderloin shank brisket.
"
};
var person2 = {
  ["first-Name"]: "Paul",
  ["last-Name"]: "Logan",
  ["age"]: 22,
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket."
};
var person3 = {
  ["first-Name"]: "Sean",
  ["last-Name"]: "Kim",
  ["age"]: 32,
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket."
};
var person4 = {
  ["first-Name"]: "Ken",
  ["last-Name"]: "Chow",
  ["age"]: 12,
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket.Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. Jerky pork loin ham, pork turducken ham hock meatball picanha doner capicola. Landjaeger shank tongue, tri-tip jerky pork chop cupim sausage. Tongue bresaola pastrami turkey shankle chicken pork loin biltong ham hock tenderloin shank brisket."
};

personArr.push(person, person2, person3, person4);

var $parent = $('.line1').eq(0);

personArr.forEach((person, i) => {
  var $name = $('
');
  var $desc = $('
');
  var $button = ('
');

  $desc.addClass("more");
  $name.html(` ${person['first-Name']} ${person['last-Name']}`);
  $desc.html(` ${person['person-desc']}`);
  $parent.append($name).append($desc);

});

//<---------------------------------------------- READ MORE FUNCTION ------------------------------------------------------->
$(document).ready(function() {
  var showChar = 300;
  var ellipsestext = "...";
  var moretext = "Read More";
  var lesstext = "Read Less";
  $('.more').each(function() {
    var content = $(this).html();

    if (content.length > showChar) {
      var c = content.substr(0, showChar);
      var h = content.substr(showChar, content.length - showChar);

      var lastH = h.lastIndexOf("<");
      if (lastH > h.length-3) {
        // process the tag in however way you need
      }

      var html = c + '' + ellipsestext + ' ' + h + '  ' + moretext + '';
      console.log(c, html)

      $(this).html(html);
    }
  });
  $(".morelink").click(function() {
    if ($(this).hasClass("less")) {
      $(this).removeClass("less");
      $(this).html(moretext);
    } else {
      $(this).addClass("less");
      $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
  });
});
//<---------------------------------------------- READ MORE FUNCTION ------------------------------------------------------->

//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
$(".tablinks").on("click",function() {
  var cityName = $(this).attr("data-id");
  $(".tabcontent").hide()
  $(".tablinks").removeClass("active");
  $("#"+cityName).show();
  $(this).addClass("active");
})
$("#defaultOpen").click();
//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
body {
  font-family: Arial;
}

/* Style the tab */

.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */

.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */

.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */

.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */

.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

.line1 {
  display: inline-block;
}

.size {
  width: 50%;
}

a.morelink {
  text-decoration: none;
  outline: none;
}

.morecontent span {
  display: none;
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

      <button class="tablinks" id="defaultOpen" data-id="People">People</button>


Q:

What graph Laplacians commute

I know that the graph Laplacian of a fully connected graph commutes with the Laplacian of any other graph.
Is there any theorem stating something similar about some more general family of graphs? I'm specially interested to know if there's any result about sparse random graphs.
Thanks.
--EDIT (Re-statement): What Laplacians commute with a -given- Laplacian?
One answer is all of its powers and their linear combination (see:Given a matrix, is there always another matrix which commutes with it?)
Are there other graphs (a more general family) with this property?

A:

Let $X_{ij}$ be the graph on $n$ vertices with exactly one edge, joining $i$ to $j$. The Laplacian of $X_{ij}$ is $(e_i-e_j)(e_i-e_j)^T$. It's not difficult to check that if this commutes with the Laplacian $L$ of a graph $G$ and $v$ is a vertex of $G$ not $i$ or $j$, then $v$ is adjacent to $i$ if and only if it is adjacent to $j$.
It follows that if $L$ commutes with the Laplacian of $X_{ij}$ for all $i$ and $j$, then $G$ is a either a complete graph, or the graph with no edges.


Q:

Debugging into external libraries in QtCreator

I have been using Qt Creator to develop some Qt apps recently with no problems. This week I started to use Qt Creator to work on an Open Scene Graph application. I have all of the source (.cpp and .h) files for Open Scene Graph and used those to build the libraries.
I then created a new project and linked those libraries into my project through the .pro file. My application works and runs, I can debug but not step into the code from the Open Scene Graph libraries.
How can I set up Qt Creator to step through these source files or even break at breakpoints within the source code of these libraries?
In Tools -> Options -> Debugger, there is Source Paths Mapping which may be what I'm after but I'm not sure.
Thanks.

A:

I assume since you can link a debug version of your app with OSG and you can't trace into OSG source code that you're using gcc (because with Visual C++ I don't think it's possible to link debug apps with non-debug libs)  If that's the case, you simply need to re-build OSG for debugging. There may be an option when you run OSG's 'configure' or you may have to edit the Makefiles. Or if it's CMake-based, you run cmake with -DCMAKE_BUILD_TYPE=Debug.


Q:

Function for parsing a date

I've been trying to create a function that converts something like 3d4h into the current unixtime+the number of seconds within that string. I unfortunately have not been successful, and now I'm turning to you all. Thanks for any help!

A:

DateTime() and DateInterval() already do this for you:
$interval = new DateInterval('P3DT4H');
$now = new DateTime();
$now->add($interval);
echo $now->format('Y-m-d H:i:s');

This example adds an interval to "now". You can, of course, make the interval relative to any date and time.
See the interval spec for what valid values are for DateInterval().


Q:

AVFoundation, how to turn off the shutter sound when captureStillImageAsynchronouslyFromConnection?

I am trying to capture an image during a live preview from the camera, by AVFoundation captureStillImageAsynchronouslyFromConnection. So far the program works as expected. However, how can I mute the shutter sound?

A:

I used this code once to capture iOS default shutter sound (here is list of sound file names https://github.com/TUNER88/iOSSystemSoundsLibrary):
NSString *path = @"/System/Library/Audio/UISounds/photoShutter.caf";
NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSData *data = [NSData dataWithContentsOfFile:path];
[data writeToFile:[docs stringByAppendingPathComponent:@"photoShutter.caf"] atomically:YES];

Then I used third-party app to extract photoShutter.caf from Documents directory (DiskAid for Mac). Next step I opened photoShutter.caf in Audacity audio editor and applied inversion effect, it looks like this on high zoom:

Then I saved this sound as photoShutter2.caf and tried to play this sound right before captureStillImageAsynchronouslyFromConnection:
static SystemSoundID soundID = 0;
if (soundID == 0) {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"photoShutter2" ofType:@"caf"];
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
}
AudioServicesPlaySystemSound(soundID);

[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:
...

And this really works! I runs test several times, every time I hear no shutter sound :)
You can get already inverted sound, captured on iPhone 5S iOS 7.1.1 from this link: https://www.dropbox.com/s/1echsi6ivbb85bv/photoShutter2.caf

A:

My Solution in Swift
When you call AVCapturePhotoOutput.capturePhoto method to capture an image like the below code.
photoOutput.capturePhoto(with: self.capturePhotoSettings, delegate: self)

AVCapturePhotoCaptureDelegate methods will be invoked.
And the system tries to play shutter sound after willCapturePhotoFor invoked.
So you can dispose of system sound in willCapturePhotoFor method.

extension PhotoCaptureService: AVCapturePhotoCaptureDelegate {

    func photoOutput(_ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) {
        // dispose system shutter sound
        AudioServicesDisposeSystemSoundID(1108)
    }
}

See also

AVCapturePhotoDelegate

A:

Method 1: Not sure if this will work, but try playing a blank audio file right before you send the capture event.
To play a clip, add the Audio Toolbox framework, #include <AudioToolbox/AudioToolbox.h>
and play the audio file like this immediately before you take the picture:
 NSString *path = [[NSBundle mainBundle] pathForResource:@"blank" ofType:@"wav"];
 SystemSoundID soundID;
 NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
 AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
 AudioServicesPlaySystemSound(soundID);

Here is a blank audio file if you need it.
https://d1sz9tkli0lfjq.cloudfront.net/items/0Y3Z0A1j1H2r1c0z3n3t/blank.wav
________________________________________________________________________________________________________________________________________
Method 2: There's also an alternative if this doesn't work.  As long as you don't need to have a good resolution, you can grab a frame from the video stream, thus avoiding the picture sound altogether.
________________________________________________________________________________________________________________________________________
Method 3: Another way to do this would be to take a "screenshot" of your application.  Do it this way:
UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:@"foo.png" atomically:YES];

If you're wanting this to fill the whole screen with a preview of the video stream so that your screenshot looks good:
AVCaptureSession *captureSession = yourcapturesession;
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
UIView *aView = theViewYouWantTheLayerIn;
previewLayer.frame = aView.bounds; // Assume you want the preview layer to fill the view.
[aView.layer addSublayer:previewLayer];


Q:

ReSharper conflict with Stylecop over using directive order SA1210 SA1211

StyleCop 4.7 rules SA1210 and SA1211 require the using directives to be sorted alphabetically.  I've run into a conflict between StyleCop's rule and Resharper's applied sort:  case-sensitivity.
Resharper 8.2 performs a case insensitive sort of the directives, while StyleCop's rule requires a case sensitive sort.  So, I ran into an odd case with the following directives because of poor namespace choices (not my own):
using AB.Common;
using ab.Utility;

Pressing ctrl-E-F sorts common first;  but the rule requires utility to be first because of the difference between AB and ab.  I've gotten past it by removing the StyleCop rule and just letting Resharper's reformat reign.  Of course the namespace itself should be refactored, but I don't have that option.
Any other opinions about how to deal with this other than turning off the StyleCop rule?

A:

Turning the StyleCop rule off seems like the best answer, there is no need for both ReSharper and StyleCop to check the ordering.
But if you want to have them both on, you could alias the namespaces to something like:
using Common=AB.Common;
using Utility=ab.Utility;


Q:

Hakyll not updating with new routes

I'm trying to use Hakyll for the first time. Following the tutorials on the official site, I'm trying to extend the route handling images to work with fonts. I've changed the code in site.hs to this:
match ("images/*" .||. "fonts/*") $ do
     route idRoute
     compile copyFileCompiler

In the fonts directory, I've got a number of .ttf font files whose permissions and owners match the rest of the site's static files (all of which work properly).
For some reason though, after rebuilding the site (with stack exec site rebuild), these updates aren't reflected in the binary, and routes to fonts/* result in a 404.
How can I get Hakyll to load fonts?

A:

stack exec site rebuild rebuilds only the site data (the files generated inside the destination directory, _site by default). Whenever you change your site source, you will need to issue stack build.
If you were running the watch server, restart it – stack build creates a new site executable, it will not restart old running instances.
If you only added new rules, executing site rebuild after the site was built should not be needed, site build or site watch should notice that the files are missing in the ‘cache’. If you modified existing rules, however, you will need to let Hakyll know the files are no longer up to date. Cleaning the site using site clean or site rebuild will force the Hakyll to re-generate everything. When you have large site and only few files affected by the change, you can also re-save them or change their modification time (e.g. using touch command) to save time.


Q:

Parsing a csv file in Java

Possible Duplicate:
Parsing CSV in java

How to do I parse a csv file correctly in java?  There are cases where simple StringTokenizer doesn't work as in the example below:
xxx,"hello, this breaks you"

A:

Try using a dedicated library for that, e.g.:

http://opencsv.sourceforge.net/

A:

ostermiller.org has a jar with nice utility-classes like CSV-Parser/Writer etc.


Q:

Can't move multiple files in a directory

I am trying to move multiple files in a directory to an archive sub folder. I used a foreach loop to do the idea. Unfortunately, It can only move a file if there is only one file in the directory. But when I put multiple in the directory the Directory.move(); won't work. Can anyone help me?
static string antJsonSerializer(){
    #region  KDI SALES
    string[] allfiles = Directory.GetFiles(@"C:\xml\"); // Put all file names in root directory into array.
    string sourceDirectory = @"C:\xml\";
    string destinationDirectory = @"C:\xml\Archive\";

    // Check if directories are existing -- Working
    bool xmlRoot = System.IO.Directory.Exists(sourceDirectory);
    if (!xmlRoot) System.IO.Directory.CreateDirectory(sourceDirectory);
    bool xmlArchive = System.IO.Directory.Exists(destinationDirectory);
    if (!xmlArchive) System.IO.Directory.CreateDirectory(destinationDirectory);

    AntHelpers drone = new AntHelpers();

    foreach (string name in allfiles)
    {
        try
        {
            drone.xmltosql(@name.Trim());
            //File.Move(@name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");  //Not working
            Directory.Move(@name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");
            //Directory.Move(sourceDirectory, destinationDirectory); //Not working

        }
        catch (Exception e)
        {
            //Console.WriteLine("Main Process Catch ERR: " + e.Message);
            //ErrLogtoDB(string TRNTYPE, string extserial, string texttowrite, string logfilename)
            AntHelpers.ErrLogtoDB("SALES", @name, "Ant JSON Serializer Failed: " + e.Message,
                "LeafCutterLogFile_JSONSerializer_" + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");
        }
        //drone.ExtractSQLSendAntHill(); //For testing: OFF
    #endregion

    return " !!!! Work Complete !!!! ";
}

A:

You are trying to save a file with year + month + day + hour.html as "NAME".  If multiple files are there, then how can you save it with same file name?  Instead you should add seconds and/or milliseconds, or use something else to distinguish the file and make it a unique name.  Otherwise, take file name without the extension then add year, month, day, and hour.  That is why you are not able to move multiple files at a time, because when try to move the second file an exception will be thrown say "unable to move an existing file."


Q:

Getting every element with a specific ID (jQuery)

I need to get every element with a specific id, get the parent of the object, and set its ID.
How would I do this?
I have this code:

Home

Subitem 1

Subitem 2

I need to find all the anchor elements with the id "selection_link", get the parent (the "list item" element [li]) and set its ID to "selected".  How would I do this with jQuery?  I'll be using the conditioning to determine if the li element will actually be allowed to get the new ID.  (if the URL matches the href property of the anchor element).

A:

HTML specification specifies that an ID should only be applied to 1 element. You can't have more then one element with the same ID.
In this case, it's better to use classes.
TO select by class:
$(".classname")...

EDIT: An example based on your code:

Home

Subitem 1

Subitem 2

A:

$('li a').each(function(){

    if ($(window).attr('location').href.match($(this).attr('href'))) {
        //example with class
        $(this).parent().addClass('selected');
        // example with id
        $(this).parent().attr('id', 'selected');

    }

});