问:
Jar File only working on my computer
I have code to run a simple runtime test on how long it takes to run a simple file, once it completes that I output the results to a file in the public users folder. It works on my computer but not on anyone other. This is my code</p>

```<code>import java.awt.List;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import javax.swing.*;
    public class Speed {
    public static void main(String[] args) {

        final long length=100000000;
        List merh = new List();
        File filename = new File("C:\\Users\\Public\\filename.txt ");
        final long startTime = System.currentTimeMillis();
        for (int i = 0; i < length; i++) {
             merh.add( "Hereherehehrehrehrherh");
        }
        final long endTime = System.currentTimeMillis();

        System.out.println("Total execution time: " + (endTime - startTime)
);

        Writer writer = null;

        try {
            writer = new BufferedWriter(new OutputStreamWriter(

                  new FileOutputStream(filename), "utf-8"));
            writer.write("Total execution time: " + (endTime - startTime));
        } catch (IOException ex) {
          // report
        } finally {
           try {writer.close();} catch (Exception ex) {/*ignore*/}
        }

     }

}
</code>```

答:
This Code is working perfectly fine. I tested this in my machine and output is

Total execution time: 6728

What error are you getting on other machines

Title: Jar File only working on my computer

Body:
I have code to run a simple runtime test on how long it takes to run a simple file, once it completes that I output the results to a file in the public users folder. It works on my computer but not on anyone other. This is my code

import java.awt.List;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import javax.swing.*;
    public class Speed {
    public static void main(String[] args) {

        final long length=100000000;
        List merh = new List();
        File filename = new File("C:\\Users\\Public\\filename.txt ");
        final long startTime = System.currentTimeMillis();
        for (int i = 0; i < length; i++) {
             merh.add( "Hereherehehrehrehrherh");
        }
        final long endTime = System.currentTimeMillis();

        System.out.println("Total execution time: " + (endTime - startTime)
);

        Writer writer = null;

        try {
            writer = new BufferedWriter(new OutputStreamWriter(

                  new FileOutputStream(filename), "utf-8"));
            writer.write("Total execution time: " + (endTime - startTime));
        } catch (IOException ex) {
          // report
        } finally {
           try {writer.close();} catch (Exception ex) {/*ignore*/}
        }

     }

}


来源: stackexchange

问:
Boost Tcp Client Receive Crash
I have been working recently with the Boost library for windows visual studio 2015. I have been recently working on a server and client that can easily transfer data via tcp connection. But recently I was trying to send a Base64 encoded file string to the client which is roughly 366,660 Bytes of data. To do this I split up the data into packets that are about 1000 in size. (not sure what the max size is) But anyway the server sends the data completely fine but when the client receives more than 160,000 bytes it crashes with no exceptions.

Client:

```<code>try
{
    for (static int i = 1000; i <= sizeofpackets /*(366,660) (currently 170,000 for testing)*/; i += 1000)
    {
        char Buffer[1000];
        memset(Buffer, 0, 1000);
        boost::asio::read(s, boost::asio::buffer(Buffer, 1000));
        std::cout << i << std::endl;
    }
}
catch (std::exception& e)
{
    std::cerr << "Exception: " << e.what() << "\n";
}
</code>```

Server:

```<code>for (int i = 1000; i <= 170000; i += 1000)
{
    std::string NewData = encodedBuffer.substr(i - 1000, i);
    NewData.erase(0, i - 1000);
    boost::asio::write(*sock, boost::asio::buffer(NewData, 1000));
    std::cout << NewData.size() + i - 1000 << std::endl;
    NewData.clear();
}
</code>```

Any comments or suggestion would help greatly!

答:
You haven't posted your complete code, so it is hard to tell, but your problem might be the way you are handling strings, not the way you are handling the socket transfers (the substr() member function takes a start offset and a size, and it looks like you are trying to use an ever-increasing size for NewData).

The following (complete) code, which uses your client and server code as a reference, but with the string handling changed, does transfer 170000 bytes just fine on my machine, so it may help:

```<code>#include <boost/asio/io_service.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <array>
#include <string>
#include <iostream>

namespace
{
    const size_t BIG_MESSAGE_SIZE = 170000;
    const size_t BLOCK_SIZE = 1000;

    void doTX(boost::asio::ip::tcp::socket& socket, size_t& TXsize)
    {
        char rawBuffer[BIG_MESSAGE_SIZE] = { 0 }; // raw data to send
        std::string encodedBuffer(rawBuffer, BIG_MESSAGE_SIZE);
        for (size_t i = 0; i < BIG_MESSAGE_SIZE; i += BLOCK_SIZE)
        {
            std::string NewData = encodedBuffer.substr(i, BLOCK_SIZE);
            TXsize += boost::asio::write(socket, boost::asio::buffer(NewData, BLOCK_SIZE));
        }
    }

    void doRX(boost::asio::ip::tcp::socket& socket, size_t& RXsize)
    {
        for (size_t i = 0; i < BIG_MESSAGE_SIZE; i += BLOCK_SIZE)
        {
            char Buffer[BLOCK_SIZE];
            memset(Buffer, 0, BLOCK_SIZE);
            RXsize += boost::asio::read(socket, boost::asio::buffer(Buffer, BLOCK_SIZE));
        }
    }
}

int main(int argc, char * argv[])
{
    std::cout << "Running:" << std::endl;

    int port = 9876;

    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), port);
    boost::asio::ip::tcp::acceptor acceptor(ios, endpoint);
    boost::asio::ip::tcp::socket TXsocket(ios);
    boost::asio::ip::tcp::socket RXsocket(ios);

    TXsocket.connect(endpoint);
    acceptor.accept(RXsocket);

    size_t TXsize = 0;
    size_t RXsize = 0;

    doTX(TXsocket, TXsize);
    doRX(RXsocket, RXsize);

    std::cout << TXsize << " " << RXsize << std::endl;

    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Boost Tcp Client Receive Crash

Body:
I have been working recently with the Boost library for windows visual studio 2015. I have been recently working on a server and client that can easily transfer data via tcp connection. But recently I was trying to send a Base64 encoded file string to the client which is roughly 366,660 Bytes of data. To do this I split up the data into packets that are about 1000 in size. (not sure what the max size is) But anyway the server sends the data completely fine but when the client receives more than 160,000 bytes it crashes with no exceptions.

Client:

try
{
    for (static int i = 1000; i <= sizeofpackets /*(366,660) (currently 170,000 for testing)*/; i += 1000)
    {
        char Buffer[1000];
        memset(Buffer, 0, 1000);
        boost::asio::read(s, boost::asio::buffer(Buffer, 1000));
        std::cout << i << std::endl;
    }
}
catch (std::exception& e)
{
    std::cerr << "Exception: " << e.what() << "\n";
}

Server:

for (int i = 1000; i <= 170000; i += 1000)
{
    std::string NewData = encodedBuffer.substr(i - 1000, i);
    NewData.erase(0, i - 1000);
    boost::asio::write(*sock, boost::asio::buffer(NewData, 1000));
    std::cout << NewData.size() + i - 1000 << std::endl;
    NewData.clear();
}

Any comments or suggestion would help greatly!

Body:
You haven't posted your complete code, so it is hard to tell, but your problem might be the way you are handling strings, not the way you are handling the socket transfers (the substr() member function takes a start offset and a size, and it looks like you are trying to use an ever-increasing size for NewData).

The following (complete) code, which uses your client and server code as a reference, but with the string handling changed, does transfer 170000 bytes just fine on my machine, so it may help:

#include <boost/asio/io_service.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <array>
#include <string>
#include <iostream>

namespace
{
    const size_t BIG_MESSAGE_SIZE = 170000;
    const size_t BLOCK_SIZE = 1000;

    void doTX(boost::asio::ip::tcp::socket& socket, size_t& TXsize)
    {
        char rawBuffer[BIG_MESSAGE_SIZE] = { 0 }; // raw data to send
        std::string encodedBuffer(rawBuffer, BIG_MESSAGE_SIZE);
        for (size_t i = 0; i < BIG_MESSAGE_SIZE; i += BLOCK_SIZE)
        {
            std::string NewData = encodedBuffer.substr(i, BLOCK_SIZE);
            TXsize += boost::asio::write(socket, boost::asio::buffer(NewData, BLOCK_SIZE));
        }
    }

    void doRX(boost::asio::ip::tcp::socket& socket, size_t& RXsize)
    {
        for (size_t i = 0; i < BIG_MESSAGE_SIZE; i += BLOCK_SIZE)
        {
            char Buffer[BLOCK_SIZE];
            memset(Buffer, 0, BLOCK_SIZE);
            RXsize += boost::asio::read(socket, boost::asio::buffer(Buffer, BLOCK_SIZE));
        }
    }
}

int main(int argc, char * argv[])
{
    std::cout << "Running:" << std::endl;

    int port = 9876;

    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), port);
    boost::asio::ip::tcp::acceptor acceptor(ios, endpoint);
    boost::asio::ip::tcp::socket TXsocket(ios);
    boost::asio::ip::tcp::socket RXsocket(ios);

    TXsocket.connect(endpoint);
    acceptor.accept(RXsocket);

    size_t TXsize = 0;
    size_t RXsize = 0;

    doTX(TXsocket, TXsize);
    doRX(RXsocket, RXsize);

    std::cout << TXsize << " " << RXsize << std::endl;

    return 0;
}


问:
Displaying Average together with other columns in a query
I want to display a list of members which is more than the average of all other members. My table looks like this: </p>

```<code>CREATE TABLE Members
(
    MemberID nvarchar(50) NOT NULL PRIMARY KEY,
    MemberName nvarchar(50) NOT NULL,
    MemberAddress nvarchar(50),
    MemberContact int,
    MemberAge int,
    RegistrationDate nvarchar(50)
);

--Inserting Values into Members' Table--
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM01', 'Muhammed Abdul', 'Damansara','01121565987', '34', '20/02/2017');
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM02', 'Kyle Franklin', 'Kuala Lumpur','01725445807','36', '10/04/2017');
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM03', 'Albert Derio', 'Shah Alam','01800235613','56','6/03/2017');
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM04', 'Khaled Ahmad', 'Penang','01602144956','33','9/01/2017');
</code>```

<p>Here's what I tried so far but no luck: </p>

```<code>SELECT MemberID, MemberName, MemberAge,FROM Members
(SELECT AVG(Members.MemberAge) AS AverageAge)
WHERE MemberAge>=AverageAge
</code>```

答:
```<code>SELECT
    Members.*,
    (SELECT AVG(MemberAge) FROM Members) AS AverageAge
FROM
    Members
WHERE
    MemberAge > (SELECT AVG(MemberAge) FROM Members)
</code>```

...though this will result in duplicate data in the new AverageAge column - a batch query (a query that returns multiple result sets) would be cleaner:

MySQL has implicit variable declaration (unlike T-SQL which requires forward declaration), so you can do this:

```<code>-- 1. Get the average-age value:
SELECT @averageAge = AVG(MemberAge) FROM Members;

-- 2. Return the average-age value to the database client as a scalar value:
SELECT @averageAge;

-- 3. Query for Members whose age is above-average in a second batch result:
SELECT
    Members.*
FROM
    Members
WHERE
    MemberAge > @averageAge
</code>```

Body:
I want to display a list of members which is more than the average of all other members. My table looks like this:

CREATE TABLE Members
(
    MemberID nvarchar(50) NOT NULL PRIMARY KEY,
    MemberName nvarchar(50) NOT NULL,
    MemberAddress nvarchar(50),
    MemberContact int,
    MemberAge int,
    RegistrationDate nvarchar(50)
);

--Inserting Values into Members' Table--
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM01', 'Muhammed Abdul', 'Damansara','01121565987', '34', '20/02/2017');
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM02', 'Kyle Franklin', 'Kuala Lumpur','01725445807','36', '10/04/2017');
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM03', 'Albert Derio', 'Shah Alam','01800235613','56','6/03/2017');
INSERT INTO Members(MemberID, MemberName, MemberAddress, MemberContact, MemberAge,RegistrationDate)
VALUES ('MEM04', 'Khaled Ahmad', 'Penang','01602144956','33','9/01/2017');

Here's what I tried so far but no luck:

SELECT MemberID, MemberName, MemberAge,FROM Members
(SELECT AVG(Members.MemberAge) AS AverageAge)
WHERE MemberAge>=AverageAge

Body:
SELECT
    Members.*,
    (SELECT AVG(MemberAge) FROM Members) AS AverageAge
FROM
    Members
WHERE
    MemberAge > (SELECT AVG(MemberAge) FROM Members)

...though this will result in duplicate data in the new AverageAge column - a batch query (a query that returns multiple result sets) would be cleaner:

MySQL has implicit variable declaration (unlike T-SQL which requires forward declaration), so you can do this:

-- 1. Get the average-age value:
SELECT @averageAge = AVG(MemberAge) FROM Members;

-- 2. Return the average-age value to the database client as a scalar value:
SELECT @averageAge;

-- 3. Query for Members whose age is above-average in a second batch result:
SELECT
    Members.*
FROM
    Members
WHERE
    MemberAge > @averageAge


问:
How do i add linting to pre-commit hook
hi everyone i have a git repo that house 3 folders (individual js projects).

here's my pre-commit hook

```<code>#!/bin/bash
echo -e "\033[1;92m Linting Staged Files . . . "

files=$(git diff --diff-filter=d --cached --name-only | grep -E '\.(js|jsx)$')
path=(${files[0]//// })

if [[ $files = "" ]] ; then
  echo -e "\033[1;31m You have no staged file, exiting . . "
  exit 1
fi

for file in $files
do
git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")
 if [ $? -ne 0 ]; then
   echo -e "\033[1;31m ESLint failed on staged file '$file'. \n Code will not be committed, Please fix your code and try again."
exit 1
 fi
done

BRANCH=`git rev-parse --abbrev-ref HEAD`

if [[ "$BRANCH" == "master" || "$BRANCH" == "develop" ]]; then
 echo "\033[1;31m commiting to $BRANCH is illegal."
 echo "\033[1;31m If you really know what you're doing, then add the argument '-n' to skip this git hook."
 exit 1
fi

exit 0
</code>```

but it keeps failing at this line git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")

with an error

.git/hooks/pre-commit: line 17: ./node_modules/.bin/eslint --stdin --stdin-filename sfa/src/SFAApp.js: No such file or directory

i have no idea what i'm doing wrong please help.

答:
You're trying to run a command literally named:

```<code>./node_modules/.bin/eslint --stdin --stdin-filename sfa/src/SFAApp.js
</code>```

rather than trying to run a command named:

```<code>./node_modules/.bin/eslint
</code>```

with arguments:

```<code>--stdin
</code>```

and:

```<code>--stdin-filename
</code>```

and:

```<code>sfa/src/SFAApp.js
</code>```

The cure is to fix your double quote placement.  Once you do, you will probably have a second problem:

```<code>git show ":$file" | $(./$path/node_modules/.bin/eslint --stdin --stdin-filename "$file")
</code>```

will run the command with the arguments, but then, because it is inside $(...), will take its output as a command.  I know nothing of eslint, but it seems likely that this should read:

```<code>git show ":$file" | ./$path/node_modules/.bin/eslint --stdin --stdin-filename "$file"
</code>```

(I'm also not at all sure what the silliness with $path is about.  The line path=(${files[0]//// }) sets path to the first file path-name component of the files listed by git diff, e.g., if the output is a/b/c.js, path is set to a.)

Title: How do i add linting to pre-commit hook

Body:
hi everyone i have a git repo that house 3 folders (individual js projects).

here's my pre-commit hook

#!/bin/bash
echo -e "\033[1;92m Linting Staged Files . . . "

files=$(git diff --diff-filter=d --cached --name-only | grep -E '\.(js|jsx)$')
path=(${files[0]//// })

if [[ $files = "" ]] ; then
  echo -e "\033[1;31m You have no staged file, exiting . . "
  exit 1
fi

for file in $files
do
git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")
 if [ $? -ne 0 ]; then
   echo -e "\033[1;31m ESLint failed on staged file '$file'. \n Code will not be committed, Please fix your code and try again."
exit 1
 fi
done

BRANCH=`git rev-parse --abbrev-ref HEAD`

if [[ "$BRANCH" == "master" || "$BRANCH" == "develop" ]]; then
 echo "\033[1;31m commiting to $BRANCH is illegal."
 echo "\033[1;31m If you really know what you're doing, then add the argument '-n' to skip this git hook."
 exit 1
fi

exit 0

but it keeps failing at this line git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")

with an error

.git/hooks/pre-commit: line 17: ./node_modules/.bin/eslint --stdin --stdin-filename sfa/src/SFAApp.js: No such file or directory

i have no idea what i'm doing wrong please help.

Body:
You're trying to run a command literally named:

./node_modules/.bin/eslint --stdin --stdin-filename sfa/src/SFAApp.js

rather than trying to run a command named:

./node_modules/.bin/eslint

with arguments:

--stdin

and:

--stdin-filename

and:

sfa/src/SFAApp.js

The cure is to fix your double quote placement.  Once you do, you will probably have a second problem:

git show ":$file" | $(./$path/node_modules/.bin/eslint --stdin --stdin-filename "$file")

will run the command with the arguments, but then, because it is inside $(...), will take its output as a command.  I know nothing of eslint, but it seems likely that this should read:

git show ":$file" | ./$path/node_modules/.bin/eslint --stdin --stdin-filename "$file"

(I'm also not at all sure what the silliness with $path is about.  The line path=(${files[0]//// }) sets path to the first file path-name component of the files listed by git diff, e.g., if the output is a/b/c.js, path is set to a.)


问:
Changing images on Bootstrap's Portfolio Item template
Using bootstrap’s template available on https://startbootstrap.com/template-overviews/portfolio-item/, I am trying to change source of figure by clicking on smaller ones. Here’s what I've tried without success. (Thanks in advance!)

Added id="myImage" on main figure

```<code><img class="img-responsive" id="myImage" src="img1.jpg">
</code>```

and onClick="changeImage()" on smaller

```<code><div class="col-sm-3 col-xs-6">
    <a href="#" onClick="changeImage()">
        <img class="img-responsive portfolio-item" src="img2.jpg">
    </a>
</div>
</code>```

The script function is:

```<code><script type="text/javascript">
    function changeImage() {
        if(document.getElementById('myImage').src == 'img1.jpg') {
            document.getElementById('myImage').src = 'img2.jpg';
        } else if(document.getElementById('myImage').src == 'img2.jpg') {
            document.getElementById('myImage').src = 'img1.jpg';
        }
    }
</script>
</code>```

(Thanks in advance!)

答:
getElementBYId('onlyIDnoDot') should be the syntax.</p>

```<code><script type="text/javascript">
    function changeImage() {
        if(document.getElementById('myImage').src == 'http://placehold.it/750x500') {
            document.getElementById('myImage').src = 'http://placehold.it/500x300';
        } else if(document.getElementById('myImage').src == 'http://placehold.it/500x300') {
            document.getElementById('myImage').src = 'http://placehold.it/750x500';
        }
    }
</script>
</code>```

Body:
Using bootstrap’s template available on https://startbootstrap.com/template-overviews/portfolio-item/, I am trying to change source of figure by clicking on smaller ones. Here’s what I've tried without success. (Thanks in advance!)

Added id="myImage" on main figure

and onClick="changeImage()" on smaller

The script function is:

(Thanks in advance!)

Body:
getElementBYId('onlyIDnoDot') should be the syntax.

<script type="text/javascript">
    function changeImage() {
        if(document.getElementById('myImage').src == 'http://placehold.it/750x500') {
            document.getElementById('myImage').src = 'http://placehold.it/500x300';
        } else if(document.getElementById('myImage').src == 'http://placehold.it/500x300') {
            document.getElementById('myImage').src = 'http://placehold.it/750x500';
        }
    }
</script>


问:
Add two quotes in JavaScript
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs); ```
</div>
</div>
</p>

<p>I want to have everything between two quotes in variable <code>valeurs</code> like this:</p>

<pre class="lang-none prettyprint-override"><code>, '12 .45 ', '45 .78', 'charone', 'chartwo'
</code>```

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'
```

I can have in my JSON other strings.

How can I do this in JavaScript?

答:
If interpret Question correctly, you can use Object.values(), Array.prototype.join() with parameter "','", template literal

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

 var valeurs = `",'${Object.values(event).join("','")}'"`;

 console.log(valeurs);```

Title: Add two quotes in JavaScript

Body:
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs);

I want to have everything between two quotes in variable valeurs like this:

, '12 .45 ', '45 .78', 'charone', 'chartwo'

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'

I can have in my JSON other strings.

How can I do this in JavaScript?


问:
Porting Applescript to Scripting Bridge: can't get value of range in Excel 2008
I have a need to move some Applescript code to Scripting Bridge to take advantage of some Cocoa hooks without the need for Applescript-ObjC.

Using Excel 2008 with Applescript, getting the value of a range is easy:

```<code>set myList to GetValuesFromColumnRange("A", 1, 100)

 on GetValuesFromColumnRange(ColumnLetter, FirstRow, LastRow) -- (string, integer, integer) as list
     set theList to {}
     tell application "Microsoft Excel"
         set theRange to ColumnLetter & FirstRow & ":" & ColumnLetter & LastRow
         set AppleScript's text item delimiters to {return}
         set theList to (get value of range theRange as list)
         set AppleScript's text item delimiters to {""}
     end tell
     set theList to ConvertItemizedListToValueList(theList) of me -- Note this dependency due to how MSE2008 returns the data
     return theList
 end GetValuesFromColumnRange
</code>```

But in Scripting Bridge, I'm having a problem getting the cells of a worksheet based on a range. The following is what I have so far.

```<code>    Excel2008Application *excelApp = [SBApplication applicationWithBundleIdentifier:@"com.microsoft.Excel"];

    Excel2008Workbook *workbook = excelApp.activeWorkbook;

    SBElementArray *sheets = [workbook sheets];

    Excel2008Sheet *targetSheet;
    int thisSheet = 0;
    int lastSheet = [sheets count];

    for (thisSheet = 0; thisSheet < lastSheet; thisSheet++) {
        Excel2008Sheet *currentSheet = [sheets objectAtIndex:thisSheet];
        NSString *currentSheetName = currentSheet.name;
        if ([currentSheetName isEqualToString:@"Metadata"]) {
            targetSheet = currentSheet;
            [targetSheet retain];
        }
    }

    Excel2008Range *range = [[[excelApp classForScriptingClass:@"range"] alloc] initWithProperties:[NSDictionary dictionaryWithObjectsAndKeys:@"A1:A10", @"formulaR1c1", nil]];

    [[targetSheet ranges] addObject:range];
    range = [[targetSheet ranges] lastObject]; // not null; stated class in log: MicrosoftExcelRange

    Excel2008Sheet *valueSheet = range.worksheetObject; // supposed to be new worksheet based upon values within the range; not null; stated class in log: MicrosoftExcelSheet
    [valueSheet retain];

    SBElementArray *valueCells = [valueSheet cells]; // not null, but count is 0
    [valueCells retain];
</code>```

The problem comes with the last line, when I actually get the cells from valueSheet, in that the returned SBElementArray isn't null, but it also doesn't contain any objects. The same goes for getting the cells in targetSheet as well.

Documentation to do this, near as I can tell from all my searching, does not exist and I've taken this about as far as I can.

答:
Solved.

```<code>NSString *rangeName = @"A1:A10";

Excel2008Range *range = [[[excelApp classForScriptingClass:@"range"] alloc] initWithProperties:[NSDictionary dictionaryWithObjectsAndKeys:rangeName, @"name", nil]];
[[targetSheet ranges] addObject:range];

Excel2008Range *currentRange;
if ([[[targetSheet ranges] objectWithName:rangeName] exists]) {
    currentRange = [[targetSheet ranges] objectWithName:rangeName];
}

NSLog(@"[currentRange.value get] = %@", [currentRange.value get]);
// result: ((key),(1),(2),(3),(4),(5),(6),(7),(8),(9)) = NSArray
</code>```

It seems the trick is to set the range string into the name property of the Excel2008Range. The one pitfall I had found while working on this is to never populate the formulaR1c1 of the range—as in [NSDictionary dictionaryWithObjectsAndKeys:rangeName, @"formulaR1c1", nil]—because that will populate the range with the value of the range string.

In hindsight this actually makes sense when reading the syntax of the exact same command in both Applescript...

```<code>tell application "Microsoft Excel"
    set theValues to get value of range "A1:A10"
end tell
</code>```

...and objc-appscript...

```<code>NSString *rangeString = @"A1:A10"
MEApplication *microsoftExcel = [MEApplication applicationWithName: @"Microsoft Excel"];
MEReference *cells = [[[microsoftExcel ranges] byName:rangeString] value];
NSArray *cellValues = [cells getItem];
</code>```

In both cases the value of the range is gained by getting a range of values with its name. But with Scripting Bridge, near as I can tell, the name has to be applied explicitly upon creation of the range object.

I'm sure there is a better way of accomplishing this (there usually is), but at least this works.

ContentLicense: CC BY-SA 2.5

Body:
I have a need to move some Applescript code to Scripting Bridge to take advantage of some Cocoa hooks without the need for Applescript-ObjC.

Using Excel 2008 with Applescript, getting the value of a range is easy:

set myList to GetValuesFromColumnRange("A", 1, 100)

 on GetValuesFromColumnRange(ColumnLetter, FirstRow, LastRow) -- (string, integer, integer) as list
     set theList to {}
     tell application "Microsoft Excel"
         set theRange to ColumnLetter & FirstRow & ":" & ColumnLetter & LastRow
         set AppleScript's text item delimiters to {return}
         set theList to (get value of range theRange as list)
         set AppleScript's text item delimiters to {""}
     end tell
     set theList to ConvertItemizedListToValueList(theList) of me -- Note this dependency due to how MSE2008 returns the data
     return theList
 end GetValuesFromColumnRange

But in Scripting Bridge, I'm having a problem getting the cells of a worksheet based on a range. The following is what I have so far.

    Excel2008Application *excelApp = [SBApplication applicationWithBundleIdentifier:@"com.microsoft.Excel"];

    Excel2008Workbook *workbook = excelApp.activeWorkbook;

    SBElementArray *sheets = [workbook sheets];

    Excel2008Sheet *targetSheet;
    int thisSheet = 0;
    int lastSheet = [sheets count];

    for (thisSheet = 0; thisSheet < lastSheet; thisSheet++) {
        Excel2008Sheet *currentSheet = [sheets objectAtIndex:thisSheet];
        NSString *currentSheetName = currentSheet.name;
        if ([currentSheetName isEqualToString:@"Metadata"]) {
            targetSheet = currentSheet;
            [targetSheet retain];
        }
    }

    Excel2008Range *range = [[[excelApp classForScriptingClass:@"range"] alloc] initWithProperties:[NSDictionary dictionaryWithObjectsAndKeys:@"A1:A10", @"formulaR1c1", nil]];

    [[targetSheet ranges] addObject:range];
    range = [[targetSheet ranges] lastObject]; // not null; stated class in log: MicrosoftExcelRange

    Excel2008Sheet *valueSheet = range.worksheetObject; // supposed to be new worksheet based upon values within the range; not null; stated class in log: MicrosoftExcelSheet
    [valueSheet retain];

    SBElementArray *valueCells = [valueSheet cells]; // not null, but count is 0
    [valueCells retain];

The problem comes with the last line, when I actually get the cells from valueSheet, in that the returned SBElementArray isn't null, but it also doesn't contain any objects. The same goes for getting the cells in targetSheet as well.

Documentation to do this, near as I can tell from all my searching, does not exist and I've taken this about as far as I can.

Body:
Solved.

NSString *rangeName = @"A1:A10";

Excel2008Range *range = [[[excelApp classForScriptingClass:@"range"] alloc] initWithProperties:[NSDictionary dictionaryWithObjectsAndKeys:rangeName, @"name", nil]];
[[targetSheet ranges] addObject:range];

Excel2008Range *currentRange;
if ([[[targetSheet ranges] objectWithName:rangeName] exists]) {
    currentRange = [[targetSheet ranges] objectWithName:rangeName];
}

NSLog(@"[currentRange.value get] = %@", [currentRange.value get]);
// result: ((key),(1),(2),(3),(4),(5),(6),(7),(8),(9)) = NSArray

It seems the trick is to set the range string into the name property of the Excel2008Range. The one pitfall I had found while working on this is to never populate the formulaR1c1 of the range—as in [NSDictionary dictionaryWithObjectsAndKeys:rangeName, @"formulaR1c1", nil]—because that will populate the range with the value of the range string.

In hindsight this actually makes sense when reading the syntax of the exact same command in both Applescript...

tell application "Microsoft Excel"
    set theValues to get value of range "A1:A10"
end tell

...and objc-appscript...

NSString *rangeString = @"A1:A10"
MEApplication *microsoftExcel = [MEApplication applicationWithName: @"Microsoft Excel"];
MEReference *cells = [[[microsoftExcel ranges] byName:rangeString] value];
NSArray *cellValues = [cells getItem];

In both cases the value of the range is gained by getting a range of values with its name. But with Scripting Bridge, near as I can tell, the name has to be applied explicitly upon creation of the range object.

I'm sure there is a better way of accomplishing this (there usually is), but at least this works.


问:
What is the Visual Studio DTE?
I have been slowly digging through Visual Studio's SDK, but could not yet figure out what DTE stands for. This is a silly question, but I really can't seem to find it. DTE is super useful, it would be super cool to know what it is as well.</p>

答:
From MSDN:

EnvDTE is an assembly-wrapped COM library containing the objects and members for Visual Studio core automation.

Title: What is the Visual Studio DTE?


问:
Is it legit to sign two apps with two different keystores, if need to be distributed under one company name?
I have a situation, where I might use two keystores for two different applications made in the same company, one with Android and one with Unity. But I have never seen any company to use more than one Keystore for signing their apps, I have verified this comparing Google, Facebook, etc apps. So, is it legit according to the market and logical according to the devs to have two keystores for the two apps made by the same company.

Note : We need to distribute the apps over the world.

答:
You can sign two different apps usign two different keystores, it is a perfectly valid way to do it. Or you can use the same keystore, but if you do this you have to use different aliases for different apps. I used different keystores to sign different apps for the same company, there is nothing wrong with that.

A keystore can be compared to a safe with keys: You can have multiple safes, but only one key per app. If you store multiple keys in one safe or have multiple safes with one key each.

And in technical terms: One alias is the key for an app, and a keystore is a safe. So essentially, it doesn't make any difference, as the aliases used are different. Doesn't matter how you store them, as the keystore (AFAIK) doesn't hold any kind of value except hold the aliases. The alias is the key it signs with, and the alias is unique for each app. If you store it in this or that keystore doesn't matter - the aliases are still unique.

TL:DR; The apps are signed using aliases meaning it doesn't matter if you store those aliases in this keystore or that keystore, the aliases are unique and for an app each.

The keystores are keySTORES, which can be understood as key storage. Anyone who has ever signed an app knows this isn't done using the keystore itself, but an alias in the keystore. The key in the storage. Whether you use this or that keystore, the aliases are still unique for each app. So each app is signed using a separate alias, and it doesn't matter what keystore it is in.

As for advantages one over the other, I personally go by this setup:

One keystore for each app

-> Lite and full version (if applicable) are in the same keystore

But app A and B are stored in two different keystores.

Why? If I lose a single keystore for an old app, it doesn't matter (old app = dead app, not receiving updates, etc) as I still have the keystores for the ones I am maintaining. I am not sure how it is with corruption of the files, but if it is possible (and happens) one app is affected instead of all.

And as mentioned by @BillyFerguson, if you sell one app you can send a single keystore instead of the whole thing.

But you would have to keep a track of a large amount of files, which can be hard to do, and you risk losing track of the keystores.

Though the advantage with having a single keystore is the fact that you know you have all apps in there, and you don't need to keep track of possibly hundreds of keystores. But this would need regular updates in the backup system, as the file updates instead of having new files added.


问:
Get an array of all dates between 2 dates from every row in one array
I'm trying to get an array of all dates between the 2 dates which im getting out the database for each row. for example there is 3 rows with 2017-02-02 and 2017-02-03 and a row with 2017-02-18 and 2017-02-20 I would like to get an array with the output [2017-02-02, 2017-02-03, 2017-02-18, 2017-02-19, 2017-02-20]

So far I have a query which gets all of the dates and echo's the start and end date and a script to get an array with the dates between 2 dates.

How can I make it work so it's getting all the dates of every row into one array?

```<code><?php
    $result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
    while ($auto = mysqli_fetch_array($result)) {
    ?>
          <h2 class="title_car">
            <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>
          </h2>
        <hr>
        <?php $dateRange = getDateRange($auto['start_date'], $auto['end_date']); ?>
    <?php } ?>

    <?php
    function getDateRange($startDate, $endDate, $format="Y-m-d")
{
    //Create output variable
    $datesArray = array();
    //Calculate number of days in the range
    $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;
    //Populate array of weekdays and counts
    for($day=0; $day<$total_days; $day++)
    {
        $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));
    }
    //Return results array
    return $datesArray;
}

print_r($dateRange);
?>
</code>```

答:
You have to foreach every array to print the dates.

```<code><?php
$result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
while ($auto = mysqli_fetch_array($result)) {?>
  <h2 class="title_car">
    <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>
  </h2>
  <hr>
  <?php
  $date_text = "";
  $dateRange = getDateRange($auto['start_date'], $auto['end_date']);
  if(!empty($dateRange)){
    foreach($dateRange as $dateR){
      $date_text .= $dateR.", ";
    }
  }
  echo rtrim($date_text,", ")."<br>";
}?>
</code>```

Output:

```<code>2011-05-03, 2011-05-04, 2011-05-05, 2011-05-06, 2011-05-07, 2011-05-08

2011-05-20, 2011-05-21, 2011-05-22, 2011-05-23

.

.
.
</code>```

Body:
I'm trying to get an array of all dates between the 2 dates which im getting out the database for each row. for example there is 3 rows with 2017-02-02 and 2017-02-03 and a row with 2017-02-18 and 2017-02-20 I would like to get an array with the output [2017-02-02, 2017-02-03, 2017-02-18, 2017-02-19, 2017-02-20]

So far I have a query which gets all of the dates and echo's the start and end date and a script to get an array with the dates between 2 dates.

How can I make it work so it's getting all the dates of every row into one array?

<?php
    $result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
    while ($auto = mysqli_fetch_array($result)) {
    ?>

            <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>

        <?php $dateRange = getDateRange($auto['start_date'], $auto['end_date']); ?>
    <?php } ?>

    <?php
    function getDateRange($startDate, $endDate, $format="Y-m-d")
{
    //Create output variable
    $datesArray = array();
    //Calculate number of days in the range
    $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;
    //Populate array of weekdays and counts
    for($day=0; $day<$total_days; $day++)
    {
        $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));
    }
    //Return results array
    return $datesArray;
}

print_r($dateRange);
?>

Body:
You have to foreach every array to print the dates.

<?php
$result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
while ($auto = mysqli_fetch_array($result)) {?>
  <h2 class="title_car">
    <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>
  </h2>
  <hr>
  <?php
  $date_text = "";
  $dateRange = getDateRange($auto['start_date'], $auto['end_date']);
  if(!empty($dateRange)){
    foreach($dateRange as $dateR){
      $date_text .= $dateR.", ";
    }
  }
  echo rtrim($date_text,", ")."<br>";
}?>

Output:

2011-05-03, 2011-05-04, 2011-05-05, 2011-05-06, 2011-05-07, 2011-05-08

2011-05-20, 2011-05-21, 2011-05-22, 2011-05-23

.

.
.


问:
How to use Windows Authentication in Windows Application?
How to use windows authentication (local machine administrator user) in windows application written in C#.

Need is whenever user opens my windows application GUI, it should authenticate local administrator credentials even if User is logged in as Administrator there.

Is this windows Impersonation?

答:
May be a bit late but to achieve Window Authentication Functionality  to a C# Desktop Application, there are two steps accomplish with below steps.

Step 1: Get currently logged in user details:

This is pretty straight forward. we can achieve this by using the WindowsIdentity class of System.Security.Principal namespace. This class provides a static method, getCurrent(), which return a object of WindowsIdentity.
Bellow is the code you can use to get the current logged in user details.

Step 2: Validate windows credentials provided by user:

Need to ask domain name, user name, password from user to pass these values to interop service.
This is little complex compared to above as we need to call a windows API using IntropServices. To accomplish this we need to add a extern function declaration, and then call the function. Following code will help you to understand this better.

```<code>bool issuccess = false;
string username = GetloggedinUserName();
if (username.ToLowerInvariant().Contains(txtUserName.Text.Trim().ToLowerInvariant()) && username.ToLowerInvariant().Contains(txtDomain.Text.Trim().ToLowerInvariant()))
    {
        issuccess = IsValidateCredentials(txtUserName.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
    }

if (issuccess)
    MessageBox.Show("Successfuly Login !!!");
else
    MessageBox.Show("User Name / Password / Domain is invalid !!!");
</code>```

Body:
May be a bit late but to achieve Window Authentication Functionality  to a C# Desktop Application, there are two steps accomplish with below steps.

Step 1: Get currently logged in user details:

This is pretty straight forward. we can achieve this by using the WindowsIdentity class of System.Security.Principal namespace. This class provides a static method, getCurrent(), which return a object of WindowsIdentity.
Bellow is the code you can use to get the current logged in user details.

Step 2: Validate windows credentials provided by user:

Need to ask domain name, user name, password from user to pass these values to interop service.
This is little complex compared to above as we need to call a windows API using IntropServices. To accomplish this we need to add a extern function declaration, and then call the function. Following code will help you to understand this better.

bool issuccess = false;
string username = GetloggedinUserName();
if (username.ToLowerInvariant().Contains(txtUserName.Text.Trim().ToLowerInvariant()) && username.ToLowerInvariant().Contains(txtDomain.Text.Trim().ToLowerInvariant()))
    {
        issuccess = IsValidateCredentials(txtUserName.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
    }

if (issuccess)
    MessageBox.Show("Successfuly Login !!!");
else
    MessageBox.Show("User Name / Password / Domain is invalid !!!");


问:
Ruby: Kruskal's Algorithm - ResultArray manipulation
I'm new to Ruby and I've been playing with the Kruskal's Algorithm a little bit but at the moment I've hit a bump and I can't understand what I need to do at this stage.

The code I've been working on is this:

```<code>def partition(arr, clusters)
  edgeValues = []
  index1 = 0
  index2 = 1
  arr = arr.sort # [3, 4, 5, 5, 6, 10, 15, 20, 75, 80, 85]

  arr.length.times{
    val = (arr[index1]-arr[index2]).abs
    edgeValues << [ val, index1, index2]

    index1 += 1
    index2 += 1

    break if (arr.length == index2)
  }

  edgeValues = edgeValues.sort

  #p edgeValues[0][0] # value cost
  #p edgeValues[0][1] # index 1
  #p edgeValues[0][2] # index 2

end

array = [5, 4, 3, 5, 15, 20, 10, 80, 75, 6, 85]
clusters = 3

partition( array, clusters ) #end result: [ [3, 4, 5, 5, 6], [10, 15, 20], [75, 80, 85] ]
</code>```

I managed to do everything except the last part.

I have no idea how to manipulate the sorted array:

```<code>[3, 4, 5, 5, 6, 10, 15, 20, 75, 80, 85]
</code>```

In order to achieve the end result:

```<code>[ [3, 4, 5, 5, 6], [10, 15, 20], [75, 80, 85] ]
</code>```

I have all the calculations handled and those values stored in the edgeValues array.

Any help would be appreciated.

答:
Not having heard of Kruskal's Algorithm  I looked it up to find that it is a method for computing a minimal spanning tree. The OP wishes to employ that algorithm here, but the reason for doing so is not stated. Neither is there a statement of the underlying problem being addressed. I assume from the example that the object is to partition a sorted array into a given number of arrays ("clusters") such that those arrays differ in size by at most one and the larger ones are to be at the beginning. If so, there are many ways of doing that--including my solution below--that do not view the problem as one of finding a minimal spanning tree.</p>

```<code>def similar_size_clusters(array, nbr_clusters)
  sorted = array.sort
  smaller_size, nbr_larger = sorted.size.divmod(nbr_clusters)
  nbr_clusters.times.each_with_object([]) do |i,a|
    a << sorted.shift(i < nbr_larger ? smaller_size + 1 : smaller_size)
  end
end

array = [5, 4, 3, 5, 15, 20, 10, 80, 75, 6, 85]
(1..array.size).each { |i| puts "clusters = #{i}: #{similar_size_clusters(array, i)}" }

clusters =  1: [[3, 4, 5, 5, 6, 10, 15, 20, 75, 80, 85]]
clusters =  2: [[3, 4, 5, 5, 6, 10], [15, 20, 75, 80, 85]]
clusters =  3: [[3, 4, 5, 5], [6, 10, 15, 20], [75, 80, 85]]
clusters =  4: [[3, 4, 5], [5, 6, 10], [15, 20, 75], [80, 85]]
clusters =  5: [[3, 4, 5], [5, 6], [10, 15], [20, 75], [80, 85]]
clusters =  6: [[3, 4], [5, 5], [6, 10], [15, 20], [75, 80], [85]]
clusters =  7: [[3, 4], [5, 5], [6, 10], [15, 20], [75], [80], [85]]
clusters =  8: [[3, 4], [5, 5], [6, 10], [15], [20], [75], [80], [85]]
clusters =  9: [[3, 4], [5, 5], [6], [10], [15], [20], [75], [80], [85]]
clusters = 10: [[3, 4], [5], [5], [6], [10], [15], [20], [75], [80], [85]]
clusters = 11: [[3], [4], [5], [5], [6], [10], [15], [20], [75], [80], [85]]
</code>```

Body:
I'm new to Ruby and I've been playing with the Kruskal's Algorithm a little bit but at the moment I've hit a bump and I can't understand what I need to do at this stage.

The code I've been working on is this:

def partition(arr, clusters)
  edgeValues = []
  index1 = 0
  index2 = 1
  arr = arr.sort # [3, 4, 5, 5, 6, 10, 15, 20, 75, 80, 85]

  arr.length.times{
    val = (arr[index1]-arr[index2]).abs
    edgeValues << [ val, index1, index2]

    index1 += 1
    index2 += 1

    break if (arr.length == index2)
  }

  edgeValues = edgeValues.sort

  #p edgeValues[0][0] # value cost
  #p edgeValues[0][1] # index 1
  #p edgeValues[0][2] # index 2

end

array = [5, 4, 3, 5, 15, 20, 10, 80, 75, 6, 85]
clusters = 3

partition( array, clusters ) #end result: [ [3, 4, 5, 5, 6], [10, 15, 20], [75, 80, 85] ]

I managed to do everything except the last part.

I have no idea how to manipulate the sorted array:

[3, 4, 5, 5, 6, 10, 15, 20, 75, 80, 85]

In order to achieve the end result:

[ [3, 4, 5, 5, 6], [10, 15, 20], [75, 80, 85] ]

I have all the calculations handled and those values stored in the edgeValues array.

Any help would be appreciated.

Body:
Not having heard of Kruskal's Algorithm  I looked it up to find that it is a method for computing a minimal spanning tree. The OP wishes to employ that algorithm here, but the reason for doing so is not stated. Neither is there a statement of the underlying problem being addressed. I assume from the example that the object is to partition a sorted array into a given number of arrays ("clusters") such that those arrays differ in size by at most one and the larger ones are to be at the beginning. If so, there are many ways of doing that--including my solution below--that do not view the problem as one of finding a minimal spanning tree.

def similar_size_clusters(array, nbr_clusters)
  sorted = array.sort
  smaller_size, nbr_larger = sorted.size.divmod(nbr_clusters)
  nbr_clusters.times.each_with_object([]) do |i,a|
    a << sorted.shift(i < nbr_larger ? smaller_size + 1 : smaller_size)
  end
end

array = [5, 4, 3, 5, 15, 20, 10, 80, 75, 6, 85]
(1..array.size).each { |i| puts "clusters = #{i}: #{similar_size_clusters(array, i)}" }

clusters =  1: [[3, 4, 5, 5, 6, 10, 15, 20, 75, 80, 85]]
clusters =  2: [[3, 4, 5, 5, 6, 10], [15, 20, 75, 80, 85]]
clusters =  3: [[3, 4, 5, 5], [6, 10, 15, 20], [75, 80, 85]]
clusters =  4: [[3, 4, 5], [5, 6, 10], [15, 20, 75], [80, 85]]
clusters =  5: [[3, 4, 5], [5, 6], [10, 15], [20, 75], [80, 85]]
clusters =  6: [[3, 4], [5, 5], [6, 10], [15, 20], [75, 80], [85]]
clusters =  7: [[3, 4], [5, 5], [6, 10], [15, 20], [75], [80], [85]]
clusters =  8: [[3, 4], [5, 5], [6, 10], [15], [20], [75], [80], [85]]
clusters =  9: [[3, 4], [5, 5], [6], [10], [15], [20], [75], [80], [85]]
clusters = 10: [[3, 4], [5], [5], [6], [10], [15], [20], [75], [80], [85]]
clusters = 11: [[3], [4], [5], [5], [6], [10], [15], [20], [75], [80], [85]]


问:
How to host an asp.net mvc app on a domain that points to a subfolder?
I have the folowing scenario:

www.somedomain.com -> this points to a folder on a shared host, say /MyFolder1
www.otherdomain.com -> this points to another folder on the same shared host, say /MyFolder2

With asp.net mvc my urls get mapped to:

www.somedomain.com/MyFolder1/Action
www.somedomain.com/MyFolder2/Action

I (obviosly) dont't want to have "MyFolder1" and "MyFolder2" on my URLs. How do i solve this on asp.net MVC?

I want to have:

www.somedomain.com/Action
www.somedomain.com/Action

But i need to keep the subfolders on IIS (or some other solution that allows me to have two sites, with different domains on the same hosting).

Help is very much appreciated.

Thanks

答:
The best way to handle this IMO is to use rewriting at the IIS level.  I just did this on a site using IIS 7 URL Rewrite.  If you don't have this module installed on your host provider, you can try to use one of the other URL rewriting tools.  But, for example on DiscountASP you can use IIS 7 URL rewrite.

First you need to point all your domains to your current site.  Then when you download the tool: http://blogs.iis.net/bills/archive/2008/05/31/urlrewrite-module-for-iis7.aspx, it provides a GUI for editing the rules.  Ultimately the rules are placed into your web.config file.  You want your rules to look something like this:

```<code>    <rewrite>
        <rewriteMaps>
            <rewriteMap name="otherdomain" />
        </rewriteMaps>
        <rules>
            <rule name="otherdomain" stopProcessing="false">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="otherdomain.com" />
                </conditions>
                <action type="Rewrite" url="/site_folder/otherdomain/{R:0}" />
            </rule>
        </rules>
    </rewrite>
</code>```

If you are using ISAPI rewrite, I'll probably have that one soon as well for another host that I'm using that doesn't support IIS rewrite

OwnerDisplayName: Thiago Sayao

Body:
The best way to handle this IMO is to use rewriting at the IIS level.  I just did this on a site using IIS 7 URL Rewrite.  If you don't have this module installed on your host provider, you can try to use one of the other URL rewriting tools.  But, for example on DiscountASP you can use IIS 7 URL rewrite.

First you need to point all your domains to your current site.  Then when you download the tool: http://blogs.iis.net/bills/archive/2008/05/31/urlrewrite-module-for-iis7.aspx, it provides a GUI for editing the rules.  Ultimately the rules are placed into your web.config file.  You want your rules to look something like this:

    <rewrite>
        <rewriteMaps>
            <rewriteMap name="otherdomain" />
        </rewriteMaps>
        <rules>
            <rule name="otherdomain" stopProcessing="false">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="otherdomain.com" />
                </conditions>
                <action type="Rewrite" url="/site_folder/otherdomain/{R:0}" />
            </rule>
        </rules>
    </rewrite>

If you are using ISAPI rewrite, I'll probably have that one soon as well for another host that I'm using that doesn't support IIS rewrite

OwnerDisplayName: Trevor de Koekkoek


问:
Notepad++ RegEx
I am in need a reg ex for the following:

```<code>/****** Object: AnyNumberofCharacters ******/
</code>```

Here is what I have Tried but I cant make it work

```<code>/^\/\*\*\*\*\*\* Object\:.*\*\*\*\*\*\*\//
</code>```

Could someone tell me what I'm doing wrong?

Edited:  Sorry I'm using NotePad++ to search a number of text files for this string.

答:
I guess that

```<code>/^\/\*{6} Object: [\w]+ \*{6}\/$/
</code>```

should do that...

Don't forget to adjust the [\w] range accordingly.

Title: Notepad++ RegEx

Body:
I am in need a reg ex for the following:

/****** Object: AnyNumberofCharacters ******/

Here is what I have Tried but I cant make it work

/^\/\*\*\*\*\*\* Object\:.*\*\*\*\*\*\*\//

Could someone tell me what I'm doing wrong?

Edited:  Sorry I'm using NotePad++ to search a number of text files for this string.

Body:
I guess that

/^\/\*{6} Object: [\w]+ \*{6}\/$/

should do that...

Don't forget to adjust the [\w] range accordingly.


问:
How to import ipyparallel function from user defined package, Python
I have a python script that contains a number of user defined functions that I have set up a as package locally.  I can run all of the functions in the input_processing.py script except for the one that I intend to run in parallel.

Here is the code that imports the package...

```<code>import attrition25.input_processing as attrition
</code>```

I get this error...

```<code>NameError: name 'dview' is not defined
</code>```

This is what the function looks like in input.processing.py...

```<code>@dview.parallel(block=True)
def get_dmat_elements(a, b, c):
    d = a + b + c
    return(d)
</code>```

I tried sync_imports() and looked at the @interactive decorator, but I couldn't get anywhere.  Any help would be appreciated.

答:
Although I don't completely get the scoping, to get the function to work, I had to add this to the beginning of the input_processing.py script...

```<code>import ipyparallel as ipp
# Create directView Instance for Parallel Processing
c = ipp.Client()
dview = c[:] # use all engines
</code>```

I have the same exact block of code in the Jupyter Notebook where I am testing, but that did not work.

Hopefully this helps someone out there.

Cheers!

Body:
I have a python script that contains a number of user defined functions that I have set up a as package locally.  I can run all of the functions in the input_processing.py script except for the one that I intend to run in parallel.

Here is the code that imports the package...

import attrition25.input_processing as attrition

I get this error...

NameError: name 'dview' is not defined

This is what the function looks like in input.processing.py...

@dview.parallel(block=True)
def get_dmat_elements(a, b, c):
    d = a + b + c
    return(d)

I tried sync_imports() and looked at the @interactive decorator, but I couldn't get anywhere.  Any help would be appreciated.

Body:
Although I don't completely get the scoping, to get the function to work, I had to add this to the beginning of the input_processing.py script...

import ipyparallel as ipp
# Create directView Instance for Parallel Processing
c = ipp.Client()
dview = c[:] # use all engines

I have the same exact block of code in the Jupyter Notebook where I am testing, but that did not work.

Hopefully this helps someone out there.

Cheers!


问:
xslt for choosing the element from subset of the selected node
I have a XML where i need to select specific elements from all nodes and for the selected elements i need to select the values from subset of the node. The structure of actual XML looks like this-

```<code><Host>
  <Node>
    <element1>type0</element1>
    <element2>Fruits0</element2>
  </Node>
  <Node>
    <element1>type1</element1>
    <element2>Fruits1</element2>
  </Node>
  <Node>
      <element1>type2</element1>
      <element2>
        <Namelist>
          <Names>
            <element2>fruit2</element2>
            <Node>
              <element1>type3</element1>
              <element2>Fruits3</element2>
            </Node>
          </Names>
        </Namelist>
      </element2>
  </Node>
  <Node>
    <element1>type4</element1>
    <element2>Fruits4</element2>
  </Node>
  <Node>
    <element1>type5</element1>
    <element2>Fruits5</element2>
  </Node>
</Host>
</code>```

Now the expected output XML is as follows-

```<code><html>
<body>
<table border="1">
  <tr>
    <td>type0</td>
    <td>Fruits0</td>
  </tr>
  <tr>
    <td>type1</td>
    <td>Fruits1</td>
  </tr>
  <tr>
    <td>type2</td>
    <td>Fruits2</td>
  </tr>
  <tr>
    <td>type3</td>
    <td>Fruits3</td>
  </tr>
  <tr>
    <td>type4</td>
    <td>Fruits4</td>
  </tr>
  <tr>
    <td>type5</td>
    <td>Fruits5</td>
  </tr>
</table>
</body>
</html>
</code>```

The XSLT written is as follows-

```<code><xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
   <xsl:for-each select="Host">
    <xsl:for-each select="//Node">
    <xsl:sort select="element1" />
    <tr>
        <td><xsl:value-of select="element1" /></td>
        <td><xsl:value-of select="element2" /></td>
    </tr>
    </xsl:for-each>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</code>```

The output is not as expected -

```<code><html>
<body>
<table border="1">
  <tr>
    <td>type0</td>
    <td>Fruits0</td>
  </tr>
  <tr>
    <td>type1</td>
    <td>Fruits1</td>
  </tr>
  <tr>
    <td>type2</td>
    <td>Fruits2Fruits3</td>
  </tr>
  <tr>
    <td>type3</td>
    <td>Fruits3</td>
  </tr>
  <tr>
    <td>type4</td>
    <td>Fruits4</td>
  </tr>
  <tr>
    <td>type5</td>
    <td>Fruits5</td>
  </tr>
</table>
</body>
</html>
</code>```

I want to format the output for element having data <element2>Fruits2Fruits3</element2> which should not include child node data. Any help would be highly appreciated. Thank you.

答:
Try changing:

```<code><td><xsl:value-of select="element2"/></td>
</code>```

to:

```<code><td><xsl:value-of select="(.//element2[text()])[1]"/></td>
</code>```

Body:
I have a XML where i need to select specific elements from all nodes and for the selected elements i need to select the values from subset of the node. The structure of actual XML looks like this-

<Host>
  <Node>
    <element1>type0</element1>
    <element2>Fruits0</element2>
  </Node>
  <Node>
    <element1>type1</element1>
    <element2>Fruits1</element2>
  </Node>
  <Node>
      <element1>type2</element1>
      <element2>
        <Namelist>
          <Names>
            <element2>fruit2</element2>
            <Node>
              <element1>type3</element1>
              <element2>Fruits3</element2>
            </Node>
          </Names>
        </Namelist>
      </element2>
  </Node>
  <Node>
    <element1>type4</element1>
    <element2>Fruits4</element2>
  </Node>
  <Node>
    <element1>type5</element1>
    <element2>Fruits5</element2>
  </Node>
</Host>

Now the expected output XML is as follows-

    type0
    Fruits0

    type1
    Fruits1

    type2
    Fruits2

    type3
    Fruits3

    type4
    Fruits4

    type5
    Fruits5

The XSLT written is as follows-

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">

   <xsl:for-each select="Host">
    <xsl:for-each select="//Node">
    <xsl:sort select="element1" />

        <xsl:value-of select="element1" />
        <xsl:value-of select="element2" />

    </xsl:for-each>
</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

The output is not as expected -

    type0
    Fruits0

    type1
    Fruits1

    type2
    Fruits2Fruits3

    type3
    Fruits3

    type4
    Fruits4

    type5
    Fruits5

I want to format the output for element having data <element2>Fruits2Fruits3</element2> which should not include child node data. Any help would be highly appreciated. Thank you.

Body:
Try changing:

<td><xsl:value-of select="element2"/></td>

to:

<td><xsl:value-of select="(.//element2[text()])[1]"/></td>


问:
NAT on TCP connections
When we establish a TCP connection from PC1 to Server and send data through this connection, how does the Router know to which of the two PCs (PC1 and PC2) should it communicate on the way back from Server to PC1?

And

How does ping (ICMP) know to which internal node it should send the answer?

答: The router adds information to the request header sent to the server that allows it to look up the sender when the reply is received.  This is usually accomplished by using a table stored in the router's memory that maps the PC's   address to the token added to the header.</p>

Title: NAT on TCP connections


问:
The operator + is undefined for the argument type(s) String, void
```<code>public class chap7p4 {
    public static void main(String[] args) {
        int[] heights = { 33, 45, 23, 43, 48, 32, 35, 46, 48, 39, 41, };
        printArray(heights);
        System.out.println("Average is " + findAverage(heights)); // this is where I get the error
    }

    public static void printArray(int[] array) {
        for (int eachNum : array) {
            System.out.println(eachNum + "  ");
        }
    }

    public static void findAverage(int[] array) {
        int average = 0;
        int total = 0;
        for (int i = 0; i <= array.length; i++) {
            total = total + array[i];
        }
        average = total / array.length;
        System.out.println(average);

    }
}
</code>```

<p>I get this error </p>

```<code>"Exception in thread "main" java.lang.Error: Unresolved compilation problem: The operator + is undefined for the argument type(s) String, void"
</code>```

答: Also here argument is of type int, and Operators like(*,+,..) won't work for argument type void and int so either change argument type or return type as mentioned above.</p>

Body:
public class chap7p4 {
    public static void main(String[] args) {
        int[] heights = { 33, 45, 23, 43, 48, 32, 35, 46, 48, 39, 41, };
        printArray(heights);
        System.out.println("Average is " + findAverage(heights)); // this is where I get the error
    }

    public static void printArray(int[] array) {
        for (int eachNum : array) {
            System.out.println(eachNum + "  ");
        }
    }

    public static void findAverage(int[] array) {
        int average = 0;
        int total = 0;
        for (int i = 0; i <= array.length; i++) {
            total = total + array[i];
        }
        average = total / array.length;
        System.out.println(average);

    }
}

I get this error

"Exception in thread "main" java.lang.Error: Unresolved compilation problem: The operator + is undefined for the argument type(s) String, void"


答:
NAT (Network Address Translation) is stateful. It creates a translation table that has the layer-3 and layer-4 protocols and addresses. By looking up the return traffic addresses in the translation table, the NAT process can determine which inside addresses should be placed in the packet.

Edit:

Per the edit to your question, asking about ICMP (it is very bad form to change the question in order to ask a different question because it can invalidate the perfectly acceptable answers already given):

It is all the same as TCP or UDP. NAT creates a state table that is dynamically built as traffic passes from inside to outside. NAPT will allow you to overload a single IP address with traffic from multiple inside addresses, and it will translate the return traffic by looking up where to send it in its state table.

With NAPT, besides looking at and translating the IP address, NAPT looks at the layer-4 protocol (TCP, UDP, ICMP) and translates the layer-4 addresses (TCP or UDP port numbers or ICMP identifies), too, storing the translations in its translation table. When return traffic is destined to a particular layer-3 and layer-4 address combination, from a particular layer-3 and layer-4 address combination, the NAPT process finds that in its translation table, and it can see where to send the traffic on the inside.

NAT is very resource intensive, and it breaks the IP paradigm of end-to-end connectivity, where every host is uniquely identified by its own IP address, which is why it is called a kludge (or worse). NAT was developed to extend the life of IPv4 until IPv6, with its nearly unlimited addressing, can become ubiquitous.

RFC 2663, IP Network Address Translator (NAT) Terminology and Considerations:

4.1.2. Network Address Port Translation (NAPT)

NAPT extends the notion of translation one step further by also
translating transport identifier (e.g., TCP and UDP port numbers, ICMP
query identifiers). This allows the transport identifiers of a number
of private hosts to be multiplexed into the transport identifiers of a
single external address. NAPT allows a set of hosts to share a single
external address. Note that NAPT can be combined with Basic NAT so
that a pool of external addresses are used in conjunction with port
translation.

For packets outbound from the private network, NAPT would translate
the source IP address, source transport identifier and related fields
such as IP, TCP, UDP and ICMP header checksums. Transport identifier
can be one of TCP/UDP port or ICMP query ID. For inbound packets, the
destination IP address, destination transport identifier and the IP
and transport header checksums are translated.

A NAPT router in figure 2 may be configured to translate sessions
originated from N-Pri into a single external address, say Addr-i.

Very often, the external interface address Addr-Nx of NAPT router is
used as the address to map N-Pri to.

Title: NAT on TCP connections

Body:
When we establish a TCP connection from PC1 to Server and send data through this connection, how does the Router know to which of the two PCs (PC1 and PC2) should it communicate on the way back from Server to PC1?

And

How does ping (ICMP) know to which internal node it should send the answer?


问:
Deny ajax file access using htaccess
There are some scripts that I use only via ajax and I do not want the user to run these scripts directly from the browser. I use jQuery for making all ajax calls and I keep all of my ajax files in a folder named ajax.

So, I was hoping to create an htaccess file which checks for ajax request (HTTP_X_REQUESTED_WITH) and deny all other requests in that folder. (I know that http header can be faked but I can not think of a better solution). I tried this:

ReWriteCond %{HTTP_X_REQUESTED_WITH} ^$

  ReWriteCond %{SERVER_URL} ^/ajax/.php$

  ReWriteRule ^.*$ -
  [F]

But, it is not working. What I am doing wrong? Is there any other way to achieve similar results. (I do not want to check for the header in every script).

答:
There are only a few predefined HTTP_* variables mapping to HTTP headers that you can use in a RewriteCond. For any other HTTP headers, you need to use a %{HTTP:header} variable.

Just change

```<code>ReWriteCond %{HTTP_X_REQUESTED_WITH} ^$
</code>```

To:

```<code>ReWriteCond %{HTTP:X-Requested-With} ^$
</code>```

Title: Deny ajax file access using htaccess

Body:
There are only a few predefined HTTP_* variables mapping to HTTP headers that you can use in a RewriteCond. For any other HTTP headers, you need to use a %{HTTP:header} variable.

Just change

ReWriteCond %{HTTP_X_REQUESTED_WITH} ^$

To:

ReWriteCond %{HTTP:X-Requested-With} ^$


答:
You could simply reindex your resampled data:</p>

```<code>df['Close3D'] = df.Close.resample('3D').mean().reindex(df.index, method='ffill')
</code>```

Title: pandas. join resampled df with original df by data range

Body:
I need to join 2 dataframes based on a datetime range.
I've already googled/stacktraced for it and found some possible work arounds.

Since I resample the data and want to join the aggregated version back to the original, I thought that there might be a way to simulate the resampling by adding a "join criteria column" which represents the possible aggregated datetime.

this is my base:

import pandas as pd
import numpy as np
import quandl

df = quandl.get("WIKI/GOOGL")
df = df.ix[:, ['Close']]

print('***************** ORIG')
print(df.head(10).to_string())

ac = df['Close'].resample('3D').mean()

print('***************** RESAMPLED')
print(ac.head(10).to_string())

frames = [ac]
ac2 = pd.concat(frames, axis=1, join='inner')

print('***************** RESAMPLED 2')
print(ac2.head(10).to_string())

#new = pd.merge(df, ac2, on=df.index, how='left')

#print('***************** JOIN')
#print(new.to_string())

and this is the output:

***************** ORIG
              Close
Date
2004-08-19  100.335
2004-08-20  108.310
2004-08-23  109.400
2004-08-24  104.870
2004-08-25  106.000
2004-08-26  107.910
2004-08-27  106.150
2004-08-30  102.010
2004-08-31  102.370
2004-09-01  100.250
***************** RESAMPLED
Date
2004-08-19    104.322500
2004-08-22    107.135000
2004-08-25    106.686667
2004-08-28    102.010000
2004-08-31    101.376667
2004-09-03    100.010000
2004-09-06    101.940000
2004-09-09    103.820000
2004-09-12    109.495000
2004-09-15    114.486667
Freq: 3D

pretty cool would be, if I could calculate a new column

***************** ORIG
              Close   newDate
Date
2004-08-19  100.335   2004-08-19
2004-08-20  108.310   2004-08-19
2004-08-23  109.400   2004-08-22
2004-08-24  104.870   2004-08-22
2004-08-25  106.000   2004-08-25
2004-08-26  107.910   2004-08-25
2004-08-27  106.150   2004-08-25
2004-08-30  102.010   2004-08-28
2004-08-31  102.370   2004-08-31
2004-09-01  100.250   2004-08-31

and use this a join criteria...

but I am not eager to re-programm the resample in a loop ... if you want to suggest that ... :)

any ideas?

Thanks!
E.

**** EDIT ****
I've found that solution to shift the date. now i'm able to join :)

print('***************** RESAMPLED 2')
ac2['folgep'] = ac2.index.shift(1)
ac2['DatumJoin'] = ac2.index
print(ac2.head(10).to_string())

df['matched'] = np.piecewise(df.index, [(df.index >= start_date)&(df.index <= end_date) for start_date, end_date in zip(ac2.index, ac2.folgep.values)], ac2.DatumJoin)

print('***************** after join')
print(df.head(10).to_string())

Body:
You could simply reindex your resampled data:

df['Close3D'] = df.Close.resample('3D').mean().reindex(df.index, method='ffill')


问:
JAVA FX is open source or not
I am working on a java project and I have to create a new desktop application. The client has stated that we shouldn't be using any open source software. I was planning to use JavaFX with Scene Builder. I am not able to figure out if this will violate what has been stipulated by the client. Can you please help to ascertain whether using Java FX will amount to violating the no open source software stipulation?

Thanks in Advance

答:
JavaFX is shipped with the Oracle JRE, you should check the license of the Oracle JVM to see if it complies to the wishes of your client. Oracle allows you to ship a complete private copy of a JRE with your application and even includes a tool for you to create such self contained applications.

I would like to stipulate that it is very likely that you will not be able to develop any modern software component without using some form of 'open source'.

There are many forms of open source licenses and many of them are commercial friendly, and some are not.

It is wiser to specify which open source licenses are not acceptable and make sure you stay compliant.

Tools such as Gradle and Artifactory can help you with that.

Title: JAVA FX is open source or not


问:
form with no focus will not move smoothly
I am building a popup keyboard.  I'm using sendkeys, so I don't want the form/keyboard to take focus.  This code prevents that:

```<code>Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
    Get
        Dim cp As CreateParams = MyBase.CreateParams
        cp.Style = cp.Style Or &H56000000
        Return cp
    End Get
</code>```

However, when I try to move the form/keyboard it doesn't move smoothly.  It will move, but only after you release the mouse.  Is there a way that I can have both, no focus and move smoothly?

答:
I added:

```<code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_MOVING Then
        Dim r As RECT
        r = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(RECT)), RECT)
        Me.Location = New Point(r.Left, r.Top)
    End If
    MyBase.WndProc(m)
End Sub
</code>```

which then allowed the form to move correctly.

Here's all of the code:

```<code>Imports System.Runtime.InteropServices

Private Const WS_CHILD = &H40000000
Private Const WS_EX_NOACTIVATE = &H8000000
Private Const WM_MOVING = &H216

Private Structure RECT
    Public Left As Integer
    Public Top As Integer
    Public Right As Integer
    Public Bottom As Integer
End Structure

Protected Overrides ReadOnly Property CreateParams() As CreateParams
    Get
        Dim p As CreateParams = MyBase.CreateParams
        p.Style = p.Style Or WS_CHILD
        p.ExStyle = p.ExStyle Or WS_EX_NOACTIVATE
        Return p
    End Get
End Property

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_MOVING Then
        Dim r As RECT
        r = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(RECT)), RECT)
        Me.Location = New Point(r.Left, r.Top)
    End If
    MyBase.WndProc(m)
End Sub
</code>```

Body:
I am building a popup keyboard.  I'm using sendkeys, so I don't want the form/keyboard to take focus.  This code prevents that:

Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
    Get
        Dim cp As CreateParams = MyBase.CreateParams
        cp.Style = cp.Style Or &H56000000
        Return cp
    End Get

However, when I try to move the form/keyboard it doesn't move smoothly.  It will move, but only after you release the mouse.  Is there a way that I can have both, no focus and move smoothly?

Body:
I added:

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_MOVING Then
        Dim r As RECT
        r = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(RECT)), RECT)
        Me.Location = New Point(r.Left, r.Top)
    End If
    MyBase.WndProc(m)
End Sub

which then allowed the form to move correctly.

Here's all of the code:

Imports System.Runtime.InteropServices

Private Const WS_CHILD = &H40000000
Private Const WS_EX_NOACTIVATE = &H8000000
Private Const WM_MOVING = &H216

Private Structure RECT
    Public Left As Integer
    Public Top As Integer
    Public Right As Integer
    Public Bottom As Integer
End Structure

Protected Overrides ReadOnly Property CreateParams() As CreateParams
    Get
        Dim p As CreateParams = MyBase.CreateParams
        p.Style = p.Style Or WS_CHILD
        p.ExStyle = p.ExStyle Or WS_EX_NOACTIVATE
        Return p
    End Get
End Property

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_MOVING Then
        Dim r As RECT
        r = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(RECT)), RECT)
        Me.Location = New Point(r.Left, r.Top)
    End If
    MyBase.WndProc(m)
End Sub


问:
PIC18F2220 LED blinking program error
I am a beginner in PIC programming. This video I have used to code my first program.

This is the code I have written:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "XC8.h"

void main(void)
{
   TRISBbits.RB0 = 0;
   OSCCON = 0x76;

   while(1)
   {
      LATBbits.LATB0 = ~LATBbits.LATB0;

      for (int countDelay=0; countDelay<20; countDelay++) __delay_ms(50);
   }
}
</code>```

And my XC8.h header file is:

```<code>// PIC18F2220 Configuration Bit Settings

// 'C' source line config statements

// CONFIG1H
#pragma config OSC = RC         // Oscillator Selection bits (External RC oscillator, CLKO function on RA6)
#pragma config FSCM = OFF       // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF       // Internal/External Switchover bit (Internal/External Switchover mode disabled)

// CONFIG2L
#pragma config PWRT = OFF       // Power-up Timer enable bit (PWRT disabled)
#pragma config BOR = OFF        // Brown-out Reset enable bit (Brown-out Reset disabled)
#pragma config BORV = 20        // Brown-out Reset Voltage bits (VBOR set to 2.0V)

// CONFIG2H
#pragma config WDT = ON         // Watchdog Timer Enable bit (WDT enabled)
#pragma config WDTPS = 32768    // Watchdog Timer Postscale Select bits (1:32768)

// CONFIG3H
#pragma config CCP2MX = ON      // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBAD = ANA       // PORTB A/D Enable bit (PORTB<4:0> pins are configured as analog input channels on Reset)
#pragma config MCLRE = OFF      // MCLR Pin Enable bit (MCLR disabled; RE3 input is enabled in 40-pin devices only (PIC18F4X20))

// CONFIG4L
#pragma config STVR = ON        // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
#pragma config LVP = ON         // Single-Supply ICSP Enable bit (Single-Supply ICSP enabled)

// CONFIG5L
#pragma config CP0 = OFF        // Code Protection bit (Block 0 (000200-0007FFh) not code-protected)
#pragma config CP1 = OFF        // Code Protection bit (Block 1 (000800-000FFFh) not code-protected)

// CONFIG5H
#pragma config CPB = OFF        // Boot Block Code Protection bit (Boot block (000000-0001FFh) is not code-protected)
#pragma config CPD = OFF        // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)

// CONFIG6L
#pragma config WRT0 = OFF       // Write Protection bit (Block 0 (000200-0007FFh) not write-protected)
#pragma config WRT1 = OFF       // Write Protection bit (Block 1 (000800-000FFFh) not write-protected)

// CONFIG6H
#pragma config WRTC = OFF       // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) are not write-protected)
#pragma config WRTB = OFF       // Boot Block Write Protection bit (Boot block (000000-0001FFh) is not write-protected)
#pragma config WRTD = OFF       // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)

// CONFIG7L
#pragma config EBTR0 = OFF      // Table Read Protection bit (Block 0 (000200-0007FFh) not protected from table reads executed in other blocks)
#pragma config EBTR1 = OFF      // Table Read Protection bit (Block 1 (000800-000FFFh) not protected from table reads executed in other blocks)

// CONFIG7H
#pragma config EBTRB = OFF      // Boot Block Table Read Protection bit (Boot block (000000-0001FFh) is not protected from table reads executed in other blocks)

// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.

#define _XTAL_FREQ 8000000
</code>```

I have followed all the steps as provided in the tutorial but I am getting the following error when I try to build the program.

```<code>make -f nbproject/Makefile-default.mk SUBPROJECTS= .build-conf
make[1]: Entering directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
make  -f nbproject/Makefile-default.mk dist/default/production/XC8.X.production.hex
make[2]: Entering directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
"C:\Program Files (x86)\Microchip\xc8\v1.42\bin\xc8.exe" --pass1  --chip=18F2220 -Q -G  --double=24 --float=24 --emi=wordwrite --opt=+asm,+asmfile,-speed,+space,-debug --addrqual=ignore --mode=free -P -N255 --warn=-3 --asmlist -DXPRJ_default=default  --summary=default,-psect,-class,+mem,-hex,-file --output=default,-inhx032 --runtime=default,+clear,+init,-keep,-no_startup,-download,+config,+clib,-plib   --output=-mcof,+elf:multilocs --stack=compiled:auto:auto:auto "--errformat=%f:%l: error: (%n) %s" "--warnformat=%f:%l: warning: (%n) %s" "--msgformat=%f:%l: advisory: (%n) %s"    -obuild/default/production/XC8.p1  XC8.c
XC8.c:15: error: (192) undefined identifier "TRISBbits"
XC8.c:15: error: (196) struct/union required
XC8.c:16: error: (192) undefined identifier "OSCCON"
XC8.c:20: error: (192) undefined identifier "LATBbits"
XC8.c:20: error: (196) struct/union required
XC8.c:20: error: (196) struct/union required
XC8.c:22: warning: (361) function declared implicit int
(908) exit status = 1
nbproject/Makefile-default.mk:100: recipe for target 'build/default/production/XC8.p1' failed
make[2]: Leaving directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
nbproject/Makefile-default.mk:84: recipe for target '.build-conf' failed
make[1]: Leaving directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
make[2]: *** [build/default/production/XC8.p1] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 467ms)
</code>```

Hope I have added sufficient input for the query. Since I am new to this section please feel free to ask for further information.

答:
You miss to include #include <xc.h>, instead you just set your configuration bits. The xc.h is the main header file that will include a lot of other header files that finally point to your special controller header file #include <pic18f2220.h>. It's done with #ifdef constructs that your MPLAB IDE should provide because you initially set the controller when creating a new project.

This guide from Microchip is very helpful as beginning because it explains a lot.

If you don't include the <xc.h> header file the register names of your controller are not known to the compiler. That is the reason for your errors.

Title: PIC18F2220 LED blinking program error

Body:
I am a beginner in PIC programming. This video I have used to code my first program.

This is the code I have written:

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

void main(void)
{
   TRISBbits.RB0 = 0;
   OSCCON = 0x76;

   while(1)
   {
      LATBbits.LATB0 = ~LATBbits.LATB0;

      for (int countDelay=0; countDelay<20; countDelay++) __delay_ms(50);
   }
}

And my XC8.h header file is:

// PIC18F2220 Configuration Bit Settings

// 'C' source line config statements

// CONFIG1H
#pragma config OSC = RC         // Oscillator Selection bits (External RC oscillator, CLKO function on RA6)
#pragma config FSCM = OFF       // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF       // Internal/External Switchover bit (Internal/External Switchover mode disabled)

// CONFIG2L
#pragma config PWRT = OFF       // Power-up Timer enable bit (PWRT disabled)
#pragma config BOR = OFF        // Brown-out Reset enable bit (Brown-out Reset disabled)
#pragma config BORV = 20        // Brown-out Reset Voltage bits (VBOR set to 2.0V)

// CONFIG2H
#pragma config WDT = ON         // Watchdog Timer Enable bit (WDT enabled)
#pragma config WDTPS = 32768    // Watchdog Timer Postscale Select bits (1:32768)

// CONFIG3H
#pragma config CCP2MX = ON      // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBAD = ANA       // PORTB A/D Enable bit (PORTB<4:0> pins are configured as analog input channels on Reset)
#pragma config MCLRE = OFF      // MCLR Pin Enable bit (MCLR disabled; RE3 input is enabled in 40-pin devices only (PIC18F4X20))

// CONFIG4L
#pragma config STVR = ON        // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
#pragma config LVP = ON         // Single-Supply ICSP Enable bit (Single-Supply ICSP enabled)

// CONFIG5L
#pragma config CP0 = OFF        // Code Protection bit (Block 0 (000200-0007FFh) not code-protected)
#pragma config CP1 = OFF        // Code Protection bit (Block 1 (000800-000FFFh) not code-protected)

// CONFIG5H
#pragma config CPB = OFF        // Boot Block Code Protection bit (Boot block (000000-0001FFh) is not code-protected)
#pragma config CPD = OFF        // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)

// CONFIG6L
#pragma config WRT0 = OFF       // Write Protection bit (Block 0 (000200-0007FFh) not write-protected)
#pragma config WRT1 = OFF       // Write Protection bit (Block 1 (000800-000FFFh) not write-protected)

// CONFIG6H
#pragma config WRTC = OFF       // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) are not write-protected)
#pragma config WRTB = OFF       // Boot Block Write Protection bit (Boot block (000000-0001FFh) is not write-protected)
#pragma config WRTD = OFF       // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)

// CONFIG7L
#pragma config EBTR0 = OFF      // Table Read Protection bit (Block 0 (000200-0007FFh) not protected from table reads executed in other blocks)
#pragma config EBTR1 = OFF      // Table Read Protection bit (Block 1 (000800-000FFFh) not protected from table reads executed in other blocks)

// CONFIG7H
#pragma config EBTRB = OFF      // Boot Block Table Read Protection bit (Boot block (000000-0001FFh) is not protected from table reads executed in other blocks)

// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.

#define _XTAL_FREQ 8000000

I have followed all the steps as provided in the tutorial but I am getting the following error when I try to build the program.

make -f nbproject/Makefile-default.mk SUBPROJECTS= .build-conf
make[1]: Entering directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
make  -f nbproject/Makefile-default.mk dist/default/production/XC8.X.production.hex
make[2]: Entering directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
"C:\Program Files (x86)\Microchip\xc8\v1.42\bin\xc8.exe" --pass1  --chip=18F2220 -Q -G  --double=24 --float=24 --emi=wordwrite --opt=+asm,+asmfile,-speed,+space,-debug --addrqual=ignore --mode=free -P -N255 --warn=-3 --asmlist -DXPRJ_default=default  --summary=default,-psect,-class,+mem,-hex,-file --output=default,-inhx032 --runtime=default,+clear,+init,-keep,-no_startup,-download,+config,+clib,-plib   --output=-mcof,+elf:multilocs --stack=compiled:auto:auto:auto "--errformat=%f:%l: error: (%n) %s" "--warnformat=%f:%l: warning: (%n) %s" "--msgformat=%f:%l: advisory: (%n) %s"    -obuild/default/production/XC8.p1  XC8.c
XC8.c:15: error: (192) undefined identifier "TRISBbits"
XC8.c:15: error: (196) struct/union required
XC8.c:16: error: (192) undefined identifier "OSCCON"
XC8.c:20: error: (192) undefined identifier "LATBbits"
XC8.c:20: error: (196) struct/union required
XC8.c:20: error: (196) struct/union required
XC8.c:22: warning: (361) function declared implicit int
(908) exit status = 1
nbproject/Makefile-default.mk:100: recipe for target 'build/default/production/XC8.p1' failed
make[2]: Leaving directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
nbproject/Makefile-default.mk:84: recipe for target '.build-conf' failed
make[1]: Leaving directory 'E:/Projects/Coding/MPLABX/Programming/XC8/XC8.X'
nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
make[2]: *** [build/default/production/XC8.p1] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 467ms)

Hope I have added sufficient input for the query. Since I am new to this section please feel free to ask for further information.


问:
Chain API http request that depends on response of previous request
I'm trying to implement chain http request that will be repeated X times and stop when there is no response from last request.

How it should work.

For example first I call

```<code>http://example.com/?skip=0
</code>```

and response is:

```<code>{
   skip=10
},
</code>```

than I call

```<code>http://example.com/?skip=10
...
http://example.com/?skip=20
</code>```

and on skip 20 response is

```<code>{
  "message" : "You reach the end"
}
</code>```

I need to stop there. But I have to repeat requests when I'm getting "skip" in response and repeat them on the way that I add skip into next request.

Thanks

答:
Based on the description it sounds like you actually mean to "paginate" the same query rather than chaining several dependent queries. For that you can use expand:

```<code>// Start with skip
Observable.of({skip: 0})
  // Feeds the response resulting stream back into this function
  .expand((response) => {
    // Continue expanding if there is a skip parameter
    if (response.skip >= 0)
      return this.http.get(`http://example.com/?skip=${skip}`);
    // Stop expanding if there is no more data
    else
      return Observable.empty();
  }, 1 /* Limit the number of consecutive queries*/);
</code>```

Body:
I'm trying to implement chain http request that will be repeated X times and stop when there is no response from last request.

How it should work.

For example first I call

http://example.com/?skip=0

and response is:

{
   skip=10
},

than I call

http://example.com/?skip=10
...
http://example.com/?skip=20

and on skip 20 response is

{
  "message" : "You reach the end"
}

I need to stop there. But I have to repeat requests when I'm getting "skip" in response and repeat them on the way that I add skip into next request.

Thanks

Body:
Based on the description it sounds like you actually mean to "paginate" the same query rather than chaining several dependent queries. For that you can use expand:

// Start with skip
Observable.of({skip: 0})
  // Feeds the response resulting stream back into this function
  .expand((response) => {
    // Continue expanding if there is a skip parameter
    if (response.skip >= 0)
      return this.http.get(`http://example.com/?skip=${skip}`);
    // Stop expanding if there is no more data
    else
      return Observable.empty();
  }, 1 /* Limit the number of consecutive queries*/);


问:
change solution file to a different folder
How do I change the folder of my existing solution file (sln)?

It's right now inside one of my project's folder; if I cut the solution file and paste it in the root folder,it doesn't load any of my projects.

答:
There are two ways you can do it:

Simply delete the entire project and create the entire project again in the other folder ( which is not recommended).

Here are the steps to follow without missing any files.

a.       Goto Source control explorer Create a new folder or Just move the solution to which you want to move the folder to.

b.      Load the solution in your local and it will prompt a message saying that do you want to reload it from source control click yes.

c.       Once we load the solution you will see that the project you have moved won’t be loaded (Since we moved to the other folder)

d.      So now, Remove the project which was not loaded and then add it as an existing project

e.      I am sure that if you have added nugetPackages they won’t get loaded.

f.        Goto file explorer of the particular project open the .csproj file and try to check the packages location, Error condition, Project reference and Import and apart from them if there are any
Which are pointing to a directory.

g.       The simplest way is just adding some nuget package and see what is the path generated by visual studio.

h.      Once we change the locations they will be loaded in references

i.         After adding references try to build the solution and it will throw some build errors because we moved the project from one folder to other.

j.        Add the project reference wherever needed after moving the files

k.       Now the build will be succeeded.

ContentLicense: CC BY-SA 4.0


问:
How to disable vmware workstation taskbar preview?
VMWare workstation uses the new taskbar preview feature in windows 7 - click on the icon in the taskbar and instead of switching to the app it shows you the open tabs. I just want to switch to the app. Does anyone know how to disable this feature?

I've tried to check the vmware website, but it's pretty awful.

答: Hold Ctrl while clicking the button.</p>

Body: Hold Ctrl while clicking the button.


问:
deviceready not firing in cordova
The deviceready isn't firing correctly (at least in iOS) for my cordova project. I have searched for hours and still cannot figure this out. Am I doing something incorrectly? The path to js/cordova.js exists as well:

```<code><html>
<head>
    <title>Geolocation</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, target-densityDpi=device-dpi, user-scalable=no" />
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/app.css">
    <script type="text/javascript">

    // Fastclick
    if ('addEventListener' in document) {
        document.addEventListener('DOMContentLoaded', function() {
        FastClick.attach(document.body);
        }, false);
    }

    </script>
    <script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // device APIs are available
    //
    function onDeviceReady() {
        alert("ready");
        // Now safe to use device APIs
    }

    </script>
</head>
<body onload="onLoad()">
</code>```

I'm not sure what I'm missing as I'm not getting any errors if I inspect in Chrome

答:
I had this same issue, but in my case cordova.js was already properly included.

Eventually what worked for me was a simple remove and add of the ios platform:

```<code>cordova platform remove ios
cordova platform add ios
</code>```

It had been quite a while since I had completely re-built the ios platform and other major changes had taken place during that time (Cordova upgrade, XCode upgrade, etc). It's possible that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements.

Title: deviceready not firing in cordova

Body:
The deviceready isn't firing correctly (at least in iOS) for my cordova project. I have searched for hours and still cannot figure this out. Am I doing something incorrectly? The path to js/cordova.js exists as well:

    <title>Geolocation</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, target-densityDpi=device-dpi, user-scalable=no" />
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/app.css">

I'm not sure what I'm missing as I'm not getting any errors if I inspect in Chrome

Body:
I had this same issue, but in my case cordova.js was already properly included.

Eventually what worked for me was a simple remove and add of the ios platform:

cordova platform remove ios
cordova platform add ios

It had been quite a while since I had completely re-built the ios platform and other major changes had taken place during that time (Cordova upgrade, XCode upgrade, etc). It's possible that my config.xml or existing ios build was somehow incompliant with the latest Cordova requirements.


问:
This inheritance program when executed gives output '2'. How?
```<code>class A { }

class B extends A { }

class C extends B { }

public class MainClass  {

    static void overloadedMethod(A a) {
        System.out.println("1");
    }

    static void overloadedMethod(B b) {
        System.out.println("2");
    }

    static void overloadedMethod(Object obj) {
        System.out.println("3");
    }

    public static void main(String[] args) {
        C c = new C();
        overloadedMethod(c);
    }
}
</code>```

This inheritance program when executed gives output 2. How?

答:
Well, you know that here C class is a child class of B and B is a child class of A. Class A is also a child class of Object class(you cannot see it because it is determined at compile time).

Documentation:

Excepting Object, which has no superclass, every class has one and
  only one direct superclass (single inheritance). In the absence of any
  other explicit superclass, every class is implicitly a subclass of
  Object.

Classes can be derived from classes that are derived from classes that
  are derived from classes, and so on, and ultimately derived from the
  topmost class, Object. Such a class is said to be descended from all
  the classes in the inheritance chain stretching back to Object.

So, what is the closest and most suitable class for class C.

```<code>C c = new C();
overloadedMethod(c);
</code>```

It's parent class B right!. When you overload the method compiler will choose the:

```<code>static void overloadedMethod(B b) {
    System.out.println("2");
}
</code>```

Since, Object class in the top of class heirarchy and class A is the grand parent of C.

Body:
class A { }

class B extends A { }

class C extends B { }

public class MainClass  {

    static void overloadedMethod(A a) {
        System.out.println("1");
    }

    static void overloadedMethod(B b) {
        System.out.println("2");
    }

    static void overloadedMethod(Object obj) {
        System.out.println("3");
    }

    public static void main(String[] args) {
        C c = new C();
        overloadedMethod(c);
    }
}

This inheritance program when executed gives output 2. How?

Body:
Well, you know that here C class is a child class of B and B is a child class of A. Class A is also a child class of Object class(you cannot see it because it is determined at compile time).

Documentation:

Excepting Object, which has no superclass, every class has one and
  only one direct superclass (single inheritance). In the absence of any
  other explicit superclass, every class is implicitly a subclass of
  Object.

Classes can be derived from classes that are derived from classes that
  are derived from classes, and so on, and ultimately derived from the
  topmost class, Object. Such a class is said to be descended from all
  the classes in the inheritance chain stretching back to Object.

So, what is the closest and most suitable class for class C.

C c = new C();
overloadedMethod(c);

It's parent class B right!. When you overload the method compiler will choose the:

static void overloadedMethod(B b) {
    System.out.println("2");
}

Since, Object class in the top of class heirarchy and class A is the grand parent of C.