text:
Q: java caesar cipher code i did caesar cipher code by java it runs but doesnt encrypt anything after user enter the key !
here is my code
public class CaesarCipher
{
    public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

    public static String encrypt(String plainText, int shiftKey)
    {
        plainText = plainText.toLowerCase();
        String cipherText = "";
        for (int i = 0; i < plainText.length(); i++)
        {
            int charPosition = ALPHABET.indexOf(plainText.charAt(i));
            int keyVal = (shiftKey + charPosition) % 26;
            char replaceVal = ALPHABET.charAt(keyVal);
            cipherText += replaceVal;
        }
        return cipherText;
    }

    public static String decrypt(String cipherText, int shiftKey)
    {
        cipherText = cipherText.toLowerCase();
        String plainText = "";
        for (int i = 0; i < cipherText.length(); i++)
        {
            int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
            int keyVal = (charPosition - shiftKey) % 26;
            if (keyVal < 0)
            {
                keyVal = ALPHABET.length() + keyVal;
            }
            char replaceVal = ALPHABET.charAt(keyVal);
            plainText += replaceVal;
        }
        return plainText;
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the String for Encryption: ");
        String message = new String();
        message = sc.next();
        System.out.println(encrypt(message, 3));
        System.out.println(decrypt(encrypt(message, 3), 3));
        sc.close();
    }
}

run:
Enter The Plain Text:
Reem LA
Enter The Key:
2
The Cipher Text

A: Try this:
import java.util.*;

public class CaesarCipher
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText, int shiftKey)
{
    plainText = plainText.toLowerCase();
    String cipherText = "";
    for (int i = 0; i < plainText.length(); i++)
    {
        char replaceVal = plainText.charAt(i);
        int charPosition = ALPHABET.indexOf(replaceVal);
        if(charPosition != -1) {
            int keyVal = (shiftKey + charPosition) % 26;
            replaceVal = ALPHABET.charAt(keyVal);
        }

        cipherText += replaceVal;
    }
    return cipherText;
}

public static String decrypt(String cipherText, int shiftKey)
{
    cipherText = cipherText.toLowerCase();
    String plainText = "";
    for (int i = 0; i < cipherText.length(); i++)
    {
        char replaceVal = cipherText.charAt(i);
        int charPosition = ALPHABET.indexOf(replaceVal);
        if(charPosition != -1) {
            int keyVal = (charPosition - shiftKey) % 26;
            if (keyVal < 0) {
                keyVal = ALPHABET.length() + keyVal;
            }
            replaceVal = ALPHABET.charAt(keyVal);
        }
        plainText += replaceVal;
    }
    return plainText;
}

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the String for Encryption: ");
    String message = new String();
    message = sc.nextLine();
    System.out.println(encrypt(message, 3));
    System.out.println(decrypt(encrypt(message, 3), 3));
    sc.close();
}
}

This will work for all alphabetical strings... But as per your program, this will convert the original message to lowercase. So this is not pure encryption since your program is case insensitive.
If you want your program to be case sensitive, here is the program:
import java.util.*;

public class CaesarCipher
{
public static final String ALPHABET_LOWER = "abcdefghijklmnopqrstuvwxyz";
public static final String ALPHABET_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String encrypt(String plainText, int shiftKey)
{
    String cipherText = "";
    for (int i = 0; i < plainText.length(); i++)
    {
        int charPosition = -1;
        char replaceVal;
        int keyVal = -1;
        char val = plainText.charAt(i);
        System.out.println(val);
        if(Character.isUpperCase(val)) {
            charPosition = ALPHABET_UPPER.indexOf(val);
            if(charPosition != -1) {
                keyVal = (shiftKey + charPosition) % 26;
                replaceVal = ALPHABET_UPPER.charAt(keyVal);
            } else {
                replaceVal = plainText.charAt(i);
            }
        } else {
            charPosition = ALPHABET_LOWER.indexOf(val);
            if(charPosition != -1) {
                keyVal = (shiftKey + charPosition) % 26;
                replaceVal = ALPHABET_LOWER.charAt(keyVal);
            } else {
                replaceVal = plainText.charAt(i);
            }
        }
        System.out.println("Cipher: "+cipherText);
        cipherText += replaceVal;
    }
    return cipherText;
}

public static String decrypt(String cipherText, int shiftKey)
{
    String plainText = "";
    for (int i = 0; i < cipherText.length(); i++)
    {
        int charPosition = -1;
        char replaceVal;
        int keyVal = -1;
        char val = cipherText.charAt(i);

        if(Character.isUpperCase(val)) {
            charPosition = ALPHABET_UPPER.indexOf(val);
            if(charPosition != -1) {
                keyVal = (charPosition - shiftKey) % 26;
                if (keyVal < 0) {
                    keyVal = ALPHABET_UPPER.length() + keyVal;
                }
                replaceVal = ALPHABET_UPPER.charAt(keyVal);
            } else {
                replaceVal = cipherText.charAt(i);
            }
        } else {
            charPosition = ALPHABET_LOWER.indexOf(val);
            if(charPosition != -1) {
                keyVal = (charPosition - shiftKey) % 26;
                if (keyVal < 0) {
                    keyVal = ALPHABET_LOWER.length() + keyVal;
                }
                replaceVal = ALPHABET_LOWER.charAt(keyVal);
            } else {
                replaceVal = cipherText.charAt(i);
            }
        }
        plainText += replaceVal;
    }
    return plainText;
}

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the String for Encryption: ");
    String message = new String();
    message = sc.nextLine();
    System.out.println(encrypt(message, 3));
    System.out.println(decrypt(encrypt(message, 3), 3));
    sc.close();
}
}

Hope this gives some idea. All the best.

A: Using indexOf is not very efficient... You can do integer arithmetic on char values to get their indices.
I included comments in the code to explain more, but this is what I came up with.
public class CaesarCipher {
    // Rotate a character k-positions
    public static char cipher(char c, int k) {
        // declare some helping constants
        final int alphaLength = 26;
        final char asciiShift = Character.isUpperCase(c) ? 'A' : 'a';
        final int cipherShift = k % alphaLength;

        // shift down to 0..25 for a..z
        char shifted = (char) (c - asciiShift);
        // rotate the letter and handle "wrap-around" for negatives and value >= 26
        shifted = (char) ((shifted + cipherShift + alphaLength) % alphaLength);
        // shift back up to english characters
        return (char) (shifted + asciiShift);
    }

    // Rotate a string k-positions
    public static String cipher(String s, int k) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            sb.append(cipher(s.charAt(i), k));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String password;
        int key;

        System.out.print("Please enter a password: ");
        password = keyboard.nextLine();

        do {
            System.out.print("Please enter a key between 1-25: ");
            key = keyboard.nextInt();

            if (key < 1 || key > 25) {
                System.out.printf(" The key must be between 1 and 25, you entered %d.\n", key);
            }
        } while (key < 1 || key > 25);

        System.out.println("Password:\t" + password);
        String encryption = cipher(password, key);
        System.out.println("Encrypted:\t" + encryption);
        System.out.println("Decrypted:\t" + cipher(encryption, -key));

    }
}

The output should be something like
Please enter a password: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Please enter a key between 1-25: 1
Password:   ABCDEFGHIJKLMNOPQRSTUVWXYZ
Encrypted:  BCDEFGHIJKLMNOPQRSTUVWXYZA
Decrypted:  ABCDEFGHIJKLMNOPQRSTUVWXYZ

A: This is probably the easiest way to do it and the most easy to understand:
import java.util.*;
public class CeaserCipher {
   public static void main (String [] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Type your message ");
      String message = input.nextLine().toUpperCase();
      System.out.print("Set Encoding Key ");
      int key = input.nextInt() % 26;
      for (int i = 0; i < message.length(); i++) {
         char c = message.charAt(i);
         if (c <= 64 || c >= 91) {
            c += 0;
          }
         else {
            c += key;
            if (c >= 91) {
               c -= 26;
            }
         }
         System.out.print(c);
      }
   }
}

A: private static final int ALPHABET_SIZE = 26;

public static String encryptOrDecrypt(String str, int rotateBy, boolean isEncryption) {
    rotateBy = rotateBy % 26;
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        char temp = str.charAt(i);
        temp = rotate(temp, rotateBy,isEncryption);
        result.append(temp);
    }
    return result.toString();
}
private static char rotate(char c, int rotateBy,boolean isEncryption) {
    int start=0;
    int end =0;
    if (isLowerCase(c)) {
        start='a';
        end = 'z';
    } else if (isUpperCase(c)) {
        start='A';
        end = 'Z';
    }else {
        return c;
    }
    if (isEncryption){
        c += rotateBy;
    }else {
        c -= rotateBy;
    }

    if (c < start) {
        return (char) (c + ALPHABET_SIZE);
    }
    if (c > end) {
        return (char) (c - ALPHABET_SIZE);
    }
    return c;
}
public static void main(String args[]) {
    String planeText= "TrilokiNathYadav";
    System.out.println("Plane Text : "+planeText);
    String encrypted =encryptOrDecrypt(planeText,2,true);
    System.out.println("Encrypted : "+encrypted);
    String decrypted = encryptOrDecrypt(encrypted,2,false);
    System.out.println("Decrypted : "+decrypted);
}


text:
Q: Pandas make comma separated key value output into a tabular form I have below output which is a kind of comma separated Key value pair, list where i want all the key to become Column Name and values will become column values, i am wondering if this can be done in pandas.
Hostname: dpc8584.test.domain.com, bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LFCPriInt:  0, LFCSecInt:  0
Hostname: dpc8585.test.domain.com, bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LFCPriInt:  0, LFCSecInt:  0
Hostname: dpc8586.test.domain.com, bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LFCPriInt:  0, LFCSecInt:  0
Hostname: dpc8587.test.domain.com, bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LFCPriInt:  0, LFCSecInt:  0
Hostname: dpc8588.test.domain.com, bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LFCPriInt:  0, LFCSecInt:  0
Hostname: dpc8589.test.domain.com, bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LFCPriInt:  0, LFCSecInt:  0
Hostname: dpc8590.test.domain.com, bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LFCPriInt:  0, LFCSecInt:  0

My expected output will be:

A: My two cents:
With a txt looking like this...

import pandas as pd
import re

df = pd.read_csv('log_to_df.txt', header=None)
df

pattern = re.compile(r'((.+?): )(.+)')
cols = []
for col in df.columns:
    temp = pattern.match(df[col][0])
    cols.append(temp[2])
    df[col] = df[col].str.replace(temp[1], '', regex=True)
df.columns = cols
df

If the column headers change just tweak the line with the regex in it...
((.+?): )(.+)')

...to match something else

A: my approach
You need read your.csv or .txt file:
df = pd.read_csv('/path/textfile.csv',header=None)

                                   0                1                      2  \
0  Hostname: dpc8584.test.domain.com   bond0: OK (up)   Active Slave: ens3f0
1  Hostname: dpc8585.test.domain.com   bond0: OK (up)   Active Slave: ens3f0
2  Hostname: dpc8586.test.domain.com   bond0: OK (up)   Active Slave: ens3f0
3  Hostname: dpc8587.test.domain.com   bond0: OK (up)   Active Slave: ens3f0
4  Hostname: dpc8588.test.domain.com   bond0: OK (up)   Active Slave: ens3f0
5  Hostname: dpc8589.test.domain.com   bond0: OK (up)   Active Slave: ens3f0
6  Hostname: dpc8590.test.domain.com   bond0: OK (up)   Active Slave: ens3f0

                        3                       4               5  \
0   PriSlave: ens3f0 (up)   SecSlave: ens3f1 (up)   LFCPriInt:  0
1   PriSlave: ens3f0 (up)   SecSlave: ens3f1 (up)   LFCPriInt:  0
2   PriSlave: ens3f0 (up)   SecSlave: ens3f1 (up)   LFCPriInt:  0
3   PriSlave: ens3f0 (up)   SecSlave: ens3f1 (up)   LFCPriInt:  0
4   PriSlave: ens3f0 (up)   SecSlave: ens3f1 (up)   LFCPriInt:  0
5   PriSlave: ens3f0 (up)   SecSlave: ens3f1 (up)   LFCPriInt:  0
6   PriSlave: ens3f0 (up)   SecSlave: ens3f1 (up)   LFCPriInt:  0

                6
0   LFCSecInt:  0
1   LFCSecInt:  0
2   LFCSecInt:  0
3   LFCSecInt:  0
4   LFCSecInt:  0
5   LFCSecInt:  0
6   LFCSecInt:  0

Then we can do:
df2 = df.stack().str.split(':',expand=True)
df2 = df2.rename(columns={0:'columns'}) #neccesary here
new_df = df2.pivot_table(index=df2.index.get_level_values(0),
                         columns='columns',
                         values=1,
                         aggfunc='first')
print(new_df)

columns  Active Slave  LFCPriInt  LFCSecInt      PriSlave      SecSlave  \
0              ens3f0          0          0   ens3f0 (up)   ens3f1 (up)
1              ens3f0          0          0   ens3f0 (up)   ens3f1 (up)
2              ens3f0          0          0   ens3f0 (up)   ens3f1 (up)
3              ens3f0          0          0   ens3f0 (up)   ens3f1 (up)
4              ens3f0          0          0   ens3f0 (up)   ens3f1 (up)
5              ens3f0          0          0   ens3f0 (up)   ens3f1 (up)
6              ens3f0          0          0   ens3f0 (up)   ens3f1 (up)

columns     bond0                  Hostname
0         OK (up)   dpc8584.test.domain.com
1         OK (up)   dpc8585.test.domain.com
2         OK (up)   dpc8586.test.domain.com
3         OK (up)   dpc8587.test.domain.com
4         OK (up)   dpc8588.test.domain.com
5         OK (up)   dpc8589.test.domain.com
6         OK (up)   dpc8590.test.domain.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regular expression taking into account next character I am trying to match our order numbers (always in the format ABC + 6 or 7 digits). e.g ABC123456 or ABC1234567
I have:
preg_match_all("/(ABC)([0-9]{6}|[0-9]{7})/", $content, $matches);

But if somebody quotes to us ABC12345678 then it is extracting ABC1234567. This is incorrect. Instead no match should be found by preg_match_all.
How can I amend the regex to say "All occurrences of ABC followed by 6 or 7 digits. Ignore anything where the character after the 7th character is a number"

A: You need a negative lookahead:
preg_match_all("/(ABC)([0-9]{6}|[0-9]{7})(?![0-9])/", $content, $matches);

This will match ABC1234567, with anything after the 7 except a digit.
The part before (?![0-9]) will match only if the part inside of (?!...) doesn't match. So if you don't want a letter after the 7 neither, do this:
preg_match_all("/(ABC)([0-9]{6}|[0-9]{7})(?![0-9a-zA-Z])/", $content, $matches);

If you don't want _ characters either, do this:
preg_match_all("/(ABC)([0-9]{6}|[0-9]{7})(?![0-9a-zA-Z_])/", $content, $matches);

Which is actually equivalent to using \b:
preg_match_all("/(ABC)([0-9]{6}|[0-9]{7})\b/", $content, $matches);

A: *

*You can combine 6 and 7 digits checks into 1

*Use word boundaries or input start/end anchors

Use this regex:
/\b(ABC)[0-9]{6,7}\b/

OR
/^(ABC)[0-9]{6,7}$/

A: Try adding $, like:
preg_match_all("/(ABC)([0-9]{6}|[0-9]{7})$/", $content, $matches);

A: Specify the end of word as
preg_match_all("/(ABC)([0-9]{6}|[0-9]{7}\>)/", $content, $matches);

A: You can also use this patterm:
^(ABC)\d{6,7}$

Here
^     = Starts with
(ABC) = ABC
\d    = followed by digits between 0-9 inclusive.
{6,7} = 6 or 7 times
$     = till the end of the order number


text:
Q: Cannot change power button or lid close action I have a Samsung 900x laptop and I want to change it so that when I close the lid, nothing happens (I often close the lid to carry it somewhere 10 seconds away, and by putting it into suspend it cancels any active downloads/etc).
Easy, right? Go to Power Options and change it there; just like on every other laptop in the world.
Not so fast:

Saywhat?! That message only shows up for the nodes for Lid Close Action, Power Button and Sleep Button. I can change every other setting except for those three.
I'm definately an Administrator on the computer, and I've googled the error and found dozens of hits on other crappy forums, but of course nothing on those worked (otherwise, I wouldn't be here). And as ususal the "Why can't..." hyperlink gives no useful infomation what so ever (just a generic Help document).
So - how can I change what closing the lid does? I will modify the registry directly if I have to.

A: I had the same problem and just found the answer here. http://answers.yahoo.com/question/index?qid=20110328121602AAFxtHH It worked for me. =]
There's this little program that by doing its work, cancels our options on what closing the lid etc do. It's called Fast Start. Run it, turn it off and now you have a fuller command of your laptop. Hope it works for you as well.

A: My Samsung N150 has a program called Fast Booting SW that seems to be responsible for this problem.  Disabling it solves the problem for me.

A: Please change the plan right now you are having Samsung Optimized and it is like a default setting. You can change it then you will be able to change those settings. I hope this will work if it doesnt then please provide more info.

A: Just right click on start menu and click properties and then in the "start menu" tab you will find Power button option.
Change it there and it changes.
I don't why it started doing that?
I tried changing it to sleep in power options like we normally do but for some reason the setting here overrides it.
Earlier by power button was set to sleep. It automatically went to Hibernate.
After googling I decided to go and see if there were option in the start menu and there was!!
I don't why this happened but here is the solution
P.S. Now I remember it happened after the latest Windows Update

A: I also have a Samsung laptop and wanted to change what happens when I close the lid because I needed to run with an external monitor and keyboard. I wanted to keep the laptop ON when it's closed, but the default was SLEEP when it's closed.  I, too, found "Access is denied" and useless WinOS help information when I accessed Power Options by right-clicking on the Battery icon > Power Options > Choose what closing the lid does.
After reading this, I found that "little program" (Samsung "Fast Start") , Ran it, turned it OFF and found full command options were restored when I reloaded the Power Options panel.


text:
Q: HTTP Content-Length incorrect size served? I'm serving some files locally via HTTP using QTcpSocket. My problem is that only wget downloads the file properly, firefox adds four extra bytes to the end. This is the header I send:
  HTTP/1.0 200 Ok
  Content-Length: 382917;
  Content-Type: application/x-shockwave-flash;
  Content-Disposition: attachment; filename=file.swf;

This is the code used to send the response:
        QTextStream os(socket);
        os.setAutoDetectUnicode(true);

        QString name = tokens[1].right(tokens[1].length() - 1);
        QString resname = ":/" + name; // the served file is a Qt resource
        QFile f(resname); f.open(QIODevice::ReadOnly);

        os << "HTTP/1.0 200 Ok\r\n" <<
              "Content-Length: " << f.size() << ";\r\n" <<
              "Content-Type: application/x-shockwave-flash;\r\n" <<
              "Content-Disposition: attachment; filename=" << name <<
              ";\r\n\r\n";

        os.flush();

        QDataStream ds(socket);

        ds << f.readAll();

        socket->close();

        if (socket->state() == QTcpSocket::UnconnectedState)
        {
            delete socket;
        }

As I stated above, wget gets it right and downloads the file properly. The problem is that Firefox (and my target application, a Flash ActiveX instance) don't.
The four extra bytes are always the same: 4E E9 A5 F4
Hex dump http://www.freeimagehosting.net/uploads/a5711fd7af.gif
My question is what am I doing wrong, and what should I change to get it right? Thanks in advance.

A: You should not be terminating the lines with semicolons. At first glance this seems like the most likely problem.
I don't know much about QDataStream (or QT in general), however a quick look at the QDataStream documentation mentions operator<<(char const*). If you are passing a null terminated string to QDataStream, you are almost certainly going over the end of the final buffer.
Try using QDataStream::writeRawBytes().
If you remove the semicolons, then the clients should at least read the correct number of bytes for the response and ignore the last four bytes.
I'd leave out "Content-Disposition" too. That's a MIME thing, not an HTTP thing.

A: So I found the whole solution to the question, and I think someone might need it, so here it is:
The first problem were the four extra bytes. The reason for this is that according to the QDataStream documentation, "each item written to the stream is written in a predefined binary format that varies depending on the item's type". And as QFile.readAll() returned a QByteArray, QDataStream.operator<< wrote that object in the following format:

*

*If the byte array is null: 0xFFFFFFFF (quint32)

*Otherwise: the array size (quint32) followed by the array bytes, i.e. size bytes

(link)
So, the four extra bytes were the four bytes of quint32 that denoted the array size.
The solution, according to janm's answer was to use the writeRawBytes() function.
QDataStream ds(socket);
ds.writeRawData(f.readAll().data(), f.size());

Wget probably got it right the first time because it strictly enforces the Content-Length field of the HTTP header, while apparently firefox does not.
The second problem was that despite the right header and working sockets, the flashplayer did not display the desired content at all. I experimented with various fields to make it work, and noticed that by uploading to a real server, it works all right. I copied the header from server, and tadaa! it works. This is the header:
  HTTP/1.1 200 OK
  Server: Apache/2.2.15 (Fedora)
  Accept-Ranges: bytes
  Content-Length: 382917
  Content-Type: application/x-shockwave-flash
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive

At first I only tried setting the version to 1.1, but that didn't help. Probably it's the keepalive thing, but honestly, I don't care at all as long as it works :).

A: There shouldn't be any semicolons at the end of the line.


text:
Q: DocuSign Dynamics CrmWorkflow automate half of the process allowing the user to complete it manually how can I create a workflow in Dynamics CRM Online that creates the envelope, add the recipients and then show the DocuSign web resource so the user can choose the document to use in the envelope and apply any available templates, and then click send?
I am sure it will need to be a custom workflow, not 100% sure how to show the DocuSign frame after the envelope creation. Can I use the existing web resource available after the DS solution installation, or would I need to create my own?

A: See the DocuSign for Microsoft Dynamics guide here
See DocuSign Custom Activities on page 21.


text:
Q: How to connect to Database from NUnit Test project? I am new to NUnit testing for asp.net mvc web app, project I want to test using entity frame work to connect with the database, from the test project I need to connect to the same data base of the project which I want to test .
controller which I am testing looks like as below.
public class EXController : Controller
{
    private readonly AppDbContext _context;
    private readonly CommonDbContext _commonContext;

    public EXController(CommonDbContext commonContext, AppDbContext context)
    {
        _commonContext = commonContext;
        _context = context;
    }

     public ActionResult Index()
    {
    // some simple code.
    }
}

I am trying to write NUnit tests as below:
In references section of the test project I added Project under testing as dll, I am able to
access all the classes from the project I want to test.
CommonDbContext and AppDbContext are the classes which I am using in the code under testing to connect with the data base, these classes takes argument as the connectionstring.
so I am passing the connection string to these classes to connect with the data base from Nunit test project.
I am trying to connect to the data base in NUnit test project, using following connection string.
CommonDbContext objcdb = new CommonDbContext("metadata =\"res://*/Data.CommonDbModel.CommonDbModel.csdl|res://*/Data.CommonDbModel.CommonDbModel.ssdl|res://*/Data.CommonDbModel.CommonDbModel.msl\";provider=MySql.Data.MySqlClient;provider connection string=\"server=servername;database=databasename;integratedsecurity=False;user id=userid;password=password");

AppDbContext Objadb = new AppDbContext("metadata = \"res://*/Data.AppDbModel.AppDbModel.csdl|res://*/Data.AppDbModel.AppDbModel.ssdl|res://*/Data.AppDbModel.AppDbModel.msl\";provider=MySql.Data.MySqlClient;provider connection string=\"server=servername;database=databasename;integratedsecurity=False;user id=userid;password=password");

// creating instance for the contrller I want to test
ExController obController = new CLINController(objcdb, Objadb);

I am getting below exception when I am trying to connect with the database from NUnit test project.
Exception:
An exception of type 'System.ArgumentException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 164.

**Stack Trace:**
   at System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, String& keyname, String& keyvalue)
   at System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions.ParseInternal(IDictionary`2 parsetable, String connectionString, IList`1 validKeywords)
   at System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions..ctor(String connectionString, IList`1 validKeywords)
   at System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
   at System.Data.Entity.Core.EntityClient.EntityConnection..ctor(String connectionString)
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
   at BidMaster.Web.Infrastructure.CurrentUser.get_User() in D:\BWM_sprint3_newcopy\BidMaster.Web\BidMaster.Web\Infrastructure\CurrentUser.cs:line 30
   at BidMaster.Web.Controllers.CLINController.Index(Nullable`1 id) in D:\BWM_sprint3_newcopy\BidMaster.Web\BidMaster.Web\Controllers\CLINController.cs:line 51
   at BidMaster.Test.Controllers.CLINControllerTests.IndexTest() in D:\BWM_sprint3_newcopy\BidMaster.Test\BidMaster.Test\Controllers\CLINControllerTests.cs:line 47

Any thing wrong with the connectin string which I am using? Please help me, please explain how to connect with the database from Unit test project. I am new to testing.

A: Unit tests should never go past a certain scope (the unit, generally a class). In other words, you shouldn't touch the DB - that's already system (integration testing).
Your unit test should rather just test the logic inside that Index method (for example), whilst mocking the layer handling the DB calls.
Something along these lines (using RhinoMocks or other mocking tool):
_commonDbContext = MockRepository.GenerateMock<CommonDbContext>();
_appDbContext = MockRepository.GenerateMock<AppDbContext>();

ExController obController = new CLINController(_commonDbContext, _appDbContext );

Otherwise, if you want to go down the system test path, you would have to issue a request towards the url (port number & all) your service resides, not through a direct reference to it.
Only wrote this as an answer because it's too long for a comment, you'll need to provide more details regarding the method you're trying to test if you need specific answers.


text:
Q: Symfony2 Form Gives Catchable Error About FormView This is really strange, and it happened after updating a Twig template:
The Controller Part
    $registration = new Registration();
    $form = $this->createForm(new RegistrationType(), $registration, array(
        'action' => $this->generateUrl('account_create'),
    ));

    return $this->render(
        'AcmeCommonBundle:Security:register.html.twig',
        array(
            'form' => $form->createView(),
            'contentBackColor' => 'canvasGreen'
            )
    );

The Template Part
{{ form_start(form) }}
    {{ form_errors(form) }}

All Fields Are Required

        {{ form_label(form.firstname, "First Name") }}
        {{ form_widget(form.firstname) }}

        {{ form_errors(form.firstname) }}

        {{ form_label(form.lastname, "Last Name") }}
        {{ form_widget(form.lastname) }}

        {{ form_errors(form.lastname) }}

        {{ form_label(form.username, "Username") }}
        {{ form_widget(form.username) }}

        {{ form_errors(form.username) }}

        {{ form_label(form.email, "Email") }}
        {{ form_widget(form.email) }}

        {{ form_errors(form.email) }}

        {{ form_label(form.password, "Password") }}
        {{ form_widget(form.password) }}

        {{ form_errors(form.password) }}

        {{ form_label(form.confirm, "Confirm Password") }}
        {{ form_widget(form.confirm) }}

        {{ form_errors(form.confirm) }}

        {{ form_label(form.terms, "Terms & Conditions") }}
        {{ form_widget(form.terms) }}

        {{ form_errors(form.terms) }}

{{ form_end(form) }}

The Error
Argument 1 passed to Symfony\Component\Form\FormRenderer::searchAndRenderBlock() must be an instance of Symfony\Component\Form\FormView, null given

As you can clearly see, I am indeed rendering the FormView, and the fact that it's null would lead me to believe that this is related to the RegistrationType() class, but nothing changed there, only in the template to render?

A: Alright, this was really specific and I figured it out, so I thought I would update here for anyone that finds this on Google.
The problem was that my original implementation of the form looked like this in twig:
{{ form(form) }}

What this does is go through the whole form variable and display everything that there was to display.
The problem was that my view variables were wrong. This was because the RegistrationType() object added another UserType() object as a user field like this:
->add('user', new UserType())

This meant that the call:
{{ form_label(form.firstname, "First Name") }}

Should have been:
{{ form_label(form.user.firstname, "First Name") }}

The main reason I didn't catch this error is because the errors Twig gives didn't tell me which form call it failed on, and I automatically assumed it was the first one, {{ form_start(form) }}. However that call was just fine.
I looked at the displayed HTML and noticed how far it got, and that caused me to investigate the particular line that was the problem.
The Twig template now looks like this and renders correctly:
{{ form_start(form) }}
    {{ form_errors(form) }}

All Fields Are Required

        {{ form_label(form.user.firstname, "First Name") }}
        {{ form_widget(form.user.firstname) }}

        {{ form_errors(form.user.firstname) }}

        {{ form_label(form.user.lastname, "Last Name") }}
        {{ form_widget(form.user.lastname) }}

        {{ form_errors(form.user.lastname) }}

        {{ form_label(form.user.username, "Username") }}
        {{ form_widget(form.user.username) }}

        {{ form_errors(form.user.username) }}

        {{ form_label(form.user.email, "Email") }}
        {{ form_widget(form.user.email) }}

        {{ form_errors(form.user.email) }}

        {{ form_label(form.user.password.password, "Password") }}
        {{ form_widget(form.user.password.password) }}

        {{ form_errors(form.user.password.password) }}

        {{ form_label(form.user.password.confirm, "Confirm Password") }}
        {{ form_widget(form.user.password.confirm) }}

        {{ form_errors(form.user.password.confirm) }}

        {{ form_label(form.terms, "Terms & Conditions") }}
        {{ form_widget(form.terms) }}

        {{ form_errors(form.terms) }}

{{ form_end(form) }}


text:
Q: Place div at center and update function when user try to re-size window var wH = $(window).height();
var wW = $(window).width();
var sT = $(window).scrollTop();
var sL = $(window).scrollLeft();

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, ((wH - $(this).outerHeight()) / 2) + sT) + "px");
    this.css("left", Math.max(0, ((wW - $(this).outerWidth()) / 2) + sL) + "px");
    return this;
}

$('div').center();

I try to place div at center of page and I have found a function can do this.
However, when windows re-size or user try to zoom in out, this function didn't update new position.
Is anyway to run this function when user try to re-size windows or zoom in out?

A: I believe the jQuery resize method should do exactly what you want:
$(window).resize(function () {
    $('div').center();
});

Alternatively, you can do this with a plain DOM method:
window.onresize = function () { $('div').center(); };

However, the plain DOM method will remove any existing handlers bound to the window resize event and may not behave identically between browsers.
Also, you'll need to move these lines into your function so that they update when the handler gets called:
var wH = $(window).height();
var wW = $(window).width();
var sT = $(window).scrollTop();
var sL = $(window).scrollLeft();


text:
Q: ComponentStatus is deprecated - what to use then What do you use instead og kubectl get ComponentStatus?
kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+

A: Yes, this API is deprecated and as it provided status of etcd, kube-scheduler, and kube-controller-manager components, which we can get through kubectl or using lives endpoint.
so you can try
kubectl get --raw='/readyz?verbose'
#local cluster
curl -k https://localhost:6443/livez?verbose

output
[+]ping ok
[+]log ok
[+]etcd ok
[+]informer-sync ok
[+]poststarthook/start-kube-apiserver-admission-initializer ok
[+]poststarthook/generic-apiserver-start-informers ok
[+]poststarthook/priority-and-fairness-config-consumer ok
[+]poststarthook/priority-and-fairness-filter ok
[+]poststarthook/start-apiextensions-informers ok
[+]poststarthook/start-apiextensions-controllers ok
[+]poststarthook/crd-informer-synced ok
[+]poststarthook/bootstrap-controller ok
[+]poststarthook/rbac/bootstrap-roles ok
[+]poststarthook/scheduling/bootstrap-system-priority-classes ok
[+]poststarthook/priority-and-fairness-config-producer ok
[+]poststarthook/start-cluster-authentication-info-controller ok
[+]poststarthook/aggregator-reload-proxy-client-cert ok
[+]poststarthook/start-kube-aggregator-informers ok
[+]poststarthook/apiservice-registration-controller ok
[+]poststarthook/apiservice-status-available-controller ok
[+]poststarthook/kube-apiserver-autoregistration ok
[+]autoregister-completion ok
[+]poststarthook/apiservice-openapi-controller ok
[+]shutdown ok
readyz check passed

The current state of this API is problematic, and requires reversing the actual data flow (it requires the API server to call to its clients), and is not functional across deployment topologies.
It should be clearly marked as deprecated.

Mark componentstatus as deprecated

The Kubernetes API server provides 3 API endpoints (healthz, livez and readyz) to indicate the current status of the API server. The healthz endpoint is deprecated (since Kubernetes v1.16), and you should use the more specific livez and readyz endpoints instead.

using-api-health-checks


text:
Q: why should i solve expressions in parenthesis first? The title speaks for it self. I would like to know the reason why i absolutely have to solve what's in a parenthesis first. Every time i search for answers, i always get results regarding the order of operations and they all seem to skip an explanation regarding the priority of the parenthesis. They always just accept it as a first priority.

A: That's the very purpose of parentheses. When you write $$3\ \times \ 2\ +\ 1\ $$
the usual priority rules are such that the result is $$6+1$$
If you want to indicate to the reader that here exceptionally you need the addition to be carried out first, the way to say it with symbols is to use parentheses:$$3\ \times \ ( 2\ +\ 1)\ $$
It's a convention.

A: I don't know what it means to solve for sure, but you should interpret expressions partitioned with sets of parenthesis as they were intended to be read. That is the point of the parentheses: to make it clear what exactly was meant by the expression.
Ignoring this convention is akin to deliberately misunderstanding written or spoken words. Not using parentheses appropriately is akin to not using punctuation or capitalization while writing. The result is ambiguous and hard to read.

A: Even though order of precedence is often explained in terms of "what must be done first", that is somewhat misleading. It's not about which order you do things in when several of them are ready to do, but just a way to specify which things it is you must do.
If you want to evaluate an expression such as
$$ 7^2 + 6\cdot(3+5) $$
then the misleading rule would tell you that you must start by adding $3$ to $5$. But actually there's nothing at all wrong with instead starting by squaring $7$, and then continuing to work on $6\cdot(3+5)$ afterwards -- no matter that there's a parenthesis there.
What the parenthesis tells you is something else, namely that the number you're supposed to multiply by $6$ is the result of $3+5$ rather than just the $3$.
The means that you can't start by multiplying by $6$ -- not in the sense that it is forbidden to start with the multiplication, but in the sense that it is impossible to start by multiplying, simply because the number you're going to multiply $6$ with is not there yet until you have computed $3+5$.

Similarly, even without parenteses,
$$ 7^{3-1} + 6\cdot5 $$
the glib rule that "exponentiation comes before multiplicate" doesn't mean that you can't start your work by multiplying $6$ and $5$ if that strikes your fancy. And it will be impossible to start doing the exponentiation before you do the subtraction to find out what the power is, no matter how much the glib rule claims that "exponentiation comes before subtraction".

Where the precedence rules actually mean something is in cases like
$$ 3+4\cdot 5 $$
where we need a rule to tell us that this means "add $3$ to the product of $4$ and $5$", and does not mean "multiply the sum of $3$ and $4$, by $5$".
In this simple case the precedence rule does indeed force you do do one operation before the other -- but it does so indirectly, by telling you which computation the formula means. Not by dictating how you carry it out.

A: This is by the rules of BODMAS/PEMDAS. First letter is brackets/parentheses.
You do parentheses first because they group a set of values together.
Here's a simple example of why this holds.

Say you have three shopping bags in one hand and five in the other. Each bag has four items. How many items are there in total?

Intuitively, you would say this:

Total: eight bags. Each has four items, so total of $32$ items

and you would be correct.
Now to formulate an expression, you could do $$(3\times4)+(5\times4).$$
Without evaluating the product in each bracket, you would get $$(3+5)\times4=8\times4=32$$ as determined previously.
But that was by doing the parentheses first. If you choose to do this $$(3+5)\times4=3+5\times4=3+20=23$$ then this is clearly incorrect. This is because you have not grouped the shopping bags together.

Another example (with units):

Trial $1$: $20$ seconds; $5$ metres per second.
Trial $2$: $10$ seconds; $5$ metres per second.
Total distance?

Correct:
$$(20\times5)+(10\times5)=(20+10)\times5=\color{red}{30\,\text{seconds}}\times\color{blue}{5\,\text{metres per second}}=150\,\text{metres}$$
Incorrect:
$$(20\times5)+(10\times5)=(20+10)\times5=\color{red}{20\,\text{seconds}}+\color{red}{10\,\text{seconds}}\times\color{blue}{5\,\text{metres per second}}$$ which gives $$20\,\text{seconds}+50\,\text{metres}$$ which clearly doesn't make sense to add.

A: In most cases it makes your life easier to evaluate what is inside parentheses first.
For example  try $$ 125(35-31) + 2^4(17-15)$$
 With parentheses first, we get $$ 125(4)+2^4(2)=500+32=532$$
Otherwise, $$ 125(35)-125(31) +2^4(17)-2^4(15) $$ which you need a calculator or you will be spending lots of time on it.

A: We use parentheses to distinguish between
(A) "Multiply 2 by 3 and subtract the result from 7"
and
(B) "Subtract 2 from 7 and multiply the result by 3"
If we just wrote both of these expressions as
$7-2\times3$
then there would be confusion as to which one we meant. If we just use an order of operations precedence (say multiply/divide before add/subtract) then we have no way of writing (B). So we use parentheses when we want to override the precedence of operations - so
(A) $7-2 \times 3 = 7-(2 \times 3) = 1$
and
(B) $(7-2) \times 3 = 15$
There are ways of writing arithmetical expressions that are unambiguous without needing parentheses - an example is reverse Polish notation - but you only see them used occasionally.

A: One way of thinking about this is to recognise that expressions without parentheses are in fact shorthand which should only be used where there is no possibility of ambiguity.
In formal terms, arithmetic operations are binary, which means you need to take two terms at a time. So an expression of the form $a @ b * c$ where $@, *$ are binary operations and $a, b, c$ are numbers, has no formal meaning until we give it one.
In terms of common definitions, in cases where there is one binary operation, it is often associative, and in such cases the order of operations doesn't matter. But consider $5-4-3$ where the operation $-$ is not associative: this is ambiguous.
Where we have two operations and we are defining them formally, the relationship between the two is often expressed in terms of a distributive law, and this generally involves the meaning of terms in brackets.
So formally the use of brackets is part of the defined language of mathematics, and expressions without them are understood by convention.

A: Its because we defined that they serve that function.
The reason is because you want to make an operation to a number calculated inside the parenthasis not just some part of it.


text:
Q: Read hyperterminal file(ht file) in R Is it possible for R to read/import hyperterminal file(.ht) ?
I have tried to use read.csv, read.table, read_tsv and read.delim, but no one works. I think because the file contain some special character(maybe due to the encoding ANSI but I am not having a very deep understanding on encoding) so that R unable to read it.
Is there any way to remove the rows of special character first before reading/importing the file?
Or can convert the file to txt/convert the encoding to general form(for example UTF-8) ?
This is when I open ht file by notepad
htfile_notepad
This is when I open ht file by excel
htfile_excel
Please help. Thanks a lot!


text:
Q: Finding and storing dominant rows of pandas df into another df I have a dataframe
df.shape (15,4)
I want to pairwise compare 2 rows, extract the dominant row into another df and now compare following row with less dominant row.
Repeat the loop till we get least dominant row at last in the new df.
Here's what I'm trying:
for i in range(len(df)):
a = df.iloc[i]
b = df.iloc[i+1]
diff=a-b
if(diff >= 0):
    l.append(a) #List/df
    df = df.drop(df.iloc[i])  #Extract 1st row into another df if it's dominant
#Now compare 3rd row with not dominant row (either 1st or 3rd) and repeat the loop
print(l)

My method seems really time consuming. Are there any inbuilt pandas functions which Can help me achieve the task easily?
df.head
      C      W       L    D
A1  82.0  78.00  1100.0  3.0
A2  19.0  99.00  9520.0  3.0
A3  25.0  42.00  1700.0  7.0
A4  93.0  37.00  1700.0  7.0
A5   9.2   0.44   510.0  7.0

(15 rows, 4 cols)
output = in new df
Count of number of times each A[i] was dominant over the following A[i+1] row for each independent column (C,W,L and D) respectively.

For example:
First for Criteria C:
new_df should be = df.head()
A1  #Since A1.C is greater than A2.C
A3  #Next comparison between A2.C and A3.C, A3.C wins, hence stored here
A4  #A2 and A4, A4 win
A2  #A2 (still remaining) and A5, here A2 wins and is stored
A5  #Now A5 stored it it's greater than A6.. so on and so forth till A15

Then for rest 4 columns.
Was I able to explain what I'm trying to do or did I make it more complicated? Waiting for your comment, I can add more info if required. Many Thanks.

A: Here's an example using a for loop for column C.
But normally when using pandas you really shouldn't use a for loop. I just don't know how else to solve this part of the problem.
import pandas as pd
from io import StringIO

text = """
      C      W       L    D
A1  82.0  78.00  1100.0  3.0
A2  19.0  99.00  9520.0  3.0
A3  25.0  42.00  1700.0  7.0
A4  93.0  37.00  1700.0  7.0
A5   9.2   0.44   510.0  7.0
"""

df_subset = df['C'].copy().reset_index()

# loop over 2 lines each, see who is the winner, and sort on that
for i in range(len(df_subset)-1):
    df_subset.iloc[i:i+2, :] = df_subset.iloc[i:i+2,:].sort_values(
        ascending=False,
        by='C',
    ).values

df_subset.set_index('index')

Resulting series:
index C
A1    82.0
A3    25.0
A4    93.0
A2    19.0
A5     9.2


text:
Q: error C4018 with vector size() in c++ im getting a warning when i use the function .size() with vectors in c++
Heres a sample code:
vector<classname*> object;
object.push_back(new classname2);

for(int i=0;i<object.size();i++){
....}

i get the warning:

warning C4018: '<' : signed/unsigned mismatch

I'm not allowed to have any errors or warnings in my final code so i need to get rid of this/find an alternative method, how can i get rid of this?

A: The problem is that there is a potential (breaking) issue that one can incur when dealing with signed-to-unsigned comparisons. If you're on a 32-bit machine where a signed int is 4 bytes, it could be possible that the size of the vector could exceed the maximum quantity representable by that type. When that happens, you get signed overflow and consequentially Undefined Behavior.
Here are a few alternatives you can uses:
vector<T>::size_type:
for (std::vector<classname>::size_type i = 0; i < object.size(); ++i);

This is guaranteed to be correct as it is the type the size returns.
Iterators
std::vector<classname>::iterator it;

for (it = object.begin(); it != object.end(); ++it);

C++11: Range-based for:
for (auto& a : object)
{
     // ...
}

std::size_t:
for (std::size_t i = 0; i < object.size(); ++i);

As doomster said in the comments, std::size_t is likely to have the bit-size of your underlying platform.
unsigned int:
for (unsigned int i = 0; i < object.size(); ++i);

Note: By using this, you're assuming that size returns a 32-bit integer. Generally this isn't a problem, but you can't be too sure; use any of the above if you can.
Another tip relative to your code is to use a vector of unique_ptr/shared_ptr to facilitate memory-management:
std::vector<std::unique_ptr<classname>> object;

A: The size of a vector is always positive. Just use an unsigned int as loop variable:
for (unsigned int i = 0; i < object.size(); i++)
{
    ...
}

An even safer way is to declare your loop variable using size_t, which is the same as unsigned int on most platforms. But since it is the return type of the vector::size() function, your counter variable is guaranteed to have the same value range as the possible size of a vector.
for (size_t i = 0; i < object.size(); i++)
{
    ...
}

A: Use an unsigned iterator:
for (unsigned int i = 0; i < object.size(); i++)
{

}


text:
Q: Transitioning between two UIViewController stacks I'm planning with my App to have a root UIViewController in the App Delegate, that basically branches off into a possible two UIViewControllers, each of those UIViewControllers will have a number of UINavigationControllers pushed onto of them, might have a UITabBarController, not too sure yet but the main issue is I want to from any view transfer from one UIViewController stack to the other, and maintain the view hierarchy.
When I want to change from one UIViewController stack to the other, I thought about calling the App delegate:
MainClass *appDelegate = (MainClass *)[[UIApplication sharedApplication] delegate];
[appDelegate.viewController someMethod];

and transitioning that way, but it seems a bit of a hacky way to do it. Also thought about passing a reference through the stack to the root UIViewController and call the method to change between the UIViewControllers.
Which way would be the better way? Or is there a way I haven't thought about that is the preferred way of doing it?

A: A UITabBarController offers you exactly that functionality. If you have one as your root view controller and two tabs with a navigation controller in each tab, then you're basically done. If you don't want to show the tab bar in the bottom you can just hide it and then trigger the tab switch from code following some events. It's pretty straight forward :)

A: do you mean you have one root view controller and this root VC manages two view controllers and these two controllers manages many sub view controllers?
if so, you may try to use custom containment controller. and every time you want to change stack from one to another, just delegate to rootVC to do so.
- (void)moveToAnotherController:(UIViewController *)vc
{
    [self displayContentController:vc];
}

- (void)displayContentController:(UIViewController *)content
{
    [self addChildViewController:content];
    [self.view addSubview:content.view];
    [content.view setFrame:self.view.bounds];
    [content didMoveToParentViewController:self];

}

//remove child controller from container
- (void)hideContentController:(UIViewController *)content animated:(BOOL)animated
{
    [content willMoveToParentViewController:nil];
    [content.view removeFromSuperview];
    [content removeFromParentViewController];
}


text:
Q: Drop ALL Views in a SQLite database? I would like to drop all the views in my SQLite database. Please help.
I am aware I can drop views if I know the view name...
DROP VIEW IF EXISTS view_name

... but I'd like to drop views that exist but for which I don't know the name.

A: You can get all the views by querying the sqlite_master table (a system table).
e.g.
SELECT name FROM sqlite_master WHERE type = 'view';

The name column will be the name of the view.


text:
Q: Sending e-mails from Windows Server If we have a Windows Small Business Server 2011 machine with MS Exchange 2010 acting as mail server on SMTP port 25, do we also need a SMPT server to send e-mail from our website?
Thanks.


text:
Q: How can I determine which browser tab a request is coming from? I set up a proxy (using Postman) that Chrome is now routing all requests through.
I see a bunch of requests being made to a site I don't recognize, and it repeats every few seconds. I have about 50 Chrome tabs open, so I'm wondering, is there a quick way I can determine which tab this request is coming from?

A:
Is there a quick way I can determine which tab this request is coming from?

After a quick Google search, a Chrome extension called Web Sniffer may be one solution to your problem. It lists requests made in real-time and has a column that has a link to the given tab that made a particular request:
ex. Active Tab Links

That is, when you click the underlined Tab number (e.g. 457), you will be taken to the open tab that generated the request.
As minor caveats, closed tabs don't have this option (i.e. there is no underline) and reopening a closed tab will (apparently) generate a different tab number.


text:
Q: Why Won't this python Tkinter code work? I've Just started to code this tkinter program and I've come appon an error.
This is the error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\rhysj_000\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "G:\Login\Login v2.py", line 21, in check_password
    if (user,'=',password in line):
TypeError: 'in <string>' requires string as left operand, not Entry

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
# from http://effbot.org/tkinterbook/entry.htm
failure_max = 3
def make_entry(parent, caption, width=None, **options):
    tk.Label(parent, text=caption).pack(side=tk.TOP)
    entry = tk.Entry(parent, **options)
    if width:
        entry.config(width=width)
    entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH)
    return entry
def enter(event):
    check_password()
def check_password(failures=[]):
    datafile = open('login\profile.passwords')
    for line in datafile:

        if (user,'=',password in line):
            root.destroy()
            print('Logged in')
            return
            failures.append(1)
            if sum(failures) >= failure_max:
                root.destroy()
                raise SystemExit('Unauthorized login attempt')
            else:
                root.title('Try again. Attempt %i/%i' % (sum(failures)+1, failure_max))
root = tk.Tk()
root.wm_iconbitmap("Login icon.ico")
root.geometry('300x160')
root.title('Enter your information')
#frame for window margin
parent = tk.Frame(root, padx=10, pady=10)
parent.pack(fill=tk.BOTH, expand=True)
#entrys with not shown text
user = make_entry(parent, "User name:", 16, show='~')
password = make_entry(parent, "Password:", 16, show="*")
#button to attempt to login
b = tk.Button(parent, borderwidth=4, text="Login", width=10, pady=8,    command=check_password)
b.pack(side=tk.BOTTOM)
password.bind('<Return>', enter)
user.focus_set()
parent.mainloop()


text:
Q: Copy resources from source folder to destination based on xml resource file using Powershell I'm trying to copy some files based XML file that contains all resources to be copied into a destination directory.
XML file
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">

  <?include Constants.wxi?>

  <Fragment>
      <Directory Id="SomeDIR" Name="XXXXX">
        <Component Id="SomeProject" Guid="{XXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX}">
          <File Id="SomeDll" Name="MS.SomeProject.dll" Source="$(var.OutPutDir)\MS.SomeProject.dll" KeyPath="yes" />
        </Component>
        <Component Id="SomeProject2" Guid="{XXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX}">
          <File Id="SomeDll2" Name="MS.SomeProject2.dll" Source="$(var.OutPutDir)\MS.SomeProject2.dll" KeyPath="yes" />
        </Component>
      </Directory>
  </Fragment>
</Wix>

And my question is, is there any other alternative to this command that accepts a collection of resources name instead of a filter?
# read resources.xml content
[xml]$xmlElm = Get-Content -Path Join-Path $BasePath  -ChildPath  '\Application\Setup\resources.xml'

# get all resources.xml resources
$Resources = $xmlElm.YYY.XXX.Name

# copy files to the destination
Get-ChildItem $Source -Recurse -filter $ItemName | Copy-Item -Destination $targetDirectory -Recurse -Force


text:
Q: Problems building C++ projects in TFS2010 while targeting the 2005 toolset I have been tasked with creating a build definition in TFS2010 that will build 2010 c++ projects (vcxproj files), but using the 2005 toolset (v80). After searching on the internet, I do believe that this is possible after reading this(1) and this(2). After reading those articles, I have installed VS2005 on my build machine and read this article and installed Daffodil for Visual Studio. Once these steps had been done, I was able to change the Platform Toolset to v80 for all required projects and proceeded to set up a build definition to build the projects for a Release configuration and Win32/x64 platforms.
After running the build definition, the very first project (on Win32 platform) failed to build with the following error message:
TRACKER: Failed to locate: "CL.exe". The system cannot find the file specified.

I also tried removing the Win32 platform from the build definition so that only the x64 platform will get built. This resulted in the following error (again, on the very first project):
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets (151): "cmd.exe" exited with code 9009.

I have a feeling I'm close to getting where I want to be, but I've obviously missed or misunderstood something on the way and I can't seem to figure out what that is.
After the first build failed (for the Win32 platform) I noticed that there was a difference to my log and the sample log file posted about half way down the page of the second article I read during research. Mine looked like this:
CL.exe /c /Zi /nologo /W3 /WX- /O2 /Ob1 /Oy- /......

While the sample build log looks like this:
C:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin\CL.exe /c /Zi /nologo /W3 /WX- /O2 /Ob1 /Oy- /......

At a guess, I would think that I have missed something concerning the .props and .targets files or possibly something to do with the VC++ directories, but the solution is eluding me.
UPDATE
I have created a test build definition to build a single vcxproj file using the 2005 toolset for the a Release Configuration with the Win32/x64 platforms. I have changed the Executable Directories in the VC++ Directories of the project properties to point at C:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin & C:\Program Files\Microsoft Visual Studio 8\VC\bin as this is where CL.exe can be found for both platforms. This does seem get around the "Failed to Locate CL.exe" problem, but the build fails for both platforms with the error "cmd.exe exited with code 9009". Not much better than before, but a little more consistent at least.


text:
Q: How to build a case sensitive query for MySQL As per title. I have found some questions roughly regarding the topic, but either proposed solutions do not work for me (error is thrown or generated query is missing conditions) or are clearly wrong, eg. suggesting that $eq operator is case sensitive - it is definitely not.
How do I modify this query to make it case sensitive?
models.Item.findOne({
    where: {
       name: 'soughtString'
    }
});

A: You can try to combine eq with SHA1 function like this:
models.Item.findOne({
    where: {
     [Op.and]: [{
         name: 'soughtString',
       },
       sequelize.where(
         sequelize.fn('SHA1', sequelize.col('name')),
         '=',
         sequelize.fn('SHA1', 'soughtString')
       )
    ]
});

This should be like a SQL condition like this:
where name = 'soughtString' and SHA1(name)= SHA1('soughtString')


text:
Q: smali - error copying double parameter I'm fairly knew to using smali, so apologies if this is a beginners question.
I am using Apktool to turn an apk file into smali, with the aim being to insert logging calls into the code.
To do this, I have incremented .locals by one (to add a new register) then am trying to move all the register back to their original positions.
I have issues when trying to move parameters that use two registers (longs and doubles). If I include code to move them, the apk recompiles but does not open on an emulator. I'm not having this issue when moving other types.
For example, the below works fine. If I add move-wide/from16 v6, p1 in line 68, the app will no longer open (the below is after I have incremented the .locals from 5).
.method public breakerTheSecond(JLjava/lang/String;)V
 59      .locals 6
 60      .param p1, "pk"    # J
 61      .param p3, "ab"    # Ljava/lang/String;
 62
 63      .prologue
 64       move-object/from16 v8, p3
 65
 66      move-object/from16 v5, p0
 67
 68
 69
 70     .line 56
 71      const/4 v0, 0x1
 72
 73      .local v0, "a":I
 74      const/4 v1, 0x2
 75
 76      .line 58
 77      .local v1, "b":I
 78      invoke-virtual {v5}, Lcom/test/bbutton
   /MyActivity;->getApplicationContext()Landroid/content/Context;
 79
 80      move-result-object v2
 81
 82      const-string v3, "test"
 83
 84      const/4 v4, 0x0
 85
 86      invoke-static {v2, v3, v4}, Landroid/widget
      /Toast;->makeText(Landroid/content/Context;Ljava
    /lang/CharSequence;I)Landroid/widg    et/Toast;
 87
 88      move-result-object v2
 89
 90      .line 59
 91      invoke-virtual {v2}, Landroid/widget/Toast;->show()V
 92
 93      .line 61
 94      return-void
 95  .end method

Thanks for you help!

A: Long and double values are referenced using only their first register. So when you do the move-object/from16 v5, p0 on line 66, it is moving the entire double value from p0, p1 to v5, v6.
Referencing the second half of a 64-bit value isn't allowed, so when you try to do move-wide/from16 v6, p1, it sees that p1 is the second half of the value in p0, and gets grumpy with you :)


text:
Q: Adding values from list in Python to make total values based on key I'm currently struggling a lot with a specific piece of code I'm writing in Python.
I'd need to get the total values of seperate objects values, based on the same key.
Here is the JSON data I'm currently getting
[{
        "name": "John",
        "data": [{
                "currency": "Euro",
                "amount": 100.00
            },
            {
                "currency": "Dollar",
                "amount": 223
            },
            {
                "currency": "Yen",
                "amount": 800
            }
        ]
    },
    {
        "name": "Jack",
        "data": [{
                "currency": "Dollar",
                "amount": 32
            },
            {
                "currency": "Euro",
                "amount": 80
            }
        ]
    },
    {
        "name": "Elise",
        "data": [{
                "currency": "Dollar",
                "amount": 12
            },
            {
                "currency": "Yen",
                "amount": 66
            }
        ]
    }
]

But! In this array of objects I would also like to add another object which contains information about the total values of each currency. I've been struggling with this for quite a bit, I've tried nested for loops but it feels like that is a waste of time and that there must be faster ways...
Anybody that can help me get the output I'm looking for?
Wanted output =
[{
        "name": "Total",
        "data": [{
            "Euro": {
                "amount": 180
            },
            "Dollar": {
                "amount": 267
            },
            "Yen": {
                "amount": 866
            }
        }]
    },

    {
        "name": "John",
        "data": [{
                "currency": "Euro",
                "amount": 100.00
            },
            {
                "currency": "Dollar",
                "amount": 223
            },
            {
                "currency": "Yen",
                "amount": 800
            }
        ]
    },
    {
        "name": "Jack",
        "data": [{
                "currency": "Dollar",
                "amount": 32
            },
            {
                "currency": "Euro",
                "amount": 80
            }
        ]
    },
    {
        "name": "Elise",
        "data": [{
                "currency": "Dollar",
                "amount": 12
            },
            {
                "currency": "Yen",
                "amount": 66
            }
        ]
    }
]

A: Assuming your list is called s, try this:
total = dict()
for d in s:
    for ccy in d["data"]:
        if ccy["currency"] in total:
            total[ccy["currency"]]["amount"] += ccy["amount"]
        else:
            total[ccy["currency"]] = {"amount": ccy["amount"]}
>>> total
'Euro': {'amount': 180.0}, 'Dollar': {'amount': 267}, 'Yen': {'amount': 866}}

If you want to combine both into a single list after, you can do:
s = [{"name": "Total", "data": [total]}] + s
>>> s
[{'name': 'Total',
  'data': [{'Euro': {'amount': 180.0},
            'Dollar': {'amount': 267},
            'Yen': {'amount': 866}}]},
 {'name': 'John',
  'data': [{'currency': 'Euro', 'amount': 100.0},
           {'currency': 'Dollar', 'amount': 223},
           {'currency': 'Yen', 'amount': 800}]},
 {'name': 'Jack',
  'data': [{'currency': 'Dollar', 'amount': 32},
           {'currency': 'Euro', 'amount': 80}]},
 {'name': 'Elise',
  'data': [{'currency': 'Dollar', 'amount': 12},
           {'currency': 'Yen', 'amount': 66}]}]


text:
Q: What are the implications that the Hamiltonian of a material lacks time reversal symmetry? When reading about topological insulators and the quantum Hall effect, I've read that some Hamiltonians of the crystal structure representing the "materials" lack time reversal symmetry. My question is, what does this imply that the Hamiltonian representing those materials lacks the time reversal symmetry? Does that mean the entropy is always increasing (so there would be no equilibrium state possible, from a thermodynamics point of view)?

A: It usually just means that the material is magnetic, since  magnetization ${\bf M}$ changes to $-{\bf M}$ under time reversal.


text:
Q: Slightly different answer second order differential equation I am writing this because I am stuck on a certain question on a homework I have to turn in. I am supposed to solve it using variation of parameters as opposed to using undetermined coefficients, which would make it easier in my opinion. Anyway, all online solution checkers like symbolab and wolfram alpha say the answer is slightly different to what I got.
However, all of the online solutions say the correct answer is
Is my work a correct solution or is that extra $e^{-x}$ wrong?


text:
Q: React Native Flat list navigate to new screen when pressing on an item I am new to React Native and I am facing a problem when i try to build a flat list that navigate to another screen with the item details when pressing on a list item.
I am using redux and react-native-router-flux to navigate between screens.
the flat list is rendering but I can not navigate to another screen when I press on item.
here is my code:
class MyListItem extends React.PureComponent {

  _onPress = () => {

    this.props.onPressItem(this.props.item);

  };

  render() {

    return (
      <TouchableOpacity

        {...this.props}
        onPress={this._onPress}>
        <View style={styles.GridViewContainer} >
          <Text style={styles.GridViewTextLayout} >{this.props.item.name}</Text>
        </View>
      </TouchableOpacity>
    );
  }
}
class CustomersList extends Component {
  componentWillMount() {
    this.props.getCustomers();

  }

  componentDidUpdate(prevProps) {
    if (prevProps.customers !== this.props.customers) {
      this.props.getCustomers();
    }
  }

  _keyExtractor = (item, index) => item._id;

  _onPressItem = (item) => {
    Actions.customerShow({ customer: item });

  };

  _renderItem = ({ item }) => (
    <MyListItem
      id={item._id}
      item={item}
      onPressItem={() => this._onPressItem(item)}
      title={item.name}
    />
  );

  render = () => {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.props.customers}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
          extraData={this.state}
          numColumns={3}
        />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  const customers = state.customers;
  console.log(customers);
  debugger
  return { customers };

};

export default connect(mapStateToProps, {
  getCustomers
})(CustomersList);

And here is the axios api :
export const getCustomers = () => {
    debugger;
    return (dispatch) => {
        dispatch(setCustomerLoading)
        axios
            .get('https://calm-sands-26165.herokuapp.com/api/customers')
            .then(res =>
                dispatch({
                    type: GET_CUSTOMERS,
                    payload: res.data,
                })
            )
            .catch(err =>
                dispatch({
                    type: GET_ERRORS,
                    payload: null
                })
            );
    };
}

the routing stacks:
const RouterComponent = () => {
  return (
    <Router >
      <Scene key="root" hideNavBar>
        <Scene key="auth">
          <Scene key="login" component={LoginForm} title="Please Login" initial />
        </Scene>
        <Scene key="main">
          <Scene
            onRight={() => Actions.customerCreate()}
            rightTitle="Add"
            key="customersList"
            component={CustomersList}
            title="Customers"
            initial
          />
          <Scene key="customerCreate" component={CustomerCreate} title="Create Customer" />
          <Scene key="customerShow" component={CustomerShow} title="Show Customer" />
        </Scene>
      </Scene>

    </Router>
  );
};

Thanx in advance,

A: The error you are getting is caused when the data source prvided to FlatList is not an array. In your case, this.props.customers is undefined until the function this.props.getCustomers() is returned.
What I would suggest is to use the state to render the flatlist in your CustomersList component. And update the state when the results are returned from the axios async call this.setState({customers : nextProps.customers}) which will rerender the FlatList with the customers array.
class CustomersList extends Component {

  constructor(props){
    super(props);
      this.state = {
      customers : []
    };
  }
  ...

  render = () => {
    return (
      <View style={{flex:1}}>
        {this.state.customers.length > 0 ?
        <FlatList
          data={this.state.customers}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
          extraData={this.state}
          numColumns={1}
      /> :
        <View style={styles.container}>
          <ActivityIndicator size={'large'}/>
        </View>
        }
      </View>
    );
  }
}

As for your navigation, I did test your code myself and it worked :) (As you can see I used <ActivityIndicator /> to render when the list is still fetching.


text:
Q: libspotify does not connect I'm trying to get familiar with libspotify and I must say the documentation on libspotify is seriously lacking. I've hacked together a small app from the examples but I can't get it to work.
I'm building a C Console Application in Visual Studio 2012. The appkey is correct.
sp_session_config config;
sp_error error;
sp_session *session;
char *blob = NULL;

memset(&config, 0, sizeof(config));

config.api_version = SPOTIFY_API_VERSION;
config.cache_location = "tmp";
config.settings_location = "tmp";
config.application_key = g_appkey;
config.application_key_size = g_appkey_size;

config.user_agent = "SpotiTest";

error = sp_session_create(&config, &session);
if (SP_ERROR_OK != error) {
    fprintf(stderr, "failed to create session: %s\n",
                    sp_error_message(error));
    return;
}

error = sp_session_login(session, "USERNAME", "PASSWORD", 1, blob);
if (SP_ERROR_OK != error) {
    fprintf(stderr, "failed to log in to Spotify: %s\n",
                    sp_error_message(error));
    sp_session_release(session);
    exit(4);
}

sp_connectionstate cs = sp_session_connectionstate (session);

No matter what the username and password (false or correct) sp_session_login always returns SP_ERROR_OK. When I check the connection state with sp_session_connectionstate it always returns SP_CONNECTION_STATE_LOGGED_OUT.
I'm not seeing what I'm doing wrong here and also can't seem to find any relevant answers through the regular channels.

A: The API is asynchronous. sp_session_login returns immediately, and the login process continues in the background. Look at the examples that come with the API. You need some kind of event loop to call sp_session_process_events, or libspotify won't get any work done, and you probably want to wait until you receive the logged_in callback.


text:
Q: Magento 1.9 admin grid custom report displays same collection data in all rows I am developing a customised grid report which gives result as per the given time period for specific order status. As a result I am getting same collection in all rows instead of getting a result according to the relevant date.

Can someone please help me fix this asap.
Thanks,


text:
Q: how to rounding the numbers after decimal point? Hi Am developing one application in java and Am using sql server database . I'm inserting values in database in 23.6 but its appending like 23.645464 . is there any method to append after decimal no only one digit. please help me.
Thanks

A: how about this in sql server.
SELECT round (cast(23.645464 AS DECIMAL(10,1)),2);

A: Hey you can try this code in Java file before storing value in database..
For example :
Function call :
float round = Round(num,1);

Definition:
public static float Round(float val, int dec) {
  float p = (float)Math.pow(10,dec);
  val = val * p;
  float tmp = Math.round(val);
  return (float)tmp/p;
  }


text:
Q: How do I get a directory size (files in the directory) in C#? I want to be able to get the size of one of the local directories using C#. I'm trying to avoid the following (pseudo like code), although in the worst case scenario I will have to settle for this:
    int GetSize(Directory)
    {
        int Size = 0;

        foreach ( File in Directory )
        {
            FileInfo fInfo of File;
            Size += fInfo.Size;
        }

        foreach ( SubDirectory in Directory )
        {
            Size += GetSize(SubDirectory);
        }
        return Size;
    }

Basically, is there a Walk() available somewhere so that I can walk through the directory tree? Which would save the recursion of going through each sub-directory.

A: Here my .NET 4.0 approach
public static long GetFileSizeSumFromDirectory(string searchDirectory)
{
 var files = Directory.EnumerateFiles(searchDirectory);

 // get the sizeof all files in the current directory
 var currentSize = (from file in files let fileInfo = new FileInfo(file) select fileInfo.Length).Sum();

 var directories = Directory.EnumerateDirectories(searchDirectory);

 // get the size of all files in all subdirectories
 var subDirSize = (from directory in directories select GetFileSizeSumFromDirectory(directory)).Sum();

 return currentSize + subDirSize;
}

Or even nicer:
// get IEnumerable from all files in the current dir and all sub dirs
var files = Directory.EnumerateFiles(searchDirectory,"*",SearchOption.AllDirectories);

// get the size of all files
long sum = (from file in files let fileInfo = new FileInfo(file) select fileInfo .Length).Sum();

As Gabriel pointed out this will fail if you have a restricted directory under the searchDirectory!

A: A very succinct way to get a folder size in .net 4.0 is below. It still suffers from the limitation of having to traverse all files recursively, but it doesn't load a potentially huge array of filenames, and it's only two lines of code. Make sure to use the namespaces System.IO and System.Linq.
private static long GetDirectorySize(string folderPath)
{
    DirectoryInfo di = new DirectoryInfo(folderPath);
    return di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}

A: You could hide your recursion behind an extension method (to avoid the issues Marc has highlighted with the GetFiles() method):
public static class UserExtension
{
  public static IEnumerable<FileInfo> Walk(this DirectoryInfo directory)
  {
    foreach(FileInfo file in directory.GetFiles())
    {
      yield return file;
    }

    foreach(DirectoryInfo subDirectory in directory.GetDirectories())
    {
      foreach(FileInfo file in subDirectory.Walk())
      {
        yield return file;
      }
    }
  }
}

(You probably want to add some exception handling to this for protected folders etc.)
Then:
using static UserExtension;

long totalSize = 0L;
var startFolder = new DirectoryInfo("<path to folder>");

// iteration
foreach(FileInfo file in startFolder.Walk())
{
    totalSize += file.Length;
}

// linq
totalSize = di.Walk().Sum(s => s.Length);

Basically the same code, but maybe a little neater...

A: First, forgive my poor english ;o)
I had a problem that took me to this page : enumerate files of a directory and his subdirectories without blocking on an UnauthorizedAccessException, and, like the new method of .Net 4 DirectoryInfo.Enumerate..., get the first result before the end of the entire query.
With the help of various examples found here and there on the web, I finally write this method :
public static IEnumerable<FileInfo> EnumerateFiles_Recursive(this DirectoryInfo directory, string searchPattern, SearchOption searchOption, Func<DirectoryInfo, Exception, bool> handleExceptionAccess)
{
    Queue<DirectoryInfo> subDirectories = new Queue<DirectoryInfo>();
    IEnumerable<FileSystemInfo> entries = null;

    // Try to get an enumerator on fileSystemInfos of directory
    try
    {
        entries = directory.EnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
    }
    catch (Exception e)
    {
        // If there's a callback delegate and this delegate return true, we don't throw the exception
        if (handleExceptionAccess == null || !handleExceptionAccess(directory, e))
            throw;
        // If the exception wasn't throw, we make entries reference an empty collection
        entries = EmptyFileSystemInfos;
    }

    // Yield return file entries of the directory and enqueue the subdirectories
    foreach (FileSystemInfo entrie in entries)
    {
        if (entrie is FileInfo)
            yield return (FileInfo)entrie;
        else if (entrie is DirectoryInfo)
            subDirectories.Enqueue((DirectoryInfo)entrie);
    }

    // If recursive search, we make recursive call on the method to yield return entries of the subdirectories.
    if (searchOption == SearchOption.AllDirectories)
    {
        DirectoryInfo subDir = null;
        while (subDirectories.Count > 0)
        {
            subDir = subDirectories.Dequeue();
            foreach (FileInfo file in subDir.EnumerateFiles_Recursive(searchPattern, searchOption, handleExceptionAccess))
            {
                yield return file;
            }
        }
    }
    else
        subDirectories.Clear();
}

I use a Queue and a recursive method to keep traditional order (content of directory and then content of first subdirectory and his own subdirectories and then content of the second...). The parameter "handleExceptionAccess" is just a function call when an exception is thrown with a directory; the function must return true to indicate that the exception must be ignored.
With this methode, you can write :
DirectoryInfo dir = new DirectoryInfo("c:\\temp");
long size = dir.EnumerateFiles_Recursive("*", SearchOption.AllDirectories, (d, ex) => true).Sum(f => f.Length);

And here we are : all exception when trying to enumerate a directory will be ignore !
Hope this help
Lionel
PS : for a reason I can't explain, my method is more quick than the framework 4 one...
PPS : you can get my test solutions with source for those methods : here TestDirEnumerate. I write EnumerateFiles_Recursive, EnumerateFiles_NonRecursive (use a queue to avoid recursion) and EnumerateFiles_NonRecursive_TraditionalOrder (use a stack of queue to avoid recursion and keep traditional order). Keep those 3 methods has no interest, I write them only for test the best one. I think to keep only the last one.
I also wrote the equivalent for EnumerateFileSystemInfos and EnumerateDirectories.

A: If you use Directory.GetFiles you can do a recursive seach (using SearchOption.AllDirectories), but this is a bit flaky anyway (especially if you don't have access to one of the sub-directories) - and might involve a huge single array coming back (warning klaxon...).
I'd be happy with the recursion approach unless I could show (via profiling) a bottleneck; and then I'd probably switch to (single-level) Directory.GetFiles, using a Queue<string> to emulate recursion.
Note that .NET 4.0 introduces some enumerator-based file/directory listing methods which save on the big arrays.

A: Have a look at this post:
http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/eed54ebe-facd-4305-b64b-9dbdc65df04e
Basically there is no clean .NET way, but there is a quite straightforward COM approach so if you're happy with using COM interop and being tied to Windows, this could work for you.

A: the solution is already here https://stackoverflow.com/a/12665904/1498669
as in the duplicate How do I Get Folder Size in C#? shown -> you can do this also in c#
first, add the COM reference "Microsoft Scripting Runtime" to your project and use:
var fso = new Scripting.FileSystemObject();
var folder = fso.GetFolder(@"C:\Windows");
double sizeInBytes = folder.Size;
// cleanup COM
System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
System.Runtime.InteropServices.Marshal.ReleaseComObject(fso);

remember to cleanup the COM references

A: I've been looking some time ago for a function like the one you ask for and from what I've found on the Internet and in MSDN forums, there is no such function.
The recursive way is the only I found to obtain the size of a Folder considering all the files and subfolders that contains.

A: You should make it easy on yourself. Make a method and passthrough the location of the directory.
    private static long GetDirectorySize(string location) {
        return new DirectoryInfo(location).GetFiles("*.*", SearchOption.AllDirectories).Sum(file => file.Length);
    }

-G


text:
Q: How to serialize (using protobuf-net) a field that is the object described in another assembly (dll)? I'm using Microsoft.CodeAnalysis.CSharp.dll in my project. I have a class, the property of this class is an object that had been described in Microsoft.CodeAnalysis.CSharp.dll and connected to my project.
[ProtoContract]
public class FunctionAnnotation :
{
     [ProtoMember(1)] public IMethodSymbol Symbol { get; set; }
}

IMethodSymbol described in Microsoft.CodeAnalysis.CSharp.dll.
I use protobuf-net.
When you try to serialize an object it throws an exception:

No serializer defined for type: Microsoft.CodeAnalysis.IMetnodSymbol

It is clear that Microsoft.CodeAnalysis.Method.Symbol is not marked as [ProtoContract]
  private void Serialization()
    {
         string folderName = @"f:/serialization/";
         Directory.CreateDirectory(folderName);
         int name = this.Symbol.ToString().GetHashCode();
         using (FileStream fs = new FileStream("f:/serialization/" + name + ".dat", FileMode.OpenOrCreate))
         {
              Serializer.Serialize(fs, this);
         }
    }

What are the options for marking of existing classes?
How to solve this problem?

A: In theory you can manually configure external types using the RuntimeTypeModel API, i.e.
RuntimeTypeModel.Default.Add(typeof(SomeTYpe), false).Add("Member", 1); // etc

But: this will work best if the external type is a DTO-style object. If it is a complex domain object, you would be better served by introducing a DTO map separately, i.e. a set of objects you control that represents the data you need, rather than the implementation.


text:
Q: What can I do to fix a null pointer error in Android for toolbar? Even after I had ensured that the toolbar id is well linked in the main activity where I declared the Toolbar, it still does push an error.
I am trying to create and understand a navigation drawer in android studio. I have once done this navigation and it worked, just trying to build a project using navigation and it started showing this error.
Here are my codes:
This is the main activity:
package com.example.demoapp;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    DrawerLayout drawerLayout;
    ActionBarDrawerToggle actionBarDrawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar.findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
    }
}

This is the toolbar layout.xml for the tool bar:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimaryDark"
        android:id="@+id/tool_bar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        />

</LinearLayout>

This is the main activity xml where I included all the fragments of xml i needed to make the navigation view work
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer"
    tools:context=".MainActivity">

    <include
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        layout="@layout/drawer_toolbar"
        />

    <include
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        layout="@layout/content_main"
        />

    <com.google.android.material.navigation.NavigationView
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:id="@+id/navigationView"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/drawer_header"
        android:fitsSystemWindows="true"
        android:layout_gravity="start"
        />

</androidx.drawerlayout.widget.DrawerLayout>

A: As @Selvin mentioned in the comment section, replace this line:
toolbar.findViewById(R.id.tool_bar);

with the following line:
toolbar = findViewById(R.id.tool_bar);


text:
Q: Access ContentControl (Combobox) in footer of Word-document I have a Word-document with a footer that contains a combobox, which I would like to access using VBA.
I've seen similar questions being asked, where the answer was 'just don't use contentcontrols in footers', but that's not really an answer, is it. ;) The reason the combobox needs to stay, is because users can also manually select one of the options if necessary.
I know that ContentControls in the main document can be accessed using ActiveDocument.ContentControls(1).Range.Text
However, I have not found how to access ContentControls in the footer.
Any help is much appreciated, thank you!
Kind regards,
Jeroen

A: You access ContentControls in the footer in exactly the same way that you access anything else that is in the footer. You need to determine which section contains the footer and which of the three footers contains the ContentControl.
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.ContentControls(1).Range.Text


text:
Q: "Building skill schema failed" error while deploying alexa skill using ask-cli I have a alexa skill live on amazon skill store. The interaction model of that skill was developed using the skill builder of alexa development portal and the lambda function was uploaded seperately. The skill is live and has many users.
Recently I felt the need of making some changes to that skill. Since now I am using ask-cli for all my alexa skill development, I decided to use the same for this skill too.
Here are the steps I followed:

*

*cloned the skill from the alexa console using command ask clone and selecting the skill I wanted to make changes in.

*made the required changes in the skill. Just changed a response, nothing special.

*tried deploying the skill again to alexa console using ask deploy command

But I got the following error:
[Error]: Building skill schema failed

I thought that the changes I made might be the cause of it, so I backtracked the changes and made the code as it was when cloned. Then I tried deployig the code again but the error remained the same.
I went through some answers on amazon portal, the most common cause of the issue for others there was some mistake in URI of skill icon URIs. To be sure, I also removed that line from skill.json and tried deploying it again but nothing changed.
Does anyone has any idea of the cause of the above mentioned issue?

A: Make sure your lambda function has Alexa Skills Kit as trigger. I solved my problem by adding back the trigger (and entering the skill ID).

A: This steps might able to fix that problem.

*

*Create a new skill in the developer portal.

*Create the Lambda function for that skill then add it as an endpoint.

*Download the skill via ask-cli

*Copy the code in the existing skill to the new skill.

*Re deploy using ask-cli.

It might be due to permission error or the appropriate profile used during deployment is configured incorrectly or missing.

A: If the cause of the issue is your image urls in Skill.json file try this hacky solution

*

*Goto your Alexa skill development portal and select "distribution"
tab

*In that upload both small and large icon. ( Do not press save ) if its a new skill,

*right click on the image and select open image in new tab and copy
the image URL. now use this URL in the skill.json
This is what i used in my skill when s3 url are all causing issue.


text:
Q: How to open a webpage that requires Adobe Flash? Adobe Flash is obsolete, but some legacy web pages are using it.
Using the current popular browsers(Google Chrome, FireFox, Microsoft Edge, ...), how can I open the webpage that requires Adobe Flash? I tried looking to download an Adobe Flash, but I couldn't find a stable download address.

A: Windows

*

*Open Microsoft Edge.

*Press Alt + F or click ...(Setting and more) button in the upper right corner.

*Click Settings.

*Click Default browser item in the left side bar.

*In Internet Explorer compatibility group, Select Allow for Allow sites to be reloaded in Internet Explorer mode (IE mode).

*Restart Microsoft Edge.

*Open your target URL (needed Adobe Flash Player).

*Press Alt + F or click ...(Setting and more) button in the upper right corner.

*Click Reload in Internet Explorer mode.


text:
Q: Remote Access to SharePoint Lists with PowerShell I have a PowerShell script that pulls data from a database. I need to push this data to a SharePoint list on a different server.
Would you have tutorial or examples that show how to do this (authentication and update)?
Update: I need this to work on both SharePoint 2007 and 2010. I do not have admin access on the SharePoint server.

A: Not sure I would use PowerShell for this.
Why not use Business Connectivity Service (SP2010) or Business Data Catalog (SP2007) for this?
If you need to move data redundantly into a list in SharePoint with certain intervals another option would be SQL Integration Services.

A: Given the information I would still chose to do a console app that leverages SharePoint's web services versus using PowerShell with remoting.  If you need it to work with both, then I would stick with the soap based services.  http://msdn.microsoft.com/en-us/library/ms479390(v=office.12).aspx

A: This is my second answer since question was updated.
I was following link provided by @MikeOryszak and I did some testing. This is the PowerShell script that uses SP web service with custom credentials to insert data:
$items #ListItem collection

$siteUrl = "http://mySite"
$fieldsToCopy = @("Title", "SomeOtherField") #fields to copy

#Build batch
$batch = "<Batch>"
for ($index = 0; $index -lt $items.Count; $index++) {
    $methodId = $index + 1
    $batch +=  "<Method ID='$methodId' Cmd='New'><Field Name='ID'>New</Field>"
    foreach ($field in $fieldsToCopy) {
            $fldValue = $items[$index][$field]
            $batch += "<Field Name='$field'>$fldValue</Field>"
    }
    $batch += "</Method>"
}
$batch += "</Batch>"

#Make webservice call
$wsProxy = New-WebServiceProxy -Uri $siteUrl/_vti_bin/lists.asmx -Credential [DOMAIN\USER]
#You will be prompted for password
$xmlB = [xml]$batch
($wsProxy.UpdateListItems($targetListId, $xmlB )).ResultStatus

Note: I have tested this on single server only with 'primitive' field types and it is working. There are many ways this script can be upgraded but I have done this just as 'proof of concept'

A: You can use the SharePoint Webservices from your Client. It´s only necessary that PowerShell 2.0 is running on your Client. You don´t need any Admin priviliges on the SharePoint.
Use the following code:
$Credential = New-Object System.Management.Automation.PSCredential('test\user',(Read-Host "Enter Password" -AsSecureString))
$SPList = New-WebServiceProxy -uri http://yoursharepoint.de/_vti_bin/lists.asmx –Credential $Credential

http://technet.microsoft.com/de-de/library/dd315258.aspx


text:
Q: Why interaction is the same while main effect changes after adjusting for covariates? Hi I am confused by a result from my analysis.
I have two linear mixed models, the data was from a family-based study. The dependent variable is V1 (continuous), and the independent variables are V2 (continuous), V3 (continuous), and several covariates (some are continuous, some are categorical).
Model 1: V1 = V2 + V3 + V2*V3

Model 2: V1 = V2 + V3 + V2*V3 + covariates

The result from model 1 shows V2 (coefficient: 0.01, p-value: 0.001) and V2*V3 (coefficient: 0.002, p-value: 0.001) are significant. However, the result from model 2 shows V2 is non-significant (coefficient: 0.006, p-value: 0.10), but V2*V3 is still the same (coefficient: 0.002, p-value: 0.001). Is this situation possible? How can I interpret it?
I also checked my R code for the models. The code for models is as below:
lmer(V1 ~ V2 + V3 + V2*V3 + covariates + (1|family), data=mydata)

Could someone help me?

A: Coefficients change when variables correlated with the predictors enter the model. Yoru results indicate that the interaction is not correlated with the predictors conditional on the other variables in the model. This would be especially plausible if the terms in the interaction were centered at their means. It doesn't really indicate anything statistically or substantively interesting, though. You probably shouldn't be interpreting the "main effects" of a regression with an interaction anyway (because they correspond to the slope of the variable when the other variable in the interaction is held at zero, which is usually not a meaningful value unless the terms are centered).