Minimum distance to points in plane

Question: Someone told me that the the following problem is elementary. Given three points $a=(-5,0)$, $b=(0,5)$ and $c=(5,0)$ in $\mathbb R^2$ with Euclidean norm:
$$\mbox{minimize}\;\; \; f(x)=\|x-a\| + \|x-b\|-2\|x-c\|,\;\; x\in \mathbb R^2.$$
I will highly appreciate for your answers. Thanks in advance.
Comment: I'll give you 2 hints:
- first, minimizing $(x-a)^2$ is equivalent to minimizing $\sqrt{(x-a)^2}$. Of course the minimum value will be different, but the location will be the same.
- Now just think, how would you find the minimum to a generic function $f_{(x)}$? And if it were $f_{(x,y)}$?
Comment: @lifesayko: I don't know how to use your hints at all! Hic, please make it more clearly.
Comment: Richkent, it is not my job to solve your your probelms for you. Please show at least what you've tried. What specifically are you having trouble with? Show how you would set up the problem. If you really have no idea, try to find the minimum to a generic problem $f_{(x)}$, such as $f_{(x)}=x^2+4$. Then reason how to transfer this to what you have.
Comment: Fist of all, I want to verify that whether the problem has a global minimum or not? I have showed that $f(x)$ is bounded but the existence of a minimum point have been not determined yet.
Comment: I have no solution, but the - not elementary - problem seems to be the "Fermat Weber Problem with positive and negative weights". Your constellation looks asymptotically bounded at $f(x)=-\sqrt{250}$ for $x=(t, -t/3) \text{ for } t \to -\infty$.
Comment: I've solved my problem yet, so thank you everybody for your attention. My solution by 2 steps: Firstly, prove that $f(x)\geq \|(a+b)/2-c\|$ for all $x$. Secondly, prove that the equality can't happen. Finally, prove that there exist a sequence of point $\{x_k\}$ tend to infinity and the optimal value at infinity is $\|(a+b)/2-c\|$, just let $\|x\| \to \infty$ along with the direction $v:=(a+b)/2-c$. Thanks lot. It is a very beautiful problem.
Answer: You seem to be serious about solving this problem. What I would try is this: Choose any $r$ such that
$$
            \|a-b\| \le r < \infty.
$$
Consider the ellipse
$$
             \|x-a\|+\|x-b\|=r,
$$
for which you can get an equation by the standard trick of expanding:
$$
                     \|x-a\|^{2}=r^{2}-2\|x-b\|+\|x-b\|^{2} \\
                         \|x-a\|^{2}-\|x-b\|^{2}-r^{2}=-2\|x-b\| \\
                (2(b\cdot x)-2(a\cdot x)+\|a\|^{2}-\|b\|^{2}-r^{2})^{2}=4\|x-b\|^{2}.
$$
("$\cdot$" represents vector dot product in the last expression.)
Now, minimize $f$ on this ellipse. This comes down to considering $f(x)=r-2\|x-c\|$ for $x$ on the ellipse. Finally, look at the minimum value of $f$ as a function of $r$, and see what you can do with that.
Note: Try finding the location of the minimum for $f(x)=r-2\|x-c\|$ on the ellipse by finding the location of the maximum for $\|x-c\|^{2}=\|x\|^{2}-2(x\cdot x)+\|c\|^{2}$ on the ellipse, which can be done by first replacing $\|x\|^{2}=x_{1}^{2}+x_{2}^{2}$ with terms from the equation for the ellipse.
No guarantee that this will lead to enough reduction in complexity, but I don't see any other reasonable suggestions. It might be worthwhile to first rotate the configuration until $a$ and $b$ are on one horizontal or on one vertical line.
Comment: @ T.A.E, here is my attempt, but there is a trouble I need to verify: http://math.stackexchange.com/questions/739262/taylor-expansion-at-infinity-and-optimal-value-at-infinity-of-a-function

Minimum distance to points in plane


Ban IP address based on X number of unsuccessful login attempts?

Question: Is it possible to ban an IP address after X number of unsuccessful login attempts to a Windows Server? Not to a particular account, which I know how to do, but to the whole machine.
We get hit pretty hard by brute force attacks trying to guess usernames, so this would really help get some load off the server.
Comment: *nix has fial2ban... not sure if there's a Windows equivalent/port.  http://www.fail2ban.org/wiki/index.php/Main_Page
Comment: From Evan Anderson: http://serverfault.com/questions/43360/cygwin-sshd-autoblock-failed-logins/43900#43900 ...looks to be a good equivalent of fail2ban's functionality but as your question is not specific enough, I don't know if you're looking to ban IPs attempting to login to a hosted website, your server (via SSH) or your domain. Clarification would go a long way. Additionally you could rate limit at your firewall, but that is implementation-dependent.
Comment: You might want to have a look at http://serverfault.com/questions/216995/is-it-worth-the-effort-to-block-failed-login-attempts/217066#217066 for a previous discussion about how useful automated banning based on IP is.
Comment: I made a windows service on github to do just that: https://github.com/jjxtra/Windows-IP-Ban-Service
Comment: If you're talking about Terminal Services / Remote Desktop have a look here: http://serverfault.com/a/335976/7200
Comment: If you get "hit hard" by these, would this end up effectively perpetually locking you out of your own server?
Comment: @HeavyWave - were you getting hit via RDP, FTP, or something else? If it's RDP and/or FTP, I posted a Powershell script [below][http://serverfault.com/a/571903/107701] that will automatically block IPs after X attempts.
Answer: You can do this with powershell and task manager. It's probably not perfect solution, but it works quite well and i have about 100 blocked IP addresses in two months. I wrote script, that select from EventLog specified events ("audit failure"). If there are many failed logins from any IP address, then it's added to firewall rule (created manually) named "BlockAttackers" which blocks any traffic to specified ip addresses.
PS1 Script:
$DT = [DateTime]::Now.AddDays(-1) # check only last 24 hours

$l = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $DT | Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]} } # select Ip addresses that has audit failure
$g = $l | group-object -property IpAddress  | where {$_.Count -gt 20} | Select -property Name # get ip adresses, that have more than 20 wrong logins

$fw = New-Object -ComObject hnetcfg.fwpolicy2 # get firewall object

$ar = $fw.rules | where {$_.name -eq 'BlockAttackers'} # get firewall rule named 'BlockAttackers' (must be created manually)

$arRemote = $ar.RemoteAddresses -split(',') #split the existing IPs into an array so we can easily search for existing IPs

$w = $g | where {$_.Name.Length -gt 1 -and  !($arRemote -contains $_.Name + '/255.255.255.255') } # get ip addresses that are not already in firewal rule. Include the subnet mask which is automatically added to the firewall remote IP declaration.

$w| %{$ar.remoteaddresses += ',' + $_.Name} # add IPs to firewall rule

Create task in scheduler and set trigger to event 4625 (windows login including terminal services). But you can set trigger to run e.g. twice per hour to avoid unnecessary loading the server.

and after trigger run powershell script. You must also set higher privileges to run this script, otherwise it will fail with security exception.

You can also bind this script to other security events.
Comment: Excellent script @remunda - thanks! I was getting a lot of 4625s from FTP as well, which the Security log doesn't have IP addresses for, so I expanded upon your script to have it check the current day's FTP log as well. Please see my answer below for more info: http://serverfault.com/a/571903/107701
Comment: There are a lot of gotchas and edge cases with the event logs, ip address logging, etc. that I've handled in IPBan - free and open source at https://github.com/jjxtra/Windows-IP-Ban-Service
Answer: I know this question is old but it was actually the first forum post I stumbled across when I started trying to do this exact same thing a couple weeks ago.  I've managed to come up with a working script that will parse the event logs 24 hours back for only bad login event log entries, grab the ones that have more than 10 bad logins, and then put them into an ipsec filter list using the netsh command.  Then I wrote a batch file with this line powershell .\*scriptname.ps1* and created a scheduled task to run the batch file every 24 hours (for some reason it wouldn't execute directly).
$DATE = [DateTime]::Now.AddDays(-1)

$EVS = Get-EventLog Security -InstanceId 529 -after $DATE

$EVS | select-string -inputobject {$_.message} -pattern "Source Network Address:(.)*\.*\.*\.*"  -allmatches | foreach-object {$_.Matches} | foreach-object {$_.Value} | foreach-object {$_.replace("Source Network Address:", "")} | group-object -property $_ | where-object {$_.count -gt 10} | select-object -property name | format-list | out-file c:\rdpblock.txt

get-content -path c:\rdpblock.txt | foreach-object {$_.replace("Name :", "")} | out-file c:\rdpblockcleaned.txt

get-content -path c:\rdpblockcleaned.txt | select-object -unique | out-file c:\rdpblocknospaces.txt

$RDPIP = get-content -path c:\rdpblocknospaces.txt | select-object -skip 1

$RDPIP | foreach-object {$_.replace("     ", "")} | foreach-object {netsh ipsec static add filter filterlist=RDP_BLOCK srcaddr=$($_) dstaddr=any}

I know that this script is probably inefficient but when I started working on this I had absolutely no experience in powershell, so my ability to optimize scripts leaves alot to be desired.  However, despite this fact I thought I would share this with anyone who could use it.
I thank Remunda for giving me the initial idea, that poster is the one that turned me on to the idea of using powershell to search the event logs.
Answer: This script builds on remunda's answer and goes a little further https://serverfault.com/a/397637/155102 It accounts for the "BlockAttackers" rule not have any IPs entered yet (which returns a "*" as a string). It also writes a comment to a log file to let you know when the IP was added to the rule.
A good tip is to create the "BlockAttackers" rule that blocks the IP addresses BUT make it disabled at first. Then, run this script once manually so it can populate the "RemoteAddresses" field with actual IP addresses that should be blocked. Take a look at those IP addresses to make sure nothing critical has been added and then enable the firewall rule. Add this rule to your firewall as remunda described.
The git for this script
#Checks for IP addresses that used incorrect password more than 10 times
#within 24 hours and blocks them using a firewall rule 'BlockAttackers'

#Check only last 24 hours
$DT = [DateTime]::Now.AddHours(-24)

#Select Ip addresses that has audit failure
$l = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $DT | Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]} }

#Get ip adresses, that have more than 10 wrong logins
$g = $l | group-object -property IpAddress | where {$_.Count -gt 10} | Select -property Name

#Get firewall object
$fw = New-Object -ComObject hnetcfg.fwpolicy2

#Get firewall rule named 'BlockAttackers' (must be created manually)
$ar = $fw.rules | where {$_.name -eq 'BlockAttackers'}

#Split the existing IPs into an array so we can search it for existing IPs
$arRemote = $ar.RemoteAddresses -split(',')

#Only collect IPs that aren't already in the firewall rule
$w = $g | where {$_.Name.Length -gt 1 -and !($arRemote -contains $_.Name + '/255.255.255.255') }

#Add the new IPs to firewall rule
$w| %{
  if ($ar.RemoteAddresses -eq '*') {
    $ar.remoteaddresses = $_.Name
  }else{
    $ar.remoteaddresses += ',' + $_.Name
  }
}

#Write to logfile
if ($w.length -gt 1) {
  $w| %{(Get-Date).ToString() + ' ' + $_.Name >> '.\blocked.txt'}
}

Answer: I can't take credit for this answer, but https://serverfault.com/users/7200/evan-anderson has mentioned his project http://opensource.wellbury.com/projects/windows_sshd_block/newest-release/
Answer: It's generally not a good idea to let somebody else control your firewall rules. That's basically what you're asking for here.
Comment: Sorry, but I didn't ask if it was a good idea.
Comment: Automatically banning IPs after a certain number of failed logins is *very* common practice.  I see hosts being banned on an hourly basis after trying to guess FTP passwords.  The only way this can be a DoS attack is if someone managed to spoof your IP (impossible on TCP connections), or if you repeatedly mistype your password (in which case it's not someone else controlling firewall rules, it's you)
Comment: +1, this is an excellent way to set yourself up for a denial of service attack. And if you're using rate-limiting, most automated brute force tools space their login attempts far enough apart to avoid getting caught.
Comment: Of course there is no reason exceptions couldn't be set for one or more specific IP addresses, which would pretty much eliminate the DoS concern.
Answer: This is an old thread. I was using the script provided by kevinmicke in 2014-2015. Then it just stopped working. So I had to edit it a bit to adopt to Windows Network Security authentication that does not leave IP addresses in the security log. Also, since I don't have regular FTP running I removed that part as it was causing errors because there was no log folder. The main change is in the source of RDP events.
    $current_date_utc = (Get-Date).ToUniversalTime()

    # Set number of failed login attempts after which an IP address will be blocked
    $int_block_limit = 10

    # Time window during which to check the Security log, which is currently set to check only the last 24 hours
    $dat_time_window = [DateTime]::Now.AddDays(-1)

    $arr_new_bad_ips_all = (get-winevent -filterhashtable @{ logname='Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational'; starttime=$dat_time_window; id=140 }).message |
        % { if ($_ -match "of (.+) failed") { $Matches[1] }} |
        Group-Object |
        Where {$_.Count -ge $int_block_limit} |
        Select -property Name

    # Sort the array, selecting only unique IPs (in case one IP shows up in both the Security and FTP logs)
    $arr_new_bad_ips_all = $arr_new_bad_ips_all | Foreach-Object { [string]$_.Name } | Select-Object -unique

    # Get firewall object
    $firewall = New-Object -comobject hnetcfg.fwpolicy2

    # Get all firewall rules matching "BlockAttackers*"
    $arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}

    # If no "BlockAttackers*" firewall rule exists yet, create one and set it to a variable
    if ($arr_firewall_rules -eq $null) {
        $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
        netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created." enable=yes remoteip="0.0.0.0" | Out-Null
        $arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}
    }

    # Split the existing IPs from current "BlockAttackers*" firewall rule(s) into an array so we can easily search them
    $arr_existing_bad_ips = @()
    foreach ($rule in $arr_firewall_rules) {
        $arr_existing_bad_ips += $rule.RemoteAddresses -split(',')
    }

    # Clean subnet masks off of IPs that are currently blocked by the firewall rule(s)
    $arr_existing_bad_ips_without_masks = $arr_existing_bad_ips | ForEach-Object {$_ -replace "/.*", ""}

    # Select IP addresses to add to the firewall, but only ones that...
    $arr_new_bad_ips_for_firewall = $arr_new_bad_ips_all | Where {
        # contain an IP address (i.e. aren't blank or a dash, which the Security log has for systems that failed FTP logins)
        $_.Length -gt 6 -and
        # aren't already in the firewall rule(s)
        !($arr_existing_bad_ips_without_masks -contains $_) -and
        # aren't the local loopback
        !($_.StartsWith('127.0.0.1')) -and
        # aren't part of the local subnet
        !($_.StartsWith('192.168.')) -and
        !($_.StartsWith('0.0.'))
    }

    # If there are IPs to block, do the following...
    if ($arr_new_bad_ips_for_firewall -ne $null) {
        # Write date and time to script-specific log file
        [DateTime]::Now | Out-File -Append -Encoding utf8 C:\Security\blockattackers.txt
        # Write newly-blocked IP addresses to log file
        $arr_new_bad_ips_for_firewall | Out-File -Append -Encoding utf8 C:\Security\blockattackers.txt

        # Boolean to make sure the new IPs are only added on one rule
        $bln_added_to_rule = 0

        # Array to hold bad IPs from each rule one at a time, so we can count to make sure adding the new ones won't exceed 1000 IPs
        $arr_existing_bad_ips_current_rule = @()

        # For each "BlockAttackers*" rule in the firewall, do the following...
        foreach ($rule in $arr_firewall_rules) {
            if ($bln_added_to_rule -ne 1) {
                # Split the existing IPs from the current rule into an array so we can easily count them
                $arr_existing_bad_ips_current_rule = $rule.RemoteAddresses -split(',')

                # If the number of IPs to add is less than 1000 minus the current number of IPs in the rule, add them to this rule
                if ($arr_new_bad_ips_for_firewall.Count -le (1000 - $arr_existing_bad_ips_current_rule.Count)) {
                    # Add new IPs to firewall rule
                    $arr_new_bad_ips_for_firewall | %{$rule.RemoteAddresses += ',' + $_}

                    # Write which rule the IPs were added to to log file
                    echo "New IP addresses above added to Windows Firewall rule:" $rule.Name | Out-File -Append -Encoding utf8 C:\Security\blockattackers.txt

                    # Set boolean so any other rules are skipped when adding IPs
                    $bln_added_to_rule = 1
                }
            }
        }

        # If there wasn't room in any other "BlockAttackers*" firewall rule, create a new one and add the IPs to it
        if ($bln_added_to_rule -ne 1) {
            $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
            netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created." enable=yes remoteip="0.0.0.0" | Out-Null
            $new_rule = $firewall.rules | Where {$_.Name -eq $str_new_rule_name}

            # Add new IPs to firewall rule
            $arr_new_bad_ips_for_firewall | %{$new_rule.RemoteAddresses += ',' + $_}

            # Write which rule the IPs were added to to log file
            echo "New IP addresses above added to newly created Windows Firewall rule:" $new_rule.Name | Out-File -Append -Encoding utf8 C:\Security\blockattackers.txt
        }
    }

The above script will work on Windows 2012. If you are still using Remote Desktop with network access level authentication on Windows 2008 then you might need to do the following trick. Windows 2008 does not have IP addresses in the security log and does not seem to have them in the Microsoft-Windows-RemoteDesktopServices-RdpCoreTS log either. So I had to actually use 2 logs - match events from the security log to successful access attempts to port 3389 in the firewall log. This is a guess work, but it seems to be detecting password attacks. Here is the part that collects violating IPs:
    $current_date_utc = (Get-Date).ToUniversalTime()

    # Set number of failed login attempts after which an IP address will be blocked
    $int_block_limit = 10

    $dat_time_window = [DateTime]::Now.AddDays(-1)

    $logfn = (netsh advfirewall show allprofiles | Select-String Filename | select-object -unique | % { $_ -replace "%systemroot%",$env:systemroot }).substring(10).trimstart().trimend()

    $badevts = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $dat_time_window | foreach-object { [datetime]$_.TimeWritten } | sort-object

    $fwlog = Select-String -Path $logfn -Pattern "ALLOW TCP" |
        % {
            if ($_ -match "(201.-..-..) (.+) ALLOW TCP (.+) (.+) (.+) 3389")
            {
                new-object psobject -property @{
                  dt = $Matches[1] + ' ' + $Matches[2]
                  ip = $Matches[3]
                }
            }
        }

    $ipa = @()
    $j = 0

    for ($i=0; $i -lt $fwlog.Count; $i++)
    {
        $conn = ([datetime]$fwlog[$i].dt).ticks
        while (($j -lt $badevts.Count) -and (($badevts[$j]).ticks -lt $conn)) { $j++ }
        if ($j -ge $badevts.Count) { break }
        if ((($badevts[$j]).ticks - $conn) -le 30000000) { $ipa += ,($fwlog[$i].ip) }
    }

    $arr_new_bad_ips_all = $ipa |
        Group-Object |
        Where {$_.Count -ge $int_block_limit} |
        Select -property Name

NOTE: Don't forget to enable firewall logs.
NOTE 2: I am not a powershell expert so it would be nice if some gurus can correct/improve my code.
Answer: Using remunda's great script as a starting point, I added the one major thing that was missing: blocking IP addresses from failed FTP logins. Windows Server doesn't log the IP address to the Security log when someone fails to login via FTP, but instead sets the "Source Network Address" to a dash. FTP is a very common attack vector for brute force attacks, so I added to his script the ability to scan the current day's FTP logs for multiple login failures and block those IP addresses as well.
Update 2014/02/07: When I made some tweaks to this to process all my old FTP logs, I realized when they had immense numbers of attempts (50,000+), the arrays it created would be huge and make the processing incredibly slow. I've since rewritten it to make it much more efficient when processing FTP logs.
I also found out that there's an arbitrary hard limit of 1000 for how many IPs can be in one Windows Firewall rule. Because of that limit, I needed it to automatically create a new rule when the latest one fills up. It now does that, and also creates the initial firewall rule (if you don't create your own) so that the only setup to do is adding it to the Scheduler to run when there's an event 4625.
Here's the code, which has been tested on both Windows Server 2008 R2 and Windows 7:
# This Windows Powershell script will automatically block IP addresses that attempt to login to the system
# and fail the number of times set below with the $int_block_limit variable or more. Is scans both the Security
# log, which covers Remote Desktop and other attempts, as well as the current day's FTP log. If the $int_block_limit
# limit is hit on either of those logs (separately, not combined), then the IP address will be added to the
# firewall rule.
#
# The script will automatically create a firewall rule named "BlockAttackers (Created yyyy-MM-dd HH:mm:ss UTC)" using
# the current time if one with a name that includes "BlockAttackers" doesn't already exist. Because there's a hard
# limit of 1000 entries (IP addresses) you can block per rule, it will also create similarly-named rules once that
# limit is reached for the latest one.
#
# I recommend setting the script to run as a scheduled task triggered by event 4625 login audit failures from the
# Security log, or alternatively you could set it to run after some amount of time (i.e. every 10 minutes).
#
# Authors:
# Majority of script written by serverfault.com user kevinmicke
# Windows Security Log portion written by serverfault.com user remunda, which provided the starting point for kevinmicke
#
# Details: https://serverfault.com/questions/233222/ban-ip-address-based-on-x-number-of-unsuccessful-login-attempts

# Set number of failed login attempts after which an IP address will be blocked
$int_block_limit = 10

# Time window during which to check the Security log, which is currently set to check only the last 24 hours
$dat_time_window = [DateTime]::Now.AddDays(-1)

# Select from the Security log all IP addresses that have more than $int_block_limit audit failures (event 4625) within $dat_time_window
$arr_new_bad_ips_security_log = @()
$arr_new_bad_ips_security_log = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $dat_time_window |
    Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]}} |
    Group-Object -property IpAddress |
    Where {$_.Count -ge $int_block_limit} |
    Select -property Name

# Get current time UTC to figure out filename for current FTP log
$current_date_utc = (Get-Date).ToUniversalTime()

# Set path to today's FTP log file
$str_log_file_name = "C:\inetpub\logs\LogFiles\FTPSVC2\u_ex" + $current_date_utc.ToString("yyMMdd") + ".log"

# Search today's FTP log file for "530 1326" to find lines that contain IPs of systems that failed to log in,
# get just the IP from each line, group the IPs by IP to count the attempts from each one, and select only the
# IPs that have $int_block_limit or more bad logins today
$arr_new_bad_ips_ftp = @()
$arr_new_bad_ips_ftp = Select-String $str_log_file_name -pattern "530 1326" |
    ForEach-Object {$_.Line.Substring(20,15) -replace " .*", ""} |
    Group |
    Where {$_.Count -ge $int_block_limit} |
    Select -property Name

# Concatenate the two arrays of IPs (one from Security log, one from FTP log)
$arr_new_bad_ips_all = @()
# $arr_new_bad_ips_all = @($arr_new_bad_ips_security_log) + @($arr_new_bad_ips_ftp_over_limit)
$arr_new_bad_ips_all = @($arr_new_bad_ips_security_log) + @($arr_new_bad_ips_ftp)

# Sort the array, selecting only unique IPs (in case one IP shows up in both the Security and FTP logs)
$arr_new_bad_ips_all_sorted = @()
$arr_new_bad_ips_all_sorted = $arr_new_bad_ips_all |
    Foreach-Object { [string]$_.Name } |
    Select-Object -unique

# Get firewall object
$firewall = New-Object -comobject hnetcfg.fwpolicy2

# Get all firewall rules matching "BlockAttackers*"
$arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}

# If no "BlockAttackers*" firewall rule exists yet, create one and set it to a variable
if ($arr_firewall_rules -eq $null) {
    $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
    netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created by BlockAttackers Powershell script written by Kevin Micke." enable=yes remoteip="0.0.0.0" | Out-Null
    $arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}
}

# Split the existing IPs from current "BlockAttackers*" firewall rule(s) into an array so we can easily search them
$arr_existing_bad_ips = @()
foreach ($rule in $arr_firewall_rules) {
    $arr_existing_bad_ips += $rule.RemoteAddresses -split(',')
}

# Clean subnet masks off of IPs that are currently blocked by the firewall rule(s)
$arr_existing_bad_ips_without_masks = @()
$arr_existing_bad_ips_without_masks = $arr_existing_bad_ips | ForEach-Object {$_ -replace "/.*", ""}

# Select IP addresses to add to the firewall, but only ones that...
$arr_new_bad_ips_for_firewall = @()
$arr_new_bad_ips_for_firewall = $arr_new_bad_ips_all_sorted | Where {
    # contain an IP address (i.e. aren't blank or a dash, which the Security log has for systems that failed FTP logins)
    $_.Length -gt 6 -and
    # aren't already in the firewall rule(s)
    !($arr_existing_bad_ips_without_masks -contains $_) -and
    # aren't the local loopback
    !($_.StartsWith('127.0.0.1')) -and
    # aren't part of the local subnet
    !($_.StartsWith('192.168.')) -and
    !($_.StartsWith('10.0.'))
}

# If there are IPs to block, do the following...
if ($arr_new_bad_ips_for_firewall -ne $null) {
    # Write date and time to script-specific log file
    [DateTime]::Now | Out-File -Append -Encoding utf8 C:\blockattackers.txt
    # Write newly-blocked IP addresses to log file
    $arr_new_bad_ips_for_firewall | Out-File -Append -Encoding utf8 C:\blockattackers.txt

    # Boolean to make sure the new IPs are only added on one rule
    $bln_added_to_rule = 0

    # Array to hold bad IPs from each rule one at a time, so we can count to make sure adding the new ones won't exceed 1000 IPs
    $arr_existing_bad_ips_current_rule = @()

    # For each "BlockAttackers*" rule in the firewall, do the following...
    foreach ($rule in $arr_firewall_rules) {
        if ($bln_added_to_rule -ne 1) {
            # Split the existing IPs from the current rule into an array so we can easily count them
            $arr_existing_bad_ips_current_rule = $rule.RemoteAddresses -split(',')

            # If the number of IPs to add is less than 1000 minus the current number of IPs in the rule, add them to this rule
            if ($arr_new_bad_ips_for_firewall.Count -le (1000 - $arr_existing_bad_ips_current_rule.Count)) {
                # Add new IPs to firewall rule
                $arr_new_bad_ips_for_firewall | %{$rule.RemoteAddresses += ',' + $_}

                # Write which rule the IPs were added to to log file
                echo "New IP addresses above added to Windows Firewall rule:" $rule.Name | Out-File -Append -Encoding utf8 C:\blockattackers.txt

                # Set boolean so any other rules are skipped when adding IPs
                $bln_added_to_rule = 1
            }
        }
    }

    # If there wasn't room in any other "BlockAttackers*" firewall rule, create a new one and add the IPs to it
    if ($bln_added_to_rule -ne 1) {
        $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
        netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created by BlockAttackers Powershell script written by Kevin Micke." enable=yes remoteip="0.0.0.0" | Out-Null
        $new_rule = $firewall.rules | Where {$_.Name -eq $str_new_rule_name}

        # Add new IPs to firewall rule
        $arr_new_bad_ips_for_firewall | %{$new_rule.RemoteAddresses += ',' + $_}

        # Write which rule the IPs were added to to log file
        echo "New IP addresses above added to newly created Windows Firewall rule:" $new_rule.Name | Out-File -Append -Encoding utf8 C:\blockattackers.txt
    }
}

Comment: FYI: For those that haven't run a powershell script on a system before, you'll need to first open a new powershell and run `Set-ExecutionPolicy RemoteSigned` so you can run local scripts. Otherwise you'll get an error: "blockattackers.ps1 cannot be loaded because the execution of scripts is disabled on this system."
Answer: I'm using ts_block freeby.
Basically it's a "VBScript program that acts as a WMI event sink to receive
events logged by Windows in response to invalid Terminal Services
logons."
Seems to work perfectly, and the script is straightforward if you need to mod it. You can either let it log attempts and then ban based on your number of allowed attempts, and/or you can hard-code login names you don't want to give access to.
I got caught out by accidentally adding the same name twice and the service just goes into an endless loop restarting every 1500ms, but very easy to fix/mod if you're ok with vbs.
My current settings are just one retry and you're banned for 2 days, with logins like 'admin' 'Admin' 'Administrator' 'guest' etc automatically banned. Should be straightforward to change to ip?
Kinda addictive to go in and see which critters have been banned overnight...
Answer: Do you mean logging on to the server/domain or logging on to a web site running on the server? If you mean logging on to the server/domain then the answer is no. Windows has no concept of blocking ip addresses based on failed logon attempts as ip addresses aren't security entities. There may be third party tools that can do this, but I'm not aware of any as I've never looked in to it.
Answer: If there is a webserver that is being attacked you can install the dynamic IP restrictions extension.  If this is for standard authentication to the server then you should be able to implement domain and server isolation which would limit the scope of the attacks to domain joined computers, and could be set to only allow attempts from the systems you need to have access to the server. In windows the prevention of brute force attacks is to set the account lockout policy to a setting like 10 mins and a bad password policy to 3 attempts - this means that the account being attacked would lock for 10 mins after 3 attempts.  IP connections are not lockable by default in windows. ( As an aside I am also curious as to how many logon attempts it is taking per second to impact the system)
Comment: On my AWS small instance, 1 attempt every 4 seconds is enough to consume 50% CPU. Pretty crap if you ask me...
Comment: Wow, I wonder why the utilization is so high.  I'll have to do some testing to see how many attempts it takes on my VMs to register.
Comment: I think it's because I'm not using Network Level Authentication, so every login attempt spins up a logon UI to actually present to the attacker through a remote desktop session. I can see why that might be expensive.
Answer: http://nerderies.blogspot.co.at/2012/12/automatically-banning-ips-with-windows.html

If what you want is an out of the box solution (Install & done) you can find a free tool here, and probably should go on reading this:
Current Version: 1.2 (.NET Framework 4.0 Client Profile)
  ->Download the current version of EvlWatcher (free for personal and commercial use)
New in 1.2 (more info in the documentation):

Management Console
WCF Service Pattern
Blacklisting
Auto-moving to the blacklist after 3 strikes (per default)

For older servers (.NET Framework 2.0)
->Download the reduced version of EvlWatcher (free for personal and commercial use)
Answer: The script of remuda, edited by kevinmicke (Feb 7 at 21:59) didn't check the FTP's control channel, which has an own folder on my system (Windows Server 2008 R2). Also 530 11001-events haven't been recognized, which seem to appear when the hacker only tries to access to the control channel. So I appended some lines in the script to check a second FTP-log-folder:
# This Windows Powershell script will automatically block IP addresses that attempt to login to the system
# and fail the number of times set below with the $int_block_limit variable or more. Is scans both the Security
# log, which covers Remote Desktop and other attempts, as well as the current day's FTP log. If the $int_block_limit
# limit is hit on either of those logs (separately, not combined), then the IP address will be added to the
# firewall rule.
#
# The script will automatically create a firewall rule named "BlockAttackers (Created yyyy-MM-dd HH:mm:ss UTC)" using
# the current time if one with a name that includes "BlockAttackers" doesn't already exist. Because there's a hard
# limit of 1000 entries (IP addresses) you can block per rule, it will also create similarly-named rules once that
# limit is reached for the latest one.
#
# I recommend setting the script to run as a scheduled task triggered by event 4625 login audit failures from the
# Security log, or alternatively you could set it to run after some amount of time (i.e. every 10 minutes).
#
# Authors:
# Majority of script written by serverfault.com user kevinmicke
# Windows Security Log portion written by serverfault.com user remunda, which provided the starting point for kevinmicke
# Checking of the FTP's control channel added by serverfault.com user Uwe Martens
#
# Details: https://serverfault.com/questions/233222/ban-ip-address-based-on-x-number-of-unsuccessful-login-attempts

# Set number of failed login attempts after which an IP address will be blocked
$int_block_limit = 3

# Time window during which to check the Security log, which is currently set to check only the last 24 hours
$dat_time_window = [DateTime]::Now.AddDays(-1)

# Select from the Security log all IP addresses that have more than $int_block_limit audit failures (event 4625) within $dat_time_window
$arr_new_bad_ips_security_log = @()
$arr_new_bad_ips_security_log = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $dat_time_window |
    Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]}} |
    Group-Object -property IpAddress |
    Where {$_.Count -ge $int_block_limit} |
    Select -property Name

# Get current time UTC to figure out filename for current FTP log
$current_date_utc = (Get-Date).ToUniversalTime()

# Set path to today's FTP Control Channel log file
$str_log_file_name_control_channel = "C:\inetpub\logs\LogFiles\FTPSVC\u_ex" + $current_date_utc.ToString("yyMMdd") + ".log"

# Search today's FTP Control Channel log file for "530 1" to find lines that contain IPs of systems that failed to log in,
# get just the IP from each line, group the IPs by IP to count the attempts from each one, and select only the
# IPs that have $int_block_limit or more bad logins today
$arr_new_bad_ips_ftp_control_channel = @()
$arr_new_bad_ips_ftp_control_channel = Select-String $str_log_file_name_control_channel -pattern "530 1" |
    ForEach-Object {$_.Line.Substring(20,15) -replace " .*", ""} |
    Group |
    Where {$_.Count -ge $int_block_limit} |
    Select -property Name

# Set path to today's FTP log file
$str_log_file_name = "C:\inetpub\logs\LogFiles\FTPSVC*\u_ex" + $current_date_utc.ToString("yyMMdd") + ".log"

# Search today's FTP log file for "530 1" to find lines that contain IPs of systems that failed to log in,
# get just the IP from each line, group the IPs by IP to count the attempts from each one, and select only the
# IPs that have $int_block_limit or more bad logins today
# In FTPSVC* has to be added the ID of the FTP-server instead of *, or just take the right log-folder
$arr_new_bad_ips_ftp = @()
$arr_new_bad_ips_ftp = Select-String $str_log_file_name -pattern "530 1" |
    ForEach-Object {$_.Line.Substring(20,15) -replace " .*", ""} |
    Group |
    Where {$_.Count -ge $int_block_limit} |
    Select -property Name

# Concatenate the two arrays of IPs (one from Security log, one from FTP log)
$arr_new_bad_ips_all = @()
# $arr_new_bad_ips_all = @($arr_new_bad_ips_security_log) + @($arr_new_bad_ips_ftp_over_limit)
$arr_new_bad_ips_all = @($arr_new_bad_ips_security_log) + @($arr_new_bad_ips_ftp_control_channel) + @($arr_new_bad_ips_ftp)

# Sort the array, selecting only unique IPs (in case one IP shows up in both the Security and FTP logs)
$arr_new_bad_ips_all_sorted = @()
$arr_new_bad_ips_all_sorted = $arr_new_bad_ips_all |
    Foreach-Object { [string]$_.Name } |
    Select-Object -unique

# Get firewall object
$firewall = New-Object -comobject hnetcfg.fwpolicy2

# Get all firewall rules matching "BlockAttackers*"
$arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}

# If no "BlockAttackers*" firewall rule exists yet, create one and set it to a variable
if ($arr_firewall_rules -eq $null) {
    $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
    netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created." enable=yes remoteip="0.0.0.0" | Out-Null
    $arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}
}

# Split the existing IPs from current "BlockAttackers*" firewall rule(s) into an array so we can easily search them
$arr_existing_bad_ips = @()
foreach ($rule in $arr_firewall_rules) {
    $arr_existing_bad_ips += $rule.RemoteAddresses -split(',')
}

# Clean subnet masks off of IPs that are currently blocked by the firewall rule(s)
$arr_existing_bad_ips_without_masks = @()
$arr_existing_bad_ips_without_masks = $arr_existing_bad_ips | ForEach-Object {$_ -replace "/.*", ""}

# Enter your server's IP (IPv4 and IPv6) in line 115 and 116.
# Select IP addresses to add to the firewall, but only ones that...
$arr_new_bad_ips_for_firewall = @()
$arr_new_bad_ips_for_firewall = $arr_new_bad_ips_all_sorted | Where {
    # contain an IP address (i.e. aren't blank or a dash, which the Security log has for systems that failed FTP logins)
    $_.Length -gt 6 -and
    # aren't already in the firewall rule(s)
    !($arr_existing_bad_ips_without_masks -contains $_) -and
    # aren't the local loopback
    !($_.StartsWith('127.0.0.1')) -and
    # aren't part of the local subnet
    !($_.StartsWith('192.168.')) -and
    !($_.StartsWith('0.0.')) -and
    !($_.StartsWith('10.0.')) -and
    !($_.StartsWith('*.*.*.*')) -and
    !($_.StartsWith('*:*:*:*:*:*'))
}

# If there are IPs to block, do the following...
if ($arr_new_bad_ips_for_firewall -ne $null) {
    # Write date and time to script-specific log file
    [DateTime]::Now | Out-File -Append -Encoding utf8 C:\inetpub\logs\LogFiles\blockattackers.txt
    # Write newly-blocked IP addresses to log file
    $arr_new_bad_ips_for_firewall | Out-File -Append -Encoding utf8 C:\inetpub\logs\LogFiles\blockattackers.txt

    # Boolean to make sure the new IPs are only added on one rule
    $bln_added_to_rule = 0

    # Array to hold bad IPs from each rule one at a time, so we can count to make sure adding the new ones won't exceed 1000 IPs
    $arr_existing_bad_ips_current_rule = @()

    # For each "BlockAttackers*" rule in the firewall, do the following...
    foreach ($rule in $arr_firewall_rules) {
        if ($bln_added_to_rule -ne 1) {
            # Split the existing IPs from the current rule into an array so we can easily count them
            $arr_existing_bad_ips_current_rule = $rule.RemoteAddresses -split(',')

            # If the number of IPs to add is less than 1000 minus the current number of IPs in the rule, add them to this rule
            if ($arr_new_bad_ips_for_firewall.Count -le (1000 - $arr_existing_bad_ips_current_rule.Count)) {
                # Add new IPs to firewall rule
                $arr_new_bad_ips_for_firewall | %{$rule.RemoteAddresses += ',' + $_}

                # Write which rule the IPs were added to to log file
                echo "New IP addresses above added to Windows Firewall rule:" $rule.Name | Out-File -Append -Encoding utf8 C:\inetpub\logs\LogFiles\blockattackers.txt

                # Set boolean so any other rules are skipped when adding IPs
                $bln_added_to_rule = 1
            }
        }
    }

    # If there wasn't room in any other "BlockAttackers*" firewall rule, create a new one and add the IPs to it
    if ($bln_added_to_rule -ne 1) {
        $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
        netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created." enable=yes remoteip="0.0.0.0" | Out-Null
        $new_rule = $firewall.rules | Where {$_.Name -eq $str_new_rule_name}

        # Add new IPs to firewall rule
        $arr_new_bad_ips_for_firewall | %{$new_rule.RemoteAddresses += ',' + $_}

        # Write which rule the IPs were added to to log file
        echo "New IP addresses above added to newly created Windows Firewall rule:" $new_rule.Name | Out-File -Append -Encoding utf8 C:\inetpub\logs\LogFiles\blockattackers.txt
    }
}

The name of the FTP's log-folder FTPSVC* on line 54 has to be completed of cause. In line 115 and 116 have to be entered your server's IP (IPv4 and IPv6), otherwise the own servers IP might be added to the firewall-rule a hundred times. The variable $int_block_limit I'm setting to 1 at my server, so the script is blocking a hackers attack causing a 4625-event within two seconds. I'm still thinking about to run the script additionally to occurring 4625-events in a time period of a few minutes. Of cause, it would also be possible, to separate the scripts and let one script check the 4625-events triggered by the 4625-event and another one the FTP's log-folders checking periodically every 5 or 10 minutes, even with separate firewall-rule and log-file.
Answer: I have added mine for SQL
# Select from the Application log (SQL) all IP addresss that have more than $int_block_limit logon failure within $dat_time_window
$arr_new_bad_ips_SQL_log = @()
$arr_new_bad_ips_SQL_log = Get-EventLog -LogName 'Application' -After $dat_time_window |
    Where-Object{$_.EventID -eq 18456} |
    Select-Object @{n='CLIENT';e={$_.ReplacementStrings[-1]}} |
    Group-Object -property CLIENT |
    Where {$_.Count -ge $int_block_limit} |
    Select -property Name |
    {
        $_.Name = $_.Name.Replace(" [CLIENT: ", "");
        $_.Name = $_.Name.Replace("]", "");
        return $_;
    }

Then you will have to add the array into ips_all
$arr_new_bad_ips_all = @($arr_new_bad_ips_SQL_log) + @($arr_new_bad_ips_security_log) + @($arr_new_bad_ips_ftp_control_channel) + @($arr_new_bad_ips_ftp)


how to make URL aliases of nodes created via form include node title of original page?

Question: Say I have a content type called "X", and every node of Content type "X" has a form that will create content type "Y"
How do I go about setting up the URL alias of content type "Y" so it will be something along the lines of "www.drupal.com/(Node title of X)/(Node title of Y).com
Thanks for any help!
Answer: try the Pathauto module:

The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

Once set up, you can have it assign the path based on the title of the current node (X) and the field value you assign to the title of node (Y).  If you are using nodetitle or something to automatically assign the title for node (Y), you will have to run some custom code when content type (Y) is created in order to assign its alias.


Can't make an element scroll while scrolling to this element overlay

Question: I'm using mcustomscrollbar plugin on a specific area, and I'm having an issue when I add an overlay to this element, I can't scroll the under element. I only can scroll on a blue area, I want to scroll another area as well. I tried to trigger mousewheel event, but no luck.
Any help very appreciated!
Here is the snippet with my issue:

(function($){
        jQuery(window).load(function(){
            jQuery(".list").mCustomScrollbar();
        });
    })(jQuery);

    jQuery('.list').mCustomScrollbar({
            theme:"dark-3"
     });

     $(".overlay").on("mousewheel", function(){
        jQuery(".list").trigger("mousewheel");
     })

.list{
    height: 100px;
    overflow-y: auto;
    overflow-x:  auto;

}
.overlay {
    position: fixed;
    opacity: 1;
    visibility: visible;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    background-color: rgba(255, 255, 255, .5);
    -webkit-transition: opacity .15s ease-out;
    -moz-transition: opacity .15s ease-out;
    transition: opacity .15s ease-out;
}

.inner-list {
    width: 30%;
    float:left;
    background: lightblue;
    position: relative;
    z-index: 9999;
    overflow: hidden;
}

.question {
      position: absolute;
    right: 120px;
    top: 40px;
}

.row{
    list-style-type: none;
    overflow: hidden;
    width: 200px;
    height: 20px;
}
.row:hover{
    background-color: #E0EBEE;
}

<link href="http://malihu.github.io/custom-scrollbar/3.0.0/jquery.mCustomScrollbar.min.css" rel="stylesheet"/>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Why can't scroll here?

Answer: You are not able to scroll because the div

 is on top of your
.
Changed width 96% from 100% from .overlay class.

(function($){
        jQuery(window).load(function(){
            jQuery(".list").mCustomScrollbar();
        });
    })(jQuery);

    jQuery('.list').mCustomScrollbar({
            theme:"dark-3"
     });

     $(".overlay").on("mousewheel", function(){
        jQuery(".list").trigger("mousewheel");
     })
.list{
    height: 100px;
    overflow-y: auto;
    overflow-x:  auto;

}
.overlay {
    position: fixed;
    opacity: 1;
    visibility: visible;
    top: 0;
    left: 0;
    width: 96%;
    height: 100%;
    z-index: 999;
    background-color: rgba(255, 255, 255, .5);
    -webkit-transition: opacity .15s ease-out;
    -moz-transition: opacity .15s ease-out;
    transition: opacity .15s ease-out;
}

.inner-list {
    width: 30%;
    float:left;
    background: lightblue;
    position: relative;
    z-index: 9999;
    overflow: hidden;
}

.question {
      position: absolute;
    right: 120px;
    top: 40px;
}

.row{
    list-style-type: none;
    overflow: hidden;
    width: 200px;
    height: 20px;
}
.row:hover{
    background-color: #E0EBEE;
}

<link href="http://malihu.github.io/custom-scrollbar/3.0.0/jquery.mCustomScrollbar.min.css" rel="stylesheet"/>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Why can't scroll here?

Comment: Thnx for the reply, but this only works while you are over the scroll, not the   overlay area! :(
Comment: @TeutaKoraqi Ok understood your problem, may I know why you need overlay div?
Comment: This overlay will be on when clicking an icon, and there is a part of content that will be visible, like this blue area. In this blue area there are cases that   will be to long content, and there scroll appears, and I should be able to scroll the content inner while mousewheel over the overlay too, not just in the visible content. I'm a clear?
Comment: OK Somewhat I understood, but what is the real purpose of this blue overlay?. I mean blue area is to prevent editing or something ????
Comment: I will vote your answer, cus you tried to help me. Thank you again! :)
Comment: @TeutaKoraqi Thanks :D, But just tell me what exactly this Overlay did do?
Answer: the problem is with .overlay, it is above the content so user action is disabled. you can simple use pointer-events: none for it. it doesn't work for IE11 so you can use display: inline-block as well to make it work for IE11.
.overlay {
  pointer-events: none;
  display: inline-block
}

Comment: that's my pleasure :)
Comment: Thnx for the reply, but I cannot use this, cus under the overlay I have some dropdowns that should not be clicked, and if I turned off all the events of the overlay, I would be able to click those elements.
Comment: which dropdown are you talking about? in that case you can still use `pointer-events: none` for that dropdown as well
Comment: In my project, cus here I only described the issue I have. But, its not a bad idea what you already suggested me. Let me try!
Answer: Because you checked if user scolled within div, not body.

(function($) {
  jQuery(window).load(function() {
    jQuery(".list").mCustomScrollbar();
  });
})(jQuery);

jQuery('.list').mCustomScrollbar({
  theme: "dark-3"
});

$("body").on("mousewheel", function() {
  jQuery(".list").trigger("mousewheel");
})
.list {
  height: 100px;
  overflow-y: auto;
  overflow-x: auto;
}

.overlay {
  position: fixed;
  opacity: 1;
  visibility: visible;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  background-color: rgba(255, 255, 255, .5);
  -webkit-transition: opacity .15s ease-out;
  -moz-transition: opacity .15s ease-out;
  transition: opacity .15s ease-out;
}

.inner-list {
  width: 30%;
  float: left;
  background: lightblue;
  position: relative;
  z-index: 9999;
  overflow: hidden;
}

.question {
  position: absolute;
  right: 120px;
  top: 40px;
}

.row {
  list-style-type: none;
  overflow: hidden;
  width: 200px;
  height: 20px;
}

.row:hover {
  background-color: #E0EBEE;
}

    <link href="http://malihu.github.io/custom-scrollbar/3.0.0/jquery.mCustomScrollbar.min.css" rel="stylesheet" />

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Why can't scroll here?


PHP usort Understanding

Question: function cmp_function($a, $b)

{

if ($a == $b) return 0;
  return ($a > $b) ? -1 : 1;

}

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" );

usort($fruits, "cmp_function");

Question: What values will be passed for $a and $b parameters for cmp_fucntion()?
Comment: "If everything else fails, read the f* manual".
Comment: @MarcinOrlowski To be fair, that isn't explained in the manual.
Comment: You could always write a little bit of test code and find out for yourself :) http://3v4l.org/YoG81
Comment: @khanz This [comment in the manual](http://php.net/manual/en/function.usort.php#108116) may help.
Answer: $a will be first element of two compared at this point, while $b will be second compared element at this point of sorting algorithm.
E.g.:
 iteration |     $a   |    $b
 -------------------------------
      1      "lemon"  |   "orange"
      2      "orange" |   "banana"
      3      "banana" |   "lemon"
           ...

PHP usort Understanding


How AWS does GPU virtualization?

Question: What kind of technology is Amazon using for GPU virtualization ? Can multiple VMs on an AWS GPU instance concurrently share GPU and have acceleration for their CUDA/ openCL programs ? I know following are the methods possible for GPU Virtualization:
1) API remoting: VMs emulate the GPU and the GPU on the host is called in RPC fashion from the VMs. This could be shared-memory based or network based remoting.
2) Actual GPU virtualization where multiple VMs can concurrently share a GPU. But as far as I know, Xen (used by AWS) does not supports this.
I have to do a project where I need to share an organization's GPUs in an internal, private cloud. I need to know through what technology, GPGPU in Cloud is commercially provided by AWS ? I have searched thoroughly, and my conclusion is that no open source software is mature enough to do this commercially.
Please Help!
Comment: Amazon do not publicise there Server setup. If you have an requriment you would need to speak to there sales team who may be able to help.
Comment: The way they do it is (most likely) a trade secret shared between amazon and their vendor, and you're not going to be doing it their way.  However, there are ways of doing this in (for instance) ESXi 5.1, for certain use cases.
Answer: NVidia's Tesla GPUs allow a degree of virtualisation, they have an API that you could look into but I'm far from an expert - they don't support this on any other of their cards though.
Comment: K20xs only I seem to recall. And even then, it's SR-IOV isn't it?

How AWS does GPU virtualization?


Linguagem Java - Funções Undo e Redo

Question: Estou a fazer um projeto em que desenvolvo funções para aplicar efeitos a fotos (como o Contrast, Vignette, Sepia...).
A medida que aplico efeitos às fotos, os vários estados das fotos vão sendo guardados num vetor de imagens.
Nesse mesmo projeto, necessito de duas funções, a Undo e a Redo. A Undo servirá para obter a foto com o efeito anteriormente aplicado e a Redo servirá para obter de novo o ultimo efeito aplicado.
Alguém me consegue ajudar no desenvolvimento destas funções (Undo e Redo)?
Obrigado.
Aqui está o que tenho na classe:
class Historico {

    private ColorImage [] VCI;
    private int atual;
    boolean undo = false;
    private int undos;
    private int redos;

    public Historico(ColorImage [] VCI) {
        this.VCI = VCI;
        atual = 0;
        undos = 0;
        redos = 0;
    }

    static ColorImage copy (ColorImage CI) {
        ColorImage NCI = new ColorImage(CI.getWidth(),CI.getHeight());
        for(int x = 0; x < CI.getWidth(); x++){
            for(int y = 0; y < CI.getHeight(); y++){
                Color c = CI.getColor(x,y);
                NCI.setColor(x,y,c);
                }
            }
        return NCI;
        }

    void saveImage(ColorImage CI) {
        VCI [atual] = copy(CI);
        atual++;
        undo = false;
        undos = 0;
        redos=0;
    }

    public void undo() {
        ColorImage CI = copy(VCI[atual-2-undos]);
        VCI[atual] = CI;
        atual = atual + 1;
        undo = true;
        undos = undos + 2;
    }

    public void redo() {
        if(undo = true) {
            ColorImage CI = copy(VCI[atual-2-redos]);
            VCI[atual] = CI;
            atual = atual + 1;
            undos--;
            if(undos<0){
                undos = 0;
                undo = false;
            }
            redos = redos + 2;
        }
    }
}

Comment: Já ouviu falar do padrão de projeto [**memento**](https://en.wikipedia.org/wiki/Memento_pattern)?
Comment: Olá Victor Stafusa. Não ouvi falar. Já consegui fazer a função Undo. A minha função Redo consigo aplicá-la 2 vezes mas à terceira deixa de funcionar (não acontece mesmo nada), consegue me ajudar? Se necessário eu copio o código que já tenho das 2 funções. Obrigado
Comment: Sim, é recomendável você postar o seu código: https://pt.meta.stackoverflow.com/a/5484/132
Comment: Ok, peço desculpa. Acabei de editar a pergunta e já lá está o código que tenho na classe. O que está a funcionar mal é a função Redo (consigo utilizá-la 2 vezes mas à terceira deixa de funcionar (passa a não acontecer nada))
Answer: Você pode usar duas listas como se fossem pilhas, uma para o "undo" e uma para o "redo". Além disso, ao usar listas ao invés de arrays, as coisas vão ficar muito mais simples de se trabalhar.
import java.util.List;
import java.util.ArrayList;

public class Historico {

    private final List<ColorImage> undos;
    private final List<ColorImage> redos;
    private ColorImage atual;

    public Historico() {
        this.undos = new ArrayList<>();
        this.redos = new ArrayList<>();
        this.atual = emBranco();
    }

    private static ColorImage emBranco() {
        return new ColorImage(256, 256);
    }

    private static ColorImage copy(ColorImage ci) {
        ColorImage nci = new ColorImage(ci.getWidth(), ci.getHeight());
        for (int x = 0; x < ci.getWidth(); x++){
            for (int y = 0; y < ci.getHeight(); y++) {
                Color c = ci.getColor(x, y);
                nci.setColor(x, y, c);
            }
        }
        return nci;
    }

    public void saveImage(ColorImage ci) {
        undos.add(atual);
        redos.clear();
        atual = ci;
    }

    public ColorImage undo() {
        if (!undos.isEmpty()) {
            redos.add(atual);
            atual = undos.remove(undos.size() - 1);
        }
        return atual;
    }

    public ColorImage redo() {
        if (!redos.isEmpty()) {
            undos.add(atual);
            atual = redos.remove(redos.size() - 1);
        }
        return atual;
    }

    public ColorImage getAtual() {
        return atual;
    }
}

Comment: Olá Victor Stafusa! Ajudou imenso! Muito obrigado. Os meus cumprimentos.
Answer: Você informou que os estados das fotos a cada modificação são guardados em um vetor de imagens, correto? Acredito que seu trabalho seria simplificado se, ao invés de utilizar um vetor, você utilizasse uma lista duplamente encadeada (LinkedList). Como ela possui referências tanto para o estado anterior quanto ao posterior da sua imagem, a implementação de suas funções Redo e Undo poderiam ser simplificadas somente à movimentação do ponteiro que indica a posição atual na sua lista através dos métodos Previous e Next de um ListIterator.
Comment: Olá Marcos Andrade. Desde já obrigado pela sua colaboração. Acontece que ainda não aprendi a utilizar a tal lista duplamente encadeada, mas acredito que seria uma boa solução.
Comment: Entendo. Você tem conhecimento da lógica de funcionamento de uma lista encadeada? Se sim, não é muito difícil montar manualmente uma lista duplamente encadeada, que funciona de forma bem simples e resolveria o seu problema. Posso te ajudar com isso se tiver interesse. Se você está na faculdade, é até interessante porque isso costuma cair bastante em estruturas de dados.
Comment: Marcos, mediante o código que meti (editei a pergunta) ainda acha que seria mais simples ?
Comment: Acredito que sim. Sinceramente, a maior vantagem que você poderia tirar dessa solução seria melhoria semântica no seu código. Ele possui variáveis de "controle de versão" (undos e redos) que são desnecessárias se você utilizar uma estrutura de dados mais adequada, e isso pode causar grandes dificuldades caso você queira expandir o codigo mais à frente adicionando mais funcionalidades ou utilizando como parte de outro projeto. Se você nao planeja expandir o código mais à frente, é OK manter ele desse modo, mas eu chego a considerar isso uma certa gambiarra... haha
Comment: Obrigado pela atencao Marcos. Nao tenciono expandir mais codigo, aliás Marcos esta classe é mesmo o final do meu projeto. O que me pedem é isto, até porque comecei à pouco tempo. Sendo assim, com o código que eu escrevi, o que me avonselhas a modificar para a função Redo dar certo Marcos?

Linguagem Java - Funções Undo e Redo


WinServer 2003: Cant find process holding onto ports

Question: We have a couple of production WCF services failing to start because their ports are apparently in use by another process. I have done a netstat -ano and found the PID's that are using these ports, which are all in the LISTEN state. The ports for endpoints/services hosted in the same processes all have the same PID's, so that checks out.
The problem is, I can't see any of these PIDs in Task Manager. When trying the -b option netstat reports that the process is [System]. It reports the correct process name for the services that are working, but not for these ports.
I suspect that old instances of our services may be hanging around...and a server reboot may fix that, but I would prefer to know what is going on before taking action. Unfortunatly I am not allowed to install Process Explorer in prodction environments.
What other options do I have to find out the names of the processes with these PIDs? Sorry about what may be a noob question but I am not a sys admin :)
Thanks
Michael
Answer: You can use SysInternals' TCPView; it doesn't require any installation, you can simply run it without having to install anything (which is also true for Process Explorer, BTW).
TCPView is also able to forcibly close connections and listening sockets.
Comment: I might look down this path, thanks. I know Process Explorer doesn't technically require installation, but the people managing these servers above country (who also can't help on this issue as its our application...) will have a fit if I put something on there that is not on their checklist without going through paperwork to have it done. Probably will have a 2 week turnaround on that, and they will screw it up. If I can convince the right people though... :)
Answer: One method which may provide some additional "hints" is to telnet against those port(s) to see if the running process(es) "gives themselves" up via some connection banner.


adding a list to a dictionary in python 2.7

Question: How do I add a list to a dictionary?
i have a dictionary:
>>> data = {}
>>> myfile='file.txt'
>>> data.update({myfile:['parama','y']})
>>> data
{'file.txt': ['parama', 'y']}

I would like to add to the key 'file.txt' another touple, such that the result would be
{'file.txt': (['parama', 'y'],['paramb','abc'])}

I tried to update this specific key like this:
data['file.txt'].update(['paramb','abc'])

but got an error:
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    data['file.txt'].update(['paramb', 'y'])
AttributeError: 'list' object has no attribute 'update'
>>>

How do I add a list to a dictionary?
Comment: that's not a tuple you're trying to add, it's a list...
Comment: First, `update` is a method on dicts, not on lists, and `data['file.txt']` is a list.
Comment: If you need to mutate things, then you shouldn't be using tuples as they are immutable. If you keep it as a list, as the value is now, is `append` so bad? You end up with a list of lists.
Comment: Second, there's no method that can convert a single list into a tuple of two lists. You can do _replace_ a list with a tuple of two lists, something like `data['file.txt'] = (data['file.txt'], ['paramb','abc'])`, but it's hard to imagine a case where that line would be the best way to write anything… If you can explain what you're actually trying to do here, it might help.
Comment: im reading files into 1 dictionary: http://stackoverflow.com/questions/26918211/read-files-into-a-dictionary-in-python  and i want the result to be file1, parama, 'some text', then next line file2, parama, "other text" etc
Comment: @nerdwaller: Yeah, I *think* what he actually wants to do is start with a list of one list, and then `append` the second list to that. But… it's hard to be sure.
Comment: @nerdwaller i think you are exactly right!! that is what i need
Comment: OK, from that other question, it looks like you either want a dict of dicts, or a dict with 2-tuples as keys, not a dict of either tuples or lists of lists.
Comment: i think i got it? http://screencast.com/t/QCYgARqi
Comment: can this still be considered a dictionary though? {'file.txt': ['parama', 'y', ['paramb', 'y']]}
Comment: @abarnert - good call, it's definitely odd. Seems like the right approach is to start with the correct structure and build it out instead of changing the structure. Changing it will make some pretty annoying code to read.
Comment: Well, that's a dictionary whose values are lists, but that doesn't seem particularly useful.
Comment: @nerdwaller i agree, but the structure is dynamic, it will change over time
Comment: @abarnert would you pick a different datatype for such a problem?
Comment: It might help to write the code you'd like to use to _access_ these values after you've built the data structure. Do you want to be able to write `d['file.txt']['parama']` and get `'y'`? Or `d['file.txt', 'parama']`?
Comment: @abarnert EXCELLENT question. thank you for asking it. i would like to be able to get ALL 3 values, the key, and each element inside of the list (values)
Answer: I think what you're after here is a dictionary whose keys are filenames, and whose values are themselves dictionaries whose keys are parameter names. Like this:
d = {
    'filename1': {
        'parama': 'A',
        'paramb': '22' },
    'filename2': {
        'parama': 'Z'}
}

This would allow you to access values like this:
>>> d['filename1']['parama']
'A'

And if you want to get all the parameters for filename1:
>>> d['filename1']
{'parama': 'A', 'paramb': '22'}
>>> for k, v in d['filename1'].items():
...     print('{}: {}'.format(k, v))
parama: A
paramb: 22

If so, you're going wrote before you've gotten to the point you're asking about. Instead of this:
data.update({myfile:['parama','y']})

… you want:
data[myfile]['parama'] = 'y'

However, there's one slight problem here. If this is the first time you've seen a parameter for myfile, there is no data[myfile] yet. To solve that, you can use the setdefault method:
data.setdefault(myfile, {})['parama'] = 'y'

Or you can make data a collections.defaultdict(dict) instead of a plain dict.


What CI should I use when finding Margin of Error?

Question: I've begun an assignment where I collect my own data. The assignment is now asking me to find margin of error with the collected data. I have nearly everything I need for the equation with the exception of the Confidence Interval.
Do you think it would matter what I choose? whether it be 90% CI for population mean or 95% etc.
Sorry about this question being a little dumb.
Answer: It depends how accurate you want your results to be. An $x$% C.I. for the population mean is such that if you repeat the experiment / data collection $100$ times, the mean should lie within the C.I. $90$ times. So for any given experiment / set of data, there's a $90$% chance the population mean lies within the C.I.


What are the techniques for improvising in the minimalist style?

Question: I've been listening to a lot of Steve Reich lately and I'd like to bring classical minimal music into my improvisational group.   I am familiar with jazz, rock and classical improvisation techniques.
From my understanding minimal music is composed ahead of time (except for folks like Terry Riley performing solo on keyboards).
What techniques could be used to created improvised minimalist music in a group setting? I can see how the polyrhythms could be done but how to coordinate and compose in the moment miminal music techniques such as slow modulation of one or more parameters as well as phase and pattern music, including repetition?
Answer: Completely improvising a minimalist piece isn't going to really capture the idea of minimalism as one of the key features of minimalism is stretching what you have to extremes. That being said, there are things you can do in a group setting to play with minimalistic ideas. Taking from Steve Reich, there are two very simple ways you can play with these ideas:

Based on Steve Reich's piano phases, you can one person at a time improvise a single melody/motif and have others play it then have some speed up and others slow down and by doing this you'll create very complex harmonies. The downside is this isn't the kind of thing that is easy to do on the fly, but after a few sessions it will become easier to do.

You can apply Steve Reich's clapping music to harmony in a similar manor as the piano phases as well. You can take a melodic motif and shift it by one beat after a certain amount of measures. So one person comes up with the motif and the others start with the same pattern then shift the pattern by one note and you can even stagger it or even have people play the pattern retrograde or inverted (or retrograde inverted). This is the one I'd recommend as the harmonies you'll create will be a lot different and a little more tangible. I've created pieces based on this that I've greatly enjoyed and I'll link it below.
Answer: Spiegelian improvisation has to be mentioned.  That is, using keyboards, sequencers and loopers, you can insert riffs as desired and have each member control the various ways to manipulate.  You can see in this acid session where they insert their loops on the fly, tapping them in.  And then they grab the knobs.

Edit: Laurie Spiegel is a composer who in the 1970s proposed leaving the tonal and rhythmic composition of the tune to computers and leaving other controls to the whim of the performer.  This method of composition and performance has been heavily uptaken by techno artists who do dabble in the original form as Laurie Spiegel performed it on occasion (see: Anthony Rother, Umek.)
Comment: A google search doesn't tun up anything for "Spiegelian improvisation".  Please elucidate.


Manually get response from class-based generic view

Question: I'm trying to write a test that validates HTML returned from a generic class-based view. Let's say I have this function-based view that simply renders a template:
# views.py
from django.shortcuts import render

def simple_view(request, template='template.html'):
    return render(request, template)

With that, during testing I can just do:
# tests.py
from django.http import HttpRequest
from .views import simple_view

request = HttpRequest()
response = simple_view(request)

and then do the validation on the response. Now I would like to convert the above to a class-based view inheriting from TemplateView:
# views.py
from django.views.generic import TemplateView

class SimpleView(TemplateView):
    template_name = 'template.html'

Now essentially the same testing method fails:
# tests.py
from django.http import HttpRequest
from .views import SimpleView

request = HttpRequest()
view_func = SimpleView.as_view()
response = view_func(request).render()

results in
Traceback (most recent call last):
    File "tests.py", line 30, in test_home_page_returns_correct_html
response = view_func(request).render()
    File "lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
    File "lib/python2.7/site-packages/django/views/generic/base.py", line 82, in dispatch
if request.method.lower() in self.http_method_names:
AttributeError: 'NoneType' object has no attribute 'lower'

I've tried setting request.method manually to GET, but that just brings up another error complaining about session not being in request.
Is there a way of getting a response from TemplateView with "empty" request?
Comment: http://stackoverflow.com/questions/8603035/how-tdd-can-be-applied-to-django-class-based-generic-views
Answer: Thanks dm03513 for the pointers! Indeed I had to use RequestFactory, but also make sure that request contains an empty session (despite SessionMiddleware being listed first):
# tests.py
from django.test import TestCase
from django.test.client import RequestFactory

class SimpleTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_home_page_returns_correct_html(self):
        request = self.factory.get('/')
        request.session = {}
        view_func = SimpleView.as_view()
        response = view_func(request)
        response.render()
        self.assertIn('', response.content)

Comment: request.session = {} failed in my testing. I set the session on the request as follows and it worked (import the modules first as needed of course): request.session = django.utils.importlib.import_module(django.conf.settings.SESSION_ENGINE).SessionStore(None) [I combined your answer with the answer in this question.](http://stackoverflow.com/questions/16865947/django-httprequest-object-has-no-attribute-session)
Answer: You could use djangos built in test client to accomplish this, instead of instantiating and calling view directly
test client allows you to make a request through django url router
response = self.get('/url/to/invoke/simpleview/')
additionally there are a couple blogposts I found touching on how to test class based views, one of which is http://tech.novapost.fr/django-unit-test-your-views-en.html
Comment: True, though as pointed out here: http://stackoverflow.com/questions/8603035/how-tdd-can-be-applied-to-django-class-based-generic-views that's more functional than unit test (you're simulating a browser as opposed to just playing with functions). I guess in this case doesn't really matter, but it's good to know both are possible!
Comment: On a second thought, using a client in this case is probably saner, if not the only, way!


How to access a method from another class outside the creator of the instance

Question: I created 3 java files:main.java, GUI.java, Serial.java
In Main I created instances of two last java files.
I can call methods from gui and serial from within Main.
I cannot call methods from the instances gui and serial outside Main.
package main;
 public class Main {

        public static void main(String[] args) {
            GUI gui = new GUI();
            gui.setVisible(true);

            Serial serial = new Serial();
            serial.getPorts();
            fillList();
        }

        public void fillList () {
            gui.setList("hoi");
        }
    }

Why is this? How can I call methods from gui from method fillList?
Thanks for any insights.
Comment: `gui` and `serial` are local variables, so they don't exist outside of the `main()` method.
Comment: I understand the why, thanks! Now the 'how' :-)
Comment: Use a class variable if you want it to live outside the method.
Answer: The instances only exist within the method they're declared, in this case the constructor. A common way of getting around this is to declare a field in your class, and assign the value of that field in the constructor (or other method). Try:
package main;
public class Main {
    // private GUI gui; // replaced this line with the below. See comment 5
    private static GUI gui; // this is the new field declaration

    public static void main(String[] args) {
        gui = new GUI(); // note I removed the class declaration here since it was declared above.
        gui.setVisible(true);

        Serial serial = new Serial();
        serial.getPorts();
        fillList();
    }

    public void fillList () {
        gui.setList("hoi"); // now this method has access to the gui field
    }
}

Comment: Good suggestion! So this 'field' gives me access to the variable in a class. Let's say I'd like to do a gui.JComboBox.addItem(text); I simply declare a field in my routine and have access to this object? Am I correct?
Comment: Yes, the field gives access to the variable to all methods in the class. Without knowing the internals of your `GUI` class, it looks as if `JComboBox` is a field on `GUI`, so as long as that field is declared to be `public`, the `gui` instance created in the `Main` constructor will have access to the `gui.JComboBox` field. Then, the `JComboBox` field in the `GUI` class appears to have a method called `addItem` (I can tell it's a method because you're calling it with parens). Again, if the `addItem` method is `public`, then the `JComboBox` and in turn the `gui` should have access to the method.
Comment: In other words, according to how the privacy settings are declared, the local `gui` field should have access to `JComboBox` (and in turn all its fields and methods) the same way it has access to `setList` on line 15. This is true for all `public` fields and methods declared in the `GUI` class.
Comment: I've tried your method (copy/pasted) but Netbeans shows an error at the lines 'gui = new GUI();' and the next. The error says "non static variable cannot be referenced from a static context". The GUI constructor is public, the init method is private. Is that the reason it shows the error?
Comment: Ah, I missed that your `main` method was `static`. The error is saying that the `gui` field is nonstatic, but we're trying to reference it from the `static` `main` method. I'll update my answer.
Comment: thanks! I think I'm getting the grasps of it! Now looking for a way to connect to this gui instance from other classes as well. Goal is to create a model-view-controller model. Not sure quite how to do that, but I think it has something to do with Inheritance. Looking into it rightnow. (thought proces: make Main a superclass, by extending GUI and Serial)...


adding custom view name in asp.net mvc4

Question: I am building an application in .net mvc4 that is based on business promotion and sales store.
User on this web application would be able to use product and access his/her personal business page also, that page can be promoted in future.
So I added one controller- Mypanel and a view of user's personal or professional business page _Mypanel.
Now the url access to this page is Bizcopter.com/Mypanel/_Mypanel
I want a custom user defined page name-
i.e. If a business name is - BookStore
Then I want to add a view in this same controller with the name of BookStore, So URL of personal business page would be-
Bizcopter.com/Mypanel/BookStore/ and this business holder can promote his business page with this URL.
Let me know if these are possible-

Replacing the view's name of user's choice
Add a view from client side in this same controller

I don't have any idea how to make it happen so don't have any trying code.
Site URL- http://bizcopter.com/Mypanel/_Mypanel
Comment: You will need to define a custom route to handle this URL template which will pass "BookStore" as a parameter to a controller function which will then redirect the user to the relevant page.
Comment: This SO question might give you some tips: http://stackoverflow.com/questions/9706183/mvc-url-routing-for-custom-url
Answer: You don't need a separate view and controller action for each business.
I would create a controller and view called MyPanel. The controller takes a parameter called something like businessName that will load data related to the parameter.
Comment: @Manoz you can customize the route the way you want it. Take a look at this -> http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs
Comment: That would still be this URL - `bizcopter.com/Mypanel/Mypanel/` not exactly the view's name with business name. Nobody would show interest in promoting my defined URL. I don't have any problem in loading data btw :)
Comment: @Manoz, no it wouldn't. The URL would be bizcopter.com/Mypanel/[buinsessName]. Although with routing you are not constrained to any format - it's very flexible.
Comment: yes man! I could access page without any controller and action name also. Great
Answer: By default you'll have a route in your AppStart/RouteConfig.cs which may look like this:
routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

The default URL structure might look something similar to: http://localhost:{PortNumber}/{Controller}/{Action}
Where we can attribute the following:
Controller = Home

Action = Index

Now if you want something similar to how you have it, you'd want something along the lines of:
http://testing.com/Fruits/Apples

Controller = Fruits

Action = Apples

By default, a URL pattern will match any URL that has the correct number of segments, in this case {controller}/{action}
Overall you should just need the MyPanel controller, and a controller taking a parameter of string which loads the correct Object/Model into the view.
Source: Pro ASP.NET MVC 4 - Adam Freeman
Answer: As the others said you can add a new route.Consider this code:
routes.MapRoute(
            name: "MyCustomRoute",
            url: "MyPanel/{name}"
            defaults: new  { controller = "MyPanel", action = "MyAction", name="" }
        );

In this route if user type this URL:
Bizcopter.com/Mypanel/

Then it goes to your MyAction in your MyPanel Controller by default.Actually it will always go to MyAction, and in your MyAction, you must take the name parameter and redirect to user to the Relevant Action like this:
public ActionResult MyAction()
{
    var name = RouteDate.Values["name"];

    // check the name and redirect user to another action if it necessary

    if(name == "BookStore") return RedirectToAction("BookStore","Mypanel");
}

adding custom view name in asp.net mvc4


Why does PIL (pillow) Image.save() reduce file size?

Question: I am using PIL to rotate some images, and I noticed that the output file is much smaller, so I tried a test:  Do nothing to the file, except save the exif info (because I know that PIL Image will by default not save the exif info).  So here is my test code:
    from PIL import Image
    test = Image.open('my_image_file.jpg')
    holdexif = test.info["exif"]
    test.save('my_saved_image_file.jpg',"jpeg",exif=holdexif)

When I do the above my_saved_image_file.jpg is significantly smaller (441 KB) than the original my_image_file (1.83 MB).  Why is that?  What is missing?
When I look at various properties of both files, they appear to be identical.  Both are 56 inches x 27 inches, both are 72 Pixels per inch, both are 4032 x 1960 pixels.  I am by no means an expert when it comes to image files.  Based on these things that I have examined (size, resolution, and the appearance of the images) the files appear to me to be the same.  From what I can see/understand, only the file size on disk is different.  What else should I be looking at?  What else may be different?
I also tried the quality= kwarg in the save:
    test.save('my_saved_image_file.jpg',"jpeg",exif=holdexif,quality=95)

which gave me a file (1.73 MB) almost as large as the original (1.83 MB).  But I have no idea what is different to account for the larger size (and I don't understand what makes the "quality" better; the images appear the same to me).  I am trying to understand what exactly is different between the two files, so that I can make a decision.  Perhaps the smaller size is perfectly fine for my purposes.
Comment: The `PIL`s IMAGE is doing the compression.
you can check https://github.com/python-pillow/Pillow/blob/master/src/PIL/Image.py#L60 here
Comment: Thanks.  Is the compression causing any loss of actual quality?  It doesn't appear to me.  But as I mentioned, for quality I only know to look at the size, resolution, and appearance to my eye on the screen.  Is there anything lost in the compression?  If so, what.  Thanks.
Comment: https://www.diffchecker.com/image-diff Let's try checking here. In the `difference` tab,
Comment: I'm reading the code, trying to find how it decodes the image from file and putting it back as a file.
Comment: Thanks.  That diffchecker is nice, but it shows no differences (using quality=95%, will try some other levels).  I am also reading this to see if I can understand the effect of compression better: http://fotoforensics.com/tutorial-estq.php   Apparently there is some loss with the compression, it just may not be obvious to the eye.
Comment: https://medium.com/breaktheloop/jpeg-compression-algorithm-969af03773da this might be a helpful resource
Comment: @CharanjitSingh Thanks again.  Looks good.  I also just found this:  https://stackoverflow.com/questions/4354543/determining-jpg-quality-in-python-pil  It appears that I can save with `qualtiy='keep'` to get the exact same level of compression as the original file.
Comment: The difference is invisible to human eye, I tried using a random image from the internet.
Initially, it was `72.8 kb`, I opened and closed it from PIL, the size `decreased` to `42kb` then I set the quality=95, The Size `Increased` to `120kb`.
Answer: The answer, as Charanjit pointed out, is in the amount of compression (which is controlled with the quality kwarg of the .save() method).  More compression means a smaller file and less "quality".
Regarding "quality", this means that, although the image size and image resolution may be the same, the crispness of object edges, and color differentiation, within the image, will be reduced (possibly not apparent to the eye) by compression.
There is a good discussion of jpeg compression here: Understanding JPEG Quality.
There is also another stackoverflow answer that addresses the issue of trying to save jpeg file with the same quality as the original: https://stackoverflow.com/a/4355281/1639359 by setting kwarg quality='keep' (instead of quality=N where N is an integer between 1 and 100 %).


Como chamar procedure utilizando Asp.net MVC com Entity Framework

Question: Em uma aplicação asp.net mvc, utilizando ADO.NET com entity framework e mysql, eu tenho uma procedure, que retorna uma listagem.
CREATE PROCEDURE SP_CATEGORIAS()
BEGIN
    select *
      from (select a.id,
                   @rownum:=@rownum+1 as rownum,
                   case when ifnull(a.categoria_id,0) = 0
                        then a.id
                        else a.categoria_id
                   end as grupo,
                   ifnull((select b.categoria_id
                             from categoria b, (select @rownum:=0) r
                            where b.id = a.categoria_id
                              and @rownum = 1), 0) || a.categoria_id || a.id as ordem,
                    a.nome
               from categoria a) as x
      order by grupo, rownum;
END

Como eu faço o call dessa procedure no meu código asp.net?
Answer: primeiro você ter um modelo que represente os dados retornados pela procedure:
public class Categoria
{
    [Column(Name = "id", Order = 1)]
    public int ID { get; set; }

    [Column(Name = "rownum", Order = 2)]
    public int RowNumber { get; set; }

    [Column(Name = "grupo", Order = 3)]
    public int Grupo { get; set; }

    [Column(Name = "ordem", Order = 4)]
    public int Ordem { get; set; }

    [Column(Name = "nome", Order = 5)]
    public string Nome { get; set; }
}

Então você pode vir chamar a sua procedure da seguinte forma:
using(var context = new DataBaseContext())
{
    var resultado = context.Database.SqlQuery<Categoria>("SP_CATEGORIAS").ToList();
}

Nota
Ainda bem que esta stored procedure é do MySQL, se fosse no SQL Server iria sugerir a remoção do prefixo sp_ da mesma.
Comment: sim, deve fazer assim.
Comment: o context, posso utilizar a declaração var context = new minhaEntities() ?


$V_0=\frac{\rho_0}{4\pi \epsilon_o}\iiint_0^{\infty}\frac{e^{-(x^2+2y^2+2z^2)}}{\sqrt{x^2+y^2+z^2}} dxdydz$

Question: Here is what i'm given:
"The so called Schwinger parametrization is based on identities like the following:
$$\frac{1}{\sqrt{R}}=\frac{2}{\sqrt{\pi}}\int_0^{\infty}e^{-Ru^2}du$$
The first octant of a three-dimensional coordinate system is filled with continuously distributed charge of density $\rho(x,y,z)=\rho_0 e^{-(x^2+2y^2+2z^2)}$. Use the above relation to evaluate the electrostatic potential in the origin, which is given by the integral:
$$V_0=\frac{\rho_0}{4\pi \epsilon_o}\iiint_0^{\infty}\frac{e^{-(x^2+2y^2+2z^2)}}{\sqrt{x^2+y^2+z^2}} dxdydz$$
Hint: The Schwinger parametrization converts the triple integral into a quadrupple integral. Three of the four integrals are Gaussian and thus can be easily evaluated. Use a computer algebra system to evaluate the last one-dimensional integral that you obtain."
This is what i've tried (but i am probably completely off base):
This problem looks like an obvious candidate for spherical coordinates so using the the identities $x=r\sin\phi\cos\theta$, $y=r\sin\phi\sin\theta$, $z=r\cos\phi$ i have tried to simplify the terms in the exponent as such:
$$Exp[-(x^2+2y^2+2z^2)]=Exp[-r^2(\sin^2\phi\cos^2\theta + 2\sin^2\phi\sin^2\theta + 2\cos^2\phi)]=Exp[-r^2(\frac{1-\cos2\phi}{2}\frac{1+\cos 2\theta}{2})+(1-\cos 2\phi)(1-\cos 2\theta)+(1+\cos 2\phi))]=Exp[-\frac{r^2}{4}(9-3\cos 2\theta -\cos 2\phi -3\cos 2\phi\cos 2\theta)]$$
Then using $r=\sqrt{x^2+y^2+z^2}$ and $dxdydz=r^2\sin\phi drd\phi d\theta$ i have rewritten the problem as:
$$V_0=\frac{\rho_0}{4\pi \epsilon_o}\int_0^{\infty}\int_0^{\frac{\pi}{2}}\int_0^{\frac{\pi}{2}}e^{-\frac{9r^2}{4}} e^{-\frac{3r^2}{4}\cos 2\theta} e^{-\frac{r^2}{4}\cos 2\phi} e^{-\frac{3r^2}{4}\cos 2\phi\cos 2\theta}r\sin\phi d\theta d\phi dr$$
Now this just doesn't seem right. I still have multiple variables in most of the  exponents and i don't see how i could separate them. The problem may be that i haven't done any multivariable calculus in over a year but i think i a missing something pretty obvious. Any help would be much appreciated.
Answer: You're completely correct in noticing that spherical coordinates can simplify the equation. The only catch is the method of embedding such a sphere space. Here's what I mean.
Originally, we are given the space:
$$B=\left\{\begin{matrix}x=x,x=[0,\infty] \\ y=y, y=[0,\infty] \\ z=z, z=[0,\infty]\end{matrix}\right.$$
One noticible thing about the parametrization of the sphere you've given:
$$\Omega_1=\left\{\begin{matrix}x=r\sin\phi\cos\theta \\ y=r\sin\phi\sin\theta \\ z=r\cos\phi\end{matrix},\phantom{..}\begin{matrix}r=[0,\infty] \\ \theta=[0..1/2\pi] \\ \phi=[0..1/2\pi]\end{matrix}\right.$$
Is that you'll find that:
$$x^2+y^2=r^2\sin^2\phi\phantom{..}\&\phantom{..}x^2+y^2+z^2=r^2$$
By expanding the integral, we find that:
$$V_0=\frac{\rho_0}{4\pi\epsilon_0}\int_B\frac{\text{e}^{-(x^2+2y^2+2z^2)}}{\sqrt{x^2+y^2+z^2}}dB=\frac{\rho_0}{4\pi\epsilon_0}\int_B\frac{\text{e}^{-(x^2+y^2+z^2)}\text{e}^{-(y^2+z^2)}}{\sqrt{x^2+y^2+z^2}}dB$$
We see that instead of having $x^2+y^2=r%2\sin^2\phi$, we need to have $z^2+y^2=r^2\sin^2\phi$. Thus we reformulate the space to the following parametrization:
$$\Omega_2=\left\{\begin{matrix}x=r\cos\phi \\ y=r\sin\phi\sin\theta \\ z=r\sin\phi\cos\theta\end{matrix},\phantom{..}\begin{matrix}r=[0,\infty] \\ \theta=[0..1/2\pi] \\ \phi=[0..1/2\pi]\end{matrix}\right.$$
Since all the coordinates are equivalent, the angular parametrizations are equivalent. In addition, since this is describing a sphere, the volume element is the same. This produces the following integral:
$$V_0=\frac{\rho_0}{4\pi\epsilon_0}\int_{\Omega_2}\frac{\text{e}^{-r^2}\text{e}^{-r^2\sin^2\phi}}{r}d\Omega_2=\frac{\rho_0}{4\pi\epsilon_0}\int_{\Omega_2}\frac{\text{e}^{-r^2(1+\sin^2\phi)}}{r}d\Omega_2$$
Implementing all limits, the final integral is much simpler than the first as:
$$\frac{\rho_0}{4\pi\epsilon_0}\int^{\frac{1}{2}\pi}_0\int^{\frac{1}{2}\pi}_0\int^\infty_0\frac{\text{e}^{-r^2(1+\sin^2\phi)}}{r}r^2\sin\phi dr d\phi d\theta$$
Implementing all formula, we find that:
$$\frac{\rho_0}{4\pi\epsilon_0}\int^{\frac{1}{2}\pi}_0\int^{\frac{1}{2}\pi}_0\int^\infty_0r\text{e}^{-r^2(1+\sin^2\phi)}\sin\phi dr d\phi d\theta$$
We can also allow $u=r^2$ to finally simplify the integral to:
$$V_0=\frac{\rho_0}{8\pi\epsilon_0}\int^{\frac{1}{2}\pi}_0\int^{\frac{1}{2}\pi}_0\int^\infty_0\text{e}^{-u(1+\sin^2\phi)}\sin\phi du d\phi d\theta$$
Evaluating past the first integral, we find:
$$V_0=\frac{\rho_0}{8\pi\epsilon_0}\int^{\frac{1}{2}\pi}_0\int^{\frac{1}{2}\pi}_0\frac{\sin\phi}{1+\sin^2\phi} d\phi d\theta=\frac{\rho_0}{16\epsilon_0}\int^{\frac{1}{2}\pi}_0\frac{\sin\phi}{1+\sin^2\phi} d\phi=\frac{\rho_0}{16\epsilon_0}\int^{\frac{1}{2}\pi}_0\frac{\sin\phi}{2-\cos^2\phi} d\phi$$
Using the subs $v=\cos\phi$, we finally obtain the single integral:
$$V_0=\frac{\rho_0}{16\epsilon_0}\int_0^1\frac{1}{2-v^2} du$$
I trust you can finish off the integral from here! It was just a matter of finding the right parametrization for the specific charge density
Comment: Really helpful; your method gives an solution that agrees with Mathematica's numerical integration. One question though. How is the Schwinger parametrization supposed to apply in this problem? Seems that we did the whole thing with standard calculus techniques.
Comment: My pleasure, the Schwinger Parametrization is used to evaluate the 'du' integral in the third-to-last line


Weblinks não abrem em nova janela

Question: Instalei a versão 3.2 do Joomla e criei os weblinks.
Tanto a configuração global, quanto a individual, estão marcadas para target uma new window, mas ao clicar o weblink só abre na mesma página.
Já limpei os temporários e nada acontece.
Onde no código posso definir o target de maneira "hard code", ou existe alguma outra solução para esse problema?
Comment: Você poderia postar essa parte?
Answer: Encontrei um caso parecido com o seu no fórum do Joomla
http://forum.joomla.org/viewtopic.php?t=643728
Existem três lugares onde a opção de destino deve ser alterado para "Abrir em uma nova janela" para que isso funcione:
As opções básicas de cada um Weblink
As opções básicas da categoria Weblink
As opções básicas do módulo de Weblink
Comment: Não está funcionando, já havia feito isso. a solução que encontrei foi instalar um plugin pra gerenciar.

Weblinks não abrem em nova janela


Compactness of stabiliser subgroup of automorphism group of an open convex cone

Question: I have a question about the following proof in Analysis on Symmetric Cones by Faraut and Koranyi (p.5). Let $G(\Omega)$ be the automorphism group of an open convex cone $\Omega$. For any point $a\in \Omega$ we define the stabiliser of $a$ in $G(\Omega)$ by
$$G(\Omega)_a = \left\{g \in G(\Omega): ga = a \right\}.$$
Now my question concerns the proof of the following proposition.

If $\Omega$ is a proper open convex cone, then for every $a$ in $\Omega,$ $G(\Omega)_a$ is compact.

Proof. The set $\Omega \cap (a - \Omega)$ is bounded, open and non-empty. $G(\Omega)_a$ maps $\Omega \cap (a - \Omega)$ to itself. It follows easily (e.g. by choosing a basis of $V$ contained in $\Omega \cap (a- \Omega)$) that there exists a constant $C$ such that
$$\frac{1}{C} ||x|| \leq ||gx|| \leq C ||x||$$
for all $g \in G(\Omega)_a$ and $x \in V.$ Hence $G(\Omega)_a$ is relatively compact in GL$(V)$, and is also clearly closed. (End of proof).
My question concerns the 'It follows easily' statement, which I just can't see. I will focus on the second inequality ($||gx|| \leq C||x||$). Let $x = c_1e_1+ \ldots c_ne_n$ where $\beta = \left\{e_1,\ldots,e_n \right\}$ is the basis we have chosen, which is contained in $\Omega \cap (a- \Omega).$ The fact that $g$ maps $\Omega \cap (a- \Omega)$ to itself suggests we could begin with something like
$$||ge_i|| \leq C||e_i|| \text{ for all } 1 \leq i \leq n,$$
then say
\begin{equation}
\begin{split}
||gx|| &= ||c_1ge_1+\cdots+c_nge_n|| \\
& \leq |c_1|\cdot||ge_1||+\cdots+|c_n|\cdot ||ge_n|| \\
& \leq C \big(|c_1|\cdot ||e_1||+\cdots |c_n| \cdot ||e_n|| \big)
\end{split}
\end{equation}
which is kinda close but obviously not good enough. Also, this suggests that bounding each basis vector isn't enough, but I can't seem to think of how to get the upper bound in terms of $||x||.$ Any help would be greatly appreciated.
Answer: $\|c_1e_1+...+c_ne_n\|_1=|c_1|\|e_1\|+...+|c_n|\|e_n\|$ is a norm defined on a finite dimensional space, and on a finite dimensional space norms are equivalent. There exists $D>0$ such that ${1\over D}\|x\|\leq \|x\|_1\leq D\|x\|$.


Implement parallax effect on Header image from Content type field

Question: I have a Header image which i can upload per node from my Basic-page Content type. I want to implement this parallax effect, on my Header image section. But I need to add:

.
How do I add data-image-src="/path/to/image.jpg" to the wrapping
? It has to be dynamic and per node you must be able to attach a specific image.
Answer: Where do you need to add that code? Into field.tlp.php, node.tpl.php or page.tlp.php? Is it D7 or D8?
If you need to extract src atribute (/path/to/image.jpg) from some HTML code (for example from the node.tlp.php field) then use Google. When you will have src then you can create desired
 element in your template files.
As universal answer as detailed question was.
Update:
I found that you have attached your site so I suggest this:

Create block in Views for header image field

NID as Contextual Filter
Enable cache per page
Output header image field as src (only image url) - there is such option in views or use this module
Override that field (rewrite the output of this field) with something as

enable block in proper region only for "Basic-page" CT
Comment: thanks i try it know. But the first step 'NID as argument' how do i do this?
Comment: [Check this](http://dannyenglander.com/blog/using-views-contextual-filters-create-related-content-block-drupal-7). It's called like `Contextual Filter: Nid`. I'm sure you know what it is - it's very common in Views. I just used wrong term from D6.
Answer: I fixed it with a much easier way:
1) I installed the Image URL Formatter module
2) now i am able in Manage Display > Full content > Field: header_image > under Format i can choose Image URL
3) Now in my page.tpl.php i can call my header_image URL like:

   <div class="parallax-window" data-parallax="scroll" data-speed="-0.2" data-image-src="<?php print render($page['header_image']); ?>">