问:
MySQL regex escape $
I have written an analysis on logfiles from a Microsoft IIS Server.
The complete log is pushed to a mysql datbase. The fields of my table are exact the same as in the log.

```<code>CREATE TABLE `iis_logging` (
    `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `DATE_TIME` DATETIME NULL DEFAULT NULL,
    `LOG_DATE` DATE NULL DEFAULT NULL,
    `LOG_TIME` TIME NULL DEFAULT NULL,
    `S_SITENAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_COMPUTERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_METHOD` VARCHAR(255) NULL DEFAULT NULL,
    `CS_URI_STEM` TEXT NULL,
    `CS_URI_QUERY` TEXT NULL,
    `S_PORT` INT(11) UNSIGNED NULL DEFAULT NULL,
    `CS_USERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `C_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_VERSION` VARCHAR(255) NULL DEFAULT NULL,
    `CS_USER_AGENT` TEXT NULL,
    `CS_COOKIE` TEXT NULL,
    `CS_REFERER` TEXT NULL,
    `CS_HOST` TEXT NULL,
    `SC_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_SUBSTATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_WIN32_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `CS_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `TIME_TAKEN` INT(11) UNSIGNED NULL DEFAULT NULL,
    PRIMARY KEY (`ID`),
    INDEX `date_key` (`LOG_DATE`),
    INDEX `DATE_URL` (`LOG_DATE`, `CS_URI_STEM`(30)),
    INDEX `URL` (`CS_URI_STEM`(100))
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=82749372
;
</code>```

Now I have written a query to get only some parts of this log:

```<code>select concat(LOG_DATE,' ', LOG_TIME) as VISIT_TS, CS_METHOD, CS_URI_STEM, CS_URI_QUERY, CS_REFERER, CS_USERNAME
from iis_logging
where CS_USERNAME NOT REGEXP '-' and CS_USERNAME NOT REGEXP '_'
order by LOG_DATE DESC , LOG_TIME DESC, CS_USERNAME DESC
limit 500
</code>```

Inside the where clause I would like to filter the usernames to get rid of technical users. This query works quite well.
But some technical users re still inside my result. Their usernames end with a $.

Example:

0#.w|domain\technical1971$

How can I write a REGEX to get rid of them?
I would like to filter on the existing $, becaue I don't want to filter on fixed names.

I already tried: (not working)

```<code>and CS_USERNAME NOT REGEXP '[.dollar-sign.]'
</code>```

and

```<code>and CS_USERNAME NOT REGEXP '\$'
</code>```

答:
```<code>where CS_USERNAME NOT REGEXP '-' and CS_USERNAME NOT REGEXP '_'
</code>```

-->

```<code>WHERE cs_username REGEXP '[^-_$]'
</code>```

But that assumes that the $ might occur anywhere in the name.  For only at the end:

```<code>WHERE cs_username NOT REGEXP '[-_]|[$]$'
</code>```

Notes:

- must be first in a character class, else it indicates a range.

[$] is an alternative to escaping $ -- by making a character class.

By putting everything in a single REGEXP, there is a slight improvement over using AND or OR.

order by LOG_DATE DESC , LOG_TIME DESC, CS_USERNAME DESC

needs

```<code>INDEX(log_date, log_time, cs_username)
</code>```

Title: MySQL regex escape $

Body:
I have written an analysis on logfiles from a Microsoft IIS Server.
The complete log is pushed to a mysql datbase. The fields of my table are exact the same as in the log.

CREATE TABLE `iis_logging` (
    `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `DATE_TIME` DATETIME NULL DEFAULT NULL,
    `LOG_DATE` DATE NULL DEFAULT NULL,
    `LOG_TIME` TIME NULL DEFAULT NULL,
    `S_SITENAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_COMPUTERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_METHOD` VARCHAR(255) NULL DEFAULT NULL,
    `CS_URI_STEM` TEXT NULL,
    `CS_URI_QUERY` TEXT NULL,
    `S_PORT` INT(11) UNSIGNED NULL DEFAULT NULL,
    `CS_USERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `C_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_VERSION` VARCHAR(255) NULL DEFAULT NULL,
    `CS_USER_AGENT` TEXT NULL,
    `CS_COOKIE` TEXT NULL,
    `CS_REFERER` TEXT NULL,
    `CS_HOST` TEXT NULL,
    `SC_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_SUBSTATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_WIN32_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `CS_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `TIME_TAKEN` INT(11) UNSIGNED NULL DEFAULT NULL,
    PRIMARY KEY (`ID`),
    INDEX `date_key` (`LOG_DATE`),
    INDEX `DATE_URL` (`LOG_DATE`, `CS_URI_STEM`(30)),
    INDEX `URL` (`CS_URI_STEM`(100))
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=82749372
;

Now I have written a query to get only some parts of this log:

select concat(LOG_DATE,' ', LOG_TIME) as VISIT_TS, CS_METHOD, CS_URI_STEM, CS_URI_QUERY, CS_REFERER, CS_USERNAME
from iis_logging
where CS_USERNAME NOT REGEXP '-' and CS_USERNAME NOT REGEXP '_'
order by LOG_DATE DESC , LOG_TIME DESC, CS_USERNAME DESC
limit 500

Inside the where clause I would like to filter the usernames to get rid of technical users. This query works quite well.
But some technical users re still inside my result. Their usernames end with a $.

Example:

0#.w|domain\technical1971$

How can I write a REGEX to get rid of them?
I would like to filter on the existing $, becaue I don't want to filter on fixed names.

I already tried: (not working)

and CS_USERNAME NOT REGEXP '[.dollar-sign.]'

and

and CS_USERNAME NOT REGEXP '\$'

Body:
where CS_USERNAME NOT REGEXP '-' and CS_USERNAME NOT REGEXP '_'

-->

WHERE cs_username REGEXP '[^-_$]'

But that assumes that the $ might occur anywhere in the name.  For only at the end:

WHERE cs_username NOT REGEXP '[-_]|[$]$'

Notes:

- must be first in a character class, else it indicates a range.

[$] is an alternative to escaping $ -- by making a character class.

By putting everything in a single REGEXP, there is a slight improvement over using AND or OR.

order by LOG_DATE DESC , LOG_TIME DESC, CS_USERNAME DESC

needs

INDEX(log_date, log_time, cs_username)


来源: stackexchange

问:
MView "enable query rewrite" usage
```<code>CREATE TABLE TEST_DATE(COL1 VARCHAR2(20),COL2 NUMBER,COL3_DATE DATE,COL4_DATE DATE)
/

create materialized view TEST_SYS
REFRESH FORCE ON DEMAND
ENABLE QUERY REWRITE  --- ????
AS
SELECT COL1,COL2
FROM    TEST_date
WHERE TRUNC(SYSDATE) BETWEEN TRUNC(COL3_DATE) AND TRUNC(COL4_DATE)
/
</code>```

If Enable Query Rewrite option is disabled, MView is getting created for the above query then what is the purpose of having ENABLE QUERY REWRITE clause while creating materialized view, can we remove it and create it, and do we have to compromise on the performance of the MView if we have to comment Enable Query Rewrite.

Please explain me the use of enable query rewrite option in detail.

答:
Query rewrite allows Oracle to rewrite a query against the base table (in this case TEST_DATE) to use the materialized view (in this case TEST_SYS) transparently.  That is highly useful when your materialized view is pre-aggregating data, for example.  If I have a transactions table and a materialized view

```<code>CREATE MATERIALIZED VIEW mv_transaction_daily
  REFRESH FORCE ON DEMAND
  ENABLE QUERY REWRITE
AS
SELECT store_id,
       transaction_day,
       SUM(transaction_amount) total_transaction_amount
  FROM transactions
 GROUP BY store_id, transaction_day
</code>```

then Oracle could transform a query like

```<code>SELECT store_id,
       transaction_day,
       SUM(transaction_amount) total_transaction_amount
  FROM transactions
 GROUP BY store_id, transaction_day
</code>```

to use the materialized view rather than hitting the base table.  And if you have appropriate dimension objects created, you could have a query like

```<code>SELECT store_id,
       trunc(transaction_day,'MM'),
       SUM(transaction_amount) monthly_transaction_amount
  FROM transactions
 GROUP BY store_id, trunc(transaction_day,'MM')
</code>```

that could also be rewritten to use the materialized view rather than the base table.

If query rewrite is not enabled, you would only see a performance benefit from using the materialized view if you explicitly queried the materialized view rather than querying the base table.  That generally requires more development effort and limits the ability of the DBAs to tune the application in the future by fine-tuning materialized views.

In your case, the presence of SYSDATE in your WHERE clause is going to prevent query rewrite because Oracle wouldn't be able to figure out that a query against TEST_DATE would actually be able to use the materialized view.  For all Oracle knows, data in the materialized view that satisfied the condition when the materialized view was refreshed no longer satisfies the condition and data that didn't make it into the materialized view now satisfies the condition simply because the SYSDATE has changed.

ContentLicense: CC BY-SA 2.5

Title: MView "enable query rewrite" usage

Body:
CREATE TABLE TEST_DATE(COL1 VARCHAR2(20),COL2 NUMBER,COL3_DATE DATE,COL4_DATE DATE)
/

create materialized view TEST_SYS
REFRESH FORCE ON DEMAND
ENABLE QUERY REWRITE  --- ????
AS
SELECT COL1,COL2
FROM    TEST_date
WHERE TRUNC(SYSDATE) BETWEEN TRUNC(COL3_DATE) AND TRUNC(COL4_DATE)
/

If Enable Query Rewrite option is disabled, MView is getting created for the above query then what is the purpose of having ENABLE QUERY REWRITE clause while creating materialized view, can we remove it and create it, and do we have to compromise on the performance of the MView if we have to comment Enable Query Rewrite.

Please explain me the use of enable query rewrite option in detail.

Body:
Query rewrite allows Oracle to rewrite a query against the base table (in this case TEST_DATE) to use the materialized view (in this case TEST_SYS) transparently.  That is highly useful when your materialized view is pre-aggregating data, for example.  If I have a transactions table and a materialized view

CREATE MATERIALIZED VIEW mv_transaction_daily
  REFRESH FORCE ON DEMAND
  ENABLE QUERY REWRITE
AS
SELECT store_id,
       transaction_day,
       SUM(transaction_amount) total_transaction_amount
  FROM transactions
 GROUP BY store_id, transaction_day

then Oracle could transform a query like

SELECT store_id,
       transaction_day,
       SUM(transaction_amount) total_transaction_amount
  FROM transactions
 GROUP BY store_id, transaction_day

to use the materialized view rather than hitting the base table.  And if you have appropriate dimension objects created, you could have a query like

SELECT store_id,
       trunc(transaction_day,'MM'),
       SUM(transaction_amount) monthly_transaction_amount
  FROM transactions
 GROUP BY store_id, trunc(transaction_day,'MM')

that could also be rewritten to use the materialized view rather than the base table.

If query rewrite is not enabled, you would only see a performance benefit from using the materialized view if you explicitly queried the materialized view rather than querying the base table.  That generally requires more development effort and limits the ability of the DBAs to tune the application in the future by fine-tuning materialized views.

In your case, the presence of SYSDATE in your WHERE clause is going to prevent query rewrite because Oracle wouldn't be able to figure out that a query against TEST_DATE would actually be able to use the materialized view.  For all Oracle knows, data in the materialized view that satisfied the condition when the materialized view was refreshed no longer satisfies the condition and data that didn't make it into the materialized view now satisfies the condition simply because the SYSDATE has changed.


问:
trying to use atoi and its not working
these are the errors i am getting:

```<code>    search.c: In function ‘checkGrades’:
    search.c:63: warning: passing argument 1 of ‘atoi’ makes pointer from
    integer without a cast
    /usr/include/stdlib.h:148: note: expected ‘const char *’ but argument is
    of type ‘char’
    search.c:63: error: expected ‘)’ before ‘;’ token
</code>```

Here is my code:

```<code>    int checkGrades(STUDENT grades[], int maxrecs, FILE* fp)
    {
    char line[LINE_MAX];
    int rc;
    int count = 0;
    int score;
    char id;
    while(fgets(line,LINE_MAX, fp) != NULL)
    {
    rc = sscanf(line,
    "%25[^:]%*c%25[^:]%*c%6s%*c%3d%*c%3d%*c%3d%*c%3d%*c%3d%*c%2c",
                 grades[count].id,
                &grades[count].score[1],
                &grades[count].score[2],
                &grades[count].score[3],
                &grades[count].grade);
    if((rc != 9) ||

                    rc == atoi (id);

                 grades[count].id < 100000 ||
                 grades[count].id > 999999 ||
                 grades[count].grade < 0 ||
                 grades[count].grade > 110)
    {

            printf("Invalid Record: %s", line);
    }
    else
    {
        count++;
        if(count == TNARRAY_MAX)break;
    }
    printf("ID: ", grades-> id);
    }
</code>```

Im not really sure if rc is what im supposed to be using for atoi, im a beginner in C and ive tried many combos with no success.  I know I need to convert the string to an int before comparing but im pretty lost here on how to do that.
Any help would be greatly appreciated!

答:
You can't use atoi on a single character.  What you can do instead is to cast the character to an integer, and then subtract the ASCII value of the character '0' from it.

```<code>int num;

num = (int)id - (int)'0';
</code>```

Also, as pointed out in the comments about, you don't actually initialize id.

ContentLicense: CC BY-SA 3.0

Title: trying to use atoi and its not working

Body:
these are the errors i am getting:

    search.c: In function ‘checkGrades’:
    search.c:63: warning: passing argument 1 of ‘atoi’ makes pointer from
    integer without a cast
    /usr/include/stdlib.h:148: note: expected ‘const char *’ but argument is
    of type ‘char’
    search.c:63: error: expected ‘)’ before ‘;’ token

Here is my code:

    int checkGrades(STUDENT grades[], int maxrecs, FILE* fp)
    {
    char line[LINE_MAX];
    int rc;
    int count = 0;
    int score;
    char id;
    while(fgets(line,LINE_MAX, fp) != NULL)
    {
    rc = sscanf(line,
    "%25[^:]%*c%25[^:]%*c%6s%*c%3d%*c%3d%*c%3d%*c%3d%*c%3d%*c%2c",
                 grades[count].id,
                &grades[count].score[1],
                &grades[count].score[2],
                &grades[count].score[3],
                &grades[count].grade);
    if((rc != 9) ||

                    rc == atoi (id);

                 grades[count].id < 100000 ||
                 grades[count].id > 999999 ||
                 grades[count].grade < 0 ||
                 grades[count].grade > 110)
    {

            printf("Invalid Record: %s", line);
    }
    else
    {
        count++;
        if(count == TNARRAY_MAX)break;
    }
    printf("ID: ", grades-> id);
    }

Im not really sure if rc is what im supposed to be using for atoi, im a beginner in C and ive tried many combos with no success.  I know I need to convert the string to an int before comparing but im pretty lost here on how to do that.
Any help would be greatly appreciated!

Body:
You can't use atoi on a single character.  What you can do instead is to cast the character to an integer, and then subtract the ASCII value of the character '0' from it.

int num;

num = (int)id - (int)'0';

Also, as pointed out in the comments about, you don't actually initialize id.


问:
Visual Studio 2017 Published web application returns 500 error
I have tried creating a test default net core web application which runs fine with IIS Express on my local machine. When I publish it to the server (Win 2012 R2), it returns a 500 error when I hit the website. Nothing is logged in the Event Log or IIS logs. I've installed the ASP.NET Core Module and restarted the server and still get the error. From what I've read, it's supposed to deploy a testproject.dll and web.config points to that but mine is generating an executable instead and web.config is pointing to that. Everything is in the root of the website as well so I'm not sure what else I can do. I didn't change any code in the test project, just using the default demo app to make sure I can get it running on a server.

Please help!

答: After a lot of testing, I finally figured out that there was a few error with IIS bindings, and permissions. Now everything is working.</p>


问:
Python- Card Selection
I'm new to python and I'm trying to figure out how to ask the user for input and then use that input to select a specific card from a deck of cards. This is what I have so far   </p>

```<code>cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["J", "Q", "K", "A"]
deck = []

for i in range(2,11):
    cardfaces.append(str(i))

for j in range(4):
    cardfaces.append(royals[j])

for k in range(4):
    for l in range(13):
        card = (cardfaces[l] + " of " + suits[k])
        deck.append(card)

for m in range(52):
    print(deck[m])
pick=input('Pick a card 1-52 :')
</code>```

答:
You're almost there!  All you need to do is to get the card out of deck.

```<code>pick = input('Pick a card 1-52 :')

card = deck[int(pick)-1]

print("You chose: The {}".format(card))
</code>```

(Psst!  remember, lists start at index 0, that's why you have to -1 from it)

Title: Python- Card Selection

Body:
I'm new to python and I'm trying to figure out how to ask the user for input and then use that input to select a specific card from a deck of cards. This is what I have so far

cardfaces = []
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
royals = ["J", "Q", "K", "A"]
deck = []

for i in range(2,11):
    cardfaces.append(str(i))

for j in range(4):
    cardfaces.append(royals[j])

for k in range(4):
    for l in range(13):
        card = (cardfaces[l] + " of " + suits[k])
        deck.append(card)

for m in range(52):
    print(deck[m])
pick=input('Pick a card 1-52 :')

Body:
You're almost there!  All you need to do is to get the card out of deck.

pick = input('Pick a card 1-52 :')

card = deck[int(pick)-1]

print("You chose: The {}".format(card))

(Psst!  remember, lists start at index 0, that's why you have to -1 from it)


问:
Get USB port of plugged in device in node
I'm using node-detection to be notify when a USB device was plugged in. However I can't seem to find out how to know to which port was it plugged in to, e.g. sdb1, sdc1, etc. Is there a simple way of doing it?

答:
You can use the drivelist module in addition to the node-detection module, made by the excellent folks at resin.io.

The drivelist module lists all connected devices including the mountpoint (path) information. This output is slightly different depending on your operating system. Check the drivelist documentation for more info.

Here's a quick example to find when a removable USB drive is inserted and mounted, and get the mount path.

From some testing, the usb-detection module fires nearly instantaneously when a device is plugged in, but it takes time for the device to mount. So I am using a setInterval to keep checking if a mountpoint exists. Once I find a mountpoint, I clear the interval.

```<code>// load modules
var usbDetect = require('usb-detection');
const drivelist = require('drivelist');
var checkUSBintervalID;

// This is the listener function for the 'add' event
function addUSBhandler() {
    console.log('added event listener for usb ADD');

    // Start interval to check if the USB is mounted
    checkUSBintervalID = setInterval(function() {
        drivelist.list(function(error, drives) {
            console.log('listening for USB mount...');
            if (error) { throw error; }

            // iterate through all drives
            for(var d = 0; d < drives.length; d++) {

                // if the drive is a removable usb
                if(drives[d].system == false) {

                    // if this drive is mounted
                    if(drives[d].mountpoints.length > 0) {
                        console.log('found removable USB');
                        // the drive is mounted
                        // do stuff here
                        // the path is at drives[d].mountpoints[0].path
                        clearInterval(checkUSBintervalID);
                    }
                }
            }
        });
    }, 1000);
}

// Add listener for when a USB is plugged in
usbDetect.on('add', addUSBhandler);
</code>```

This answer does not take into account if the USB is inserted and removed before it is mounted. You probably need to add a timeout or something similar. Hoped this helped, and good luck.

Body:
You can use the drivelist module in addition to the node-detection module, made by the excellent folks at resin.io.

The drivelist module lists all connected devices including the mountpoint (path) information. This output is slightly different depending on your operating system. Check the drivelist documentation for more info.

Here's a quick example to find when a removable USB drive is inserted and mounted, and get the mount path.

From some testing, the usb-detection module fires nearly instantaneously when a device is plugged in, but it takes time for the device to mount. So I am using a setInterval to keep checking if a mountpoint exists. Once I find a mountpoint, I clear the interval.

// load modules
var usbDetect = require('usb-detection');
const drivelist = require('drivelist');
var checkUSBintervalID;

// This is the listener function for the 'add' event
function addUSBhandler() {
    console.log('added event listener for usb ADD');

    // Start interval to check if the USB is mounted
    checkUSBintervalID = setInterval(function() {
        drivelist.list(function(error, drives) {
            console.log('listening for USB mount...');
            if (error) { throw error; }

            // iterate through all drives
            for(var d = 0; d < drives.length; d++) {

                // if the drive is a removable usb
                if(drives[d].system == false) {

                    // if this drive is mounted
                    if(drives[d].mountpoints.length > 0) {
                        console.log('found removable USB');
                        // the drive is mounted
                        // do stuff here
                        // the path is at drives[d].mountpoints[0].path
                        clearInterval(checkUSBintervalID);
                    }
                }
            }
        });
    }, 1000);
}

// Add listener for when a USB is plugged in
usbDetect.on('add', addUSBhandler);

This answer does not take into account if the USB is inserted and removed before it is mounted. You probably need to add a timeout or something similar. Hoped this helped, and good luck.


问:
C# serialize private class member
```<code>class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

```<code>class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

OR (continue of fact #3) an attribute that goes on the class which would look like:

```<code>[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}
</code>```

Now, what can I do to achieve it?

答:
If you use BinaryFormatter, it will go for your class' private parts.

Mark every class of yours with [Serializable] or you won't go far...

Also, look this: Why is Serializable Attribute required for an object to be serialized

Since you need XML, maybe you can pull yourself though it all with SoapFormatter.  See
this.

Apropos version compatibility:  I use BinaryFormatter and have no problems with schema upgrades.  Try it please: you can handle schema changes yourself, our simply replace null pointers left out by the Deserialize with appropriate default constructs.  If you don't really need the features that XML provide, go binary - you'll never look back.

Also, one more EDIT:

BF will readily resolve all your multiple references so it won't create multiple instances of the same reference over and over.  Guess you won't get that with XmlSerializer - it's obvious that it has no place for storing that information.

Example:

```<code>class Data
{
    int a;
}

class ManyData
{
    Data d1;
    Data d2;
}

...

ManyData md=new ManyData();
md.d1=new Data();
md.d2=md.d1;
</code>```

Try serializing/deserializing md with several alternatives...

Title: C# serialize private class member

Body:
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Simple question yet it seems like a big mess when trying to answer it.

Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?

How do I serialize private class members?

Edit #1:

Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.

Anyway, here are more facts:

 1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.

 2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.

 3.I was hoping that there's a certain attribute like:

class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}

OR (continue of fact #3) an attribute that goes on the class which would look like:

[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Now, what can I do to achieve it?

Body:
If you use BinaryFormatter, it will go for your class' private parts.

Mark every class of yours with [Serializable] or you won't go far...

Also, look this: Why is Serializable Attribute required for an object to be serialized

Since you need XML, maybe you can pull yourself though it all with SoapFormatter.  See
this.

Apropos version compatibility:  I use BinaryFormatter and have no problems with schema upgrades.  Try it please: you can handle schema changes yourself, our simply replace null pointers left out by the Deserialize with appropriate default constructs.  If you don't really need the features that XML provide, go binary - you'll never look back.

Also, one more EDIT:

BF will readily resolve all your multiple references so it won't create multiple instances of the same reference over and over.  Guess you won't get that with XmlSerializer - it's obvious that it has no place for storing that information.

Example:

class Data
{
    int a;
}

class ManyData
{
    Data d1;
    Data d2;
}

...

ManyData md=new ManyData();
md.d1=new Data();
md.d2=md.d1;

Try serializing/deserializing md with several alternatives...


问:
Adding a second y-axis related to the first y-axis
I hope one of you may be able to help. I have a plot with one y-axis value and one x-axis corresponding to these y values. I want to add a second y-axis on the right hand side of the plot. The values that will appear on the second y-axis are determined through the first y-axis values by some relation: for example, y2 might be y2 = y1**2 - 100. How do I make a second y-axis which has its values determined by the y1 values, so that the y2 values correctly align with their y1 values on the y-axis?

答:
twin axis

Adding a second y axis can be done by creating a twin axes, ax2 = ax.twinx().
The scale of this axes can be set using its limits, ax2.set_ylim(y2min, y2max). The values of y2min, y2max can be calculated using some known relationship (e.g. implemented as a function) from the limits of the left axis.

```<code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,50,101)
y = np.cumsum(np.random.normal(size=len(x)))+20.

fig, ax = plt.subplots()
ax2 = ax.twinx()

ax.plot(x,y, color="#dd0011")
ax.set_ylabel("Temperature [Celsius]")
ax2.set_ylabel("Temperature [Fahrenheit]")

# set twin scale (convert degree celsius to fahrenheit)
T_f = lambda T_c: T_c*1.8 + 32.
# get left axis limits
ymin, ymax = ax.get_ylim()
# apply function and set transformed values to right axis limits
ax2.set_ylim((T_f(ymin),T_f(ymax)))
# set an invisible artist to twin axes
# to prevent falling back to initial values on rescale events
ax2.plot([],[])

plt.show()
</code>```

secondary axis

From matplotlib 3.1 onwards one can use a secondary_yaxis. This takes care of synchronizing the limits automatically. As input one needs the conversion function and its inverse.

```<code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,50,101)
y = np.cumsum(np.random.normal(size=len(x)))+20.

# Convert celsius to Fahrenheit
T_f = lambda T_c: T_c*1.8 + 32.
# Convert Fahrenheit to Celsius
T_c = lambda T_f: (T_f - 32.)/1.8

fig, ax = plt.subplots()
ax2 = ax.secondary_yaxis("right", functions=(T_f, T_c))

ax.plot(x,y, color="#dd0011")
ax.set_ylabel("Temperature [Celsius]")
ax2.set_ylabel("Temperature [Fahrenheit]")

plt.show()
</code>```

The output is the same as above, but as you can see one does not need to set any limits.

Body:
twin axis

Adding a second y axis can be done by creating a twin axes, ax2 = ax.twinx().
The scale of this axes can be set using its limits, ax2.set_ylim(y2min, y2max). The values of y2min, y2max can be calculated using some known relationship (e.g. implemented as a function) from the limits of the left axis.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,50,101)
y = np.cumsum(np.random.normal(size=len(x)))+20.

fig, ax = plt.subplots()
ax2 = ax.twinx()

ax.plot(x,y, color="#dd0011")
ax.set_ylabel("Temperature [Celsius]")
ax2.set_ylabel("Temperature [Fahrenheit]")

# set twin scale (convert degree celsius to fahrenheit)
T_f = lambda T_c: T_c*1.8 + 32.
# get left axis limits
ymin, ymax = ax.get_ylim()
# apply function and set transformed values to right axis limits
ax2.set_ylim((T_f(ymin),T_f(ymax)))
# set an invisible artist to twin axes
# to prevent falling back to initial values on rescale events
ax2.plot([],[])

plt.show()

secondary axis

From matplotlib 3.1 onwards one can use a secondary_yaxis. This takes care of synchronizing the limits automatically. As input one needs the conversion function and its inverse.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,50,101)
y = np.cumsum(np.random.normal(size=len(x)))+20.

# Convert celsius to Fahrenheit
T_f = lambda T_c: T_c*1.8 + 32.
# Convert Fahrenheit to Celsius
T_c = lambda T_f: (T_f - 32.)/1.8

fig, ax = plt.subplots()
ax2 = ax.secondary_yaxis("right", functions=(T_f, T_c))

ax.plot(x,y, color="#dd0011")
ax.set_ylabel("Temperature [Celsius]")
ax2.set_ylabel("Temperature [Fahrenheit]")

plt.show()

The output is the same as above, but as you can see one does not need to set any limits.

ContentLicense: CC BY-SA 4.0


问:
Python String to dateTime conversion
I have a string like

```<code>a = "datetime.datetime(2009,04,01)"
</code>```

I would like to convert this to a datetime object in python. How should I proceed?

答:
you could use eval. eval lets run python code within python program

```<code>a = "datetime.datetime(2009,04,01)"
import datetime
a = eval(a)
print a
print type(a)
</code>```

will result in

```<code>2009-04-01 00:00:00
<type 'datetime.datetime'>
</code>```

Title: Python String to dateTime conversion

Body:
I have a string like

a = "datetime.datetime(2009,04,01)"

I would like to convert this to a datetime object in python. How should I proceed?

Body:
you could use eval. eval lets run python code within python program

a = "datetime.datetime(2009,04,01)"
import datetime
a = eval(a)
print a
print type(a)

will result in

2009-04-01 00:00:00
<type 'datetime.datetime'>


问:
Access React component from Socket IO listener
When I listen for a 'new-message' event I am trying to call my Dashboard component's createMessage function:

```<code>var socket = io.connect()

socket.on('new-message', (data) => {
    console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
    Dashboard.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
})

const Dashboard = React.createClass({

  createMessage: function(id, body, context, urgent, customContext) {

    this.setState({
      messages: [
        ...this.state.messages,
        {id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
      ]
    })
   }
  })
</code>```

However, I get an error: Uncaught TypeError: Dashboard.createMessage is not a function

Is there a way to access the Dashboard createMessage method from outside the component?

Alternatively is there a way to have the Dashboard component always listen for an event and I can do something like this:

```<code>var socket = io.connect()

const Dashboard = React.createClass({

  alwaysListenForEvent: function() {
      socket.on('new-message', (data) => {
          console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
          this.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
      })
  }

  createMessage: function(id, body, context, urgent, customContext) {

    this.setState({
      messages: [
        ...this.state.messages,
        {id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
      ]
    })
   }
  })
</code>```

答:
You could wrap your Dashboard component with a Socket HoC or a container component.

Example code:

```<code>class SocketListener extends React.Component {
  state = {
    messages: []
  }
  componentDidMount() {
    socket.on('new-message', (data) => {
      this.setState({ messages: this.state.messages.concat(data) })
    });
  }

  render() {
    return (
      <Dashboard
        messages={this.state.messages}
      />
    )
  }
}
</code>```

This way your Dashboard component does not need to know anything about the messages.

Body:
When I listen for a 'new-message' event I am trying to call my Dashboard component's createMessage function:

var socket = io.connect()

socket.on('new-message', (data) => {
    console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
    Dashboard.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
})

const Dashboard = React.createClass({

  createMessage: function(id, body, context, urgent, customContext) {

    this.setState({
      messages: [
        ...this.state.messages,
        {id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
      ]
    })
   }
  })

However, I get an error: Uncaught TypeError: Dashboard.createMessage is not a function

Is there a way to access the Dashboard createMessage method from outside the component?

Alternatively is there a way to have the Dashboard component always listen for an event and I can do something like this:

var socket = io.connect()

const Dashboard = React.createClass({

  alwaysListenForEvent: function() {
      socket.on('new-message', (data) => {
          console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
          this.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
      })
  }

  createMessage: function(id, body, context, urgent, customContext) {

    this.setState({
      messages: [
        ...this.state.messages,
        {id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
      ]
    })
   }
  })

Body:
You could wrap your Dashboard component with a Socket HoC or a container component.

Example code:

class SocketListener extends React.Component {
  state = {
    messages: []
  }
  componentDidMount() {
    socket.on('new-message', (data) => {
      this.setState({ messages: this.state.messages.concat(data) })
    });
  }

  render() {
    return (
      <Dashboard
        messages={this.state.messages}
      />
    )
  }
}

This way your Dashboard component does not need to know anything about the messages.


问:
Getting 'too many parameters passed' to stored procedure on ASPX page
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

```<code>"Procedure or function <sp_name> has too many arguments specified."
</code>```

Here is the code for the grid and the datasource:

```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>
</code>```

Here's the code from the stored procedure:

```<code>ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END
</code>```

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

```<code>        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }
</code>```

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?

答: Use Profiler and check what parameters are really passed to SP. </p>

Body:
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

"Procedure or function <sp_name> has too many arguments specified."

Here is the code for the grid and the datasource:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>

Here's the code from the stored procedure:

ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?


答:
The atoi function expects a single pointer to a const string, like this: (const char *str)

You can see an example of its usage here: https://www.tutorialspoint.com/c_standard_library/c_function_atoi.htm

Also I'm not sure you meant to copy your entire code(I assume LINE_MAX and TNARRAY_MAX are macros defined somewhere?) but as it stands you have a curly brace mismatch, meaning this section of code as you've posted it needs one more '}' at the very end.

Title: trying to use atoi and its not working


问:
Ways to speed up code with multiple IF statements
I've been working on this code all day and have finally gotten everything to work perfectly. The only problem, is that the code does run pretty slow. Considering that it will be used on a workbook with thousands of rows I would like to change that. I am extremely new to vba so there is probably stuff in here that is wrong or seems like a bad shortcut. I think I added a couple of ways that could speed it up but i didnt know if anything else could be done. </p>

```<code> Sub Degree_Workboook_Names_major1()

 Application.ScreenUpdating = False
 Application.DisplayStatusBar = False
 Application.EnableEvents = False

'Inserts a new column after column H named department names
 range("I1").EntireColumn.Insert
 range("I1").Value = "DeptName"

 Dim abbrRange As range              'range to hold the columns with the department names
 Set abbrRange = range("H:H")

'Writes the department name in the the department name column next to the associated abbr

 For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

 Next

 'Inserts a new column after column H named department names
range("M1").EntireColumn.Insert
range("M1").Value = "DeptName"

'Dim abbrRange As range              'range to hold the columns with the   dpeartment names
Set abbrRange = range("L:L")

'Writes the department name in the the department name column next to the associated abbr

For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

Next

range("I:I").HorizontalAlignment = xlLeft
range("M:M").HorizontalAlignment = xlLeft

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True

End Sub
</code>```

答:
In this scenario, I would prefer arrays, though Dictionary is the good option.
An example code would be like this....</p>

```<code>Sub Degree_Workbook_Names_major1()
Dim abbrRange As Range
Dim Abbr, Dept()
Dim lr As Long, i As Long

With Application
    .Calculation = xlCalculationManual
    .EnableEvents = False
    .DisplayAlerts = False
    .ScreenUpdating = False
End With

lr = Cells(Rows.Count, "H").End(xlUp).Row
Columns("I").Insert
Range("I1").Value = "DeptName"

Set abbrRange = Range("H2:H" & lr)
Abbr = abbrRange.Value
ReDim Dept(1 To lr)

For i = 1 To UBound(Abbr, 1)
    Select Case UCase(Abbr(i, 1))
        Case "ACC"
            Dept(i) = "Department of Accounting"
        Case "ACS"
            Dept(i) = "Department of Adolescent, Career and Special Education"
        Case "AES"
            Dept(i) = "Department of Animal and Equine Science"
        Case "AGR"
            Dept(i) = "Department of Department of Agricultural Science"
        Case "AHS"
            Dept(i) = "Department of Applied Health Science"
        Case "AHT"
            Dept(i) = "Department of Veterinary Technology and Pre-Veterinary Medicine"
        Case "ART"
            Dept(i) = "Department of Art and Design"
        Case "BIO"
            Dept(i) = "Department of Biology"
        'similarly add rest of the Abbreviations with Case statement and set the array Dept as shown above
    End Select
Next i
Range("I2").Resize(UBound(Dept)).Value = Application.Transpose(Dept)

With Application
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
    .DisplayAlerts = True
    .ScreenUpdating = True
End With

End Sub
</code>```

Body:
I've been working on this code all day and have finally gotten everything to work perfectly. The only problem, is that the code does run pretty slow. Considering that it will be used on a workbook with thousands of rows I would like to change that. I am extremely new to vba so there is probably stuff in here that is wrong or seems like a bad shortcut. I think I added a couple of ways that could speed it up but i didnt know if anything else could be done.

 Sub Degree_Workboook_Names_major1()

 Application.ScreenUpdating = False
 Application.DisplayStatusBar = False
 Application.EnableEvents = False

'Inserts a new column after column H named department names
 range("I1").EntireColumn.Insert
 range("I1").Value = "DeptName"

 Dim abbrRange As range              'range to hold the columns with the department names
 Set abbrRange = range("H:H")

'Writes the department name in the the department name column next to the associated abbr

 For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

 Next

 'Inserts a new column after column H named department names
range("M1").EntireColumn.Insert
range("M1").Value = "DeptName"

'Dim abbrRange As range              'range to hold the columns with the   dpeartment names
Set abbrRange = range("L:L")

'Writes the department name in the the department name column next to the associated abbr

For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

Next

range("I:I").HorizontalAlignment = xlLeft
range("M:M").HorizontalAlignment = xlLeft

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True

End Sub

Body:
In this scenario, I would prefer arrays, though Dictionary is the good option.
An example code would be like this....

Sub Degree_Workbook_Names_major1()
Dim abbrRange As Range
Dim Abbr, Dept()
Dim lr As Long, i As Long

With Application
    .Calculation = xlCalculationManual
    .EnableEvents = False
    .DisplayAlerts = False
    .ScreenUpdating = False
End With

lr = Cells(Rows.Count, "H").End(xlUp).Row
Columns("I").Insert
Range("I1").Value = "DeptName"

Set abbrRange = Range("H2:H" & lr)
Abbr = abbrRange.Value
ReDim Dept(1 To lr)

For i = 1 To UBound(Abbr, 1)
    Select Case UCase(Abbr(i, 1))
        Case "ACC"
            Dept(i) = "Department of Accounting"
        Case "ACS"
            Dept(i) = "Department of Adolescent, Career and Special Education"
        Case "AES"
            Dept(i) = "Department of Animal and Equine Science"
        Case "AGR"
            Dept(i) = "Department of Department of Agricultural Science"
        Case "AHS"
            Dept(i) = "Department of Applied Health Science"
        Case "AHT"
            Dept(i) = "Department of Veterinary Technology and Pre-Veterinary Medicine"
        Case "ART"
            Dept(i) = "Department of Art and Design"
        Case "BIO"
            Dept(i) = "Department of Biology"
        'similarly add rest of the Abbreviations with Case statement and set the array Dept as shown above
    End Select
Next i
Range("I2").Resize(UBound(Dept)).Value = Application.Transpose(Dept)

With Application
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
    .DisplayAlerts = True
    .ScreenUpdating = True
End With

End Sub


问:
How to change bootstrap columns reponsive layout with php?
I'm very new to php and wordpress and need help. I'm trying to change my bootstrap responsive grid with php. >992px I should have 3 columns, >768px I should have only 2 columns and <767px I should have only one. How can I do this with php? Really appreciate the help.

Here's my code:

```<code><div class="row">

    <?php $i = 1; while(have_posts()) : the_post();?>
    <div class="col-xs-12 col-sm-6 col-md-4">
      <div class="cover-card">
            <?php the_post_thumbnail('full', array('class' => 'image img-responsive')); ?>

            <div class="overlay">
                <div class="text">
                  <strong><?php the_title(); ?></strong>
                  <?php the_content(); ?>
                  <a href="<?php the_permalink(); ?>" class="btn btn-primary">Comprar</a>
                </div> <!-- /.text -->
            </div> <!-- /.overlay -->
        </div> <!-- /.cover-card -->
    </div> <!-- /.col-md-4 -->

<?php if ( $i % 3 === 0 ) { echo '</div> <!-- /.row -->

<div class="row">'; } ?>
<!-- store item -->
<?php $i++; endwhile; wp_reset_query(); ?>

</div>
</code>```

This is what happens with my loop on the sm resolution:

答:
```<code><div class="col-lg-4 col-md-6 col-sm-12"></div>
</code>```

The grid system is based off the idea that there are 12 columns. In the documentation it will describe what width pertains to the xs, sm, md, and lg classes.

The above solution should work because it will place three cards per row if the display is greater than 992px, two if greater than 768px, and one if less.

Here's a little example

Body:
I'm very new to php and wordpress and need help. I'm trying to change my bootstrap responsive grid with php. >992px I should have 3 columns, >768px I should have only 2 columns and <767px I should have only one. How can I do this with php? Really appreciate the help.

Here's my code:

    <?php $i = 1; while(have_posts()) : the_post();?>

            <?php the_post_thumbnail('full', array('class' => 'image img-responsive')); ?>

                  <?php the_title(); ?>
                  <?php the_content(); ?>
                  <a href="<?php the_permalink(); ?>" class="btn btn-primary">Comprar

<?php if ( $i % 3 === 0 ) { echo '

'; } ?>

<?php $i++; endwhile; wp_reset_query(); ?>

This is what happens with my loop on the sm resolution:

Body:
<div class="col-lg-4 col-md-6 col-sm-12"></div>

The grid system is based off the idea that there are 12 columns. In the documentation it will describe what width pertains to the xs, sm, md, and lg classes.

The above solution should work because it will place three cards per row if the display is greater than 992px, two if greater than 768px, and one if less.

Here's a little example


问:
PHP Move_uploaded_file not moving my file to directory
I am making an image uploading feature for a program I am developing however I cant seem to get move_uploaded_file to actually move my file and I am not sure why.

I am receiving the form data as I can see the data when I use the print_r function print_r($_FILES)

My directory struct is as follows
root->app->lib->uploadCode.php and root->app->images

I dont get any errors.
I am running this on ubuntu 16.04 with php7 installed

Here is my code.

```<code><?php
error_reporting(E_ALL);
if(!empty($_FILES['newImage']['name']))
{
    $fname = $_FILES['newImage']['name'];
    $fext = explode(".",$fname);
    $sex = array("jpg", "jpeg", "JPG", "JPEG", "png", "PNG");//Supported extensions
    //Check if file extension supported
    $extRes = array_intersect($fext, $sex);//Checks to see if file uploaded extension exists in the supported extension array
    if(count($extRes) == 1)
    {
        print_r($_FILES);
        $name = $_FILES['newImage']['name'];
        $ext = end($fext);
        $tmp = $_FILES['newImage']['tmp_name'];
        $path = '/../images/';
        $newName = uniqid().".".$ext;
        /*if(move_uploaded_file($tmp,$path.$newName))
        {
            echo "uploaded";
        }
        else
            {
                echo "not uploaded";
                echo $path.$newName;
            }*/

        move_uploaded_file($tmp,$path.$newName);
    }
    elseif(count($extRes) > 1)
        {//More than just one file extension was found possibly something like image.png.jpg
            echo 02;
        }
        else
            {// Nothing was found so wrong file type was used
                echo 01;
            }
}else
    {//Do if no image was uploaded
        echo 00;
    }
</code>```

`

答:
It was a permission issue.

I had to do the following to my www/html directory.

sudo chown -R username:www-data /var/www/html/
 sudo chmod 775 /var/www/html/
 sudo chmod g+s /var/www/html
Once I ran those commands I was able to upload

Body:
I am making an image uploading feature for a program I am developing however I cant seem to get move_uploaded_file to actually move my file and I am not sure why.

I am receiving the form data as I can see the data when I use the print_r function print_r($_FILES)

My directory struct is as follows
root->app->lib->uploadCode.php and root->app->images

I dont get any errors.
I am running this on ubuntu 16.04 with php7 installed

Here is my code.

<?php
error_reporting(E_ALL);
if(!empty($_FILES['newImage']['name']))
{
    $fname = $_FILES['newImage']['name'];
    $fext = explode(".",$fname);
    $sex = array("jpg", "jpeg", "JPG", "JPEG", "png", "PNG");//Supported extensions
    //Check if file extension supported
    $extRes = array_intersect($fext, $sex);//Checks to see if file uploaded extension exists in the supported extension array
    if(count($extRes) == 1)
    {
        print_r($_FILES);
        $name = $_FILES['newImage']['name'];
        $ext = end($fext);
        $tmp = $_FILES['newImage']['tmp_name'];
        $path = '/../images/';
        $newName = uniqid().".".$ext;
        /*if(move_uploaded_file($tmp,$path.$newName))
        {
            echo "uploaded";
        }
        else
            {
                echo "not uploaded";
                echo $path.$newName;
            }*/

        move_uploaded_file($tmp,$path.$newName);
    }
    elseif(count($extRes) > 1)
        {//More than just one file extension was found possibly something like image.png.jpg
            echo 02;
        }
        else
            {// Nothing was found so wrong file type was used
                echo 01;
            }
}else
    {//Do if no image was uploaded
        echo 00;
    }

`


问:
jQuery if-else working 50%
The code below is inside a document.ready function. The if-else statement works only half the way... the first part (if) works fine, and I made an alert after powerClicked to show me if it's setting powerClicked to 1, and it is. The else if does absolutely nothing... Anyone seeing my error? I don't know if something might be bugging the jQuery, the entire HTML is being rendered over ReactJS VDOM.

var powerClicked = 0;

    if(powerClicked == 0) {
        $('#Power').click(function() {
            powerClicked = 1;
           $('#Power').animate({
              backgroundColor: 'rgba(255,0,0,1)'
           }, 1500);
            //fading in text
        $('#boxText').delay(2000).fadeIn(500).text('Listening');

        });

    } else if(powerClicked == 1) {
        $('#Power').click(function() {

           $('#Power').animate({
              backgroundColor: 'rgba(255,255,255,1)'
           }, 1500);
           //fading out text
            $('boxText').fadeOut(500);
            powerClicked = 0;
        });
    }```

答:
When your code runs, the if statement runs and creates the function to handle clicks for the $('#Power') element.

Whenever the $('#Power') element is clicked, the function defined within it will be triggered.  The if-else will never execute again.  You need to move the if-else logic within the click handler.  Something like this should work:

```<code>    var powerClicked = false;
    $('#Power').click(function() {
       powerClicked = !powerClicked;

       if (powerClicked) {
         $('#Power').animate({
            backgroundColor: 'rgba(255,0,0,1)'
         }, 1500);
       } else {
         $('#Power').animate({
            backgroundColor: 'rgba(255,255,255,1)'
         }, 1500);

       }

       //fading in text
       $('#boxText').delay(2000).fadeIn(500).text('Listening');
    });
</code>```

Title: jQuery if-else working 50%

Body:
When your code runs, the if statement runs and creates the function to handle clicks for the $('#Power') element.

Whenever the $('#Power') element is clicked, the function defined within it will be triggered.  The if-else will never execute again.  You need to move the if-else logic within the click handler.  Something like this should work:

    var powerClicked = false;
    $('#Power').click(function() {
       powerClicked = !powerClicked;

       if (powerClicked) {
         $('#Power').animate({
            backgroundColor: 'rgba(255,0,0,1)'
         }, 1500);
       } else {
         $('#Power').animate({
            backgroundColor: 'rgba(255,255,255,1)'
         }, 1500);

       }

       //fading in text
       $('#boxText').delay(2000).fadeIn(500).text('Listening');
    });


问:
C# asp.NET displaying output of a query to screen. Error: 'System.ArgumentException' in Oracle.DataAccess.dll
First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.

Here's my front end:

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    DataConnector dc = new DataConnector();
    GridView2.DataSource = dc.getCodeTypes();
    GridView2.DataBind();
}
</code>```

When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015

Back End:

```<code>//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
    try
    {
        OracleConnection con = new OracleConnection(connString);
        con.Open();

       string query = "select id, descr from code_desc where code_type_id = 0";

        // Create the OracleCommand
        OracleCommand cmd = new OracleCommand();

        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;

        // Execute command, create OracleDataReader object
        OracleDataReader reader = cmd.ExecuteReader();

        List<CodeDesc> L = new List<CodeDesc>();

        while (reader.Read())
        {
            CodeDesc c = new CodeDesc();
            c.id = reader.GetInt32(0);
            c.description = reader.GetString(1);
            L.Add(c);
        }
        // Clean up
        reader.Dispose();
        cmd.Dispose();
        con.Dispose();

        System.Diagnostics.Debug.WriteLine(L);
        return L;
    }
    catch (Exception ex)
    {
      // catch clause here...
    }
}
</code>```

CodeDesc:

```<code>public class CodeDesc
{
    public int id { get; set; }
    public string description { get; set; }
}
</code>```

Any help would be great.

答:
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.

Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block

```<code>public List<CodeDesc> getCodeTypes()
{
    try
    {
        List<CodeDesc> L = new List<CodeDesc>();
        string query = "select id, descr from code_desc where code_type_id = 0";
        using(OracleConnection con = new OracleConnection(connString))
        using(OracleCommand cmd = new OracleCommand(query, con))
        {
            con.Open();
            // Execute command, create OracleDataReader object
            using(OracleDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                   CodeDesc c = new CodeDesc();
                   c.id = reader.GetInt32(0);
                   c.description = reader.GetString(1);
                   L.Add(c);
                }
            }
       }
       System.Diagnostics.Debug.WriteLine(L);
       return L;
  }
</code>```

Body:
First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.

Here's my front end:

protected void Button1_Click(object sender, EventArgs e)
{
    DataConnector dc = new DataConnector();
    GridView2.DataSource = dc.getCodeTypes();
    GridView2.DataBind();
}

When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015

Back End:

//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
    try
    {
        OracleConnection con = new OracleConnection(connString);
        con.Open();

       string query = "select id, descr from code_desc where code_type_id = 0";

        // Create the OracleCommand
        OracleCommand cmd = new OracleCommand();

        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;

        // Execute command, create OracleDataReader object
        OracleDataReader reader = cmd.ExecuteReader();

        List<CodeDesc> L = new List<CodeDesc>();

        while (reader.Read())
        {
            CodeDesc c = new CodeDesc();
            c.id = reader.GetInt32(0);
            c.description = reader.GetString(1);
            L.Add(c);
        }
        // Clean up
        reader.Dispose();
        cmd.Dispose();
        con.Dispose();

        System.Diagnostics.Debug.WriteLine(L);
        return L;
    }
    catch (Exception ex)
    {
      // catch clause here...
    }
}

CodeDesc:

public class CodeDesc
{
    public int id { get; set; }
    public string description { get; set; }
}

Any help would be great.

Body:
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.

Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block

public List<CodeDesc> getCodeTypes()
{
    try
    {
        List<CodeDesc> L = new List<CodeDesc>();
        string query = "select id, descr from code_desc where code_type_id = 0";
        using(OracleConnection con = new OracleConnection(connString))
        using(OracleCommand cmd = new OracleCommand(query, con))
        {
            con.Open();
            // Execute command, create OracleDataReader object
            using(OracleDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                   CodeDesc c = new CodeDesc();
                   c.id = reader.GetInt32(0);
                   c.description = reader.GetString(1);
                   L.Add(c);
                }
            }
       }
       System.Diagnostics.Debug.WriteLine(L);
       return L;
  }


问:
Facebook Connect and Photo Albums
I am currently developing a site for models/actors, and at this point I am just trying to ascertain what I can and can't do with Facebook Connect (I have virtually no experience in using Facebook Connect or FQL).

Basically there is going to be a facility whereby users will be able to upload their pictures. I want to know is it possible to use Facebook Connect to get the user's photo albums, in order to save the user from re-uploading all the photo's that are already on FB?

If so, do I/should I LINK to these photos, or FETCH them from Facebook and save a copy on my server?

EDIT: Just to clarify, this is what I want to do:

User will register on my site and agree to associate their Facebook ID with my site.

I then want to present the user with a list of all their albums that are on Facebook, the user can then select which albums they want to display on my site.

(optional) The user can select which specific photos in each album they want to display on my site.

Is this possible to do at all?

答:
You can upload photos using the API. Check out this: http://developers.facebook.com/docs/reference/api/photo

If it were me, I would just upload the photo to Facebook and save the URL of the image rather than store it on my own server. You could do either one, but I don't see the sense is storing the image twice. The one issue could be if you wanted your photo at a higher quality than Facebook allows, but their quality is pretty high.

Title: Facebook Connect and Photo Albums