text:
Q: On the Definition of Conformality On here, conformality is defined by saying that a continuous map $w=f(z)$ on a domain $\Omega$ is conformal at a point $z_0\in \Omega$ if given any two differentiable curves $a(t),b(t)$ that pass through $z_0$, then the oriented angle is preserved, in the sense that
$$\arg \frac{d}{dt}f(a(t)) \Bigr|_{t=t_1} -\arg \frac{d}{dt}f(b(t)) \Bigr|_{t=t_2} = \arg a'(t_1)-\arg b'(t_2)$$
where $a(t_1)=z_0=b(t_2)$ and the limit
$$\lim_{z\rightarrow z_0}{\frac{|f(z)-f(z_0)|}{|z-z_0|}}$$ is finite.
However, what I fail to understand is the well-definedness of the above definition: we do not know that $f(a(t))$ or $f(b(t))$ are real-differentiable.  The obvious solution would be to require, where $f(x,y)=u(x,y)+iv(x,y),a(t)=x_1(t)+iy_1(t),b(t)=x_2(t)+iy_2(t)$, $u(x_k(t),y_k(t))$ and $v(x_k(t),y_k(t))$ to be real-differentiable for $k=1,2$.
But is this necessary? I.e. is there a better way to define the preservation of angles in such a way that this issues of $f$ being differentiable as a function of $t$ do not arise?

A: There are many better definitions of conformality. For instance: Complex-differentiable at $z_0$ with nonzero derivative. The geometric meaning is that it preserves orientation of the tangent plane at $z_0$ and also preserves angles between tangent vectors at this point. For the geometric definition you would require also this function to be differentiable at $z_0$ as a function of two real variables.


text:
Q: CSS Change on hover other element not working I am trying to display sub-menu items and a div at the same time in Wordpress Genesis. But when I hover on the div the sub-menu disappear.
I am using the following code but it doesn't work
.sbclass:hover + #nav li:nth-child(3):hover ul,
#nav li:nth-child(3) ul,
#nav li:nth-child(3).sfHover ul,
#nav li:nth-child(3) .submenu {
    visibility:visible !important;
    display:block !important;
}

You can check the third nav menu item menu here
http://174.120.233.154/~a348/nextmktg/jle/

A: ** The original post ended with the poster asking how to approach his problem with mouseenter/mouseleave, that is why this a javascript response to his css question **
Welp, your using jquery, so the most basic approach is below. There are prettier ways to do it as well.
$('selector').on('mouseenter', function(){
  $(this).addClass('open');
});
$('selector').on('mouseleave', function(){
  $(this).removeClass('open');
});

More here: Combining jquery functions - on() hover/mouseenter/mouseleave
And here: http://api.jquery.com/on/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error when opening a jquery dialog on a textfield focus event I have a dynamic textfield and i am binding it to focus event to open a dialog.
$('#formtable').on('focus', '#textbox1', function (e) {
 callOpenDialog('Dialog');
});

where formtable is div container for the textfield and the function is defined as
function callOpenDialog(title)
{
 $("#Dialog").dialog({
        title: title,
        resizable: false,
        modal: true,
        height: 300,
        width: 300,
        position: 'top'
    });
}

The problem is that:
1) On textfield focus, the dialog opens but the focus remains to the textfield itself.i want the focus to the dialog;
2)On closing the dialog an error is shown as
Uncaught TypeError: Cannot call method '_focusTabbable' of null
however when i bind to click event it works properly but i have to do it on focus event.
I tried using
e.preventDefault()
or
$("#Dialog").focus()

but to no avail.
Please help.

A: I have got answer to the problems
1)i disabled the text box on focus event.
$('#formtable').on('focus', '#textbox1', function (e) {
   $("#textbox1").attr('disabled','disabled');
   callOpenDialog('Dialog');
});

the focus is now transferring to the dialog box.
2)For this error "Cannot call method '_focusTabbable' of null"
I called destroy method on close event of jquery dialog.
  close: function (event, ui) {
            $(this).dialog('destroy');
        }

A: You can  initialize your stuff in open callback method,
$( "#Dialog" ).dialog({
  open: function( event, ui ) {}
});

Bind an event listener to the dialogopen event:
$( "#Dialog" ).on( "dialogopen", function( event, ui ) {} );

To know more about Events & methods : http://api.jqueryui.com/dialog/


text:
Q: Find $k$-clique with max min weight. I have a problem with the following equivalent formulation in graph theory:
Take $G(V, E, W)$ a complete weighted graph, where $w_{ij} > 0$ is the weight of edge $e_{ij}$. For a given $k$, find the clique $Q$ with $k$ vertices, such that its minimum edge weight is maximized over the graph.
$$Q = \text{argmax}_{I} \min_{i,j \in I} w_{i,j}\\
\text{such that } |I| = k$$
I have seen similar problems such as finding cliques where the sum of weights are maximized, but not a maxmin problem like above.
I have also found the following paper [1], which addresses a similar problem, but again different than what I have here.
Based on what I have seen in similar problems, I suspect that this problem is also NP-hard. I was wondering if this is the case, and whether anyone knows an approximation to this problem.
[1] T. F. Gonzalez, Clustering to minimize the maximum intercluster distance, Theoretical Computer Science, 38(2-3):293-306, 1985.

A: This problem is easy and can be solved by the following algorithm. Remove all the edges from the graph and order them with respect to its weight, from the biggest to the smallest. Then reinsert the edges of the graph consecutively with respect to the order (if several edges have the same weight then we reinsert them simultaneously). A first $k$-clique appeared in the graph will be the required $\operatorname{argmax}$.


text:
Q: How to connect javascript and c# I need to connect a javascript/jquery-based webpage (which is executed locally only) using a c# application.
I guess the easiest ways are using a database (what seems to be problematically to connect with from javascript) or a tcp-socket. I tried to create a socket but for some reason I'm stuck. However I was able to create a server running with node.js which sends a "hello world" to c#, but I'm not able to connect to that server with javascript.
My particular use case is a webpage to recognize gestures of a leap motion. The C# part will be run in Unity, which is not able to execute the given javascript files. So the communication between javascript and C# is not used to build the website (which would be the main reason to use asp.net, correct?)
WCF sounds interesting but is there a way to connect with it from javascript?
My "server" was created with socket.io:
var net = require('net');

var server = net.createServer(function(socket){
    console.log("function called: " + socket.value);
    socket.write('hello\n');
    socket.end('world\n');
});
server.listen(8000);

I can connect to this server from my c# application, but I don't know how to send a message from javascript. When trying to connect using WebSocket I get the following error:
WebSocket connection to 'ws://127.0.0.1:8000/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

using io.connect results in:
net::ERR_NAME_NOT_RESOLVED

How do I get by those errors to talk to the web application from client-side javascript?

A: Try creating a web service with WCF:
https://msdn.microsoft.com/en-us/library/vstudio/bb412178(v=vs.100).aspx

A: ASP.Net is the thing that you're looking for. It was built for c# and web
      http://www.asp.net/mvc/overview
If you need two way connection, then take a look at SignalR


text:
Q: How to keep secret key information out of Git repository I have some files in my repository, and one contains a secret Adafruit key. I want to use Git to store my repository, but I don't want to publish the key.
What's the best way to keep it secret, without having to blank it out everytime I commit and push something?

A: Depending on what you're trying to achieve you could choose one of those methods:

*

*keep file in the tree managed by git but ignore it with entry in gitignore

*keep file content in environment variable,

*don't use file with key at all, keep key content elsewhere (external systems like hashicorp's vault, database, cloud (iffy, I wouldn't recommend that), etc.)

First approach is easy and doesn't require much work, but you still has the problem of passing the secret key to different location where you'd use the same repository in a secure manner. Second approach requires slightly more work, has the same drawback as the first one.
Third requires certainly more work then 1st and 2nd, but could lead to a setup that's really secure.

A: This highly depends on the requirements of the project
Basically, the best strategy security-wise is not to store keys, passwords and in general any vulnerable information inside the source control system. If its the goal, there are many different approaches:

*

*"Supply" this kind of information in Runtime and keep it somewhere else:

./runMyApp.sh -db.password=

*Use specialized tools (like, for example Vault by Hashicorp) to manage secrets

*Encode the secret value offline and store in git the encoded value. Without a secret key used for decoding, this encoded value alone is useless. Decode the value again in runtime, using some kind of shared keys infra / asymmetric key pair, in this case, you can use a public key for encoding, a private key for decoding

A:
I want to use Git to store my repository, but I don't want to publish the key.

For something as critical as a secret key, I would use a dedicated keyring infrastructure located outside the development environment, optionally coupled to a secret passphrase.
Aside this case, I personnaly use submodules for this. Check out :
git submodule

In particular, I declare a global Git repository, in which I declare in turn another Git repository that will contain the actual project that will go public. This enables us to store at top level everything that is related to the given project, but not forcibly relevant to it and that is not to be published. This could be, for instance, all my drafts, automation scripts, worknotes, project specifications, tests, bug reports, etc.
Among all the advantages this facility provides, we can highlight the fact that you can declare as a submodule an already existing repository, this repository being located inside or outside the parent one.
And what's really interesting with this is that both main repository and submodules remains distinct Git repositories, that still can be configured independently. This means that you don't need your parent repository to have its remote servers configured.
Doing that way, you get all the benefits of a versioning system wherever you work, while still ensuring yourself that you'll never accidentally push outside something that is not stored inside the public submodule.

A: If you don't have too many secrets to manage, and you do want to keep the secrets in version control, I make the parent repository private.  It contains 2 folders - a secrets folder, and a gitsubmodule for the public repository (in another folder).  I use ansible crypt to encrypt anything in the secrets folder, and a bash script to pass the decrypted contents, and load those secrets as environment vars to ensure the secrets file always stays encrypted.
Ansible crypt can encrypt and decrypt an environment variable, which I wrap in a bash script to do these functions like so-
testsecret=$(echo 'this is a test secret' | ./scripts/ansible-encrypt.sh --vault-id $vault_key --encrypt)
result=$(./scripts/ansible-encrypt.sh --vault-id $vault_key --decrypt $testsecret)
echo $result

testsecret here is the encrypted base64 result, and it can be stored safely in a text file.  Later you could source that file to keep the encrypted result in memory, and finally when you need to use the secret, you can decrypt it ./scripts/ansible-encrypt.sh --vault-id $vault_key --decrypt $testsecret
This bash script referenced above is below (ansible-encrypt.sh).  It wraps ansible crypt functions in a way that can store encrypted variables in base64 which resolves some problems that can occur with encoding.
#!/bin/bash

# This scripts encrypts an input hidden from the shell and base 64 encodes it so it can be stored as an environment variable
# Optionally can also decrypt an environment variable

vault_id_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing vault_id_func option: '--${opt}', value: '${val}'" >&2;
    fi
    vault_key="${val}"
}
secret_name=secret
secret_name_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing secret_name option: '--${opt}', value: '${val}'" >&2;
    fi
    secret_name="${val}"
}
decrypt=false
decrypt_func () {
    if [[ "$verbose" == true ]]; then
        echo "Parsing secret_name option: '--${opt}', value: '${val}'" >&2;
    fi
    decrypt=true
    encrypted_secret="${val}"
}

IFS='
'
optspec=":hv-:t:"

encrypt=false

parse_opts () {
    local OPTIND
    OPTIND=0
    while getopts "$optspec" optchar; do
        case "${optchar}" in
            -)
                case "${OPTARG}" in
                    vault-id)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        vault_id_func
                        ;;
                    vault-id=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        vault_id_func
                        ;;
                    secret-name)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        secret_name_func
                        ;;
                    secret-name=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        secret_name_func
                        ;;
                    decrypt)
                        val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
                        opt="${OPTARG}"
                        decrypt_func
                        ;;
                    decrypt=*)
                        val=${OPTARG#*=}
                        opt=${OPTARG%=$val}
                        decrypt_func
                        ;;
                    encrypt)
                        encrypt=true
                        ;;
                    *)
                        if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
                            echo "Unknown option --${OPTARG}" >&2
                        fi
                        ;;
                esac;;
            h)
                help
                ;;
            *)
                if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
                    echo "Non-option argument: '-${OPTARG}'" >&2
                fi
                ;;
        esac
    done
}
parse_opts "$@"

if [[ "$encrypt" = true ]]; then
    read -s -p "Enter the string to encrypt: `echo $'\n> '`";
    secret=$(echo -n "$REPLY" | ansible-vault encrypt_string --vault-id $vault_key --stdin-name $secret_name | base64 -w 0)
    unset REPLY
    echo $secret
elif [[ "$decrypt" = true ]]; then
    result=$(echo $encrypted_secret | base64 -d | /snap/bin/yq r - "$secret_name" | ansible-vault decrypt --vault-id $vault_key)
    echo $result
else
    # if no arg is passed to encrypt or decrypt, then we a ssume the function will decrypt the firehawksecret env var
    encrypted_secret="${firehawksecret}"
    result=$(echo $encrypted_secret | base64 -d | /snap/bin/yq r - "$secret_name" | ansible-vault decrypt --vault-id $vault_key)
    echo $result
fi

Storing encrypted values as environment variables is much more secure than decrypting something at rest and leaving the plaintext result in memory.  That's extremely easy for any process to siphon off.
If you only wish to share the code with others and not the secrets, you can use a git template for the parent private repo structure so that others can inherit that structure, but use their own secrets.  This also allows CI to pickup everything you would need for your tests.
Alternatively, If you don't want your secrets in version control, you can simply use git ignore on a containing folder that will house your secrets.
Personally, this makes me nervous, its possible for user error to still result in publicly committed secrets, since those files are still under the root of a public repo, any number of things could go wrong that could be embarrassing with that approach.

A: For Django
add another file called secrets.py or whatever you want and also another called .gitignore
type secrets.py in .gitignore
paste the secret key into the secrets.py file and to import it in the settings file by using
from foldername.secrets import *

this worked for me.


text:
Q: Azure CDN url redirect issues Im currently trying to move my current redirect engine off a nginx proxy on a linux box to Azure. Currently ive been triyng to do it with this example:
dev.oldurl.com --> dev.newurl.com
This is the rule I currently have:
CDN Rules
When I have gone to the URL, im just getting a certificate error, I should also add that on the Domains section on the CDN I have this error "CNAME/alias record is not currently detected" I can confirm these are present in our on prem DNS server.
Thanks in advance.

A: As for the certificate error. You should have certificates corresponding to the URL's/domain names you are using in respective places. So the nginx server object receiving and redirecting dev.oldurl.com requests should have a certificate for dev.oldurl.com and the server receiving/handling requests for dev.newurl.com should have a certificate for dev.newurl.com.
For the CNAME record error, the Azure CDN will be looking at the public DNS records published on the internet. So you should check with your internet DNS provider for your domain to update the records.


text:
Q: Different Results from Levenshtein Algorithm in Java when interchanging words I'm facing some issues with a levenshtein matrix i've implemented. I'm a complete newbie, so this question might seem stupid to some, but i've been staring at this for ours and just cannot figure out, why it does not work out.
Here are the words I test out in my main class:
public static void main(String[] args) {
        // just some random words to picture my problem
        LevenshteinLogic levenshteinLogic = new LevenshteinLogic();
        int levenshteinZahl = levenshteinLogic.getLevenshteinDifference("abcdefghij", "adb");
        System.out.println(levenshteinZahl);
        levenshteinZahl = levenshteinLogic.getLevenshteinDifference("adb", "abcdefghij");
        System.out.println(levenshteinZahl);
    }

the resulting matrix (plus levenshtein difference at the end) look like this:
0 1 2
1 0 0
2 1 1
3 2 2
4 3 2
5 4 3
6 5 4
7 6 5
8 7 6
9 8 7
8
0 1 2 3 4 5 6 7 8 9
1 0 0 0 0 0 0 0 0 0
2 1 1 1 0 1 1 1 1 1
2
this is the levenshtein class i've written:
can anyone see the mistake? should it not do the exact same thing, no matter which word is longer than the other?
public class LevenshteinLogic {
    public int getLevenshteinDifference(String word1, String word2) {
        int levenshteinMatrix[][] = new int[word1.length() + 1][word2.length() + 1];
        final int word1Length = word1.length();
        final int word2Length = word2.length();
        // make sure capital letters aren't a problem
        word1 = word1.toLowerCase();
        word2 = word2.toLowerCase();
        // if empty, return length of other word
        if (word1Length == 0) return word2Length;
        if (word2Length == 0) return word1Length;

        // fill levenshteinMatrix first lines (x and y)
        for (int i = 0; i < (word1Length + 1); i++) {
            levenshteinMatrix[i][0] = i;
        }
        for (int i = 0; i < (word2Length + 1); i++) {
            levenshteinMatrix[0][i] = i;
        }

        for (int x = 1; x < (word1Length + 1); x++) {
            for (int y = 1; y < (word2Length + 1); y++) {
                int notMatching = 0;
                if (word1.charAt(x - 1) != word2.charAt(y - 1)) {
                    notMatching = 1;
                }
                int minValue = levenshteinMatrix[x - 1][y] + 1;
                if ((levenshteinMatrix[x][y - 1] + 1) < minValue) {
                    minValue = levenshteinMatrix[x][y - 1];
                }
                if ((levenshteinMatrix[x - 1][y - 1] + notMatching) < minValue) {
                    minValue = levenshteinMatrix[x - 1][y - 1] + notMatching;
                }
                levenshteinMatrix[x][y] = minValue;
                System.out.print(levenshteinMatrix[x-1][y-1] + " ");
            }
            System.out.println(" ");
        }
        return levenshteinMatrix[word1Length][word2Length];
    }
}

i know i can solve this issue by checking the lengths of the words and give them the correct order, but i really hope to understand what's going on there. After all, I've just started learning all this.
All help is highly appreciated! =)


text:
Q: Python, py2exe, & pyopengl ImportError: No module named win32 When I try to build an exe using py2exe, it builds but when i try to run the exe it throws this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
File "OpenGL\GL\__init__.pyc", line 3, in <module>
File "OpenGL\GL\VERSION\GL_1_1.pyc", line 10, in <module>
File "OpenGL\platform\__init__.pyc", line 35, in <module>
File "OpenGL\platform\__init__.pyc", line 26, in _load
File "OpenGL\plugins.pyc", line 14, in load
File "OpenGL\plugins.pyc", line 28, in importByName
ImportError: No module named win32

It only does this when I use pyopengl, It builds and runs perfectly with pygame and almost any other library/module I have used.
My setup.py script looks like this:
from distutils.core import setup
import py2exe
setup(console=['main.py'])

I am on Windows 7 64bit

A: Actually, After another hour or so of searching I found the solution!
For anyone else who has this problem: http://www.py2exe.org/index.cgi/PyOpenGL


text:
Q: APPLY and Passing Arguments to Functions Note: This is in SQL Server 2008.
I'm trying to use the APPLY operator to allow me to call user-defined in-line table-valued functions on each other in a sensible manner, but it doesn't seem to faithfully do so.  I'm using OUTER APPLY, but CROSS APPLY does the same thing.  Here's the relevant chunk:
SELECT addresses.Book,addresses.Page,foo.BookInput,foo.PageInput
FROM [dbo].bookPageFromAddress(@address) addresses
outer apply [dbo].[imageFileFromBookPage](addresses.Book, addresses.Page) foo

Nothing is bizarre:
GO
CREATE FUNCTION [dbo].imageFileFromBookPage (@book nvarchar(max), @page nvarchar(max))
RETURNS TABLE AS RETURN(
    WITH ids AS (
        SELECT right('00000000'+ltrim(str(c.DocID)),8) as VarString,
               right('0000000000'+ltrim(str(i.ImageID)),12) as PathVar6
        FROM [Resolution].[dbo].[Constant] c, [Resolution].[dbo].[Images] i
        WHERE ltrim(c.[Book]) like @book
        AND ltrim(c.[Page]) like @page
        AND i.DocID = c.DocID
)
SELECT '/Images/' +
    substring(ids.VarString,1,2)+'/' +
    substring(ids.VarString,3,2)+'/' +
    substring(ids.VarString,5,2)+'/' +
    right(ids.VarString,8)+'/' +
    PathVar6 + '.tif' as ImageLocation
    ,@book as BookInput, @page as PageInput
FROM ids

);
So, in essence,imageFileFromBookPage outputs its input to BookInput and PageInput.  Here's the result of that outer apply on sample input:
Book 4043
Page 125
BookInput NULL
PageInput NULL

Note that Book and Page are strings, not integers; they just happen to be holding numeric characters here, but BookInput and PageInput are really NULL, not strings.  I thought at first it was a typing issue; both Book and Page are nchar(10) in their original table, and both of my functions expect nvarchar(max) inputs.  I tried CASTing the arguments as nvarchar(max) and got identical results, however.
Am I barking up the wrong tree?  I'm not familiar with APPLY, but it sure seems like what I want, here.  How do I get APPLY or something like it to actually pass along values to the next function?
EDIT:  Modified code above to include more information.

A: Looking at the APPLY docs, shouldn;t the function be declared as:
CREATE FUNCTION [dbo].imageFileFromBookPage (@book nvarchar(max), @page nvarchar(max))
     returns @Data Table
     (
          book nvartchar(max),
          page nvarchar(max)
     )
as
begin
   insert into @Data
   select @book, @page;

end

In other words, it's not a problem with APPLY, it's a problem that your function needs to return a Table.
Cheers -


text:
Q: OSX stackshot format I have a stackshot file and I'm trying to figure out what's going on in it. Here's a thread from one of the processes in it (this is from WindowServer):
  Thread 0xf09            1000 samples (1-1000)   priority 79 (base 79)   cpu time 0.044s
  1000  thread_start + 13 (libsystem_pthread.dylib + 4981) [0x7fff952b3375]
    1000  _pthread_start + 168 (libsystem_pthread.dylib + 15248) [0x7fff952b5b90]
      1000  _pthread_body + 131 (libsystem_pthread.dylib + 15379) [0x7fff952b5c13]
        1000  thread_fun + 25 (QuartzCore + 129849) [0x7fff816e1b39]
          993  CA::Render::Server::server_thread(void*) + 257 (QuartzCore + 130113) [0x7fff816e1c41]
            993  mach_msg_trap + 10 (libsystem_kernel.dylib + 70534) [0x7fff8f639386]
             *992  ipc_mqueue_receive_continue + 0 (kernel + 828992) [0xffffff80002ca640]
             *1    Thread_continue + 8 (kernel + 1879576) [0xffffff80003cae18]
               *1    thread_continue + 67 (kernel + 1001955) [0xffffff80002f49e3] (running)
          7    CA::Render::Server::server_thread(void*) + 563 (QuartzCore + 130419) [0x7fff816e1d73]
            7    CA::Render::Server::ReceivedMessage::dispatch() + 31 (QuartzCore + 1031139) [0x7fff817bdbe3]
              6    CA::Render::Server::ReceivedMessage::run_command_stream() + 567 (QuartzCore + 1032931) [0x7fff817be2e3]
                5    CA::Render::decode_commands(CA::Render::Decoder*) + 2276 (QuartzCore + 1030108) [0x7fff817bd7dc]
                  3    CA::Render::Context::did_commit(bool, bool) + 76 (QuartzCore + 750372) [0x7fff81779324]
                    2    CA::Render::post_notification(CA::Render::NotificationName, CA::Render::Object*, void*, bool) + 249 (QuartzCore + 104465) [0x7fff816db811]
                      2    contextChanged + 127 (CoreGraphics + 5099842) [0x7fff91bf3142]
                        2    mach_msg_trap + 10 (libsystem_kernel.dylib + 70534) [0x7fff8f639386]
                         *2    hndl_mach_scall64 + 22 (kernel + 2030166) [0xffffff80003efa56]
                           *2    mach_call_munger64 + 410 (kernel + 1817898) [0xffffff80003bbd2a]
                             *2    mach_msg_overwrite_trap + 197 (kernel + 877285) [0xffffff80002d62e5]
                               *2    ipc_kmsg_send + 307 (kernel + 813363) [0xffffff80002c6933]
                                 *2    ipc_mqueue_send + 599 (kernel + 827767) [0xffffff80002ca177]
                                   *2    ipc_mqueue_post + 932 (kernel + 828756) [0xffffff80002ca554] (running)
                    1    CA::Render::post_notification(CA::Render::NotificationName, CA::Render::Object*, void*, bool) + 99 (QuartzCore + 104315) [0x7fff816db77b] (running)
                  1    CA::Render::post_notification(CA::Render::NotificationName, CA::Render::Object*, void*, bool) + 94 (QuartzCore + 104310) [0x7fff816db776] (running)
                  1    CA::Render::post_notification(CA::Render::NotificationName, CA::Render::Object*, void*, bool) + 249 (QuartzCore + 104465) [0x7fff816db811]
                    1    contextDidCommit + 125 (CoreGraphics + 5100116) [0x7fff91bf3254] (running)
                1    CA::Render::decode_commands(CA::Render::Decoder*) + 61 (QuartzCore + 1027893) [0x7fff817bcf35]
                  1    CA::Render::Context::will_commit() + 30 (QuartzCore + 163728) [0x7fff816e9f90]
                    1    CA::Render::post_notification(CA::Render::NotificationName, CA::Render::Object*, void*, bool) + 94 (QuartzCore + 104310) [0x7fff816db776] (running)
              1    CA::Render::Server::ReceivedMessage::run_command_stream() + 683 (QuartzCore + 1033047) [0x7fff817be357]
                1    x_mem_dealloc_chain + 35 (QuartzCore + 54163) [0x7fff816cf393] (running)

The title line claims 1000 samples, so I'm going to guess that the number in front of the stack frames is a count of how many times the sampler found that frame in the snapshot? That would also explain the indentation. What does the * next to the sample number mean? For example, hndle_mach_scall64 has *2 next to it. What does that mean?

A: Looking at it again, it seems like the * denotes code on the other side of a syscall.


text:
Q: Different UICollectionViewCells having the same address I need help making each cell adddress unique. When i change the background colour of cell 1, cell 4's background colour also changes. after checking the cell description i found that my cells are using the same 3 address. cell 1 address the same as cell 4, 7, 10..., cell 2 address is the same as cell 5, 8, 11... and cell 3 is the same as cell 6, 9, 12...

I want each cell to be unique but i want to reuse the same cell type for each cell.
my collectionView protocal code:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return noOfQuestions!
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as! QuestionCell

    cell.starPageLabel.text = String(indexPath.row + 1)

    cell.addImageButton.tag = indexPath.item
    cell.addImageButton.addTarget(self, action: #selector(handleAddImage), for: .touchUpInside)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    currentPage = Int(targetContentOffset.move().x / view.frame.width)
}

@objc func handleAddImage () {
    print("Current Page: \(currentPage!)")
    let cell = collectionView.cellForItem(at: IndexPath(row: currentPage!, section: 0)) as! QuestionCell
    print(cell.description)
    cell.questionTextField.backgroundColor = .red
}


text:
Q: need to return exit code of spawned procees from expect script I have below expect script
expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
"

if [ $? != 0 ]; then
   echo "Failed to Add a String $StringName."
else
   echo "\"add <string>\" ==> [OK]"
fi

I tried modifying the expect script i.e. added some lines after "send"
expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
expect eof
catch wait reason
exit [lindex $reason 3]
"

But it is returning always a non-zero value irrespective of process's failure/success.
Could you give me some pointers in identifying the correct exit code whenever process fails/success.
Thanks in advance
regards,
Srikrishna Erra.

A: The problem is the $reason is getting substituted by your shell (and not expect). Moreover, it's probably being substituted with the empty string, which leads to a syntax error. The quickest way to fix this is to put a backslash in front of the $, like this:
expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
expect eof
catch wait reason
exit [lindex \$reason 3]
"

OTOH, it would probably be better now that you're getting up to this level of complexity to put that script in a separate file so you can reduce the number of backslashes. At that point, you then switch to passing the thing to add as a command line argument.
Thus, in addWallet.exp you have this:
spawn tdwallet add [lindex $argv 0]
expect "^Enter"
send "Krishna123\r"
expect eof
catch wait reason
exit [lindex $reason 3]

And then your main script is this:
expect addWallet.exp $StringName

That's much easier to work with!


text:
Q: SharePoint List View Filter I have a choice column "Position" which I am referencing in the new list view filter to create a bunch of different views for departments. Each department can only view certain relevant "Position" choices.
Every view I have made so far works fine, but for my last view, I have 19 choices that could be a possible selection that will show up for this departments view.
All of my other views had 6 or less options. In the filter section, I have filled in 10 options and the "show more columns" option disappears from adding more.
Why is that? And is there a way around this?

A: This is a default behavior of SharePoint.
You can only use 10 conditions in list view filter.
Workaround (Not tested):
Try setting the list view query using PowerShell: SharePoint Online: PowerShell to Update List View
View query requires CAML Query.


text:
Q: PHP MySQL Delete function in while loop Evening,
I'm kinda stuck here. I've made a login for our employees to easily create new invoice (it's in danish though, sorry) and almost everything is completed. But one thing I can't figure out how to do, is to delete a material (materiale in danish) from a while loop. I've got a form with a while loop within it, which displays all of the materials, and right next to the material input fields I've created a small a href link, which should delete the field with some help from javascript. It deletes the field perfectly, but doesn't delete the data from our mysql database. So every time I refresh the page, then the data are back. Updating and inserting isn't a problem. The code looks like this:
$ct_update = 0;

foreach ($_POST['beskrivelse_update'] as $k => $value) {
    $beskrivelse_update = addslashes($value);
    $enhed_update           = addslashes($_POST['enhed_update'][$ct_update]);
    $stk_update         = addslashes($_POST['stk_update'][$ct_update]);
    $vejl_eks_moms_update   = addslashes($_POST['vejl_eks_moms_update'][$ct_update]);

    $update_id              = (int)$_POST['update_id'][$ct_update];

    $db->query("UPDATE faktura_materialer SET beskrivelse = '$beskrivelse_update', enhed = '$enhed_update', stk = '$stk_update', vejl_eks_moms = '$vejl_eks_moms_update', subtotal = '$stk_update' * '$vejl_eks_moms_update' WHERE id = '$update_id' LIMIT 1");

    $ct_update++;
}

$ct_ny = 0;

if(isset($_POST['beskrivelse_ny'])){
    foreach ($_POST['beskrivelse_ny'] as $k => $value) {
        $beskrivelse_ny = addslashes($value);
        $enhed_ny           = addslashes($_POST['enhed_ny'][$ct_ny]);
        $stk_ny         = addslashes($_POST['stk_ny'][$ct_ny]);
        $vejl_eks_moms_ny   = addslashes($_POST['vejl_eks_moms_ny'][$ct_ny]);

        $db->query("INSERT INTO faktura_materialer (faktura_id, beskrivelse, enhed, stk, vejl_eks_moms, subtotal) VALUES ('".$_faktura->faktura_id."', '".$beskrivelse_ny."', '".$enhed_ny."', '".$stk_ny."', '".$vejl_eks_moms_ny."', '".$stk_ny."' * '".$vejl_eks_moms_ny."')");

        $ct_ny++;
    }
}

Hopefully you understand what I want to do, otherwise just comment. Have a nice evening peeps :)
Edit:
I want the delete query to be submitted when the user clicks the submit button "Save changes". This is my javascript code:

When the user clicks the delete icon right next to the material, then it will be deleted. And it does delete the input fields, but not from the database in mysql.
Second edit:
This is HTML and PHP for updating current data in MySQL database:
$materialer_query = $db->query("SELECT faktura_materialer.id as materialer_id, faktura.*, faktura_materialer.* FROM faktura, faktura_materialer WHERE faktura_materialer.faktura_id = faktura.id");

while($mat = $materialer_query->fetch_object()){
    ?>

        <input type="hidden" name="update_id[]" value="<? print $mat->id; ?>" />
        <input style="width:450px;" class="text-input" type="text" name="beskrivelse_update[]" value="<? print $mat->beskrivelse; ?>">
        <input style="width:60px;" class="text-input" type="text" name="enhed_update[]" value="<? print $mat->enhed; ?>">
        <input style="width:30px;" class="text-input" type="text" name="stk_update[]" value="<? print $mat->stk; ?>">
        <input style="width:205px;" class="text-input" type="text" name="vejl_eks_moms_update[]" value="<? print $mat->vejl_eks_moms; ?>">

    <?
}

The hidden input field name="update_id[]" is added to the form when I am updating. I hope this helps...

A: You need to inform the PHP script that you wish to delete the record. One solution would be to use a hidden input which is set when you call removeRow, e.g.
function removeRow(el) {
    // get the table row
    var row = $(el).parents('tr:first');

    // disable the input fields for the row
    $('input', row).attr('disabled', 'disabled');

    // rename update_id to delete_id and re-enable the field
    $('input[name="update_id[]"]', row).attr('name', 'delete_id[]').removeAttr('disabled');

    // hide the row
    row.hide();
}

This method no longer removes the table row from the DOM. However, it will disable the input fields contained in the row and adds a hidden input with the name beskrivelse_delete.
When the form is submitted, your PHP will now have a way to know which records need to be deleted.
foreach ($_POST['delete_id'] as $deleteId) {
    $deleteId = (int)$deleteId;
    $db->query("DELETE FROM faktura_materialer WHERE id = $deleteId");
}

Update: I've created a phpfiddle which has some improvements that you may wish to learn about. These points include:

*

*Supporting deletion where JavaScript is not enabled

*Using prepared statements (preferred to add_slashes)

*Escaping output by using htmlspecialchars

*Explicitly defining input ids to avoid guessing based on an incremental counter


text:
Q: Read server streaming data using jQuery This is my original question
SailsJS stream status from backend to frontend
This question led me to this,
Now the server is streaming these information perfectly but I cannot get this streamed data from the server to be read by jQuery before the RESPOSE from the server is finished. ( In sailsJS it is res.end() )
So this is not the way i want it. I need jQuery to tell me 1/1000 is complted when the server send that information from the backend. and next tell me 2/1000 is completed.
Hope you understand what im asking of you.
Cheers.


text:
Q: Regex for strings that contain only odd clusters of b's with set {a,b} This must be valid
ababbba

This must be invalid
bb

I only know that this regex ensures odd b's per iteration
b(bb)*

However my current regex fails when repeated.
(a*b(bb)*)*

A: The problem with the expression (a*b(bb)*)* is that the a* can match 0 or more a, so it would match abbb[0 a]b. I think what you want is something like this:
^a*b(bb)*(a+b(bb)*)*a*$

that would match any number of a, then an odd number of b followed by 0 or more odd numbers of b, as long as there is one or more a in between, then any number of a at the end. I included the start and end terminators because regex coach gives me partial matches without them.


text:
Q: Subtracting a particular column value by 1 every time when a query is activated Table leave_details contains the following column

1.Employee name
2.Employee ID
3.Leavefrom
4.Leaveto
5.Leavetype (Earned leave / sick leave)
6.Leavestatus (Approved/Rejected)

Whenever a employee applies for leave it will be approved or rejected by the manager. Query for approval

"UPDATE leave_details join managerlogin on managerlogin.manager_id=leave_details.manager_id SET leave_details.leave_status='Approved' where (employee_id='$myemployee_id' and managerlogin.manager_id= '".$_SESSION['mymanager_id']."' )";

This will change the leave_status column as "Approved"
I have another table called employee which has the overall Earned leave and Sick leave balance of an employee. Employee table has the following columns

1.Employee name
2.Employee ID
3.Earned leave (for example 20)
4.Sick leave (for example 5)

When ever he applies for leave and when the leave_status becomes approved then the earned leave and sick leave column in employee table should be decreased by 1 (for example if he applies for earned leave then that particular employees column value should be reduced by 1 [here 20-1=19] , when he applies for the next time [19-1=18] like that it should continue).
How to do it. Please help. Thanks in advance

A: Updating the leave entitlements in the employee table is a bad design - as once changed you have no further references as to what they were; and no temporal reference as to when taken.
So I'd recommend changing the records in the leave_details table status to taken - and then count the days taken from the leave_details table to determine how many leave days are remaining, e.g. to find the number of days leave taken in 2011
select sum(datediff(leaveto,leavefrom)) as days_leave_taken
from leave_details
where employeeid = 1000
      and leavefrom between '2011-01-01' and '2011-12-31 23:59'

However if you must update the employee table;
UPDATE Employee SET EarnedLeave = EarnedLeave - 1 WHERE EmployeeID = <Id>

will do the trick.


text:
Q: How do I disable my CD/DVD drive? I'd like to disable my CD/DVD drive so that it doesn't spin up every time I select Save in my Kate editor, or select a file-accessing action in other applications. The spinning up just delays what I'm doing, and I'm not even using the DVD drive.
I want to leave the CD in the drive, and not have it spin up.
I found a website that said a udev rule will definitely disable the drive.
So far, I've tried the following 2 rules (separately), but neither of them disable the DVD drive (it still spins up - even when not mounted):
ENV{ID_SERIAL}=="PIONEER_DVD-RW_DVRTD11RS_SAC1009942", ENV{UDISKS_IGNORE}="1"

KERNEL=="sr0",ENV{UDISKS_IGNORE}="1", RUN+="/bin/touch /home/peter/udev-rule-ran"

The RUN+ in the second instance, creates my test file "udev-rule-ran", so this tells me that my rule file is being executed, and that the rule line is being run.
My Question:
Could you tell me what I should be doing to definitely disable the darned DVD drive? I also want to be able to enable the drive again on the occasions that I need it.
Supplementary Details:
I'm trying very hard to write a udev rule to disable my CD/DVD drive. I've tried various non-udev methods to disable it but none of them work.
There is no loaded module¹⁾ for the drive that I can unload, so I can't use that method to disable the drive.
¹⁾ So I think the driver must be compiled into the kernel.

A: To the fine Administrator from OP:
I'm sorry that I can't leave a comment because I'm a guest. So could I humbly
ask if you would add my comment below to the page please. Thanks so much.
Thanks Hans-Martin Mosner and Gypsy Spellweaver. Sorry but yes I do have a
reason why I want to keep the CD in the drive. Re Gypsy: After umounting the CD,
the drive still spins up when I select a file-accessing action in an
application. For example, in Kate, when I select File/Save, the Save window
appears, then the DVD drive spins up, presumably offering itself for possible
use. I checked, and the CD remains unmounted.

A: I have also fought with udisks/udisks2 in the past (because may CD is behind a cheap SATA-IDE bridge, which goes into a reset loop if an audio CD is present when udisk tries to poll), and it's really difficult to disable it reliably. It's not properly documented, some stuff changed from udisks to udisks2, etc.
I ended up making a file /etc/udev/rules.d/80-udisks2.rules to circumvent the original /lib/udev/rules.d/80-udisks2.rules with contents:
ACTION!="add|change", GOTO="udisks_end"
SUBSYSTEM!="block", GOTO="udisks_end"
KERNEL=="ram*", GOTO="udisks_end"
ENV{UDISKS_PRESENTATION_NOPOLICY}="1"
ENV{UDISKS_DISABLE_POLLING}="1"

########

LABEL="udisks_end"

This is still not 100% effective, under some conditions udisks2 still gets invoked. For whatever reason.
If you find a more reliable and selective way to disable it, I'd be interested to know.


text:
Q: JavaScript Call and Apply in internet explorer 8 (and 7) for window.print OK, I looked a lot for this on the web but cannot find an answer.
I can expect CSS differences between browsers but there are JavaScript differences too?
So why this works in IE8:
window.print(); // works

but when I pass window.print to a function and call it, it don't work in IE8 (works in IE9):
function callIt(f){
    f.call();
};

callIt(window.print);

Is it a known issue?

EDIT
OK it does not work means it will simply ignore it, no javascript error or anything.
Sorry it gives this error:
   Object doesn't support this property or method

EDIT 2
I need to use call or apply since I need to pass the context. I am trying to create a class which I can pass functions and it can call it with the possibility of passing context or arguments. Do not tell me to use f() that is not an answer since it does not fix my problem. The question is on call and apply.

A:     function callIt(f) {
        if (f) f();
    }

    callIt(window.print);

Done, no?

Update
per the poster's request that I answer the question, not recommend a solution that works, here she goes:
If you view typeof(window.print) in IE, you'll see that it reports itself as type object.  Type object has no apply or call method.  In my opinion, your design is wrong for the task.  HOWEVER, if what you want is a rabbit hole to follow, here's the top:
var p = window.print;
window.print = function() { p(); }

function callIt(f){
     f.call();
}

callIt(window.print);

I have no idea what will happen in any other browser or how many procedural exceptions you'll have to make to account for it everywhere you'll need to.

A: It seems window.* functions are separate types than user-created functions in IE < 9. Thus, they don't get any of the Function.prototype.*. You'll see that
typeof alert === 'object'

function a(){}

typeof a === 'function'

This would happen for any of the window.* functions. Only for IE < 9. WTG Miscrosoft.
However you can try
Function.prototype.call.call(window.print)

See if that works for you.

A: You almost certainly should not be using .call() here. f() will call the method, while f.call() will call it with an unset this. Under es3 (but not es5 strict,) an undefined value for this will be coerced to window. I suspect that IE9 properly handles this, while IE8 does not, but that's just a guess based on behavior.
If print cares about the value of this, you should call it as window.print() in order for this to be set correctly. In that case, you may have to wrap it in an anonymous function so that print doesn't get "sliced off" of window. callIt(function() { window.print();});


text:
Q: Xpath reverse searching Is there a way, when using DOM_Document Xpath to search in reverse (from the end of the page moving up instead of from the top down?)
If so, how would I do this?
I am doind a scrape of a web site. (linked below).
http://www.sturmfh.com/obit-display.jhtml?DB=update/obits/dbase&DO=display&ID=1189477693_24578
I only want to scrape the 3 obituary paragraphs. So i figured it'd be easiest to start at the end and move up.

A: Use:
(//p)[position() > count(//p) - 3]

This selects the last (up to three) p elements in the XML document.
XSLT - based verification:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy-of select="(//p)[position() > count(//p) - 3]"/>
 </xsl:template>
</xsl:stylesheet>

When applied against the document, referenced in the question, this transformation evaluates the XPath expression and outputs the selected p elements.
The result is:

                If you would like to share your thoughts and memories,
 we will deliver your message to the family.

   Click

   here.

To Request a Tribute Folder

   Click

   here


text:
Q: google Banner failed to load ad 3 I was using google demo test bannerAd. Until yesterday it was working just fine. Yesterday the banner didn't load anymore, I did not change anything in the code. Reinstaling the demo did not show the banner either.
The InterstitialAd demo still works fine. What could possible cause this problem.
 I recently upgraded Android Studio and the SDK to the latest version. Could this cause the problem.

A: I have absolutely the same problem. Testing banner will not load. Intertitials and live ads are OK.
I have realized that AdMob is not showing preview banner even while creating new banner unit in my AdMob account. So I think the problem can not be at my side.
EDIT: "AdMob is currently experiencing a service disruption for its iOS and Android test banners. The engineers are working on it, but in the meantime, there's nothing wrong with your code." (No test ads are loaded with AdMob)


text:
Q: NSXMLParser returns Error 0 but doesn't parse a file The following code:
- (void)ParseFile:(id)sender
{
NSLog(@"Parsing URL: '%@'", FileURL);
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:FileURL];
[parser setDelegate:self];
parser.shouldProcessNamespaces = NO;
if ([parser parse]) {
    NSLog(@"parse successful.");
    [self performSelector:@selector(PostProcessing:) withObject:nil afterDelay:0.1];
    }
else {
    NSError* perror = [parser parserError];
    NSLog(@"parseFailed. Error %ld at line %ld col %ld:", (long)[perror code], (long)[parser lineNumber], (long)[parser columnNumber]);
    NSLog(@" > %@", [perror localizedDescription]);
    NSLog(@" > %@", [perror localizedFailureReason]);
    }
return;
}

When called by:
FileURL = [NSURL fileURLWithPath:@"/Users/me/Documents/Target.xml"];
[self performSelector:@selector(ParseFile:) withObject:nil afterDelay:0.1];

Returns the following:
Parsing URL: 'file:///Users/me/Documents/Target.xml'
parseFailed. Error 0 at line 0 col 0:
  > (null)
  > (null)

(yes, the file exists).
But when I call it from the following,
NSOpenPanel* panel = [NSOpenPanel openPanel];
panel.canChooseDirectories = YES;
panel.canChooseFiles = YES;
panel.allowsMultipleSelection = NO;
[panel beginWithCompletionHandler:^(NSInteger result) {
    if (result == 1) {
        FileURL = panel.URL;
        NSLog(@"OnFileOpen:  '%@'", FileURL);
        [self performSelector:@selector(ParseFile:) withObject:nil afterDelay:0.1];
        }
    return;
    }];

and select the same file, it works as expected:
OnFileOpen:  'file:///Users/me/Documents/Target.xml'
Parsing URL: 'file:///Users/me/Documents/Target.xml'
parse successful.

WTF is the difference?


text:
Q: WAMP - Remove localhost from project URL The URLs of my projects in WAMP are not resolving as I'd expect. For example, I'd expect the project in the folder c:\wamp\www\project1 to have the URL http://project1/, but it actually has the URL http://localhost/project1/.
This can cause problems when accessing server variables. How do I fix this?

A: Okay, I had this problem. So, I troubleshooted the problem and traced it to an actual solution, NOT A HACK.
The SOLUTION :

*

*Right-Click WAMP-server icon

*Select WAMP Settings,

*Select (enable) option Add localhost in URL
DONE. The remainder is FYI of how and why.

Note: localhost/myproject.php or myproject.php. Although the solution was already accepted, I saw some posts that got me confused. The accepted solution is based on a single project wrt different server applications, based on the OP's specific question, and how to influence that single project in question. But all the other solutions are hacks and don't really answer the solution to the OP's question, but do bring up a good point about the URL. So, according to the other "solutions", here is how to toggle the localhost reference in the URL. Hence my additional solution added to the mix.

This is a toggle switch.

Troubleshooting Process (no hacking involved):

Let's peek at the index.php

Let's look at the config file. Note the variables and Array?

Here is the array. A variable used earlier. Let's see... Oh, it tells us where and what to do.

As noted in the SOLUTION:

A: You can also look at this answer specially if you are now using WAMPServer 3 or greater, for a simple clikc and go way to create Virtual hosts.
Actually this change was intended by the WAMPServer developers and for a good reason.
There is a problem using the localhost/project1 url and the default WAMPServer DocumentRoot in that it causes problems for some frameworks and WordPress type environments, as well as your own code if you are using code which depends on knowing anything about the server environment.
The correct solution is to create Virtual Hosts for all your projects even those that you store in the \wamp\www\project1 style folders.
When doing that the DocumentRoot is \wamp\www and that is what causes these problems.
These tools expect the DocumentRoot to be the root of the site i.e. \wamp\www\project1 so that when they use PHP variables like
$_SERVER['HTTP_HOST']
$_SERVER['SERVER_NAME']
$_SERVER['DOCUMENT_ROOT']

they get the correct answer i.e. the answer they would get on a real live server hosting just that site.
So using the localhost\project1 style url would mean these variables would return
$_SERVER['HTTP_HOST'] = localhost
$_SERVER['SERVER_NAME'] = localhost
$_SERVER['DOCUMENT_ROOT'] = C:/wamp/www

When they should return
$_SERVER['HTTP_HOST'] = project1
$_SERVER['SERVER_NAME'] = project1
$_SERVER['DOCUMENT_ROOT'] = C:/wamp/www/project1

So what you should do to make the My Projects menu work and reduce your pain in copying sites to live servers is:
Create an entry in the HOSTS file for each project like so and remember to create one for access via IPV4(127.0.0.1) and one for access via IPV6 (::1):-
127.0.0.1 localhost
127.0.0.1 project1

::1 localhost
::1 project1

Remember to refresh the Windows DNS Cache after any change to this file like so :-
Start a command window using Run as Administrator and run :-
net stop Dnscache
net start Dnscache

Now you must create a Virtual Host definition, so edit the \wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhost.conf file ( apache versions may differ )
Delete the default stuff in there the first time you do this. And then create your Virtual Host definitions like so :-
#
# Use name-based virtual hosting.
# This next line is not required if you are using Apache 2.4.x and should be deleted
NameVirtualHost *:80

## should be first so the wamp menu page loads and is the default site
## should also never be changed from only allowing access from the local machine
## for a bit of extra security from casual ip address probing
<VirtualHost *:80>
    DocumentRoot "C:/wamp/www"
    ServerName  localhost
    ServerAlias localhost
    <Directory  "C:/wamp/www">
        AllowOverride All

        <IfDefine APACHE24>
            Require local
        </IfDefine>

        <IfDefine !APACHE24>
            Order Deny,Allow
            Deny from all
            Allow from 127.0.0.1 localhost ::1
        </IfDefine>
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "C:/wamp/www/project1"
    ServerName  project1
    ServerAlias project1
    <Directory  "C:/wamp/www/project1">
        AllowOverride All

        <IfDefine APACHE24>
            Require local
        </IfDefine>

        <IfDefine !APACHE24>
            Order Deny,Allow
            Deny from all
            Allow from 127.0.0.1 localhost ::1
        </IfDefine>

    </Directory>
</VirtualHost>

Now you need one more change, you must uncomment the line in httpd.conf that includes the above file we have just changed. So edit the httpd.conf file, use the wampmanager menus to do this as it ensures you edit the correct file.
Find this line #Include conf/extra/httpd-vhosts.conf and remove the comment # symbol from the beginning of the line like so :-
Include conf/extra/httpd-vhosts.conf

Now of course you will need to restart Apache so that it picks up your configuration changes.
If Apache does not restart, you probably made a mistake in the config, to find out what is wrong try this.
Open a command window and CD into the \wamp\bin\apache\apache2.4.9\bin folder.
Then run this :-
httpd -t

If the error is in httpd.conf or the httpd-vhost.conf files it will tell you the error and also give you the line number to make finding the error very easy.

A: Your wamp seems to be configured to run a website on the normally non-existant domain helloworld.
add:
 127.0.0.1    helloworld

inside this file: c:\windows\system32\drivers\etc\hosts
Make sure you start your text editor with administrator privileges to be able to edit that file.
This will tell your computer that the otherwise non-existant domain helloworld should be resolved to your loop back address.

A: in your www folder open index.php
at line 30 change:
$suppress_localhost to be false
this is should look:
$suppress_localhost = false;

A: In your www folder open index.php at line 30. Here, change $suppress_localhost to be false. So, it is should look:
$suppress_localhost = false;

That was the quickest and easiest fix for me. I'm using 64 bit Wamp.

A: For me was the easiest way go to http://localhost and in wampserver homepage use Add a Virtual Host (Tools section). There is nice and easy form to create alias without any problem (instead console when you using tray icon to create alias). No source edit, just using what wamp offers. Remember refresh DNS after creating of alias. Tested on Win10, WampServer 3.0.6 64bit.

A: Create a virtualhost like RiggsFolly said.
And try to uncomment LoadModule rewrite_module modules/mod_rewrite.so in httpd.conf

A: If your "Your Projects" folder exists in "wamp/www/" and if you can see the localhost home page after starting wampserever correctly, and still you can't access your projects, then simply go to "wamp/www/" folder, open index.php and search for $suppress_localhost and set its value to false. Restart wampserver, go to localhost and try to access your project.

A: HostnameLookups ON not OFF in httpd.conf with DocumentRoot changed or not.
tested in browser for
    $_SERVER['HTTP_HOST']
    $_SERVER['SERVER_NAME']
    $_SERVER['DOCUMENT_ROOT']

A: C:\wamp\www

In index.php
line 338

($suppress_localhost ? 'http://' : '')

change http://   to http://localhost/

A: To do this you can create a virtual host using Add a virtual Host utility under Tools menu on localhost's homepage.
For more info on how to create a virtual host visit : Step by step instructions

A: I think that the easiest and quickest way is to:

Open index.php in your www folder >>> change: $suppress_localhost to
  be false / no.

A: This isn't really an answer per se. It seems that the quickest way of removing a Virtual Host using WAMP is either not create one in the first place or be prepared to uninstall/reinstall it. What is the path to the config file to correct a errant and otherwise not malfunctioning WAMP Server?

A: i also faced same problem after installing new wamp setup on window 7, 64bit.
just change line no. 30
$suppress_localhost = false;
Its work for me.

A: Open index.php in www folder and set
$suppress_localhost = True;===>$suppress_localhost = false;
that is work.

A: You can update "urlAddLocalhost" variable in "wamp64/wampmanager.conf" file to on/off. By default it is "off".
My wamp version is 3.0.6.
urlAddLocalhost = "off"


text:
Q: What is the short for "focusing on the key component of the problem?" I am writing a research essay which contains something like "a policy that focuses on the key component of the problem." I am struggling to come up with a short name for this policy because I need to write it in a section title. I need something like "key-component-focusing policy," but this is still a little long. Could anyone please help me with this? Thanks.

A: "root cause" is often the term used
https://en.wikipedia.org/wiki/Root_cause_analysis

A: If something focuses on the key component of an issue then it is said to focus on the 'crux of the issue'.

Crux: the basic, central, or critical point or feature: 'the crux of the matter'; 'the crux of an argument'.

A synonym of crux is nub.

Nub: the essence; the core: 'the nub of a story'.

Both definitions sourced from thefreedictionary.com

A: You might call it the keystone policy.

a central cohesive source of support and stability

... which would indicate without this core, central, primary, main, critical, etc. policy, then the other policies would have little effect and everything would fall to pieces.


text:
Q: Accessing Macro enabled file using macro I have macro enabled Excel files and I want to consolidate the values from these files into a new file. I wrote the following macro, which navigates to the specific cells in each file and sums it up into a new consolidated file.
Sub SumWB()
  Dim Arr(2) As Long, MyWB As Workbook, fStr As String
  Const Folder = "C:\Users\user123\Downloads\New folder\"
  file = Dir(Folder)
  While (file <> "")

    If file <> "Consolidated.xlsm" Then
       Set MyWB = Workbooks.Open(Folder & file, , True)
       ThisWorkbook.Sheets(2).Range("B4") = Arr(0) + MyWB.Sheets(1).Range("B4").Value
       ThisWorkbook.Sheets(2).Range("C4") = Arr(0) + MyWB.Sheets(1).Range("C4").Value
       ThisWorkbook.Sheets(2).Range("D4") = Arr(0) + MyWB.Sheets(1).Range("D4").Value
       ThisWorkbook.Sheets(2).Range("E4") = Arr(0) + MyWB.Sheets(1).Range("E4").Value
       ThisWorkbook.Sheets(2).Range("F4") = Arr(0) + MyWB.Sheets(1).Range("F4").Value
       ThisWorkbook.Sheets(2).Range("G4") = Arr(0) + MyWB.Sheets(1).Range("G4").Value
       ThisWorkbook.Sheets(2).Range("H4") = Arr(0) + MyWB.Sheets(1).Range("H4").Value
       ThisWorkbook.Sheets(2).Range("I4") = Arr(0) + MyWB.Sheets(1).Range("I4").Value
       ThisWorkbook.Sheets(2).Range("J4") = Arr(0) + MyWB.Sheets(1).Range("J4").Value
       ThisWorkbook.Sheets(2).Range("K4") = Arr(0) + MyWB.Sheets(1).Range("K4").Value
       ThisWorkbook.Sheets(2).Range("L4") = Arr(0) + MyWB.Sheets(1).Range("L4").Value
       ThisWorkbook.Sheets(2).Range("M4") = Arr(0) + MyWB.Sheets(1).Range("M4").Value
       ThisWorkbook.Sheets(2).Range("N4") = Arr(0) + MyWB.Sheets(1).Range("N4").Value
       MyWB.Save
       MyWB.Close
    End If
    file = Dir
  Wend

End Sub

I get Run time error '13' : Type Mismatch. The error points towards the Range("C4") line.
Another problem is, once the macro enabled file is opened, while saving it, "the file is a read only. To save a copy, click OK, then give the workbook a new name in the Save as dialog box". Which defeats the purpose of automating the entire process. Because I didn't want to manually open and close all these files. Is there a way I can avoid this?

A: If you're just pulling info out of the files, I'm not sure why you would need to save them.  Since you're opening them read only, that prevents you from saving and generates that message.  I would just remove the myWB.Save line.  If it still ends up prompting to save changes, replace myWB.Close with myWB.Close(False) to close without saving changes.
Regarding the type mismatch, is it possible that the value from the workbook is not a number?  (adding 5 + "5 " will result in a type mismatch instead of 10)


text:
Q: re.findall and regex I need to get the names of something like this content:

orense

toledo

sevilla

but with this code:
names = []
matches = re.findall(r'''<a\stitle="(?P<title>[^">]+)"\sname="(?P<name>[^">]+)">''',content, re.VERBOSE)
for (title, name) in matches:
    if title == name:
        names.append(title)
return names

...I get names=[ ]; what is wrong?.  Thanks.

A: Uh, well obviously, in your sample text, name comes before title, and in your regex, title is expected before name. This is precisely the reason (or one of them) why you should be using an HTML parser instead. Try BeautifulSoup for example.
If you insist on regex, just turn the parameters around (and make sure that you'll never get those attributes in a different order, and never any other attributes than those):
names = []
matches = re.findall(r'''<a\sname="(?P<name>[^">]+)"\stitle="(?P<title>[^">]+)">''',content, re.VERBOSE)
for (name, title) in matches:
    if title == name:
        names.append(title)

Result:
>>> names
['blu', 'bla', 'blo']


text:
Q: Are the new users going through the FAQ of SO? Most of new users, even existing users are not considering FAQ. Making of reputation does matter for some users here. But, the scope of SO is not only that.
So, What action should be taken into consideration for the new users must take a look at FAQ ?

A: You can answer your own question. Why didn't you read the FAQ?

If you want to talk about the site
  itself, please don't do it here. Visit
  our meta-discussion site where you can
  talk about things like what questions
  are appropriate, what tags we should
  use, suggest a feature, or generally
  discuss how Stack Overflow works.

A: Noone is required to read the FAQ. You end up in the FAQ if you ask an unrelated question and users link to it, or if you are curious about the little link in the top row. Nowadays noone, with respect to those who do, reads the manual until something goes wrong.
Actually, it's almost better if you don't have to read the FAQ at all and instead find the site so intuitively to use that having questions like learning about how the reputation system works or how you can ask a question is already answered before you read about it.
Perhaps instead of making users read the FAQ, we can focus on why users don't follow the FAQ in the first place, and discuss improvements on the part on the site that users find dubious in regards to the topics discussed in the FAQ.

A: How about knowing which type of Questions belong here

A: From my observations, no.
Why? Well, duh: users don't read. "FAQ? What FAQ?"
Then you show them the condensed FAQ before posting, and you require them to check a box saying "yeah, I've read that". I imagine this internal monologue happens: "It's a bird! It's a plane! It's a wall of text spanning the entire screen! Quickly, what do I click to make it go away?!?" (it's probably more like "TL;DR, whatever.[click click]")


text:
Q: $C^1$ function is a subset of Sobolev Space $H^1$ In Brezis' book (chapter 8, section 2), he mentioned that a continuous function on $[0,1]$ that is piecewise $C^1$ on $[0,1]$ belongs to $H^1(0,1)$.
Shouldn't we restrict to $C(0,1)$? or because every element in $H^1$ is an equivalent class of $L^2(0,1)$ and we perform restriction on the $C[0,1]$ to $C(0,1)$, so the end point $0,1$ does not matter here?

A: Note that $C^1(0,1)$ is a larger space than $C^1[0,1]$, since the map $f\mapsto f|_{(0,1)}$ is injective, so if you could say that $C^1(0,1)$ is a subspace of $H^1(0,1)$, you'd be in the clear. Note, however, that not all $C^1$ functions on $(0,1)$ admit $L^2$derivatives. Indeed, take any function $g\in (C(0,1)\cap L^1(0,1))\setminus L^2(0,1)$ and consider $f(x)=\int_0^x g(t)\textrm{d}t$.
So what we really need is some assurance that the classical derivatives will also be integrable. This is true for $C^1[0,1]$ functions since it is true for the class of $C^1$ functions on $(0,1)$ with classical derivatives in $L^{\infty}$. Hence, the latter is really the "natural class at play here".


text: Q: Is it possible to detect services that will be restarted after getting killed..? I am trying to make a task killer app. I have seen that many of the running services are Automatically restarted after getting killed. From this post I know that service with START_STICKY are automatically restarted. Is it possible to Identify if a service is set for automatic restart or to return START_STICKY from onStartCommand.?


text:
Q: Git strategy to minimize merge conflicts over multiple repos An external software vendor delivers product updates as complete snapshots as a zip file. In this case it is external-base.zip. Furthermore, it also delivers other zip files that are almost identical, but are localized versions of the software.

Problem
The problem is that I need to keep some modifications to this software, while simultaneously minimize manual merge conflict resolution.

*

*To do so, I first create git repositories ext-base, extLC_EN,
extLC_GE and commit to them each time I recieve a new zip file.

*Next, I push whatever is inside extBase into intBase. When I
create modifications, I add them to intBase. Each time I push from
extBase into intBase, I might risk losing my modifications.

*As I want my modifications also to end up in the localized versions,
I push from intBase into intLC_EN and intLC_GE.
=> So I have to resolve conflicts on intBase, intLC_EN, and intLC_GE each time when those 3 newly updated zip files arrive, all the while the resolutions of these conflicts would be similar.

Considerations

*

*Base and LC-versions have almost the same structure.

*Would git rerere be of any help here?

Question
What strategy could you recommend me to minimize work?

A:
What strategy could you recommend me to minimize work?

Import your vendor snapshots to a single history dag, with a branch structure chosen by you (since the vendor's not supplying ancestry you have a free hand, it's entirely for your convenience). Then maintain your own work as branches on those.

Would git rerere be of any help here?

git rerere was made for this, for easing the task of applying a set of changes when merging histories from … wherever.

For a concrete example of the vendor history you want to construct, let's use this:
  a---b---c-------e    LC_EN  (let's say you somehow didn't import the fourth one)
 /   /   /       /
A---B---C---D---E      external-base perhaps aka master
 \   \   \   \   \
  α---β---γ---δ---ε    LC_GE

with A, B, C etc. snapshots tagged with their vendor revision numbers. Git famously just doesn't care how you do your work, the point is to do it.
That looks about right for the setup you've described.  Your changes are a parallel branch structure, with A' being your changes on the external A base, α' being your A' work applied onto the α base, and so on.  (Sorry for using greek instead of the Georgian alphabet, it's what I know).
Let's say you're up to Din your existing repositories, and you've got the E set of .zips.

Job One is to construct the vendor base history.  Job Two is to construct your patched history. Job Three is to get the new-vendor-release dance down cold.
The thing to understand is that Git finds a repo, and its work tree, index and object db, if you don't tell it explicitly, but you can just tell it.  Say you've got an extracted vendor download that looks exactly like a content snapshot (because it is one), so tell Git that's the work tree you're adding from.
Here's a pretty direct way. Let's start with your existing constructed histories, let's say you're up to D so far and you recorded no d snapshot, hey, it happens.

edit: I'm happy to flesh out the remainder of this but (a) I've got things to do today and the git core commands are offputting to some, and (b) just the details of the mind-that-first step might be enough to set you on the right path.  Ask about any confusing or simply not-clear-enough details and I'll put more work into it.

Job one: construct the desired vendor base history from the snapshots in your existing repositories.  To keep things simple-ish while still providing a little tour of Git's git-r-dun flavor, let's construct a new unified vendor history repo.
git init /path/to/new-vendor-history      # make the unified-vendor-history repo
cd !$                                     # switch to it
mkdir -p .git/objects/info                # set it up to leech off the older histories
printf %s\\n >.git/objects/info/alternates \
   /path/to/old/{extBase,extLC-EN,extLC_GE}/.git/objects

This is quicker and cheaper than adding remotes for all the existing repos and fetching their histories, you'll be weaning yourself off the old-history teat soon enough but for now, just tell Git hey, there's a bunch of objects in these places I'm using for now.
Since you're taking your extBase repo's history verbatim, just take it. You've already told git where to find the objects, the quickest way to point your current branch (the as-yet-unspecified local master) at that history is
git reset -q $(git -C /path/to/old/extBase rev-parse master)  \
                                          # set my master branch to current extBase tip

and now, since for this example you're up to D in your existing repos, your new-vendor-history master looks like
A---B---C---D

because that's what you just reset it to.
So to finish the first job, it's time to construct your vendor localization branches from the existing snapshots. Start the branch off with the existing snapshot and a single parent (I'm using the letters from the commit graph I drew above, sub in the actual hash id's or any other ref git can resolve to those here)
git branch LC_EN A

then to add a merge of the b tree
git update-ref refs/heads/LC_EN $(
        git commit-tree -p LC_EN -p B -m 'your merge message here' b:
        )

and so on for each.  b here is the existing corresponding commit in your extLC_EN repo, the resulting commit, the resulting commit in your new-vendor-base repo is the one I drew as b above.
Do that again for the LC_GE branch and you're done restructuring your already-gitted vendor snapshots. Now you can repack and cut ties:
git repack -ad
rm .git/objects/info/alternates

The only thing left to do to finish converting the vendor snapshots to the new system is to add new snapshots from the downloaded E set of .zips.
( cd ~/down; unzip external-base.zip )        # unpack the new snapshot
git --work-tree ~/down/external-base add .    # add to repo and update index from there
git commit                                    # commit to the current tip

( cd ~/down; unzip external-LC_EN.zip )       # unpack the new snapshot
git --work-tree ~/down/external-LC_EN add .   # add to repo and update index from there
git update-ref refs/heads/LC_EN $(            # commit to a different tip
        git commit-tree -p LC_EN -p master -m 'vendor LC_EN' `git write-tree`
        )

( cd ~/down; unzip external-LC_GE.zip )       # unpack the new snapshot
git --work-tree ~/down/external-LC_GE add .   # add to repo and update index from there
git update-ref refs/heads/LC_GE $(            # commit to a different tip
        git commit-tree -p LC_GE -p master -m 'vendor LC_GE' `git write-tree`
        )

(you probably want to write a little script to factor out the boilerplate and sub the vendor versions into the commit messages, maybe even a repo-local git alias if you're willing to step that carefully through the three-layers-of-quoting minefield, especially since this is the first step in your new-vendor-release dance).

So that's Job One, the heavy lifting, the going-back-and-converting-your-existing-structure-to-a-single-unified-vendor-history work.

Job Two is bringing your patches up to speed with the new system as well.
You could, if you wanted, carry your patches in that same repository.  I'd do it that way, I make separate repos only when (a) I have some concrete use for multiple independent, concurrent work trees or (b) I've got that uh-oh-here's-my-chance-to-really-screw-up-the-refs-namespace feeling and I want a clone I can just abandon if things go south.  But here you're going to have
So let's accumulate your rerere catalog by way of showing how to import existing intXYZ histories in similar fashion.
git config rerere.enabled true                # light auto-rerere
printf %s\\n >.git/objects/info/alternates \
    /path/to/old/int{Base,LC_EN,LC_GE}/.git/objects

Now: rerere works by noticing any new conflicts or resolutions and resolving any old ones in the work tree and index it's run in.  Lighting auto-rerere just means git rerere runs whenever a merge stops with a conflict and whenever you commit the correct results of a conflicted merge, you can run it yourself whenever that's useful.


text:
Q: How to speed up loading audio files in processing I finished networking in arduino and processing.
I use ultrasonic sensor in arduino.
When i keep my hand close enough in arduino ultrasonic sensor, processing gets a information from arduino. And processing load audio file.
Here is the big problem. Processing loading speed is little late.
It is not extremely late. But it doesn't feel like interacting.
I want to speed up only 0.5sec.
Is there have any solution? here is my code.
ETC. I am trying to many different ways. For example i am trying to press button rather than ultrasonic. But still have problem. And try to change delay. But it doesn't work well

<arduino>

int led2=5;
int trigPin2 = 6;
int echoPin2 = 8;
int state;
int val,old_val;
int b=2;
int rate;

void setup()
{

  Serial.begin(9600);
  pinMode(trigPin2,OUTPUT);
  pinMode(echoPin2,INPUT);
   pinMode(led2, OUTPUT);
  state,val,old_val=0;

}

void loop()
{

  long duration, cm;

  digitalWrite(trigPin2,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin2,LOW);

  duration = pulseIn(echoPin2,HIGH);
  cm = microsecondsToCentimeters(duration);

  rate=map(cm,5,200,0,30);
  rate=constrain(rate,0,1);
  val=rate;

   if ((val == 1) && (old_val == 0)){
    state = 1 - state;
    Serial.println(b);///////////////////////////////////////////////////sound load
    old_val = 1;

    delay(10);
  }
old_val = val;

  if (state == 1){
    digitalWrite(led2,LOW);
  } else {
    digitalWrite(led2, HIGH);

  }
}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

<processing>

import ddf.minim.*;
import ddf.minim.signals.*;
import ddf.minim.analysis.*;
import ddf.minim.effects.*;

import processing.serial.*;

import ddf.minim.*;

Minim minim;
AudioPlayer a1;
AudioPlayer a2;
AudioPlayer a3;
AudioPlayer a4;
AudioPlayer mpcard;
//int dia = 0;
int val=0;
int red=0;
int green=0;
int blue=0;
Serial port;
//Serial port2;
color c;
String buffer = "";
String buffer2 = "";

void setup()
{
   minim = new Minim(this);

   a1=minim.loadFile("1.mp3");
   a2=minim.loadFile("dd.mp3");
   a3=minim.loadFile("3.mp3");
   a4=minim.loadFile("4.mp3");
   mpcard=minim.loadFile("card.mp3");
   // a1.loop();
  size(500, 500);
  frameRate(200);
  fill(255);
  println(Serial.list());
  String arduinoPort = Serial.list()[0];
  port =  new Serial(this, arduinoPort, 9600);

}

void draw()
{
  int b;
  background(red,green,blue);
 // ellipse(255, 255, dia, dia);
    b = port.read();
   println(b);
      if(b == 50) {
     println(b);
     a2.play(0);
     }
      else if(b != 2) {
        println(1);
      }
  }


text:
Q: Compute centroid and accuracy I have two points feat_left, feat_right obtained from siamese network and I plotted these points in x,y coordinates as shown below.
Here is the python script
import json
import matplotlib.pyplot as plt
import numpy as np

data = json.load(open('predictions-mnist.txt'))

n=len(data['outputs'].items())
label_list = np.array(range(n))
feat_left = np.random.random((n,2))

count=1

for key,val in data['outputs'].items():
    feat = data['outputs'][key]['feat_left']
    feat_left[count-1] = feat
    key = key.split("/")
    key = int(key[6])
    label_list[count - 1] = key
    count = count + 1

f = plt.figure(figsize=(16,9))

c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff',
     '#ff00ff', '#990000', '#999900', '#009900', '#009999']

for i in range(10):
    plt.plot(feat_left[label_list==i,0].flatten(), feat_left[label_list==i,1].flatten(), '.', c=c[i])
plt.legend(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
plt.grid()
plt.show()

Now I want to calculate the centriod and then purity of each cluster.

A: The centroid is simply the mean:
centorids = np.zeros((10,2), dtype='f4')
for i in xrange(10):
    centroids[i,:] = np.mean( feat_left[label_list==i, :2], axis=0 )

As for accuracy, you can compute the mean square error (distance) from the centroid:
sqerr = np.zeros((10,), dtype='f4')
for i in xrange(10):
    sqerr[i] = np.sum( (feat_left[label_list==i, :2]-centroids[i,:])**2 )

Computing purity:
def compute_cluster_purity(gt_labels, pred_labels):
  """
  Compute purity of predicted labels (pred_labels), given
  the ground-truth labels (gt_labels).

  Assuming gt_labels and pred_labels are both lists of int of length n
  """
  n = len(gt_labels) # number of elements
  assert len(pred_labels) == n
  purity = 0
  for l in set(pred_labels):
    # for predicted label l, what are the gt_labels of this cluster?
    gt = [gt_labels[i] for i, il in enumerate(pred_labels) if il==l]
    # most frequent gt label in this cluster:
    mfgt = max(set(gt), key=gt.count)
    purity += gt.count(mfgt) # count intersection between most frequent ground truth and this cluster
  return float(purity)/n

See this answer for more details on selecting the most frequent label in a cluster.


text:
Q: How to Handle CellForRowAtIndexpath method I had one table view in which I had 15 row in one section.
so when the table view get loaded it shows only first 9 rows, I checked it with method CellForRowAtIndexpath method but I want to get all 15 rows to be get called in this method for the viewload method.
please help me on out.
thanks in advance....

A: it depends how much rows you set from
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

if you have an array then return
[arr count]; as number of rows and if you want static rows then use return 15; in this method

A: You use these method or if you want all your cell on front of first time view then you should decrease the height of the cell using last method.And also check your array how much values he have.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView  numberOfRowsInSection:(NSInteger)section
{
return [Array count];

}
-(UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {
    cell = [[[UITableViewCell alloc]
             initWithStyle:UITableViewCellStyleSubtitle
             reuseIdentifier:CellIdentifier]
            autorelease];
 }
   cell.textLabel.text=[Array objectAtIndex:indexPath.row];

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 20;//use this method for cell height
}


text:
Q: Applescript: Parse from Mail I am looking for an applescript which fetches thru my Mails to get the desired results:
Subject of the E-Mail: Registrierung fuer die Badener Hochzeitstage - 2587 (here I need the number)
Contents of the E-Mail I need are the Name after "Frau/Herr/Firma" until the next "space"
I had an error in my php/mysql code therefor I do not have this in my database, so I need to parse around 400 E-Mails.
tell application "Mail"

set theMessages to message 1 of mailbox "INBOX" of account "Die Badenerhochzeitstage" whose subject begins with "Registrierung fuer"
set theContent to content of theMessages

set someData to paragraphs of theContent
repeat with someData in theContent

    if someData begins with "Firma" then
        set theURL to paragraph of someData
    else
        set theURL to paragraph 10 of theContent -- this works but this line can change weekly
    end if
end repeat

end tell

Here I have tried but as result I just get some lines and not what I wanted.

A: Try this:
   set TID to text item delimiters
set myRecords to {}

set outputFile to quoted form of (POSIX path of ((path to desktop as text) & "LaunchAgent_Alert.txt")) -- represents "MacHD:Users:david:Desktop:result.txt"

tell application "Mail" to set theMessages to every message of mailbox "INBOX" of account "Badener Hochzeitstage" whose subject begins with "Registrierung fuer"

repeat with aMessage in theMessages
   tell application "Mail" to set {mSubject, mContent} to {subject, content} of aMessage
   set AppleScript's text item delimiters to "-"
   set mSubject to text item 2 of mSubject

   set AppleScript's text item delimiters to "Herr/Frau/Firma "
   set mContent to first word of (text item 2 of mContent)

   set end of myRecords to {mSubject & return & mContent & return & return}

end repeat

set myRecords to myRecords as text
do shell script "echo " & myRecords & " > " & outputFile

set text item delimiters to TID

A: Try this...
set theAccount to "Die Badenerhochzeitstage"
set subjectText to "Registrierung fuer"
set subjectSearch to "-"
set contentSearch to "Frau/Herr/Firma"
set theResults to {}

tell application "Mail"
    try
        set theMessages to messages of mailbox "INBOX" of account theAccount whose subject begins with subjectText
        if theMessages is {} then
            display dialog "No Messages were found which begins with:" & return & subjectText buttons {"OK"} default button 1
            return
        end if

        repeat with aMessage in theMessages
            tell aMessage
                set theSubject to subject
                set theContent to content
            end tell
            set theNumber to my getFirstWordAfterSearchText(subjectSearch, theSubject)
            set theWord to my getFirstWordAfterSearchText(contentSearch, theContent)
            set end of theResults to {theNumber, theWord}
        end repeat
    on error theError
        display dialog theError buttons {"OK"} default button 1
        return
    end try
end tell
return theResults

(*============== SUBROUTINES =================*)
on getFirstWordAfterSearchText(searchString, theText)
    try
        set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, searchString}
        set textItems to text items of theText
        set AppleScript's text item delimiters to tids
        return (first word of (item 2 of textItems))
    on error theError
        return ""
    end try
end getFirstWordAfterSearchText


text:
Q: Do I need to run Boost's configure script to build libraries (e.g. graph, test)? If I don't want to install Boost but I want to build one of the libraries (i.e. BGL, for using graphml) is there a way to build the library in a system independent manner without running .configure?

A: The short answer is: it depends.
I'd just try to copy the relevant sources to your project and build them. Boost is fairly good at supporting that sort of thing, as it doesn't rely too much on configure, but rather on compiler-/platform-specific defines to sort out which platform it's being built on.
I suspect that something like BGL would even be a better candidate, while highly platform-dependent code like the threading code wouldn't work as well. Having said that, I know at least one project that successfully copies boost's threading code and spirit into it's own repository, and it works like a charm.
I'd just give it a try and see what happens.


text:
Q: Php duplicate rows on join I have two tables.
One is products and the other is upload where images are stored.
I'm try to get all detail for product by id from table products. In the same query, I'm trying to get all images from upload table where upload.assign_product_id = products.id. The query duplicating product detail for how image product I have but the image show OK. When I use group by products.id, the product detail is not duplicated but the images disappear, leaving only one image.
The sql query is:
SELECT * FROM products
JOIN upload
ON products.id = upload.assign_id
WHERE products.id=$pid

What am I doing wrong?

A: Most probably in your upload table you have more than one image for every product. You can re-size the array after retrieving it where index id will be product. This way you can get one image for every product.
Thanks


text:
Q: How to connect Node.js app properly to Cassandra node? I have two Cassandra nodes hosted on two IPs. Now, when I am connecting to one of those nodes via cassandra-driver in Node.js from Windows, I am getting 'connection timed out' and 'host unreachable' kind of errors. However, I am able to connect to those nodes via CQLSH from outside of their network.
Am I doing something wrong? Here is the sample code.
var cassandra = require('cassandra-driver');

var uuid = require('uuid')
var client = new cassandra.Client({ contactPoints: ['(PUBLIC IP Here) X.X.X.X:9042'], localDataCenter: 'datacenter1', keyspace: 'ksks' });

function getAllPersons() {
    var query = 'SELECT * FROM person';
    return new Promise((resolve, reject) => {
        client.connect(function (err) {
            if (err) return console.error(err);
            else {
                client.execute(query, function (err, result) {
                    if(err)  {
                        reject([])
                    }
                    else {
                        if(result.rows.length) {
                            resolve(result.rows);
                        }
                        else {}
                            reject([])
                    }
                });
            }
        });
     });
}

In the cassandra.yaml, I have these values:
listen_address: 10.0.0.4
native_transport_port: 9042
rpc_address: 10.0.0.4
rpc_port: 9160
api_port: 10000
api_address: 10.0.0.4

What do I need to change? The nodes are working fine and can CQLSH to each other (from remote networks as well).

A: If you are using a public IP to access the cluster remotely your configurations are not correct.
This table might help you figure out the correct IPs in the scylla.yaml:
https://docs.scylladb.com/operating-scylla/procedures/cluster-management/ec2_dc/#ec2-configuration-table
Do NOT use Ec2Snitch unless you are on AWS. The table is just a reference.


text:
Q: Set response headers from angular http interceptor I am trying to set a new header on every http response so the response includes a content-security-policy using the latest version of angular. I have created this http interceptor, and when I go to add to the header I don't get any errors or anything, but nothing actually gets added to the response headers. Here is the code I have for the interceptor. Is there anything that I should change here, or is it not possible to add response headers to every http response from angular.
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { filter, map, tap } from 'rxjs/operators';

@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

      return next.handle(req).pipe(
        filter(event => event instanceof HttpResponse),
        tap((event: HttpResponse<any>) => {
          event.headers.append('content-security-policy', 'some content-security-policy')
        })
      );
      }
    }

A: You can not alter history: The network tab shows what was sent across the network, and you can not retroactively change that.
What an HttpInterceptor can do is change its own copy of the received headers before passing it on to the subscriber.
Also, a content security header is interpreted by the browser before it passes the response to JavaScript.


text:
Q: bison LAC (Lookahead Correction) example I saw LAC but still I can't find any good example or tutorial
 on how to improve syntax errors handling using this mechanism (or any similar way)
any help would be appreciated


text:
Q: Outlook VSTO - determine correct 'email' signature based on user I'm writing an Outlook 2010 add-in with VSTO, one part of which will automatically add the correct email signature to a new AppointmentItem.  The issue I've come across is how to determine which signature is the correct one.  For example, I have 2 email signatures set up in Outlook, which have rules on use based on which address my email is coming from.  How can I access these rules?
My issue is not with finding the signature files, but in applying the correct rules based on the user's settings.  Any ideas?

A: You can access the rules by using the code below. You can loop through them and get the rule type and actions
app is the current instance of the Outlook.Application
Outlook.Rules rules= app.Session.DefaultStore.GetRules();
foreach (Outlook.Rule r in rules)
{

}

A: I ended up solving this by creating a dictionary object with the key being the email address and the value as the filepath:
private Dictionary<string, string> signatureDictionary()
        {
            string sigDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft\Signatures";
            Dictionary<string, string> returnValue = new Dictionary<string,string>();
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook\9375CFF0413111d3B88A00104B2A6676", false);
            string[] str = key.GetSubKeyNames();
            foreach (string s in str)
            {
                Microsoft.Win32.RegistryKey subKey = key.OpenSubKey(s, false);
                if (subKey.GetValue("New Signature") != null)
                {
                    returnValue.Add(System.Text.Encoding.Unicode.GetString(subKey.GetValue("Account Name") as
                        Byte[],0,(subKey.GetValue("Account Name") as Byte[]).Length - 2)
                        , Path.Combine(sigDataDir,System.Text.Encoding.Unicode.GetString(
                        subKey.GetValue("New Signature") as Byte[], 0, (subKey.GetValue("New Signature") as
                        Byte[]).Length - 2) + @".rtf"));
                }
            }
            key.Close();
            return returnValue;
        }

This answer to a similar question initially pointed me in the right direction, and figuring out that the "New Signature" key is only populated when a signature has been set for that account.  Undoubtedly there will be situations where this doesn't work, but it sorts it out for my current issue.  Since I use the WordEditor when I'm editing emails in VSTO I use the RTF files in this function, but there are also .HTM and .TXT files in the same directory so you can use those if you prefer.


text:
Q: how to get document that contain more than collection in xslt? let $stylesheet := "abc.xsl"
let $params := map:map()
let $_ := map:put ($params,"col1","abc")
return
xdmp:xslt-invoke(
            $stylesheet, (), $params,
            <options xmlns="xdmp:eval">
                 <template>a:schema</template>

            </options>)

abc.xsl
<xsl:template name="a:schema">
          <xsl:param name="collection-uri" as="xs:string" select="$col1"/>
          <xsl:apply-templates select="collection($collection-uri)"/>
       </xsl:template>

In this currently ,we are taking all the document ,which is coming in collection "abc".
But I want to add more than one collection in $param map, so that the document which contain ,both collection "abc" and "def"  will comes
for example :
 | Document| collection
|:---------|:----------:|
| Doc1     | abc, def   |
| Doc2     | abc        |
| Doc3     | abc, def   |

it will pick Doc1 and Doc3

A: collection() accepts a sequence of xs:string, but would return any of the documents in either of the collections specified.
If you want only the docs that are in all of the collections specified, you could use cts:search() with a sequence of cts:collection-query() inside of a cts:and-query().
<xsl:template match="/">
  <xsl:param name="collection-uri" as="xs:string*" select="$col1"/>
  <xsl:apply-templates select="cts:search(doc(), cts:and-query(( $collection-uri ! cts:collection-query(.) )))"/>
</xsl:template>

Enable the 1.0-ml dialect, so that you can use the cts built-in functions by adding the following attribute to your xsl:stylesheet element:
xdmp:dialect="1.0-ml"

The $collection-uri param is declared as xs:string, so it will only have one string value. You could change that to be a sequence of strings with either * or + quantifier:
<xsl:param name="collection-uri" as="xs:string*" select="$col1"/>

and then set the collections on the $col1 param:
let $_ := map:put ($params,"col1", ('abc', 'def'))