Q:

MySQL won't start after reboot. Exiting with signal 11

last night I was doing a server maintenance that required DB reboot.
No changes in a config were made.
Current setup is as follows:
master (server1) - master (server2) and slave (server0)
MySQL version: mysql-5.5.32
server0 and server1 started fine after a reboot but when i try to start server0 it crashes with signal 11 error:
Here's the log output:
140604 03:10:08 mysqld_safe Starting mysqld daemon with databases from /opt/mysql/mysql_data
140604  3:10:08 [Note] Plugin 'FEDERATED' is disabled.
140604  3:10:08 InnoDB: The InnoDB memory heap is disabled
140604  3:10:08 InnoDB: Mutexes and rw_locks use GCC atomic builtins
140604  3:10:08 InnoDB: Compressed tables use zlib 1.2.3
140604  3:10:08 InnoDB: Using Linux native AIO
140604  3:10:08 InnoDB: Initializing buffer pool, size = 32.0G
140604  3:10:10 InnoDB: Completed initialization of buffer pool
02:10:10 UTC - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

key_buffer_size=67108864
read_buffer_size=8388608
max_used_connections=0
max_threads=2000
thread_count=0
connection_count=0
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 49240442 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 0 thread_stack 0x40000
/usr/local/mysql/bin/mysqld(my_print_stacktrace+0x35)[0x7a2825]
/usr/local/mysql/bin/mysqld(handle_fatal_signal+0x403)[0x670b43]
/lib/x86_64-linux-gnu/libpthread.so.0(+0xf030)[0x7f1c2db0e030]
/usr/local/mysql/bin/mysqld[0x93ec38]
/usr/local/mysql/bin/mysqld[0x8328d2]
/usr/local/mysql/bin/mysqld[0x861511]
/usr/local/mysql/bin/mysqld[0x7f302f]
/usr/local/mysql/bin/mysqld[0x7c40dd]
/usr/local/mysql/bin/mysqld(_Z24ha_initialize_handlertonP13st_plugin_int+0x48)[0x673948]
/usr/local/mysql/bin/mysqld[0x58307a]
/usr/local/mysql/bin/mysqld(_Z11plugin_initPiPPci+0xb5d)[0x586c9d]
/usr/local/mysql/bin/mysqld[0x507bab]
/usr/local/mysql/bin/mysqld(_Z11mysqld_mainiPPc+0x3e2)[0x508772]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xfd)[0x7f1c2ccccead]
/usr/local/mysql/bin/mysqld[0x4fe17a]
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
140604 03:10:10 mysqld_safe mysqld from pid file /opt/mysql/mysql_data/odb2.pid ended

After that I started mysql with innodb_force_recovery = 1 and server started ok.
Looking at the documentation:

*1 (SRV_FORCE_IGNORE_CORRUPT) Let the server run even if it detects a corrupt page. Try to make SELECT * FROM tbl_name jump over corrupt
  index records and pages, which helps in dumping tables.*

So my next step was to run mysqlcheck on all databases but no errors were found.
Any ideas how to bring that server to life? I have a backup of all databases (~300GB) but restoring it would take a considerable amount of time and if possible I'd like to avoid that

A:

Turns out it was a bug introduced in 5.5.32  http://bugs.mysql.com/bug.php?id=69623 where MySQL fails to open a second tablespace if stored in more than 1 file.
Update to 5.5.39 solved the issue


Q:

Convergence of series $A_n = \sqrt{\sum_{k=n}^{\infty} a_k} - \sqrt{\sum_{k=n+1}^{\infty}a_k} $ if series $a_n$ converges

I must show that if a series $\sum_{n=1}^{\infty} a_n$ with positive terms converges, then the series $\sum_{n=1}^{\infty} A_n$, where $A_n = \sqrt{\sum_{k=n}^{\infty} a_k} - \  \sqrt{\sum_{k=n+1}^{\infty} a_k},$ also converges, and $a_n = o(A_n)$ as $n\to\infty$.
Here is my (rough) attempt:
Since $\sum_{n=1}^{\infty}a_n$ is positive and finite, $\sqrt{\sum_{k=n}^{\infty}a_k} $ is defined $\forall n \in \Bbb N$.
By the Cauchy criterion, for all $\frac{\varepsilon^2}{4} > 0,$ there is a $N \in \Bbb N$ such that $|\ a_n+\ ...\ +a_m \ | < \frac{\varepsilon^2}{4}$ for all $m \geq n > N$.
Then for $| \ A_n+\ ...\ +A_m | = \left|\sqrt{\sum_{k=n}^{\infty} a_k} - \  \sqrt{\sum_{k=m+1}^{\infty} a_k} \ \right|  \leq \left|\sqrt{\sum_{k=n}^{\infty} a_k}\right| + \left|\sqrt{\sum_{k=m+1}^{\infty} a_k}\right| $=
$ \sqrt{ \left | \sum_{k=n}^{\infty} a_n \right| }$ + $\sqrt{ \left | \sum_{k=m+1}^{\infty} a_n \right| }$ $ < \frac{\varepsilon}{2} + \frac{\varepsilon}{2} = \varepsilon $, where $m \geq n >  N$. Thus $A_n$ converges.
For $$\lim \limits_{n \to \infty} \frac{a_n}{ \left(\sqrt{\sum_{k=n}^{\infty} a_k} - \  \sqrt{\sum_{k=n+1}^{\infty} a_k}\right)} = \lim \limits_{n \to \infty} \frac{a_n \cdot \left( \sqrt{\sum_{k=n}^{\infty} a_k} + \  \sqrt{\sum_{k=n+1}^{\infty} a_k}\right)}{\left( \sqrt{\sum_{k=n}^{\infty} a_k} - \  \sqrt{\sum_{k=n+1}^{\infty} a_k}\right)\cdot\left( \sqrt{\sum_{k=n}^{\infty} a_k} + \  \sqrt{\sum_{k=n+1}^{\infty} a_k}\right)} =
\lim \limits_{n \to \infty} \frac{a_n \cdot \left( \sqrt{\sum_{k=n}^{\infty} a_k} + \  \sqrt{\sum_{k=n+1}^{\infty} a_k}\right)}{ \left(\sum_{k=n}^{\infty} a_k - \  \sum_{k=n+1}^{\infty} a_k\right)} =
\lim \limits_{n \to \infty} \frac{a_n \cdot \left( \sqrt{\sum_{k=n}^{\infty} a_k} + \  \sqrt{\sum_{k=n+1}^{\infty} a_k}\right)}{ a_n} =
\lim \limits_{n \to \infty}   \sqrt{\sum_{k=n}^{\infty} a_k} + \  \sqrt{\sum_{k=n+1}^{\infty} a_k} = 0 + 0 = 0 $$

A:

Fix some sequence $(b_k)_{k\geqslant1}$ and define $c_k=b_k-b_{k+1}$ for every $k\geqslant1$. Then, for every $n\geqslant0$,
$$
\sum_{k=1}^nc_k=b_1-b_{n+1}.
$$
If the sequence $(b_k)$ converges, this implies that the series $\sum\limits_kc_k$ converges and that its sum is $b_1-b_\infty$, where $b_\infty=\lim\limits_{k\to\infty}b_k$.
Applying this to
$$
b_k=\sqrt{\sum_{i=k}^\infty a_i},
$$
one sees that the series $\sum\limits_kA_k$ converges and that its sum is
$$
\sum_{k=1}^\infty A_k=\sqrt{\sum_{i=1}^\infty a_i}.
$$
To prove that $a_n\ll A_n$, note that
$$
a_n=A_n\cdot\left(b_n+b_{n+1}\right),\qquad b_n+b_{n+1}\to0.
$$


Q:

Iterate thru ec2 describe instance boto3

I am trying to get specific values for a describe instance call. So for example, if I want to get the 'Hypervisor' value or the Ebs has 'DeleteOnTermintation' value from the output. Below is the current code I am currently using to make the call and iterate thru the dictionary output.
import boto3
import pprint
from datetime import datetime
import json

client = boto3.client('ec2')

filters = [{
'Name': 'tag:Name',
'Values': ['*']
}]

class DatetimeEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, datetime):
        return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
    elif isinstance(obj, date):
        return obj.strftime('%Y-%m-%d')
    # Let the base class default method raise the TypeError
    return json.JSONEncoder.default(self, obj)

output = json.dumps((client.describe_instances(Filters=filters)), cls=DatetimeEncoder)

pprint.pprint(output)

for v in output:
  print v['Hypervisor']

Getting this error:
TypeError: string indices must be integers, not str

Using the pprint to see all the values available from the output.

A:

Here's how you could display the information via the AWS Command-Line Interface (CLI):
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Hypervisor, NetworkInterfaces[0].Attachment.DeleteOnTermination]'

Here's some Python:
import boto3

client = boto3.client('ec2')

response = client.describe_instances()

for r in response['Reservations']:
  for i in r['Instances']:
    print i['InstanceId'], i['Hypervisor']
    for b in i['BlockDeviceMappings']:
      print b['Ebs']['DeleteOnTermination']

A:

Here's John's answer but updated for Python3
import boto3

client = boto3.client('ec2')

response = client.describe_instances()

for r in response['Reservations']:
    for i in r['Instances']:
        print(i['InstanceId'], i['Hypervisor'])
        for b in i['BlockDeviceMappings']:
            print(b['Ebs']['DeleteOnTermination'])


Q:

Create a button on click of a button

I have a button and I need to create more buttons when I pressed the button.
Here it is what I have written for the button:

    Add button

I am trying to learn Backbone.js so I wrote a view to create more buttons when click add-button.
createButton = Backbone.View.extend({
    events: {
        'click .add-button': 'add_script'
    },
    add_script: function() {
        console.log('Pressed');
        //create a new button from here?
     }
});

Can anyone help me to do it? console.log('Pressed') doesn't even work. I am trying to learn web development so, is there any document that you can suggest me? I am welcome for all suggestions in Backbone.js

A:

You have to create an object of the view.
Like this
var createButton = Backbone.View.extend({
  el: '#response-container',
    events: {
        'click .add-button': 'add_script'
    },

    initialize: function() {
        console.log("initialized");
    },
    add_script: function() {
        console.log('Pressed');
        //create a new button from here?

    this.$el.append('<input type="button" value="new button"/>');

     }
});

var cb = new createButton();
Here is the DEMO


Q:

In TypeScript, can we use "runtime" keys for defining a new type?

Better explain this as an example:
class ModuleOptions {
  key1?: string;
  key2?: string;

  keyA?: string;
  keyB?: string;
}

class Module {
  static options: ModuleOptions = {
    key1: 'key1',
    key2: 'key2',

    keyA: 'keyA',
    keyB: 'keyB'
  };

  static create(options: ModuleOptions) {
    Object.assign(Module.options, options);
  }
}

const myModule = Module.create({
  key1: 'foo'
});

// Now Module.options static field has "foo" as key1...
// Could we constrait fooArgs to have a property named "foo" of type string?
function foo(fooArgs: NewType) {
  // Do stuff
}

It's possible to make fooArgs (that is, NewType) to only accept 'foo' as key, with the same type defined for it (string)?
This is not working (even making it simple):
class NewType {
  [k in keyof [ModuleOptions.options]]: string;
}

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.

A:

You can probably get something like what you want, but there are definitely pain points.  The first major problem is that TypeScript doesn't allow you to arbitrarily mutate the types of existing values.  So if a variable named foo has type string, you can't change it to number later.  In your case, if Module.options.key1 is known by the compiler to be the string-literal type "key1", then you can't change its type to the string-literal type "foo" later.  The compiler will expect it to be "key1" forever, even after you call Module.create().   There are a few ways around this.  One is using type guards to narrow the type of a value (types of values can get more specific, but they can't change arbitrarily), and another is to use new variables to represent the value of the new type.
Here's a possible solution using the latter method... have create return a new version of Module with a different type:
module Module {

  type Module = typeof Module; // handy type alias

  const defaultOptions = {
    key1: 'key1' as 'key1',
    key2: 'key2' as 'key2',
    keyA: 'keyA' as 'keyA',
    keyB: 'keyB' as 'keyB',
  }; // use type assertions to narrow to string literals

  type DefaultOptions = typeof defaultOptions; // handy type alias

  export const options: Record<keyof DefaultOptions, string> = defaultOptions;

  // represent overwriting properties from T with properties from U
  type Assign<T, U> = {
    [K in keyof T | keyof U]: K extends keyof U ? U[K] : K extends keyof T ? T[K] : never
  };

  export function create<T>(
    o: T
  ): { [K in keyof Module]: 'options' extends K ? Assign<DefaultOptions, T> : Module[K] } {
    Object.assign(options, o);
    return Module as any; // can't represent type mutation, use type assertion here
  }

}

That uses conditional types to represent what happens to options when you call create.  Let's see how it works:
const almostMyModule = Module.create({
  key1: 'foo'
});
almostMyModule.options.key2; // "key2"
almostMyModule.options.key1; // string? oops

Oops, the type of the parameter passed to create() is inferred as {key1: string}, not {key1: "foo"}.  This is another pain point.  There are ways to get the inference to be correct, but for now I'll just use a type assertion to narrow it:
const myModule = Module.create({
  key1: 'foo' as 'foo'
});
myModule.options.key1; // 'foo', that's better
myModule.options.key2; // 'key2'

Now that myModule.options.key1 is known by the compiler to be "foo", we can make that NewType you wanted:
type ValueOf<T> = T[keyof T];
type NewType = { [K in ValueOf<typeof myModule.options>]: string };

Inspecting NewType gives us:
// type NewType = {
//   foo: string;
//   key2: string;
//   keyA: string;
//   keyB: string;
// }

And you can use it:
function foo(fooArgs: NewType) {
  fooArgs.foo // okay
}

Hope that helps.  Good luck!


Q:

How to insert MAX function in a subquery? (SQL Server)

I have the following SQL code that's shows me the number of selling per seller per sector.
SELECT
    [JO_Info].Name, [Proc].Sector, COUNT([JO].JO_ID) AS total
FROM
    [JA]
INNER JOIN
    [Proc] ON [JA].ProcessID = [Proc].ProcessID
INNER JOIN
    [JO] ON [JA].JO_ID = [JO].JO_ID
INNER JOIN
    [JO_Info] ON [JO].JOI_ID = [JO_Info].JOI_ID
WHERE
    ([JO].JO_ID = 'seller')
GROUP BY
    [JO_Info].Name, [Proc].Sector

The output is the following:
    Name      | Sector  | total
   -----------+---------+----------
    Grace     |  1      |  4
    Elizabeth |  2      |  1
    Bette     |  3      |  3
    Angelina  |  4      |  6
    Karl      |  4      |  1
    Alberto   |  13     |  1
    Jorge     |  15     |  1

But I want the seller that sold more per sector. So, my question is how to insert the MAX function in order to get the following result (No repeats in the sector).
    Name      | Sector  | total
   -----------+---------+----------
    Grace     |  1      |  4
    Elizabeth |  2      |  1
    Bette     |  3      |  3
    Angelina  |  4      |  6
    Alberto   |  13     |  1
    Jorge     |  15     |  1

A:

You can use row_number():
with t as (<your query here>)
select t.*
from (select t.*, row_number() over (partition by sector order by total desc) as seqnum
      from t
     ) t
where seqnum = 1;


Q:

Jquery Accordion Menu - Keep Selected Menu Open

I'm attempting to create a vertical accordion menu for a website I'm working on. This is my first time ever doing anything with jquery. I've been able to get a working menu the way I want it, except for a couple of things.
1) I need a menu that will stay expanded based on which page is loaded, if you click on an item inside the second menu, then the second menu needs to be expanded when the page is reloaded. The menu doesn't stay expanded when you click and load a new page from within the menu. Upon page reload, it just completely collapses until you click on a header to expand it again. I've been searching online for days and can't find anything that I can use to solve this problem. I've looked at using the jquery cookie plugin and just checking to see which page is currently loaded and using that to determine which menu needs to be expanded, but I can't get either of them to work.
2) My menu only expands when clicked, it doesn't collapse when clicked again. Is it possible to collapse the same menu you just expanded by clicking again?
Here's the js file I created:
function initMenu() {
    $('#menu ul').hide();
    $('#menu li a').click(function () {
        var checkElement = $(this).next();
        if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
            $(this).siblings().removeClass("selected");
            return false;
        }
        if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
            $('#menu ul:visible').slideUp('normal');
            checkElement.slideDown('normal');
            if (!$(this).hasClass("selected")) {
                // Remove the class from anything that is active
                $("a.selected").removeClass("selected");
                // And make this active
                $(this).addClass("selected");
            }
            return false;
        }
    });
}
$(document).ready(function () {
    initMenu();
});

Here's a jsfiddle for full html and css as well: http://jsfiddle.net/CShsY/
Thanks.

A:

I've updated your fiddle: http://jsfiddle.net/CShsY/4/
It's got a lot of general improvements and also fixes your second problem. Your initMenu() function now looks like this:
function initMenu() {
    $('#menu li > a').click(function(e){

        if($(this).next('ul').length > 0){

            e.preventDefault();

            var subNav = $(this).next('ul');

            if (subNav.is(':visible')){
                subNav.slideUp('normal')
                $(this).removeClass("selected");
            }else{
                $('#menu ul:visible').slideUp('normal');
                subNav.slideDown('normal');
                $("a.selected").removeClass("selected");
                $(this).addClass("selected");
            }
        }

    });
}

e.preventDefault() just prevents the default action of the a. I've also added a check in there so any a elements which don't have a ul after them will still work as regular links.
For your first problem you might want to take a look at this question: highlight the navigation menu for the current page. The answer was basically to add a class or id to your body element which uniquely identifies the page as well as adding classes to each of your menu links. For example:

    /* other code here */

Menu 1

            /* more code here */

CSS:
#home #menu ul.home{display:block}
/* The sub menu of 'home' will show on the home page */


Q:

Node.js bodyparser cannot ready AFNetworking POST array

I am trying to post a JSON message which contains an array to my server. However the server is unable to identify the elements in the array. After inspecting the issue I have come across what I believe is the problem.
AFNetworking code:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kServiceBaseUrl]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager PUT:@"/api/createRubaway"
   parameters:myDictionary
      success:^(NSURLSessionDataTask *task, NSDictionary *responseObject)
     {/* stuff */}
      failure:^(NSURLSessionDataTask *task, NSError *error)
     {/* stuff */}
 ];

LLDB print out of 'myDictionary':
{
    description = description;
    title = title;
    transitions =     (
                {
            idx = 0;
            resource =             {
                data = testdata;
                name = transition;
                type = image;
            };
            threshold = "0.75";
            type = rubaway;
        },
                {
            idx = 1;
            resource =             {
                data = testdata;
                name = transition;
                type = image;
            };
            threshold = "0.75";
            type = rubaway;
        }
    );
}

After AFNetworking has serialized the request. If I print out the HTTPBody from the NSMutableRequest, this is what it is sending (this is what is being sent to my server):
description=description&title=title&transitions[][idx]=0&
transitions[][resource][data]=testdata&
transitions[][resource][name]=transition&
transitions[][resource][type]=image&
transitions[][threshold]=0.75&
transitions[][type]=rubaway&transitions[][idx]=1&
transitions[][resource][data]=testdata&
transitions[][resource][name]=transition&
transitions[][resource][type]=image&transitions[][threshold]=0.75&
transitions[][type]=rubaway

Is the above formatting correct. As my server (Node.js - BodyParser) I believe is expecting it in this format https://stackoverflow.com/a/18402556/623750
Is there a way to change the formatting of the JSON serializer?. Alternatively is there a way to configure BodyParser to accept the above formatting?
Thanks,
Ryan

A:

All you need to do, to set requestSerializer to  AFJSONRequestSerializer, this will fix the issue.
 [manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
 [manager setResponseSerializer:[AFJSONResponseSerializer serializer]];


Q:

Foreach loop array with same array name

What I am trying to do is this:
I want to echo information based on year/month/day.
My code is:
  $data = array(
    "2018" => array(
        "September" => array(
            "02" => array(
                "Line 1"
            ),
            "02" => array(
                "Line 11"
            ),
            "12" => array(
                "Line 2"
            ),
            "31" => array(
                "Line 3"
            )
        ),
        "December" => array(
            "02" => array(
                "Line 11"
            ),
            "12" => array(
                "Line 22"
            ),
            "31" => array(
                "Line 33"
            ),
            "32" => array(
                "Line 66"
            )
        )
    ),
    "2019" => array(
        "May" => array(
            "05" => array(
                "Line z"
            ),
            "15" => array(
                "Line y"
            ),
            "55" => array(
                "Line x"
            )
        )
    )
);

echo '
';
print_r($data);
echo '
';

foreach ($data as $years => $year) {

    echo $years . "
";

    foreach ($year as $months => $month) {

        echo $months . "
";

        foreach ($month as $days => $day) {

            foreach ($day as $key => $value) {
                echo $days . " - " . $value . "
";
            }
        }
    }
}

As you see for 2018 september there are two arrays for the date of 2nd.
I was hoping to see this when print_r
2018
September
02 - Line 1
02 - Line 11
12 - Line 2
31 - Line 3

but instead I get this
2018
September
02 - Line 11
12 - Line 2
31 - Line 3

How can I echo both values of september 2, 2018?

A:

You cannot have duplicate keys. You are defining "02" twice.
Solution: Define "September" as:
    "September" => array(
        "02" => array(
            "Line 1",
            "Line 11"
        ),
        "12" => array(
            "Line 2"
        ),
        "31" => array(
            "Line 3"
        )
    ),


Q:

Find $\lim_{n\to\infty} (1+\frac{1}{2}+...+\frac{1}{n})\frac{1}{n}$

Find the following limit:
  $$\lim_{n\to\infty} \left(1+\frac{1}{2}+...+\frac{1}{n}\right)\frac{1}{n}$$

My intuition says that this goes to zero, because $1/n$ goes much faster to zero than the harmonic series go to infinity, but how can I prove this?

A:

A slightly easier way out is prove that
$$1 + \dfrac12 + \dfrac13 + \cdots + \dfrac1n < 2\sqrt{n}$$ using induction.
Hence, you have that $$ 0 < \left(1 + \dfrac12 + \dfrac13 + \cdots + \dfrac1n\right) \dfrac1n < \dfrac2{\sqrt{n}}$$
Now use squeeze theorem to get what you want.

A:

If you know that $1+\frac12 +\cdots+\frac1n\approx \ln n$ and $\frac{\ln n}n\to 0$, you are done.
More elementary, your limit is the Cesáro sum of the sequence $(\frac 1n)$, hence has the same limit $0$.
That is:
$$\lim_{n\to\infty} a_n= a \qquad\Rightarrow\qquad \lim_{n\to\infty} \frac{a_1+\cdots+a_n}n= a$$

A:

What you want to do here is find an upper bound for $1 + \frac{1}{2} + \frac{1}{3} + \ldots$.  That is, you want to replace every term in that series with a larger term in such a way that the sums are easier to do.  One clever way to do this (which I thought of by trying to modify the classic Oresme proof of divergence by exhibiting a lower bound) is to note that it's smaller than
$$1 + \frac{1}{2} + \frac{1}{2} + \frac{1}{4} + \frac{1}{4} + \frac{1}{4} + \frac{1}{4} + \frac{1}{8} \ldots.$$
The sum of the first $2^k-1$ terms of this sequence is $k$. Which should be enough for you to prove this limit directly.


Q:

read mp3 stream and echo back to client in php

What I intend to achieve, is a page that when a client is to connect, the page is to constantly read from a local ice-cast server (http://127.0.0.1:8000/stream.mp3), and echo the stream back to the client, from there, the client can be play it back in a basic audio tag.
<?php
header("Content-Transfer-Encoding: binary");
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
header('Content-Disposition: attachment; filename="stream.mp3"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
print file_get_contents("http://127.0.0.1:443/stream.mp3");

With this code it only eats up ram and returns nothing useful to the client, I'm thinking something along the lines of waiting until a megabyte buffer is full, then echoing it to the client.  But idk, so yeah.
Please note that I'm not that experienced with php.  Thanks!

A:

file_get_contents attempts to read a stream up to the end, and since you're trying to read from a broadcast server there will be no end.
If HTML5 is an option, the following may work.
<audio autoplay>
  <source src="http://127.0.0.1:443/stream.mp3" type="audio/mpeg">
</audio>

Alternative solution:
<?php
ob_start();
header("Content-Transfer-Encoding: binary");
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
header('Content-Disposition: attachment; filename="stream.mp3"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
$handle = fopen("http://127.0.0.1:443/stream.mp3");

while (($data = fread($handle, $bufferSize)) { //Buffer size needs to be large enough to not break audio up while getting the next part
      echo $data;
      ob_flush();
      flush();
      set_time_limit(30); // Reset the script execution time to prevent timeouts since this page will probably never terminate.
}


Q:

C#: Why don't generics use the most generic type it can when we don't specify one?

For example I now created a this tiny class:
public static class FileSystemInfoComparers<T> where T : FileSystemInfo
{
    public static IEqualityComparer<T> FullName
    {
        get { return new FullNameComparer(); }
    }

    private class FullNameComparer : IEqualityComparer<T>
    {
        public bool Equals(T x, T y)  { return x.FullName == y.FullName;   }
        public int GetHashCode(T obj) { return obj.FullName.GetHashCode(); }
    }
}

I would like it if I could just do
var comparer = FileSystemInfoComparers.FullName;

and have an instance of IEqualityComparer<FileSystemInfo>, since I didn't specify any type and FileSystemInfo is the most generic type T can be. With no type constraint the default type could for example be object or something.
Maybe not the best example, but anyways just got curious here :p

A:

Sounds like a recipe for trouble to me.
In particular, you could easily create a non-generic class called FileSystemInfoComparers with a static property of the same name, and suddenly your code would mean something completely different.
I'd rather keep things simple. (Generics are complicated enough already, and type inference in particular is pretty hairy.)


Q:

Can't get MATCH AGAINST to work with wildcard

Longtime reader, first time asker here.
I'm putting together a MySQL database of books as a learning project.  I'm trying to implement full-text search with PHP and MySQL.  It's working so far, but the * truncation operator isn't working as expected.  I'll omit the PHP for simplicity, since the behavior is the same when I run the queries in PhpMyAdmin too.
    SELECT * FROM Mainbooks WHERE MATCH(Title,Author,Description) AGAINST('blaze')

returns one row containing the entry for "Blaze" by Richard Bachman, but
    SELECT * FROM Mainbooks WHERE MATCH(Title,Author,Description) AGAINST('blaz*')

returns no rows.  For another example,
    SELECT * FROM Mainbooks WHERE MATCH(Title,Author,Description) AGAINST('Sacks')

returns the row containing "Migraine" by Oliver Sacks, but
    SELECT * FROM Mainbooks WHERE MATCH(Title,Author,Description) AGAINST('Sack*')

returns no rows.  A slightly different case is
    SELECT * FROM Mainbooks WHERE MATCH(Title,Author,Description) AGAINST('blaze*')

or
        SELECT * FROM Mainbooks WHERE MATCH(Title,Author,Description) AGAINST('migraine*')
both of which return results, apparently ignoring the * character.  I'm running this in MAMP, if that makes any difference.
What am I missing?

A:

You need to use BOOLEAN MODE when using * operator
http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html
SELECT * FROM Mainbooks
WHERE MATCH(Title,Author,Description) AGAINST('blaz*' IN BOOLEAN MODE)


Q:

Como inicializar uma constante com o valor de time.Now() em Golang?

Estou acostumado a fazer projetos em Python onde, ao inicializar o mesmo eu guardo uma variável dizendo quando ele iniciou (para poder medir o tempo de execução do projeto) assim:
import time
started_at = time.perf_counter()

Assim no final do código eu posso calcular a diferença entre o started_at e um novo time.perf_counter() e saber o tempo de execução do código.
Estou começando a estudar Golang agora e, ao tentar fazer a mesma coisa está aparecendo uma mensagem de erro "const initializer &time.Now() is not a constant" . Segue o código que comecei a montar:
package app

import "time"

const startedAt = time.Now()

O que preciso fazer para poder ter o mesmo comportamento do primeiro código em Golang?

A:

fazer projetos em Python onde, ao inicializar o mesmo eu guardo uma variável

Destaquei a palavra variável. Não consigo imaginar porque tentou usar uma constante em Go se em Python usou uma variável, se quer fazer o mesmo então escreva um código compatível, não introduza uma outra semântica.
Uma constante deve ser um valor que não mudará nunca. Um horário é a definição perfeita de algo que muda, é impossível pegar o mesmo dado em duas execuções.
Parece acreditar que constante é uma variável que não muda seu valor e isso não é correto. Para entender melhor: Constante é realmente útil? (siga os links).

O que preciso fazer para poder ter o mesmo comportamento do primeiro código em Golang?

Manter o dado como uma variável. Só trocar const por var ou atribuir com :=.
Se quer uma variável imutável, Go, hoje, não tem isso, assim como Python não tem nem mesmo constante.
Eu não acho que só isso fará o comportamento do código em Python acontecer em Go, afinal em Python está usando um biblioteca de análise de performance e em Go está usando uma biblioteca que trabalha com horário normal. Eu sei que é intuitivo a pessoa achar que é só pegar o horário que começou e que terminou a operação, subtrair um do outro e sabe quanto tempo demorou, mas essas bibliotecas de horário não costumam ter resolução e precisão suficiente para entregar resultados confiáveis para análise de desempenho.
Até onde eu sei se faz isso com go test, então pra que reinventar a roda?

A:

Para ter o mesmo comportamento você deve usar var e não const:
package app

import "time"

var startedAt = time.Now()

Quando a variável está dentro de uma função também é possível usar o := para criar a variável (como startedAt := time.Now()).

O Golang não permite utilizar funções como constante. Isto serve para tudo, mesmo aquilo que, em tese, é constante. Da mesma maneira que não pode usar const v = time.Now(), você não pode usar const v = math.Abs(1.2).

Toda regra tem exceções, existem poucas funções que podem ser usadas como const, a maioria delas é pertencente ao unsafe,  que o próprio nome já dá uma pista do que se trata. Além de algumas funções (e em alguns casos) que já são da própria linguagem (com o len).
Se for ver a documentação do unfsafe, pode notar o comentário:

// The return value of Alignof is a Go constant.

Então, é possível utilizar um const c = unsafe.Sizeof([]int{}). Também pode utilizar const c = len("abc"), mas não pode usar len([]int{1,2,3}), já que slice não são constantes.


Q:

Detect Mobile or Windows PHP

I want to make a website and I messed something up. I want to make two versions, one for desktops and one for mobile, but do not know how to redirect people .. I want to have two folders, mobile and web and file index.php. If they use mobile phones i want to redirect in mobile folder if they use PC redirect to web folder.
How could I do this? Thanks
Sorry for english

A:

Case 1 : Redirecting a site to a mobile version
Say we have a normal website that we need to redirect to a mobile version if viewed from a mobile device. All the code required for mobile detection is in a single file ‘Mobile_Detect.php’, which we can include in our web pages or in the primary index file. To simplify discussion let us assume you have a website ‘example1.com’ with a single index file, and need to redirect to ‘mobile.example1.com’ if a mobile device is detected. We need to put the following in the header of the index file of ‘example1.com’.
/* Change path info depending on your file locations */
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

if($detect->isMobile()) {
    header('Location: http://mobile.example1.com/');
    exit;
}

Case 2: Loading different resources depending on the device
We can load or modify existing content based on the users device profile. For example we could load a different CSS for a mobile or a tablet.
$detect = new Mobile_Detect;

if($detect->isMobile() || $detect->isTablet()) {
    echo "<link rel='stylesheet' href='mobile.css type='text/css' />";
} else {
    echo "<link rel='stylesheet' href='style.css type='text/css' />";
}

you can also user Javascript:
<script type="text/javascript">
  <!--
  if (screen.width <= 800) {
    window.location = "http://m.domain.com";
  }
  //-->
</script>

or
You can use a .htaccess redirect to transfer visitors based upon the MIME types the browser supports. For example, if the user's browser accepts mime types that include WML (Wireless Markup Language), then most likely it is a mobile device.
The code below should be placed in your .htaccess file:
RewriteEngine On
# Check for mime types commonly accepted by mobile devices
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ http://m.domain.com%{REQUEST_URI} [R,L]

If youve got 2 sites one for each device (not the best thing to do here) you can have a index.php file on the root with :
<script type="text/javascript">
  <!--
  if (screen.width <= 800) {
    window.location = "http://your.domain.com/mobile";
  } else {  window.location = "http://your.domain.com/desktop";  }
  //-->
</script>


Q:

KeyListener ignores if-statements

In this code:
public class KeyManager implements KeyListener{

public void keyPressed(KeyEvent e) {
    boolean spacePressed = false;

if(e.getKeyCode() == KeyEvent.VK_SPACE){
    if(spacePressed == false){
    spacePressed = true;
    System.out.println("Hello world");
    }
  }
}

I am trying to have space only print out "Hello world" once, then switch spacePressed to true and not do anything more from that point onward.
Using System prints I've managed to find out that it does change spacePressed to true after I've pressed it, but for some reason I can press space again and once more print out "Hello world".
In short, the compiler seems to ignore the if statement and just continue reading, which isn't supposed to happen.

A:

This is because spacePressed is declared inside the method. Every time the method executes, it gets re-declared and initialized to false.
Declare it outside:
public class KeyManager implements KeyListener{

    boolean spacePressed = false;

    public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == KeyEvent.VK_SPACE){
            if(spacePressed == false){
            spacePressed = true;
            System.out.println("Hello world");
            }
          }
        }

Please note that spacePressed == false can be written as !spacePressed:
if(!spacePressed){

A:

As spacePressed is a local variable, on the next call it is initialized with false again. Solution: Move it to a field of the KeyManager class:
public class KeyManager implements KeyListener{
    private boolean spacePressed = false;

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_SPACE){
            if(this.spacePressed == false){
                this.spacePressed = true;
                System.out.println("Hello world");
            }
        }
    }


Q:

Exception when using secondary UI message pump for a splash screen

I have encountered an odd issue with the way I am showing a splash form, that causes an InvalidAsynchronousStateException to be thrown.
First of all, here is the code for Main{} where I start the splash form:
[STAThread]
static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    Thread splash = new Thread(new ThreadStart(ShowSplash));
    splash.Start();

     Application.Run(new MainForm());
}

static void ShowSplash()
{
    using (SplashForm splash = new SplashForm())
    {
        Application.Run(splash);
    }
}

I am using .NET2.0, with Win XP.
During some testing where the app was left running for may hours, I noticed that the number of exceptions would occasionally increase by one or two.
(Numbers obtained by PerfMon, viewing '# of Exceps Thrown' counter.) These exceptions seem to be caught and swallowed by the runtime, because they do
not ripple up and cause anything to go wrong in the app itself. At least nothing that I can determine anyway.
I have discovered that the exception is thrown when the UserPreferenceChanged event is fired by the system. Since finding this out, I can generate the exception
at will by changing the background picture or screen saver, etc.
I am not explicitly subscribing to this event myself anywhere in code, but I understand (via the power of Google) that all top level controls and forms subscribe
to this event automatically.
I still have not determined why this event is being fired in the first place, as it appears to happen while the app is running over night, but I guess that is another mystery to be solved.
Now, if I stop the splash form thread from running, the exception disappears. Run the thread, it comes back. So, it appears that something is not unsubscribing from the event, and this is causing the subsequent exception perhaps?
Interestingly, if I substitute my splash form with a default, out of the box Form, the problem still remains:
static void ShowSplash()
{
    using (Form splash = new Form())
    {
        Application.Run(splash);
    }
}

While this form is being displayed, any UserPreferenceChanged events do not cause any exceptions. As soon as the form is closed, and the thread exits, exceptions will be thrown.
Further research has lead me to this Microsoft article, that contains the following comment:

Common causes are a splash screens
  created on a secondary UI thread or
  any controls created on worker
  threads.

Hmm, guilty as charged by the looks of it. Note that my app is not freezing or doing anything untoward though.
At the moment, this is more of a curiosity than anything else, but I am conecerned that there may be some hidden nasties here waiting to bite in the future.
To me, it looks like the form or the message pump started by Application.Run is not cleaning up properly when it terminates.
Any thoughts?

A:

Yes, you are running afoul with the SystemEvents class.  That class creates a hidden window that listens to system events.  Particularly the UserPreferenceChanged event, a lot of controls use that event to know when they need to repaint themselves because the system colors were changed.
Problem is, the initialization code that creates the window is very sensitive to the apartment state of the thread that calls it.  Which in your case is wrong, you didn't call Thread.SetApartmentState() to switch to STA.  That's very important for threads that display a UI.
Beware that your workaround isn't actually a fix, the system events will be raised on the wrong thread.  Your splash thread instead of the UI thread of your program.  You'll still get random and extremely hard to diagnose failure when an actual system event gets fired.  Most infamously when the user locks the workstation, the program deadlocks when it is unlocked again.
I think calling Thread.SetApartmentState() should fix your problem.  Not 100% sure, these UI thread interactions are very difficult to analyze and I haven't gotten this wrong yet.  Note that .NET already has very solid support for splash screens.  It definitely gets details like this right.


Q:

Haskell type synonym declaration with constraint possible?

Let's say I wanna make a type synonym for all lists with Int's.
I could do:
type NumberList = [Int]

But what if I want to call all lists that contains numbers NumberList? How would I put a constraint and say that all [a] as long as "Num a" should be called the same?
Edit:: After seeing the answers I rethought. It seemed like I was going against one of the basic ideas behind Haskell and the reward was relatively small (just a formal matter). I decided on this: If a type has the need for two instances identical to each other that only differ in Int or Float, then the difference between them is too small to warrant the workaround needed to accomplish the use of both Int and Float but calling them the same thing, which is why I must restrict the use to one of them. IF however there is an important reason to why I should have both, then I can probably reflect this important reason in the name of the instance and thereby avoid the problem by doing:
data Thing = Thing_A(String, String Float) | Thing_B(String,String,Int)

---and thereby stick to Haskell's typing system and still accept both of them as data type Thing. What I wanted to do at first was
data Thing = Thing(String, String, Float) | Thing(String, String, Int)

A:

This corresponds to existential quantification. In pseudo-Haskell,
type NumberList = exists a . Num a => [a]

I say «pseudo» because GHC doesn't allow introducing existential quantifiers on the fly — you need to create a separate datatype for that.
Now, most of the type you'd use NumberList to the left of the arrow, where «exists» effectively changes its meaning to «forall».
That is, instead of writing
isIncreasing :: NumberList -> Bool

which is the same as
isIncreasing :: (exists a . Num a => [a]) -> Bool

you can write
isIncreasing :: forall a . Num a => [a] -> Bool

or simply
isIncreasing :: Num a => [a] -> Bool

Of course, having a type synonym seems like less code, but it has disadvantages as well.
These disadvantages, by the way, are typical for object-oriented programming, which is based on the existential approach.
For example, you want to concatenate two lists. Ordinarily you would write
(++) :: forall a . [a] -> [a] -> [a]

(where again forall is unnecessary and added for clarity). Since a is the same across the entire signature, that ensures that you are concatenating lists of the same type.
How do we concatenate two numeric lists? A signature
(++) :: NumberList -> NumberList -> NumberList

wouldn't work, since one list may contain Ints and the other may contain Doubles. And the resulting NumberList has to contain values of a single type.
Or, say, you want to find the sum of the list elements.
Usually you write
sum :: Num a => [a] -> a

Notice that the result type is the same as the type of list elements. Alas, we cannot do the same for NumberList!
sum :: NumberList -> ???

What is the result type? We could apply existential quantification there as well.
sum :: NumberList -> (exists a . Num a => a)

But now the connection between the original list type and the sum type is lost — at least for Haskell's type system. If you then decide to write a function like
multiplySum :: Integer -> [Integer] -> Integer
multiplySum x ys = x * sum ys

then you'll get a type error, because sum ys may be of any type, not necessarily of type Integer.
It would work if you pushed everything to extreme and made every type existentially-quantified — but then you'd end up essentially with another object-oriented-like language with all their problems.
(That said, there are some good use cases for existential quantification, of course.)

A:

Use data and parameters, not existentials to get contexts
I think if you wanted
data Thing = Good [(Char,Int)] | Bad String | Indifferent Leg

but also sometimes
data Thing = Good [(Char,Float)] | Bad String | Indifferent Arm

You could define
data Thing num bodypart = Good [(Char,num)] | Bad String | Indifferent bodypart

or if you want to make sure num is always numeric, you could do
data Num num => Thing num bodypart = Good [(Char,num)] | Bad String | Indifferent bodypart

and finally, you could restrict the types allowed in bodypart by defining your own class:
class Body a where
   -- some useful function(s) here

instance Body Leg where
   -- define useful function(s) on Legs
instance Body Arm
   -- define useful function(s) on Arms

data (Num num,Body bodypart) => Thing num bodypart =
                                                             Good [(Char,num)] | Bad String | Indifferent bodypart

I'd like to discourage you from using existential types via the forall constructor or via GADTs because adding the num parameter to your data type is considerably more useful in practice, even though it takes more typing.
Constraints on type synonyms?
Note that when you use a constraint like
data (Num num) => Thing num = T [(Char,num)]

really only changes the type of the constructor T to
T :: (Num num) => [(Char,num)] -> Thing num

instead of T :: [(Char,num)] -> Thing num. This means every time you use T, there needs to be a context (Num num), but that's really what you wanted - to stop people putting data in your data type that isn't numeric.
A consequence of this fact is that you can't write
type Num num => [(Char,num)]

because there's no data constructor function T for the context (Num num) to be required on; if I have a [('4',False)], it automatically matches the type [(Char,num)] because it's a synonym. The compiler can't be going running around your code looking for instances before it decides what type something is. In the data case, it's got a constructor T that tells it the type, and it can guarantee there's a Num num instance because it checked your use of the function T. No T, no context.


Q:

Are there differences in the AppEngine Python SDK development server code between platforms?

I have created a buildout for a Pyramid project on GAE and as part of the buildout, it pulls http://googleappengine.googlecode.com/files/google_appengine_1.6.3.zip and places it in the project structure. This works fine for Linux and OS X (although of course extras like the Launcher are not present).
Are the Python code differences with the GAE Windows SDK such that I can't use the .zip file or is the developer server code the same between platform versions? (the differences just being extras and the install method)

A:

The Python code for the tools (dev_appserver and appcfg) are identical for all three platforms.


Q:

Navigation Pipeline Aurelia

I followed the Aurelia documentation about adding a Navigation Pipeline step.
I've created my Auth service and AuthRouterPipelineStep:
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
import {Router} from 'aurelia-router';
import {AuthResult} from './authResult';
import {Redirect} from 'aurelia-router';

@inject(HttpClient, Router)
export class Auth {
    constructor(httpClient, router) {
        this.httpClient = httpClient;
        this.router = router;
        this.internalIsLoggedIn = false;
    }

    login(username, password) {

        if (username === "callum" && password === "password") {
            this.router.navigate('products');

            this.internalIsLoggedIn = true;
        }

        return new AuthResult("Unable to login.");
    }

    get isLoggedIn() { return this.internalIsLoggedIn; }
}

@inject(Auth)
export class AuthRouterPipelineStep {
    constructor(auth) {
        this.auth = auth;
    }

    run(navigationInstruction, next) {
        console.log("Navigating");
        if (navigationInstruction
                .getAllInstructions()
                .some(i => i.config.settings.roles.indexOf('public') === -1))
        {
            var isLoggedIn = this.auth.isLoggedIn;
            if (!isLoggedIn) {
                return next.cancel(new Redirect('welcome'));
            }
        }

        return next();
    }
}

And in my App I've configure it all:
import {Auth, AuthRouterPipelineStep} from './auth/auth';
import {inject} from 'aurelia-framework';
import {Redirect} from 'aurelia-router';

@inject(Auth)
export class App {
    constructor(auth) {
        this.auth = auth;
    }

    get isLoggedIn() { return this.auth.isLoggedIn; }

    configureRouter(config, router) {
        config.title = 'Reaper';
        config.addPipelineStep('authorise', AuthRouterPipelineStep);
        config.map([
            { route: ['', 'welcome'], name: 'welcome',      moduleId: 'welcome',           nav: true, title: 'Home',      settings: { icon: 'fa-home', roles: ['public'] } },
            { route: 'contacts',      name: 'contacts',     moduleId: './contacts/index',  nav: true, title: 'Contacts',  settings: { icon: 'fa-' } },
            { route: 'companies',     name: 'companies',    moduleId: './companies/index', nav: true, title: 'Companies', settings: { icon: 'fa-' } },
            { route: 'products',      name: 'products',     moduleId: './products/index',  nav: true, title: 'Products',  settings: { icon: 'fa-' } }
        ]);

        this.router = router;
    }
}

I have a console.log on the Navigation Pipeline step Run function. That never gets called. What have I missed...?
I do know that all navigation steps are injected by the container, so you can have dependencies in the constructor...

A:

So as of Aurelia Beta 1. There are several hooks in the Navigation Pipeline. One being authorize and the other being modelbind.
So the name of pipeline step to add is very important. Authorise in my code is wrong, that is why the "middleware" isn't getting picked up.
You can however stack up middleware and it will run sequentially:
config.addPipelineStep('authorize', AuthRouterPipelineStep);
config.addPipelineStep('authorize', AnotherAuthRouterPipelineStep);


Q:

What is one word for "the nervous excitement associated with new things"?

Here are feelings which to some degree are related:

The feeling of waking up in a new city for the first time or starting work on a new job.
The feeling of new love, meeting someone for a date, getting married or having a baby.
The feeling of imagining what will it be like being in some place or time you have only read or heard about.

I have always felt myself at a loss of words, trying to convey that sort of a feeling precisely. I have to throw in several words to convey the effect: anxious, dreamy, excited, nervous, fresh, overwhelmed and so forth.
In contrast, if I have to describe the sad longing associated with old things, I have a precise term, namely, 'Nostalgia'.
The closest one word I could think of was 'Forward-looking'. But I feel, it is a bit too positive. Another word that I would consider is 'Ambivalent', but it needn't necessarily convey the feelings of new beginning. There must be a better word, isn't it?
p.s.: There are other similar questions like: this or this. So I have tried asking the question in manner, that highlights the different expectations from the answer.

A:

Anticipation (or expectation) may suggest the feeling excitement you are referring to:

a feeling of excitement about something that is going to happen in the near future:

As with most pleasures, it's not so much the experience itself as the anticipation that is enjoyable.
  The postponement of the film's sequel has held cinemagoers in eager anticipation for several months.

(Cambridge Dictionary)

A:

Butterflies:

a feeling of hollowness or queasiness caused especially by emotional or nervous tension or anxious anticipation (MW)

As the definition suggests, this works for both positive and negative anxiety.  Plus, it communicates the idea of nervousness effectively.

A:

"anxiety" is a general term and describes what we feel when we are facing something new.
Not all types of anxiety are pathological, though.  Some degree of anxiety is part of the human condition and an optimal level of arousal is necessary to best complete a task such as an exam, performance, or competitive event. Without it, we are likely to achieve much less than we would otherwise. But when anxiety exceeds that optimum, the result is a decline in performance and in this case it is certainly pathological.
Some common situations where anxiety may be exacerbated are:

When you have to give a lecture or make a speech for the first time.
When you go out with a sweetheart for the first time.
When you have intercourse for the first time.
When your wife is in labor.
When you wake up for the first time in a place you always dreamed visiting.

All the conditions mentioned by the OP can result in anxiety. Either "first-time anxiety" or "performance anxiety" depending on the situation.
Read more about anxiety here


Q:

Putting a Windows DC, Exchange in a DMZ

I have one guy at my company telling me that I should put FF:TMG in between my main Internet-facing firewall (Cisco 5510) and put my Exchange server and DC on the internal network.
I have another guy telling me that I should put the Exchange server and DC in a DMZ
I don't particularly like the idea of having my mailboxes and DC's usernames/passwords in a DMZ and I think that Windows authentication would require me opening up so many ports between my DMZ and my internal network that it would be a moot point to have it out there anyways.
What are some thoughts? How do you have it set up?

A:

Exchange
It depends on what Exchange version you're using. If you have Exchange 2007 or 2010, there is a role custom made for living in a DMZ: the Edge Server. Put that server in your DMZ and configure correct ports between that server and your private-network Exchange Hub-Transport servers. If you have Exchange 2000/2003, there is no good solution as far as InfoSec is concerned, you're pretty much stuck opening up SMTP (and TCP/443 if you use OWA) to a domained machine.
AD
Again, depends on your Exchange version. If you're at 2007/2010, the Edge server is designed to operate without any live connection to an actual domain-controller so there is absolutely no need to put a DC in the DMZ. If you're with 2000/2003 the server that's receiving Internet mail will have to be domain-connected somehow, which can be to a DC in DMZ (but with no DMZ/Internet firewall ports open) or to DCs on the private network by way of DMZ/Private firewall policy allowing the traffic.

Keep in mind that "DMZ" does not equate to "all ports open", you can open just the ports you need for both your DMZ/Internet and Private/DMZ firewalls. You can keep an Exchange 2000/2003 server in the DMZ and poke holes in your private/DMZ firewall to allow it to communicate to the DCs in the private network. Yes, it's a stepping stone to having your DC's hacked, but if that really concerns you upgrade to Exchange 2010 where Microsoft has engineered a much better solution to the problem.


Q:

CakePHP 3 is using primary key (setPrimaryKey) to do a JOIN even though I've specified a foreign key

CakePHP 3.7
I have 2 model Table classes as follows:

/src/Model/Table/SubstancesTable.php
/src/Model/Table/TblOrganisationSubstancesTable.php

The schema for each table in MySQL is as follows:
1.
mysql> describe substances;
+-------------+-----------------------+------+-----+---------+----------------+
| Field       | Type                  | Null | Key | Default | Extra          |
+-------------+-----------------------+------+-----+---------+----------------+
| id          | mediumint(8) unsigned | NO   | PRI | NULL    | auto_increment |
| app_id      | varchar(8)            | NO   | UNI | NULL    |                |
| name        | varchar(1500)         | NO   |     | NULL    |                |
| date        | date                  | NO   |     | NULL    |                |
+-------------+-----------------------+------+-----+---------+----------------+

2.
mysql> describe tbl_organisation_substances;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| o_sub_id    | int(255)     | NO   | PRI | NULL    | auto_increment |
| o_id        | int(255)     | NO   | MUL | NULL    |                |
| app_id      | varchar(15)  | YES  |     | NULL    |                |
| os_name     | varchar(255) | YES  |     | NULL    |                |
| ec          | varchar(35)  | YES  |     | NULL    |                |
| cas         | varchar(255) | YES  |     | NULL    |                |
| upload_id   | int(100)     | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

I've written a custom finder which needs to perform a JOIN between these 2 tables. The custom finder looks like this and is in SubstancesTable.php:
public function findDistinctSubstancesByOrganisation(Query $query, array $options)
{
    $o_id = $options['o_id'];

    $query = $this->find()->select('id')->contain('TblOrganisationSubstances')->where(['TblOrganisationSubstances.o_id' => $o_id]);

    return $query;
}

Each table has an app_id column and this is the foreign key that links the 2 tables.
Initially I was getting an error:

The TblOrganisationSubstances association is not defined on Substances.

Which made sense as no definitions had been put in place.
So in SubstancesTable.php I've defined this:
$this->setPrimaryKey('id');

// ...

$this->belongsTo('TblOrganisationSubstances', [
    'foreignKey' => 'app_id',
    'joinType' => 'INNER'
]);

But this produces the following SQL statement:
SELECT Substances.id AS `Substances__id` FROM substances Substances INNER JOIN tbl_organisation_substances TblOrganisationSubstances ON TblOrganisationSubstances.o_sub_id = (Substances.app_id) WHERE TblOrganisationSubstances.o_id = :c0

This isn't going to work because TblOrganisationSubstances.o_sub_id = (Substances.app_id) is wrong. It needs to JOIN based on app_id, in other words it should be:
TblOrganisationSubstances.app_id = (Substances.app_id)

I also tried changing the belongsTo to a hasMany association (not even sure which one is right here!):
$this->hasMany('TblOrganisationSubstances', [
    'foreignKey' => 'app_id',
]);

But the joining doesn't even seem to occur. The SQL produced is:
SELECT Substances.id AS `Substances__id` FROM substances Substances WHERE TblOrganisationSubstances.o_id = :c0

I also tried putting a belongsTo in TblOrganisationSubstances.php to try and define the relationship from both sides:
$this->belongsTo('Substances', [
    'foreignKey' => 'app_id',
    'joinType' => 'INNER'
]);

Again, this doesn't work. It produces the SQL without the join.
Please can someone help in terms of advising which is the correct type of association (hasMany vs belongsTo) and how to perform the join based on app_id, which is the foreign key that links the 2 tables.

A:

In a BelongsTo association, the source table holds the foreign key, hence with your configuration it will use app_id on Substances, and compare against the primary key of TblOrganisationSubstances.
In order to get the query that you're looking for, you also have to define the bindingKey, ie the foreign key of the target table, so that it doesn't use its primary key:
$this->belongsTo('TblOrganisationSubstances', [
    'foreignKey' => 'app_id', // Substances.app_id
    'bindingKey' => 'app_id', // TblOrganisationSubstances.app_id
    'joinType' => 'INNER'
]);

Whether it's HasMany or BelongsTo is dictated by your data, and what and how you want to retrieve it. Generally if one Substances has 0 or 1 TblOrganisationSubstances (1:1), then it's BelongsTo or HasOne. If one Substances can have more than 1 TblOrganisationSubstances (1:n), then it's HasMany.
And if you want to filter by a HasMany association, then you need to use either matching or a join (matching(), innerJoinWith(), leftJoinWith()), as HasMany associated records will be retrieved in a separate query when using contain().
See also

Cookbook > Database Access & ORM > Associations - Linking Tables Together
Cookbook > Database Access & ORM > Query Builder > Filtering by Associated Data


Q:

Get the startup path in a vb.net console exe

How do get the startup path ( system.windows.forms.application.StartupPath ) of my exe without adding a reference to system.windows.forms?

A:

You could try
System.AppDomain.CurrentDomain.BaseDirectory

which would work for most cases.

A:

EDIT: @KiwiBastard's answer is the correct method:
System.AppDomain.CurrentDomain.BaseDirectory

Add a reference to System.Reflection and use
Assembly.GetExecutingAssembly().Location

EDIT: Depending where you intend getting the startup path, this might be more appropriate:
Assembly.GetEntryAssembly().Location

A:

You can get the startup path without reflection by using:
IO.Path.GetDirectoryName(Diagnostics.Process.GetCurrentProcess().MainModule.FileName)


Q:

Coding path to file when it is called using registry and context menu

In my c# console application, which takes string as arguments,
I have a context menu item for images, that calls "myexe.exe %1", so path to file becomes argument for application. Even if path to file contains spaces, when I watch, what argument my application takes, I can see something like "VISUAL~3/...." (it is example when path to file contains "visual stuido", it has space).
But my application should understand how many arguments are given, so if it is called from context menu, everything is ok, because result argument has no spaces.
But I need call exe file from other application and give string arguments with spaces too. When I just give argument with spaces, my application splits it, so I don't know how to code spaces in argument to give it to exe file, like context menu does. How to do it?

A:

You should double quote your command lines arguments, e.g.,
string args = "\"arg 1\" \"arg 2\"";


Q:

NetBeans: how to split window and place output panel to the right?

By default NetBeans has projects on the left, open files on the top part of right panel and output/variables/... on the bottom part of the left panel. As a result file panel is wide and tall. Is it possible to reorganize panels, so that "projects" panel is on the left, "open files" panel is on the center and "output/variables/..." panel is on the right?

A:

This can be done much the same way you split the string horizontally. Grub the page tab and move it until you see that the red rectangle indicating alignment appears vertically along the right side of screen. This works in NetBans 8.1 and above.


Q:

nomencl: left alignment for description text

Does anyone know how to left align the description text of abbrevations in a nomencl list of abbrevations. For example: I would like to left align the text "Kategorien- und
Variablebezeichnungen" or "absolute Häufigkeit" in the following example. At the moment this text is justified. Thanks to all!
\documentclass[
a4paper,%
headings=small,%
]{scrbook}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{multicol}
\usepackage{ifthen}

%Abkürzungsverzeichnis
\usepackage[intoc]{nomencl}
\let\abk\nomenclature
\renewcommand{\nomname}{Abkürzungsverzeichnis}
\setlength{\nomlabelwidth}{.20\hsize}
\renewcommand{\nomlabel}[1]{#1 \dotfill}
\setlength{\nomitemsep}{-\parsep}
\RequirePackage{ifthen}
\renewcommand{\nomgroup}[1]{%
\ifthenelse{\equal{#1}{S}}{\medskip\item[\textbf{Statistik}]}{%
\ifthenelse{\equal{#1}{K}}{\medskip\item[\textbf{Notationskonventionen}]}}}
\renewcommand*\nompreamble{\setlength{\columnsep}{5pc}\begin{multicols}{2}}
\renewcommand*\nompostamble{\end{multicols}}
\makenomenclature

\begin{document}
\printnomenclature[3.2cm]

\abk[S]{n}{Stichprobengröße}
\abk[S]{H\textsubscript{n}}{absolute Häufigkeit}
\abk[K]{\frqq\dots\flqq}{Kategorien- und Variablebezeichnungen}
\abk[K]{\textit{Kursivdruck}}{Objektsprache}

\end{document}

A:

I think you're looking for ragged right justification of the nomenclature. If so, try adding the ragged2e package to the preamble, and putting the \printnomenclature in a group with \RaggedRight. Before (from your MWE):

after, adding
\usepackage{ragged2e}

and changing to
{\RaggedRight
\printnomenclature[3.2cm]
}


Q:

If .NET uses mark&sweep GC, why does it cut the memory addresses space in half?

According to MSDN, the .NET framework uses the mark&sweep garbage collection method. The same page also says that on 32bit systems, the address space is 2GB - which means that the address space is cut in half from the 4GB of 32bit systems.
Cutting the available memory in half is a trait of the stop&copy garbage collection method, but .NET uses mark&sweep which can operate on the whole address space - so why does .NET cut the address space in half?

A:

This is Windows, not .NET.  32bit Windows reserved the top 2GB of the address space for the operating system, and restricted applications to 2GB (provided the /3GB flag wasn't used).
Note that, in practice, it's actually worse.  A 32bit .NET application will typically start raising OutOfMemoryException between 1.2 and 1.6GB of RAM usage, even on a 64bit system with plenty of phsyical memory.


Q:

.NET Core and .NET Framework 4.7 edit project option not available

When I create a .NET Core 2.0 Project I have to select both .NET Core version (2.0) and a .NET Framework version (4.7).  But when I edit the project, I cannot change the .NET Framework version.  Why is that?  I am trying to use the function app.UseRewriter(options); and it is unavailable so I am theorizing that I have the wrong .NET Framework

I guess I just needed this package
Install-Package Microsoft.AspNetCore.Rewrite -Version 2.0.1

A:

Yes, that's a confusing GUI. That got me mad as well (like some other stuff in Visual Studio if you are used to Jetbrains-IDEs).
You have chosen an ASP.NET Core Web Application as project type. So the only target frameworks that are being offered to you are .NET Core 1.0, 1.1 and 2.0 (in case you have installed 2.0, like you did).
Chose Web -> ASP.NET Web Application (.NET Framework) to get what you want.


Q:

Unique factorization consequence

Let R be principal ideal domain and $p$ prime element and $b \in R$, $b\neq 0$, $E=R/(pb)$ module over $R$ and let $E_p$ be submodule consisting of elements with exponent $p$ (there exist positive intiger $r$ so that $p^rx=0$). I need to prove  $E_p=bR/(pb)$. One inclusion is trivial, and for other solution say it follows at once from unique factorization in $R$.
My try:
Let $x \in E_p$ so $x=a+(pb)$ and $p^ra+(pb)=(pb)$ which implies $p^ra=cpb$ for some $c \in R$. How do I use unique factorization here to prove that $a=by$ for some $y \in R$? What I can conclude from unique factorization in general? In some way I think i can "divide by $p$"?

A:

The correct statement should be that $E_p=b'R/pbR$, where $b'$ is $b/p^v$, where $p^v$ is the maximum power of $p$ appearing in the factorization of $b$.
The inclusion $b'R/pbR\subseteq E_p$ is obvious, because $p^{v+1}b'z=pbz\in pbR$ for any $z\in R$.
The submodule $E_p$ can be described as the set of cosets $x+(pb)$ such that, for some $k>0$, $p^kx\in(pb)$ or, equivalently, the set of cosets $x+(pb)$ such that, for some $k\ge0$, $p^kx\in(b)$.
If $x+(pb)\in E_p$, then $p^kx=by$. Let $r$ be the maximum exponent such that $p^r$ divides $y$. If $r\ge k$, we have
$$
x=b\frac{y}{p^k}
$$
so $x\in bR$. Otherwise, we get
$$
p^{k-r}x=b\frac{y}{p^r}
$$
and so we can assume $p^kx=pby$ where $p$ does not divide $y$ and $k\ge0$.
Now, consider the factorizations of $x$, $b$ and $y$, writing them as
$$
x=x_0p^up_1^{u_1}\dots p_s^{u_s},\quad
b=b_0p^vp_1^{v_1}\dots p_s^{v_s},\quad
y=y_0p_1^{w_1}\dots p_s^{w_s}
$$
where the exponent can be zero, the primes are all distinct and $x_0$, $b_0$, $y_0$ are units.
Thus we have
$$
x_0p^{u+k}p_1^{u_1}\dots p_s^{u_s}=
b_0y_0p^vp_1^{v_1}\dots p_s^{v_s}p_1^{w_1}\dots p_s^{w_s}
$$
This implies
$$
\begin{cases}
u+k=v\\
u_1=v_1+w_1\\
\dots\\
u_s=v_2+w_s
\end{cases}
$$
In particular $v_i\le u_i$ (for $i=1,2,\dots,s$) and so $b'$ divides $x$.
Note that when $b=p^v$ we have $b'=1$ and indeed $E_p=R/pbR$ in this case. On the other hand, if $p$ does not divide $b$, then $b'=b$ and $E_p=bR/pbR$.


Q:

How to pass EventArgs to DelegateCommand?

I have a Xamarin.Forms project. In Prism as a MVVM framework. I have a custom control (derived from CocosSharpView, but that's not important). I'm rising a custom event in that class with a parameter, but can't transfer this parameter to the ViewModel. Here's the code:
The View part. I'm firing up a custom OnTouched event with some argument:
public class CustomCocosSharpView : CocosSharpView
{
    public event EventHandler<CustomEventArgs> OnTouched;
    public CCGameView gameView;

    // ... not important stuff ...

    private void OnViewCreated(object sender, EventArgs ea)
    {
        if (gameView == null)
        {
            gameView = sender as CCGameView;
            if (gameView != null)
            {
                _gameScene = new GameScene(gameView);
                _gameScene.OnTouched += (s, e) =>
                {
                    CustomEventArgs custom = new CustomEventArgs() { Foo = 4 };
                    OnTouched?.Invoke(s, custom);
                };
                gameView.RunWithScene(_gameScene);
            }
        }
        OnCreated?.Invoke(sender, ea);
    }
}

public class CustomEventArgs : EventArgs
{
    public int Foo { get; set; }
}

XAML part:
  <mobile:CustomCocosSharpView>
    <behaviors:Interaction.Behaviors>
      <behaviors:BehaviorCollection>
        <behaviors:EventToCommand EventName="OnTouched"
                                  Command="{Binding OnTouchedCommand}" />
      </behaviors:BehaviorCollection>
    </behaviors:Interaction.Behaviors>
  </mobile:CustomCocosSharpView>

and finally ViewModel:
    private DelegateCommand<CustomEventArgs> onTouchedCommand;
    public DelegateCommand<CustomEventArgs> OnTouchedCommand
    {
        get
        {
            return onTouchedCommand ?? (onTouchedCommand = new DelegateCommand<CustomEventArgs>((arg) =>
            {
                Debug.WriteLine("OnTouchCommand " + arg?.Foo.ToString()); //arg is null. Why?
            }));
        }
    }

The question:
How can I get CustomEventArgs argument in the DelegateCommand? It must be possible! But nothing works:/
Thanks for help!

A:

If you are using Prism 6.3-pre2 you can use the built-in EventToCommand and have complete control over what you pass to the DelegateCommand using either a converter or a path.  You can check out the docs here:  http://prismlibrary.readthedocs.io/en/latest/Xamarin-Forms/6-EventToCommandBehavior/#using-the-eventtocommandbehavior


Q:

C/C++ Code not working with DEV C++. (floating point or type)

#include<stdlib.h>
#include<stdio.h>

long double fact(unsigned long int n)
    /*The factorial of a positive integer by recursion*/
{
    if (n==0)
        return 1;
    else
        return n*fact(n-1);
}

int main()
{
    long double  sum, n;
    int i, m;
    printf("\t/*Code to find the approximate value of e */");
check:
    printf("\n\n\tPlease Enter the value of n := ");
    scanf("%lf", &n);
    sum=0;
    for (i=0; i<=n; i++)
        sum +=1/(fact(i));
    printf("\n\n\tThe appriximate value of e := %.15lg\n\n\t", sum);
    printf("Let's do this again? 1/ YES Any key/ NO := ");
    scanf("%d", &m);
    if (m==1)
        goto check;
    else (1);
    return 0;
}

This code worked perfectly well with Visual C++ 2010 but not with DEV C++. It kept on returning zero for the value of e. Can someone please explain why! Thanks!

A:

use this scanf("%Lf", &n); the Format specifier of long double is %Lf,%le,%lg so use this
and also consider these point
Dev-C++  It uses GCC (MinGW).  No ammount of Dev-C++ updates will fix this issue.

Dev-C++ has not been updated for 5 years; don't hold your breath.
The derivative wxDev-C++ is maintained.
If you want a compiler update, go to www.mingw.org, and hope that the latest version still works with the ancient Dev-C++. Or use a different IDE or compiler.  I'd recommend VC++ 2010 Express Edition (Free, and a far better debugger), your code works as is in VC++ 2008, but that does not make it safe.
How did you determine the value was "0"?  It is likely that it was in fact something like 0.000001, and your method of interrogation rounded it.  You should view the value in the debugger rather than a print statement.  Unfortunately Dev-C++'s debugger sucks.
The ISO C standard library defines  functions only for double precision.  If you want versions defined for float, you need to compile as C++ and include .  C does not support function overloading, so it is impossible to do in C without differently named functions.


Q:

Border effect in photoshop

I would like some help.
I am posting an image below, I need that kind of selection border effect

A:

Before PS CS5, you had the extract filter (which was EPIC), then they decided to update it and mix it with the selection tools and "REFINE EDGE" came out, which needs a bit more work but you get even better results.
It's something long enough for not putting it here, but thanks to youtube... you can find a brilliant tutorial here: https://www.youtube.com/watch?v=soJdXsFx8V8&feature=youtu.be#aid=P9n5_Rj5c9Q
EDIT: If you want just to achieve the stroke effect around the girl, open the image in Illustrator first, draw a path around the wanted object and then play with the Dashed Line options. After that just copy paste the path into Photoshop as "Smart Object" and place it wherever needed. Here's an image from Illustrator:


Q:

Transpose results of a sql query

How to transpose this display.
SeqNo   Step        Date        By
1       Quoted      2018-03-01  Person1
2       Checked     2018-03-02  Person2
3       Authorized  2018-03-02  Person3
4       Approved    2018-03-03  Person4

Into this display.
1               2               3               4
Quoted          Checked         Authorized      Approved
2018-03-01      2018-03-02      2018-03-02      2018-03-03
Person1         Person2         Person3         Person4

A:

You'll have to use combination of unpivot and pivot syntax to achieve your result and also end up casting everything in to same compatible datatype like varchar(max)
live demo here
See query below
create table srcTable (SeqNo int,  Step varchar(10), [Date] date,  [By] varchar(10));
insert into srcTable values
(1,'Quoted','2018-03-01','Person1')
,(2,'Checked','2018-03-02','Person2')
,(3,'Authorized','2018-03-02','Person3')
,(4,'Approved','2018-03-03','Person4')

select [1],[2],[3],[4] from
(
    select
        SeqNo,
        [c2]=cast(Step as varchar(max)) ,
        [c3]=cast([Date] as varchar(max)),
        [c4]=cast([By] as varchar(max))
    from
         srcTable
    )s
unpivot
(
    value for data in ([c2],[c3],[c4])
)up
pivot
(
    max(value) for SeqNo in ([1],[2],[3],[4])
   )p


Q:

$_GET JavaScript and AJAX...

I am relatively new to PHP and I am (trying to) developing my first AJAX code...
I am trying to pass an attribute from a select with several options, each option with its very own unique attribute "values" that is a String.
The PHP file GETs the value and does something with it (for instance prints it out). And the generated file is then returned to my main HTML page.
Here is the source code...
Here is my javaScript:
function showUser(myElement) {

    var str = myElement.options[myElement.selectedIndex].getAttribute("values");

    if (str == "") {
        document.getElementById("myResponse").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("myResponse").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","getuser.php?q="+encodeURIComponent(str),true);
        xmlhttp.send();
    }
}

My HTML is as following:
<form>
<select name="users" onchange="showUser(this)">
  <option values="">Select a person:</option>
  <option values="Rasmus Lerdorf">Creator of PHP</option>
  <option values="Linus Torvalds">Developed Linux</option>
  <option values="Dennis Ritchie">Developper of C</option>
  </select>
</form>

Person info will be listed here...

My PHP is:
<?php
$q = intval($_GET['q']);
echo $q;
?>

I get 0 instead of the text string, what is wrong with my code?

A:

Silly me,
I copied and pasted a basic example from a tutorial and I did not realize that the PHP code was casting the string that was sent over the GET to an integer.
$q = intval($_GET['q']);
The code should be :
$q = $_GET['q'];
On my earlier stage of the development I was indeed passing an integer, so the code was working.
The code returned 0 instead of an error because the intval of a string is 0 on failure.
Writing down the question here I realized the mistake...


Q:

SQL Server Right() function to remove characters from certain point on column

I'm trying to remove text from my Description column after the "-" character. I know I would have to use the Right() function, but what would the syntax look like to loop through all the records and change all the records in the Description column?
Example...
BEFORE:
0002    55  Actor Hill - 0002
0004    57  Adair - 0004
0005    74  Adams - 0005

AFTER:
0002    55  Actor Hill
0004    57  Adair
0005    74  Adams

A:

try this in SQL Server:
DECLARE @String varchar(50)
SET @String='0002 55 Actor Hill - 0002'
SELECT LEFT(@String,CHARINDEX(' - ',@String)-1)

OUTPUT:
--------------------------------------------------
0002 55 Actor Hill

(1 row(s) affected)

here is an example using a table:
DECLARE @YourTable table (RowValue varchar(50))
INSERT @YourTable VALUES ('0002 55 Actor Hill - 0002')
INSERT @YourTable VALUES ('0004 57 Adair - 0004')
INSERT @YourTable VALUES ('0005 74 Adams - 0005')

SELECT
    LEFT(RowValue,CHARINDEX(' - ',RowValue)-1), '|'+LEFT(RowValue,CHARINDEX(' - ',RowValue)-1)+'|'
    FROM @YourTable

OUTPUT:
-------------------- ---------------------
0002 55 Actor Hill   |0002 55 Actor Hill|
0004 57 Adair        |0004 57 Adair|
0005 74 Adams        |0005 74 Adams|

(3 row(s) affected)

I used the | characters to show there are no trailing spaces
to change the actual data use:
UPDATE @YourTable
    SET RowValue=LEFT(RowValue,CHARINDEX(' - ',RowValue)-1)


Q:

How to port forward for DynDNS without touching the NAT router

I got a bit of a problem lately. I want to access my home network from the internet using a VPN and DynDNS.
For DynDNS I registered a free domain name at TwoDNS. My router is also setup to tell the DNS server its current IP address once in a while.
But then I realized that the address shown at TwoDNS doesn't match the address my router has. This is due to the fact that I am living at a student residence that is connected to the network of our university.
So my local network probably lies behind multiple NAT-routers. Usually this would require a port forward but how if I am not in control of the routers.
Maybe an external server with a constant connection to my home network will do the trick. What do you think?
Is there some kind of dynamic NAT?
Thanks in advance for any help

A:

The solution is simple and there is one specific service to enable just what I described: LogMeIn Hamachi


Q:

Ratio estimation model in 2-stage cluster sampling

I've been reading about stratified sampling, 2-stage SRS sampling, and ratio estimation in finite populations and I have a question. When the ratio estimator is introduced, it seems that in order for it to perform well it is necessary that the population follows the following model (which I'll denote $\xi$):
$$y_{ij} = \beta x_{ij} + \epsilon_{ij}$$
with the additional requirement that $E(\epsilon_{i,j}) = 0$ and $V(\epsilon_{i,j}) = \sigma^2 x_{i,j}$ where $x$ refers to the auxiliary information. I'm using subscripts $i, j$ since I'm thinking of this in the context of clusters.
Here's my understanding of this issue as a whole: from the design-based perspective (perhaps I should call this the model-assisted design-based perspective?), inference about the ratio point estimate is based on all possible samples under the design (2-stage SRS) and is not at all based upon this model, although if this model is met by the population then we'll see much better performance. If instead we assume this model (i.e. take the model-based route) then inference is based upon it and we actually need it to be true. As I understand it, this will lead to the same point estimate but potentially different variance estimates because we are either estimating the variance over all possible samples (design-based) or over all possible populations realizable under this model with these model parameters (i.e. $\beta$ and $\epsilon_{i,j}$).  We'll also have that the ratio estimate is design-biased and model-unbiased. Please correct me if any of this is wrong.
Here's my actual question. When we move on to cluster sampling, this model does not seem to be mentioned at all. As I understand it, the auxiliary information is the size of the clusters (denoted $M_i$). That the relationship passes through the origin, i.e. $y_{i,j} = 0$ iff $M_i = 0$, is clearly built in, but what about the variance relationship? I don’t see where variance proportional to cluster size comes in. Yet the ratio estimator seems to be viewed as a very reasonable (simple) choice so it seems that the conditions for it to perform well must be met. Any clarification would be tremendously appreciated.

A:

If the model for your data is
$$
y_{ij} = \mu_i + \varepsilon_{ij}, \quad {\rm E}_\xi \varepsilon_{ij} = 0, {\rm V}_\xi \varepsilon_{ij} = \sigma^2
$$
where the subindex $\xi$ stands for the model expectations, then the cluster totals $T_i[y] = \sum_j y_{ij}$ have the model moments
$$
{\rm E}_\xi T_i[y] = M_i \mu, \quad {\rm V}_\xi T_i[y] = M_i \sigma^2,
$$
so there clearly is proportionality to the cluster size.
If you want to understand design-based inference, think in totals. These are the only linear statistics; everything else is a ratio or another non-linear statistic that requires a delta-method.


Q:

NullPointerException on ENTER-key press in JavaFX Application Thread

I currently have the following situation:
I want to make my application listen to user input. First, I did this with an invisible TextField, but this screwed up my design and I thought it was not sophisticated enough. So, I am now trying to make a onKeyPressed EventHandler on my upper FlowPane, like this:
public String input = "";
@FXML public void listenToInput(KeyEvent key) {

    if (key.getCode() != KeyCode.ENTER) {

        if (key.getCode().isDigitKey() || key.getCode().isLetterKey()) {
            String newChar = key.getText();
            input = input.concat(newChar);
        }

    }
    else {
        this.addScanToList(input);
        input = "";
    }

}

This is working for just plain text and digits. But as soon as I press ENTER, I get the following error:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.sun.javafx.scene.control.behavior.TableViewBehaviorBase.activate(TableViewBehaviorBase.java:915)
at com.sun.javafx.scene.control.behavior.TableViewBehaviorBase.callAction(TableViewBehaviorBase.java:179)
at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent(BehaviorBase.java:218)
at com.sun.javafx.scene.control.behavior.TableViewBehaviorBase.callActionForEvent(TableViewBehaviorBase.java:208)
at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda$new$75(BehaviorBase.java:135)
at com.sun.javafx.scene.control.behavior.BehaviorBase$$Lambda$146/1103773754.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$KeyHandler.process(Scene.java:3926)
at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3872)
at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2001)
at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2463)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:197)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:147)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$346(GlassViewEventHandler.java:228)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$208/996795822.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:406)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:227)
at com.sun.glass.ui.View.handleKeyEvent(View.java:540)
at com.sun.glass.ui.View.notifyKey(View.java:950)

Where I already thought of:

The upper FlowPane has no focus, but then I gave it focus, but no result.
The enter key does not get recognized, which could be true, because the 'else' of my listenToInput never gets entered.

EDIT 1:

The FlowPane does not have a 'setOnAction', so it does not know how to handle the ENTER press.

Does anyone know what triggers this error?
Edit 2:
I changed onKeyPressed to onKeyReleased, and then my code runs properly, but I still get the error. Maybe it helps to know that.
Edit 3:
I tried to add the scan to the list with ALT instead of ENTER, and this works perfectly, so it has something to do with the ENTER

A:

After trying for several days, I was able to fix this. As I already mentioned in Edit 3, it had something to do with the ENTER key. When it was pressed, it looked like the FXML file was searching for an element which could consume an action. Somehow, the first thing it found was a TableView. I tried this code to make it non-focusable:
tableview.setFocusTraversable(false)

And it works. Can anyone explain what JavaFX wants to do with the ENTER key? I had my focus on the FlowPane, so it should send the action to the appropriate listener. If it has something to do with a Event Handler that has to be overridden, please let me know.


Q:

Cannot run IntelliJ - NoClassDefFoundError: Could not initialize class sun.awt.X11GraphicsEnvironment

I am unable to start IntelliJ with my fresh installed OpenSUSE 13.2
Here's the logs:
xybrek@opensuse:~/idea-IC-139.659.2/bin> ./idea.sh
OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=350m; support was removed in 8.0
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11GraphicsEnvironment
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:260)
    at java.awt.GraphicsEnvironment.createGE(GraphicsEnvironment.java:102)
    at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:81)
    at javax.swing.RepaintManager.<clinit>(RepaintManager.java:226)
    at javax.swing.JComponent.repaint(JComponent.java:4798)
    at java.awt.Component.repaint(Component.java:3303)
    at javax.swing.text.JTextComponent.setEditable(JTextComponent.java:1758)
    at javax.swing.text.JTextComponent.<init>(JTextComponent.java:309)
    at javax.swing.JEditorPane.<init>(JEditorPane.java:199)
    at javax.swing.JTextPane.<init>(JTextPane.java:90)
    at com.intellij.idea.Main.showMessage(Main.java:221)
    at com.intellij.idea.Main.showMessage(Main.java:208)
    at com.intellij.idea.Main.main(Main.java:81)
xybrek@opensuse:~/idea-IC-139.659.2/bin> java -version
openjdk version "1.8.0_25"
OpenJDK Runtime Environment (Zulu 8.4.0.1-linux64) (build 1.8.0_25-b17)
OpenJDK 64-Bit Server VM (Zulu 8.4.0.1-linux64) (build 25.25-b02, mixed mode)

What could be the problem here?

A:

I was able to reproduce your issue on OpenSUSE machine with not installed fonts. You may want to try to fix that by installing x11 fonts:
zypper install xorg-x11-fonts xorg-x11-fonts-core

Oracle JDK worked because they have proprietary fonts included in the bundle and fontconfig.properties for them.


Q:

extend a right floating div to the left

I am trying to extend a right floating div to the left.
I have an image and would like to put some text on the right of the image.
EDIT
the goal is that the site stays dynamic. So I can not use a fixed width.
One way would be to use Javascript, I guess but I would prefer to do this in HTML CSS only if possible.
Here is a picture of what I have

And here is a picture of what I would like to have

How can I extend the right div to left ?
Or should I use a div in the middle ?
Here is the HTML

    test
address 1
address2

and the CSS
#logo_container

{
padding: 0px;
overflow: hidden;
zoom: 1;

}

#logo_image

{
float: left;
background-color: transparent;
border: 1px solid red;

}

#logo_address

{
background-color: #0E4194;
color: #FFFFFF;
margin-left: auto;
padding: 0px;
float: right;
border: 1px solid red;
height: 150px;

}

A:

#logo_address
{
background-color: #0E4194;
color: #FFFFFF;
padding: 0px;
textalign: right;
float: left;
border: 1px solid red;
height: 150px;
width: ENTER VALUE HERE;
}

This would be a solution. If you float the #logo_address to the left, align the text to the right and enter a width value it would look as you want.


Q:

Remove chapter number from \frontmatter

This code is building from the solution posted by Ronny found here.
I wanted to know how to remove the chapter number "0" from the front matter pages (like the TOC, list of figures etc.) and the back matter pages that do not have a chapter number associated with them (like the appendix and index).
Here is his code:
\documentclass{book}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{lipsum}
\usepackage{xcolor,etoolbox,fancyhdr}
\patchcmd{\chapter}{\thispagestyle{plain}}{\thispagestyle{fancy}}{}{}
\usepackage{fourier}
\usepackage{titlesec}
\definecolor{lightblue}{RGB}{199,232,250}
\definecolor{darkblue}{RGB}{59,134,215}
\usetikzlibrary{calc}
% Define just chapter start pages

\pagestyle{fancy}
\fancyhf[LE]{Author's Name}\fancyhead[LE,RO]{}

\fancyhead[LO]{%\textcolor{mybluei} \rightmark%
\begin{tikzpicture}[overlay,remember picture]
    % Box
    \draw[fill=lightblue,draw=none] ($(current page.north east) - (1cm,0)$) -- (current page.north east) -- (current page.south east) -- ++ (-1cm,0) -- cycle;
    % Chapter Number
    \node[scale=3,darkblue] at ($(current page.north east) + (-1cm,-4cm)$)  {\thechapter};
    % Chapter
    \node[rotate=90, anchor=east] at ($(current page.north east) + (-.5cm,-4cm)$) {\leftmark{}};
    % Circle for page number
    \draw[fill=darkblue,draw=none] ($(current page.south east) + (-1cm,3cm)$) circle (3mm);
    % Page number
    \node at ($(current page.south east) + (-1cm,3cm)$)  {\textcolor{white}\thepage};
  \end{tikzpicture}}
\fancyhead[RE]{
\begin{tikzpicture}[overlay,remember picture]
    \draw[fill=lightblue,draw=none] ($(current page.north west) + (1cm,0)$) -- (current page.north west) -- (current page.south west) -- ++ (1cm,0) -- cycle;
    \node[rotate=90,anchor=east] at ($(current page.north west) + (.5cm,-4cm)$) {\rightmark};
    \node[scale=3,darkblue] at ($(current page.north west) + (1cm,-4cm)$) {\thechapter};
    \draw[fill=darkblue,draw=none] ($(current page.south west) + (1cm,3cm)$) circle (3mm);
    \node at ($(current page.south west) + (1cm,3cm)$)  {\textcolor{white}\thepage};
  \end{tikzpicture}}

\renewcommand{\chaptermark}[1]{%
\markboth{#1}{}}

\begin{document}

%========================================================================================
%   TABLE OF CONTENTS
%========================================================================================
\frontmatter
\tableofcontents

\listoffigures

%\lstlistoflistings

\mainmatter
\chapter{My first Chapter: Problems}

\section{Problem 1}
\subsection{Problem 1}
\lipsum[1]
\subsection{Solution 1}
\lipsum[1-7]
\newpage
\section{Problem 2}
\subsection{Problem 2}
\lipsum[1]
\subsection{Solution 2}
\lipsum[1-4]

\chapter{A second Chapter Title}
\section{Problem 1}
\subsection{Problem 1}
\lipsum[1]
\newpage
\subsection{Solution 1}
\lipsum[1]
\newpage
\section{Problem 2}
\subsection{Problem 2}
\lipsum[1]
\subsection{Solution 2}
\lipsum[1]

\end{document}

A:

The chapter number is inserted into the margin as the label of a tikz node using \thechapter. As you want to only print the chapter number in the "main matter" parts of the document the best way to control this is to use the \@mainmatter if-flag that is set to true by \mainmatter. The code below replaces the two uses of \thechapter, for the left and right margins, with \TheChapter, which is defined by:
\makeatletter% print \the chapter in main matter components of the document
\newcommand\TheChapter{\if@mainmatter\thechapter\fi}
\makeatother

This has the desired effect (the left-hand margins are similar):

As I have used \if@mainmatter, the numbers will stop appearing in the margins after a\backmatter command, which is what I think you wanted.
Here is the full code:
\documentclass{book}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{lipsum}
\usepackage{xcolor,etoolbox,fancyhdr}
\patchcmd{\chapter}{\thispagestyle{plain}}{\thispagestyle{fancy}}{}{}
\usepackage{fourier}
\usepackage{titlesec}
\definecolor{lightblue}{RGB}{199,232,250}
\definecolor{darkblue}{RGB}{59,134,215}
\usetikzlibrary{calc}
% Define just chapter start pages

\pagestyle{fancy}
\fancyhf[LE]{Author's Name}\fancyhead[LE,RO]{}
\makeatletter% print \the chapter in main matter components of the document
\newcommand\TheChapter{\if@mainmatter\thechapter\fi}
\makeatother
\fancyhead[LO]{%\textcolor{mybluei} \rightmark%
\begin{tikzpicture}[overlay,remember picture]
    % Box
    \draw[fill=lightblue,draw=none] ($(current page.north east) - (1cm,0)$) -- (current page.north east) -- (current page.south east) -- ++ (-1cm,0) -- cycle;
    % Chapter Number
    \node[scale=3,darkblue] at ($(current page.north east) + (-1cm,-4cm)$)  {\TheChapter};% selectively print chapter number
    % Chapter
    \node[rotate=90, anchor=east] at ($(current page.north east) + (-.5cm,-4cm)$) {\leftmark{}};
    % Circle for page number
    \draw[fill=darkblue,draw=none] ($(current page.south east) + (-1cm,3cm)$) circle (3mm);
    % Page number
    \node at ($(current page.south east) + (-1cm,3cm)$)  {\textcolor{white}\thepage};
  \end{tikzpicture}}
\fancyhead[RE]{
\begin{tikzpicture}[overlay,remember picture]
    \draw[fill=lightblue,draw=none] ($(current page.north west) + (1cm,0)$) -- (current page.north west) -- (current page.south west) -- ++ (1cm,0) -- cycle;
    \node[rotate=90,anchor=east] at ($(current page.north west) + (.5cm,-4cm)$) {\rightmark};
    \node[scale=3,darkblue] at ($(current page.north west) + (1cm,-4cm)$) {\TheChapter};% selectively print chapter number
    \draw[fill=darkblue,draw=none] ($(current page.south west) + (1cm,3cm)$) circle (3mm);
    \node at ($(current page.south west) + (1cm,3cm)$)  {\textcolor{white}\thepage};
  \end{tikzpicture}}

\renewcommand{\chaptermark}[1]{%
\markboth{#1}{}}

\begin{document}

%========================================================================================
%   TABLE OF CONTENTS
%========================================================================================
\frontmatter
\tableofcontents

\listoffigures

%\lstlistoflistings
\mainmatter
\chapter{My first Chapter: Problems}

\section{Problem 1}
\subsection{Problem 1}
\lipsum[1]
\subsection{Solution 1}
\lipsum[1-7]
\newpage
\section{Problem 2}
\subsection{Problem 2}
\lipsum[1]
\subsection{Solution 2}
\lipsum[1-4]

\chapter{A second Chapter Title}
\section{Problem 1}
\subsection{Problem 1}
\lipsum[1]
\newpage
\subsection{Solution 1}
\lipsum[1]
\newpage
\section{Problem 2}
\subsection{Problem 2}
\lipsum[1]
\subsection{Solution 2}
\lipsum[1]

\end{document}


Q:

Either Remote or Local Sandbox, why not both ?

WRT : http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e3f.html
Why a flash application can either use Remote  or Local Sandbox . What is the problem if it's using both of them ?
Say a flash application at one time communicating with a local file... and also communicating with some file on the server. Isn't that allowed ?

A:

It is not allowed because of security reasons, if it was allowed to communicate with both you can potentially take files from the users machine and send them to a server on the web.


Q:

How to setup and test an Android Library Project with Gradle and Android-Studio?

I'm working on an Android Library Project utility class (no activity). I tried to test by configuring an other project but I can't make it work, I don't how to use instrumentTest and can't understand for what purpose I should use it (unit test or Activity using my lib).

A:

i think this tutorial will help you : http://cyrilmottier.com/2013/06/27/a-productive-android-development-environment/ !