问:
The vector has a size = 2, but it still has a value in the index 100
I run the following codes in http://cpp.sh/.
The outputs show that name1.size()=2, but name1[100]=10; </p>

```<code>// Example program
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<vector<int>> name;
    vector <int> name1;
    name1.push_back(1);
    name1.push_back(3);
    vector <int> name2;
    name2.push_back(4);
    name.push_back(name1);
    name.push_back(name2);
    name1[100]=10;
    cout<<name1.size()<<endl;
    cout<<name1[100];
}
</code>```

答:
The short answer is that you are invoking undefined behavior, so you won't find any further specification of what must happen in the standard.

The long answer is that C++ is an unsafe language and doesn't guarantee any type of deterministic error for various invalid operations, including accessing a vector out of bounds using operator[]. Instead, it uses the broad brush of undefined behavior which basically allows anything at all to happen: the idea being that by allowing the user the flexibility to avoid checks which they know are redundant, good performance can be achieved for well-behaved code.

If you want the vector to check that you aren't accessing an out-of-bounds index, no problem - just use the vector::at() which does exactly that, and throws std::out_of_range for invalid accesses.

As for why your particular code is (apparently) returning a value, note that a typical1 implementation of operator[] will just access the underlying storage directly, meaning that at the assembly level you will access whatever is 100 * sizeof(int) bytes from the start of the storage underlying the vector. That's usually going to be something random on the heap (since the storage is usually allocated on the heap), but it may also be an inaccessible address, resulting in an access violation.

1 Some compilers such as MSVC will provide more error checking in "debug" modes, which might cause operator[] to call vector.at() instead, which does do range checking and has defined behavior, and at least a few other compilers/standard libraries seem to be jumping on board with that idea.

Body:
I run the following codes in http://cpp.sh/.
The outputs show that name1.size()=2, but name1[100]=10;

// Example program
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<vector<int>> name;
    vector <int> name1;
    name1.push_back(1);
    name1.push_back(3);
    vector <int> name2;
    name2.push_back(4);
    name.push_back(name1);
    name.push_back(name2);
    name1[100]=10;
    cout<<name1.size()<<endl;
    cout<<name1[100];
}


来源: stackexchange

问:
azure web service app date format issue
Im developing an app thats hosted up in Azure.  On my development machine when i edit and save dates (UK format - saving to local sql server 2012) theres no problem.  When I deploy the same code base to Azure (same database structure & sql server version - db hosted in VM in Azure) Im getting an error

'the value 23/01/2014' is not valid for contract date

has anyone else experienced anything like this and could give me some pointers ?
Ive set the os on the VM machine to be uk region and the underlying dates in the tables both locally and remotely are exactly the same format.  Is there anything obvious I could be missing ?

答:
the value 23/01/2014' is not valid for contract date

Please run dbcc useroptions to check the language and dateformat. And by default, the date format for SQL server is in U.S. date format MM/DD/YY, unless a localized version of SQL Server has been installed.

You could try to use the international format YYYYMMDD for sending the datetime data to SQL Server or pass the date in date format being used on the SQL Server.

ContentLicense: CC BY-SA 3.0

Title: azure web service app date format issue


问:
How to get Test variable through custom code in HP UFT - ApiTest
I want to set value to the Test Variable using Custom Code.
Can you tell me how to do it as i am not able to access the variable from code.

I need to access the User Variable URL in my custom code and set the value.

Please help me if you know how to do it using Custom Code.

Thanks,
Madhan

答:
answer provided here is valid when the need is to set string values. The "SetVariableValue" method takes two "String" type parameters. This limits the ability to set Int32 type variables. Obviously, C# throws an error when trying to set an integer value.

Now, an integer value is particularly useful while setting values for loop iterations. I am not sure whether this is a limitation of the tool or whether my lack of knowledge. So, to work around this, i used the output property of custom code activity. To do this, create a custom code activity and create an output property of the desired type, say Int. Now, assign a value to this output property using the line:

this.ActivityName.Output.property name = property value

This is available in UFT help and can be useful while trying to pass values other than string between different activities in a flow.


问:
C++ Issue Using Getline
I'm trying to create a program in which the user can enter a series of player names and scores and read them back. However, I'm having trouble storing their input using getline. On getline in the InputData function, visual studio states, "Error: no instance of overloaded function "getline" matches the argument list          argument types are: (std::istream, char)", and on ==, it says, "Error: operand types are incompatible ("char" and "const char *")". Here is my code: </p>

```<code>#include <iostream>
#include <string>

using namespace std;

int InputData(string [], int [], int);
void DisplayPlayerData(string [], int [], int);

void main()
{
    string playerNames[100];
    int scores[100];

    int sizeOfArray = sizeof(scores);
    int sizeOfEachElement = sizeof(scores[0]);
    int numberOfElements = sizeOfArray / sizeOfEachElement;

    cout << numberOfElements;

    int numberEntered = InputData(playerNames, scores, numberOfElements);

    DisplayPlayerData(playerNames, scores, numberOfElements);

    cin.ignore();
    cin.get();
}

int InputData(string playerNames, int scores[], int size)
{
    int index;

    for (index = 0; index < size; index++)
    {
        cout << "Enter Player Name (Q to quit): ";
        getline(cin, playerNames[index]);
        if (playerNames[index] == "Q")
        {
            break;
        }
        cout << "Enter score: ";
        cin >> scores[index];
    }

    return index;
}
</code>```

答:
int InputData(string playerNames, int scores[], int size)

should be

int InputData(string playerNames[], int scores[], int size)

In your code, you pass playerNames as a string instead of a string array.

In getline(cin, playerNames[index]); playerNames[index] is a char, because playerNames is a string.

Title: C++ Issue Using Getline

Body:
I'm trying to create a program in which the user can enter a series of player names and scores and read them back. However, I'm having trouble storing their input using getline. On getline in the InputData function, visual studio states, "Error: no instance of overloaded function "getline" matches the argument list          argument types are: (std::istream, char)", and on ==, it says, "Error: operand types are incompatible ("char" and "const char *")". Here is my code:

#include <iostream>
#include <string>

using namespace std;

int InputData(string [], int [], int);
void DisplayPlayerData(string [], int [], int);

void main()
{
    string playerNames[100];
    int scores[100];

    int sizeOfArray = sizeof(scores);
    int sizeOfEachElement = sizeof(scores[0]);
    int numberOfElements = sizeOfArray / sizeOfEachElement;

    cout << numberOfElements;

    int numberEntered = InputData(playerNames, scores, numberOfElements);

    DisplayPlayerData(playerNames, scores, numberOfElements);

    cin.ignore();
    cin.get();
}

int InputData(string playerNames, int scores[], int size)
{
    int index;

    for (index = 0; index < size; index++)
    {
        cout << "Enter Player Name (Q to quit): ";
        getline(cin, playerNames[index]);
        if (playerNames[index] == "Q")
        {
            break;
        }
        cout << "Enter score: ";
        cin >> scores[index];
    }

    return index;
}


答: i might be wrong because it's been a really long time since i've used c++, but have you tried cin.getline instead of just getline?</p>

Title: C++ Issue Using Getline


答:
Try this code here.

You declared:

```<code>vector <int> name1; // An empty vector. name1.size = 0 here.
</code>```

Once you push_back the two values.

```<code>name1.push_back(1);
name1.push_back(3); // name1.size = 2, Index starts at 0, so
                    // name[0] = 1 and name[1] = 2
</code>```

So the value for:

```<code>name1[100] = undefined (garbage). // You never initialised this value, so it yields unexpected behaviour.
</code>```

An alternative for this is to use a default initialiser for an int vector and declare it like this:

```<code>vector <int> name1(101);
</code>```

Here:

```<code>name1[100] = 0 // Because you defined it in the vector constructor to initialise 100 default values.
name1[0] = 0 // This is the first value of the now initialised vector.
name1[69] = 0 // This is the 70th value of the initialised vector.
name[101] = undefined // Again, this is undefined (garbage). You defined a vector of size n = 101, so that means the vector's range is [0,100]. 0 index counts and the last value is n - 1 (101 - 1 = 100). Index 101 is undefined.
</code>```

Title: The vector has a size = 2, but it still has a value in the index 100

Body:
Try this code here.

You declared:

vector <int> name1; // An empty vector. name1.size = 0 here.

Once you push_back the two values.

name1.push_back(1);
name1.push_back(3); // name1.size = 2, Index starts at 0, so
                    // name[0] = 1 and name[1] = 2

So the value for:

name1[100] = undefined (garbage). // You never initialised this value, so it yields unexpected behaviour.

An alternative for this is to use a default initialiser for an int vector and declare it like this:

vector <int> name1(101);

Here:

name1[100] = 0 // Because you defined it in the vector constructor to initialise 100 default values.
name1[0] = 0 // This is the first value of the now initialised vector.
name1[69] = 0 // This is the 70th value of the initialised vector.
name[101] = undefined // Again, this is undefined (garbage). You defined a vector of size n = 101, so that means the vector's range is [0,100]. 0 index counts and the last value is n - 1 (101 - 1 = 100). Index 101 is undefined.


问:
want to hide image when image is not found at the src location?
```<code>jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });
</code>
```

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

答:
You dealing with a race condition.  jQuery may or may not have been loaded when the image is loaded.  The following code handles both cases.</p>

```<code>$('img').each(function() {
    var img = this;
    if (img.complete) {
        if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
            console.log(img, 'load failed');
        } else {
            console.log(img, 'load ok');
        }
    } else {
        $(img).error(function() { console.log(img, 'load failed - error()'); });
        $(img).ready(function() { console.log(img, 'load ok - onload()'); });
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

Body:
You dealing with a race condition.  jQuery may or may not have been loaded when the image is loaded.  The following code handles both cases.

$('img').each(function() {
    var img = this;
    if (img.complete) {
        if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
            console.log(img, 'load failed');
        } else {
            console.log(img, 'load ok');
        }
    } else {
        $(img).error(function() { console.log(img, 'load failed - error()'); });
        $(img).ready(function() { console.log(img, 'load ok - onload()'); });
    }
});


问:
how to estimate best, worst and average cases for time complexity?
how can we tell whether the obtaining time complexity for an algorithm is in best case or worst case or an average case?
example if we get time complexity as
t(n) = 2n^2 + 3n -1, how to estimate the best or worst or average cases?</p>

答:
  >>Bast Case:

If you are finding the Best case Complexity then you check image and following statement.

```<code>T(n)= c1n+c2(n-1)+c4(n-1)+c5(n-1)+c8(n-1)
      (c1+c2+c5+c8)n-(c2+c4+c5+c6)
</code>```

The Maximum Power of n is 1, so we are say tha Best Case Complexity is Insertion Sort O(n).

>>Worst Case:

If you are finding the Worst case Complexity then you check image and following statement.

```<code>T(n)= c1n+c2(n-1)+c4(n-1)+c5(n(n+1)/2)+c6(n(n-1)/2)+c7(n(n-1)/2)+c8(n-1)
      (c5/2 + C6/2 +C7/2)n^2 +(c1+c2+c4+ c5/2 -C6/2 -C7/2+ c8)
</code>```

The Maximum Power of n is 2, so we are say tha Best Case Complexity is Insertion Sort O(n^2).

Body:
  >>Bast Case:

If you are finding the Best case Complexity then you check image and following statement.

T(n)= c1n+c2(n-1)+c4(n-1)+c5(n-1)+c8(n-1)
      (c1+c2+c5+c8)n-(c2+c4+c5+c6)

The Maximum Power of n is 1, so we are say tha Best Case Complexity is Insertion Sort O(n).

>>Worst Case:

If you are finding the Worst case Complexity then you check image and following statement.

T(n)= c1n+c2(n-1)+c4(n-1)+c5(n(n+1)/2)+c6(n(n-1)/2)+c7(n(n-1)/2)+c8(n-1)
      (c5/2 + C6/2 +C7/2)n^2 +(c1+c2+c4+ c5/2 -C6/2 -C7/2+ c8)

The Maximum Power of n is 2, so we are say tha Best Case Complexity is Insertion Sort O(n^2).


问:
Best architecture for new web site calling existing services (ASP.NET Web API with authentication and authorisation)
What I am trying to achieve:

I currently have mobile apps on top of services and would like to add a web site on top of the same services.

Services details:

ASP.NET Web API project using OAuth (bearer token) and Identity for authentication and authorisation.

Microsoft.AspNet.WebApi 5.2.3

Microsoft.Owin.Security.OAuth 3.0.1

Microsoft.AspNet.Identity.Core 2.2.1

Mobile details:

Xamarin projects.

Xamarin.Forms 2.3.3.193

What architecture should I use for the web site?

Create a new ASP.NET MVC project and call my current services from the MVC controllers?  This seems bad because:

I would have 2 layers of controllers (web site MVC controllers calling services API controllers)

I would need to store bearer tokens in cookies

I would need to manage the tokens and cookies expirations

Create a new ASP.NET MVC project and call current services database directly?  This seems bad because:

I would have to duplicate the models in the services project and in the web site project

Create a new ASP.NET project and call my current services using ajax?  This seems bad because:

I would need to create my own register/login pages

I would need to store bearer tokens in cookies

I would need to manage the tokens and cookies expirations

I would need to say bye to future social authentication (OAUTH2) implementation because I wouldn’t be using OWIN

Thanks,

fcorbeil

答: If you already have the API a brand new MVC app shouldn't be such a bad choice. If you have your models stored in a different project just reference them to the MVC one. As for the services, them would work perfectly with the new application. This all can be achieved without changing almost nothing to the current implementation.</p>


问:
SQL-Oracle: Difficulties in resolving basic problems, part2
Problem:
The HR department needs a query that prompts the user for an employee
last name. The query then displays the last name and hire date of any employee
in the same department as the employee whose name they supply(excluding that employee).
For example, if the user enters Zlotkey, find all employees who work with
Zlotkey (excluding Zlotkey).

I managed to do this so far, but i have no clue how to finish it. For now it shows me all employees after i write the last_name excluding it. Any suggestions please how to continue?

```<code>SELECT last_name, TO_CHAR(hire_date,'DD-MON-YYYY') AS "HIRE_DATE"
FROM   employees
WHERE  last_name <>ALL (SELECT '&last_name'
                         FROM  employees)

AND    department_id  IN  (SELECT department_id
                           ???....
</code>```

P.S: This problem is from the Oracle tutorials (Oracle Database 11g: SQL Fundamentals 1 of 1 (year 2009), Practice 7 , exercise 1 for people who already done this:).

答:
```<code>SELECT  LAST_NAME, HIRE_DATE
FROM EMPLOYEES
WHERE DEPARTMENT_ID= (SELECT DEPARTMENT_ID
FROM EMPLOYEES
WHERE LAST_NAME LIKE '&NAME')
AND LAST_NAME <> '&NAME';
</code>```

Body:
Problem:
The HR department needs a query that prompts the user for an employee
last name. The query then displays the last name and hire date of any employee
in the same department as the employee whose name they supply(excluding that employee).
For example, if the user enters Zlotkey, find all employees who work with
Zlotkey (excluding Zlotkey).

I managed to do this so far, but i have no clue how to finish it. For now it shows me all employees after i write the last_name excluding it. Any suggestions please how to continue?

SELECT last_name, TO_CHAR(hire_date,'DD-MON-YYYY') AS "HIRE_DATE"
FROM   employees
WHERE  last_name <>ALL (SELECT '&last_name'
                         FROM  employees)

AND    department_id  IN  (SELECT department_id
                           ???....

P.S: This problem is from the Oracle tutorials (Oracle Database 11g: SQL Fundamentals 1 of 1 (year 2009), Practice 7 , exercise 1 for people who already done this:).


问:
How to apply gradient using svg filter
I want to create a filter that when applied to an html element, would apply a gradient to the entire element. The css gradient only applies to the background, so it is not what I want.
What I want is say my element contains a triangle and a circle, I want to apply a filter to my element and the triangle and the circle would have a gradient applied to them.

This is what I've got so far:

.my-element{
    filter: url(svg.svg#filter);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs>
        <linearGradient id="lightGradient" gradientTransform="rotate(-5)">
            <stop stop-color="white" stop-opacity="0.4" offset="0%"/>
            <stop stop-color="white" stop-opacity="0.5" offset="5%"/>
            <stop stop-color="black" stop-opacity="0.2" offset="6%"/>
            <stop stop-color="black" stop-opacity="0.3" offset="19%"/>
            <stop stop-color="black" stop-opacity="0.2" offset="12%"/>
            <stop stop-color="white" stop-opacity="0.8" offset="13%"/>
            <stop stop-color="white" stop-opacity="0.9" offset="15%"/>
            <stop stop-color="white" stop-opacity="0" offset="15%"/>
            <stop stop-color="white" stop-opacity="0" offset="16%"/>
            <stop stop-color="white" stop-opacity="0.8" offset="16%"/>
            <stop stop-color="white" stop-opacity="0.9" offset="18%"/>
            <stop stop-color="white" stop-opacity="0" offset="18%"/>
            <stop stop-color="white" stop-opacity="0" offset="20%"/>
            <stop stop-color="white" stop-opacity="1" offset="20%"/>
            <stop stop-color="white" stop-opacity="1" offset="25%"/>
        </linearGradient>

        <rect id="recGradient" x="0" y="0" width="100%" height="100%" fill="url(#lightGradient)"/>

        <filter id="filter" primitiveUnits="objectBoundingBox">
            <feImage x="0" y="0" width="100%" height="100%" preserveAspectRatio="none" xlink:href="#recGradient"/>

            <feComposite operator="in" in="SourceGraphic"/>
        </filter>
      </defs>
    </svg></code>```

Edit: with the above code the element just becomes invisible in Firefox, in chrome it seems to work.

so, obviously I'm doing it wrong. I have no idea how to create svg filters, so any help would be appreciated.

答:
This is how you construct a cross-browser filter that does what you want here. The sizings are tricky because you're defining a rect with an applied gradient within a DataURI, then pulling that into a filter using an feImage and then applying that to HTML content using the SVG filter trapdoor in CSS filters. But it does work.

(BTW - it's not clear whether you want to retain the color of the original text and just apply a opacity gradient, or whether you want the black/white gradient to over-ride the original color. You can toggle this by changing the "in2" to "in" in the feComposite. This governs whether you're applying the opacity of the sourcegraphic to the gradient or vice versa.)

div {
  filter: url(#myGradient);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg>
  <defs>
<filter id="myGradient" primitiveUnits="objectBoundingBox">
       <feImage x="0%" y="0%" width="100%" height="100%" preserveAspectRatio="none" xlink:href="data:image/svg+xml;charset=utf8,%3Csvg%20width%3D%22200px%22%20height%3D%22200px%22%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20xmlns%3Axlink%3D'http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink'%3E%3Cdefs%3E%3ClinearGradient%20id%3D'lightGradient'%20gradientTransform%3D'rotate(-5)'%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.4'%20offset%3D'0%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.5'%20offset%3D'5%25'%2F%3E%3Cstop%20stop-color%3D'black'%20stop-opacity%3D'0.2'%20offset%3D'6%25'%2F%3E%3Cstop%20stop-color%3D'black'%20stop-opacity%3D'0.3'%20offset%3D'19%25'%2F%3E%3Cstop%20stop-color%3D'black'%20stop-opacity%3D'0.2'%20offset%3D'12%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.8'%20offset%3D'13%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.9'%20offset%3D'15%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'15%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'16%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.8'%20offset%3D'16%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.9'%20offset%3D'18%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'18%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'20%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'1'%20offset%3D'20%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'1'%20offset%3D'25%25'%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%0A%20%20%3Crect%20id%3D'recGradient'%20x%3D'0%25'%20y%3D'0%25'%20width%3D'100%25'%20height%3D'100%25'%20fill%3D'url(%23lightGradient)'%2F%3E%3C%2Fsvg%3E"/>
  <feComposite operator="in" in2="SourceGraphic"/>
 </filter>
  </defs>
</svg>

<div>
  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text   Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text
</div></code>```

Title: How to apply gradient using svg filter

Body:
I want to create a filter that when applied to an html element, would apply a gradient to the entire element. The css gradient only applies to the background, so it is not what I want.
What I want is say my element contains a triangle and a circle, I want to apply a filter to my element and the triangle and the circle would have a gradient applied to them.

This is what I've got so far:

.my-element{
    filter: url(svg.svg#filter);
}

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs>
        <linearGradient id="lightGradient" gradientTransform="rotate(-5)">
            <stop stop-color="white" stop-opacity="0.4" offset="0%"/>
            <stop stop-color="white" stop-opacity="0.5" offset="5%"/>
            <stop stop-color="black" stop-opacity="0.2" offset="6%"/>
            <stop stop-color="black" stop-opacity="0.3" offset="19%"/>
            <stop stop-color="black" stop-opacity="0.2" offset="12%"/>
            <stop stop-color="white" stop-opacity="0.8" offset="13%"/>
            <stop stop-color="white" stop-opacity="0.9" offset="15%"/>
            <stop stop-color="white" stop-opacity="0" offset="15%"/>
            <stop stop-color="white" stop-opacity="0" offset="16%"/>
            <stop stop-color="white" stop-opacity="0.8" offset="16%"/>
            <stop stop-color="white" stop-opacity="0.9" offset="18%"/>
            <stop stop-color="white" stop-opacity="0" offset="18%"/>
            <stop stop-color="white" stop-opacity="0" offset="20%"/>
            <stop stop-color="white" stop-opacity="1" offset="20%"/>
            <stop stop-color="white" stop-opacity="1" offset="25%"/>
        </linearGradient>

        <rect id="recGradient" x="0" y="0" width="100%" height="100%" fill="url(#lightGradient)"/>

        <filter id="filter" primitiveUnits="objectBoundingBox">
            <feImage x="0" y="0" width="100%" height="100%" preserveAspectRatio="none" xlink:href="#recGradient"/>

            <feComposite operator="in" in="SourceGraphic"/>
        </filter>
      </defs>
    </svg>

Edit: with the above code the element just becomes invisible in Firefox, in chrome it seems to work.

so, obviously I'm doing it wrong. I have no idea how to create svg filters, so any help would be appreciated.

Body:
This is how you construct a cross-browser filter that does what you want here. The sizings are tricky because you're defining a rect with an applied gradient within a DataURI, then pulling that into a filter using an feImage and then applying that to HTML content using the SVG filter trapdoor in CSS filters. But it does work.

(BTW - it's not clear whether you want to retain the color of the original text and just apply a opacity gradient, or whether you want the black/white gradient to over-ride the original color. You can toggle this by changing the "in2" to "in" in the feComposite. This governs whether you're applying the opacity of the sourcegraphic to the gradient or vice versa.)

div {
  filter: url(#myGradient);
}

<svg>
  <defs>
<filter id="myGradient" primitiveUnits="objectBoundingBox">
       <feImage x="0%" y="0%" width="100%" height="100%" preserveAspectRatio="none" xlink:href="data:image/svg+xml;charset=utf8,%3Csvg%20width%3D%22200px%22%20height%3D%22200px%22%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20xmlns%3Axlink%3D'http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink'%3E%3Cdefs%3E%3ClinearGradient%20id%3D'lightGradient'%20gradientTransform%3D'rotate(-5)'%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.4'%20offset%3D'0%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.5'%20offset%3D'5%25'%2F%3E%3Cstop%20stop-color%3D'black'%20stop-opacity%3D'0.2'%20offset%3D'6%25'%2F%3E%3Cstop%20stop-color%3D'black'%20stop-opacity%3D'0.3'%20offset%3D'19%25'%2F%3E%3Cstop%20stop-color%3D'black'%20stop-opacity%3D'0.2'%20offset%3D'12%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.8'%20offset%3D'13%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.9'%20offset%3D'15%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'15%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'16%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.8'%20offset%3D'16%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0.9'%20offset%3D'18%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'18%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'0'%20offset%3D'20%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'1'%20offset%3D'20%25'%2F%3E%3Cstop%20stop-color%3D'white'%20stop-opacity%3D'1'%20offset%3D'25%25'%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%0A%20%20%3Crect%20id%3D'recGradient'%20x%3D'0%25'%20y%3D'0%25'%20width%3D'100%25'%20height%3D'100%25'%20fill%3D'url(%23lightGradient)'%2F%3E%3C%2Fsvg%3E"/>
  <feComposite operator="in" in2="SourceGraphic"/>
 </filter>
  </defs>
</svg>

<div>
  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text   Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text    Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text  Imagine a very large piece of text
</div>


问:
Visual Studio 2013 Add custom toolbar Button
Hey all I have been searching Google for a while now trying to find anything on how to go about setting up you're own button on the VS toolbar.

What I am talking about is this:

And when I click on that button I would like to be able to execute some C# code.

As an example, say I had the word "HELLO" highlighted and I pushed on that button on the toolbar and I wrote some code behind it that, when pressed, have whatever is highlighted turn bold and change color from normal BLACK to .

I was originally thinking that it was called Visual Studio Extensibility Tools but that doesn't seem to be what I am looking for here - it seemed more as a Nuget plugin type of thing?

I'm looking for more like what you can do with the Office suite of products within VS addins - As in make a button for Outlooks toolbar, etc..

The only remotely close thing I could find so far would be this.

If anyone has done this before or at least know what to search for then please let me know!

答:
You were on the right track with Visual Studio Extensiblilty tools.

There are several steps.

Create the Toolbar and add the button.

Create the event handler that runs when the button is clicked.

Determine what document has focus   (c# doc, xml doc, vb doc, etc.)

Determine what is selected in the document.

Change the code formatting

Start with an overview of the Extensions SDK.

Here's how to create a toolbar with the VS extensions.
Creating a Toolbar for the IDE


问:
'grunt watch' won't run from a package.json script on Windows
I am doing a dev run of a small node app on a Windows machine.  I have set up grunt-contrib-watch and can run it successfully from the bash command line by typing 'grunt watch'. It works as expected.

However when I run the following script in my package.json file:

```<code>"scripts": {
"start": "node app",
"predev": "grunt",
"dev": "start http://localhost:3000 & node-dev app & grunt watch"
}
</code>```

...and start the app using 'npm run dev' a new browser tab opens successfully and the app runs on port 3000 as expected, however 'grunt watch' does not run. I can open a new bash window and run 'grunt watch' separately and it works successfully. I can also automate opening the browser window and then running 'grunt watch' successfully, but it seems that I cannot start up the server AND run grunt from the same bash window - is this a known issue in Windows?

答:
When chaining different command with & commands are executed one after the other. That mean that in your configuration the & node-dev app & grunt watch commands will be executed only once you close the server.

To execute different command in parallel in my build I use the parallelshell module... I'm not sure how stable it is though but it seems to work for me. There is probably other more suitable solution.

link to the npm page of parallelshell : https://www.npmjs.com/package/parallelshell

Body:
I am doing a dev run of a small node app on a Windows machine.  I have set up grunt-contrib-watch and can run it successfully from the bash command line by typing 'grunt watch'. It works as expected.

However when I run the following script in my package.json file:

"scripts": {
"start": "node app",
"predev": "grunt",
"dev": "start http://localhost:3000 & node-dev app & grunt watch"
}

...and start the app using 'npm run dev' a new browser tab opens successfully and the app runs on port 3000 as expected, however 'grunt watch' does not run. I can open a new bash window and run 'grunt watch' separately and it works successfully. I can also automate opening the browser window and then running 'grunt watch' successfully, but it seems that I cannot start up the server AND run grunt from the same bash window - is this a known issue in Windows?


问:
textAlignent to right in cellForRowAt in Swift 3.0
I cannot manage to get my text to align to the right side of my table view. My code sets the text alignment to right but it only justifies the text if there is more that 1 line. Here is my cellforRowAt code

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
    cell.textLabel?.text = self.messages[indexPath.row]
    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.textAlignment = .right
    return cell
}
</code>```

How can I fix this?

答:
You're using the subtitle UITableViewCell style aren't you? This is a style that for what ever reason don't allow you to override the text label's alignment.

To solve this problem, you can make a simple subclass of UITableViewCell with a label in the same position.

Body:
I cannot manage to get my text to align to the right side of my table view. My code sets the text alignment to right but it only justifies the text if there is more that 1 line. Here is my cellforRowAt code

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
    cell.textLabel?.text = self.messages[indexPath.row]
    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.textAlignment = .right
    return cell
}

How can I fix this?


问:
PHP ONE Script to handle ALL requests
I just started with PHP development and I've been looking at my company's web server files. The previous programmers have put a single endpoint to handle all requests. For example,

```<code>www.example.com/webservice.php
</code>```

Using this endpoint, the client will send a myriad of query parameters with an "action" parameter that is mandatory. "action"'s value dictates the function that will be called.

So, webservice.php is a large file with an extremely long if...else statement, which checks $_GET["action"] and calls the respective function in another file (functions.php) together with the related parameters.

My concerns regarding this design is:-

The performance issue

With almost ~100 else if checks for "action", surely it is not efficient coding right?

The RESTfulness of the design

Having some knowledge regarding the RESTful philosophy, my approach would be to separate it into components such as

```<code>www.example.com/module/submodule/action.php
</code>```

答:
The 100 if-then-else could be turned into a switch, which might be cleaner.

Another trick is to have 100 functions.  Let's say the actions are 'foo' and 'bar', etc.  The functions could be Go_foo and Go_bar, etc.  Then some semi-ugly code would go direct to the desired function:

```<code>$to = @$_GET['action'];
if (! isset($to))  die("action= must be supplied");
$fcn = "Go_$to";
$fcn->();
</code>```

Each function would parse whichever arguments it needs.  (Or you could parse some/all up front.)

As others have said, the performance hit is negligible.  Focus on clarity of code, not speed.

<opinion>As for "REST", I find it to be an unnecessarily bloated syntax that provides nothing over old-fashioned arguments.  Even the "versioning" turns out to be useless.  An argument is /widgit/123 instead of &widgit=123; I think = is clearer.`

Title: PHP ONE Script to handle ALL requests

Body:
I just started with PHP development and I've been looking at my company's web server files. The previous programmers have put a single endpoint to handle all requests. For example,

www.example.com/webservice.php

Using this endpoint, the client will send a myriad of query parameters with an "action" parameter that is mandatory. "action"'s value dictates the function that will be called.

So, webservice.php is a large file with an extremely long if...else statement, which checks $_GET["action"] and calls the respective function in another file (functions.php) together with the related parameters.

My concerns regarding this design is:-

The performance issue

With almost ~100 else if checks for "action", surely it is not efficient coding right?

The RESTfulness of the design

Having some knowledge regarding the RESTful philosophy, my approach would be to separate it into components such as

www.example.com/module/submodule/action.php

Body:
The 100 if-then-else could be turned into a switch, which might be cleaner.

Another trick is to have 100 functions.  Let's say the actions are 'foo' and 'bar', etc.  The functions could be Go_foo and Go_bar, etc.  Then some semi-ugly code would go direct to the desired function:

$to = @$_GET['action'];
if (! isset($to))  die("action= must be supplied");
$fcn = "Go_$to";
$fcn->();

Each function would parse whichever arguments it needs.  (Or you could parse some/all up front.)

As others have said, the performance hit is negligible.  Focus on clarity of code, not speed.

<opinion>As for "REST", I find it to be an unnecessarily bloated syntax that provides nothing over old-fashioned arguments.  Even the "versioning" turns out to be useless.  An argument is /widgit/123 instead of &widgit=123; I think = is clearer.`


问:
How to check a type is of a given template type
I have a template type:

```<code>template<class T>
struct Shadow {
   T field[100];
};
</code>```

I want to create a tuple, whose types are instantiations of Shadow, but should not allow any other types. For example,

```<code>tuple< Shadow<int>, Shadow<double> > x; // correct instantiation.
tuple< Shadow<int>, double > x; // incorrect instantiation.
</code>```

How can I achieve this (and have compiler flag an error in case of incorrect instantiation)?

答:
You could use type alias:</p>

```<code>template<class ...Args>
using shadow_tuple = std::tuple<Shadow<Args>...>;

int main()
{
    shadow_tuple<int, double> xx;
    return 0;
}
</code>```

Body:
I have a template type:

template<class T>
struct Shadow {
   T field[100];
};

I want to create a tuple, whose types are instantiations of Shadow, but should not allow any other types. For example,

tuple< Shadow<int>, Shadow<double> > x; // correct instantiation.
tuple< Shadow<int>, double > x; // incorrect instantiation.

How can I achieve this (and have compiler flag an error in case of incorrect instantiation)?

Body:
You could use type alias:

template<class ...Args>
using shadow_tuple = std::tuple<Shadow<Args>...>;

int main()
{
    shadow_tuple<int, double> xx;
    return 0;
}


问:
Segmented Python turtle drawing
Is there a way we can draw something in boxes so that when boxes are arranged in order that it creates a whole picture. I have drawn an image and now I want into break into four boxes so that each box draws a part of the picture:</p>

```<code>from turtle import *
y=0

def head():
    color('green')
    fd(160)
    x=xcor()
    seth(90)
    begin_fill()
    #color('green')
    circle(x/2,180)
    end_fill()
    penup()
    goto(33,37)
    pendown()
    dot(13,'black')
    penup()
    goto(126,37)
    pendown()
    dot(13,'black')
    penup()
    home()
    pendown()
    hideturtle()
    fd(160)
    seth(90)
    circle(x/2,60)
    right(90)
    pensize(5)
    fd(30)

    penup()
    home()
    #pendown()
    hideturtle()
    fd(160)
    seth(90)
    circle(x/2,120)
    right(90)
    pensize(5)
    pendown()
    fd(30)
    penup()
    home()
    penup()

def body():
    pensize(0)

    home()
    showturtle()
    goto(0,-7)
    pendown()
    begin_fill()
    fd(160)
    right(90)
    fd(120)
    right(90)
    fd(160)
    y=ycor()
    right(90)
    fd(120)
    end_fill()

def legs():
    penup()
    #color('red')
    goto(33,-169)
    pendown()
    pensize(32)
    fd(43)
    penup()
    goto(130,-169)
    pendown()
    fd(43)
    penup()

def hands():
    home()
    pensize(30)
    goto(-18,-77)
    pendown()
    left(90)
    fd(65)
    penup()
    goto(179,77)
    pendown()
    fd(65)
    penup()
    fd(100)
    hideturtle()
    circle(100)
    circle(100,360,59)

hideturtle()

head()
body()
legs()
hands()
done()
</code>```

答:
For maximum control over the quality of the image, the best approach is to break an image up externally into separate GIF images and load them into cursors using the register_shape() and shape() methods.

However, if you really want to draw them, here's a rough example.  I'm not using 'boxes' but just drawing elements of the shape that can then be dragged around to produce a final drawing:

```<code>from turtle import *

ANTENNA_WIDTH = 5
ANTENNA_HEIGHT = 30
HEAD_RADIUS = 80

def head():

    begin_poly()

    setheading(90)
    circle(HEAD_RADIUS, 60)
    current_heading = heading()
    setheading(60)
    forward(ANTENNA_HEIGHT)
    backward(ANTENNA_HEIGHT)
    setheading(current_heading)
    circle(HEAD_RADIUS, 60)
    current_heading = heading()
    setheading(120)
    forward(ANTENNA_HEIGHT)
    backward(ANTENNA_HEIGHT)
    setheading(current_heading)
    circle(HEAD_RADIUS, 60)

    end_poly()

    register_shape("head", get_poly())

    reset()

BODY_HEIGHT = 120

def body():

    begin_poly()

    right(90)
    forward(BODY_HEIGHT)
    right(90)
    forward(HEAD_RADIUS * 2)
    right(90)
    forward(BODY_HEIGHT)

    end_poly()

    register_shape("body", get_poly())

    reset()

LEG_LENGTH = 43
LEG_WIDTH = 32

def legs():

    begin_poly()

    forward(LEG_WIDTH)
    setheading(-90)
    forward(LEG_LENGTH)
    circle(LEG_WIDTH / 2, 180)
    forward(LEG_LENGTH)
    setheading(0)

    forward(LEG_WIDTH)
    setheading(-90)
    forward(LEG_LENGTH)
    circle(LEG_WIDTH / 2, 180)
    forward(LEG_LENGTH)
    setheading(0)

    forward(LEG_WIDTH)

    end_poly()

    register_shape("legs", get_poly())

    reset()

ARM_WIDTH = 30
ARM_LENGTH = 65

def arm():

    begin_poly()

    setheading(90)
    circle(ARM_WIDTH / 2, 180)
    forward(ARM_LENGTH)
    circle(ARM_WIDTH / 2, 180)

    end_poly()

    register_shape("arm", get_poly())

    reset()

head()
head_turtle = Turtle("head")
head_turtle.color("green")
head_turtle.setheading(90)
head_turtle.penup()
head_turtle.goto(150, 150)

body()
body_turtle = Turtle("body")
body_turtle.color("green")
body_turtle.setheading(90)
body_turtle.penup()
body_turtle.goto(-150, -150)

legs()
legs_turtle = Turtle("legs")
legs_turtle.color("green")
legs_turtle.setheading(90)
legs_turtle.penup()
legs_turtle.goto(150, -150)

arm()
left_arm_turtle = Turtle("arm")
left_arm_turtle.color("green")
left_arm_turtle.setheading(90)
left_arm_turtle.penup()
left_arm_turtle.goto(-150, 150)

right_arm_turtle = Turtle("arm")
right_arm_turtle.color("green")
right_arm_turtle.setheading(90)
right_arm_turtle.penup()
right_arm_turtle.goto(0, 0)

hideturtle()

def drag_handler(turtle, x, y):
    turtle.ondrag(None)  # disable ondrag event inside drag_handler
    turtle.goto(x, y)
    turtle.ondrag(lambda x, y, turtle=turtle: drag_handler(turtle, x, y))

head_turtle.ondrag(lambda x, y: drag_handler(head_turtle, x, y))
body_turtle.ondrag(lambda x, y: drag_handler(body_turtle, x, y))
legs_turtle.ondrag(lambda x, y: drag_handler(legs_turtle, x, y))
left_arm_turtle.ondrag(lambda x, y: drag_handler(left_arm_turtle, x, y))
right_arm_turtle.ondrag(lambda x, y: drag_handler(right_arm_turtle, x, y))

mainloop()
</code>```

Although the turtle documentation shows just using goto() as a drag event handler, you won't be happy with the result.  The above handler is just a goto() wrapped in code that disables and reenables the event so they don't stack up while you're dragging the element.

STARTING SCREEN

SCREEN AFTER DRAGGING

Title: Segmented Python turtle drawing

Body:
Is there a way we can draw something in boxes so that when boxes are arranged in order that it creates a whole picture. I have drawn an image and now I want into break into four boxes so that each box draws a part of the picture:

from turtle import *
y=0

def head():
    color('green')
    fd(160)
    x=xcor()
    seth(90)
    begin_fill()
    #color('green')
    circle(x/2,180)
    end_fill()
    penup()
    goto(33,37)
    pendown()
    dot(13,'black')
    penup()
    goto(126,37)
    pendown()
    dot(13,'black')
    penup()
    home()
    pendown()
    hideturtle()
    fd(160)
    seth(90)
    circle(x/2,60)
    right(90)
    pensize(5)
    fd(30)

    penup()
    home()
    #pendown()
    hideturtle()
    fd(160)
    seth(90)
    circle(x/2,120)
    right(90)
    pensize(5)
    pendown()
    fd(30)
    penup()
    home()
    penup()

def body():
    pensize(0)

    home()
    showturtle()
    goto(0,-7)
    pendown()
    begin_fill()
    fd(160)
    right(90)
    fd(120)
    right(90)
    fd(160)
    y=ycor()
    right(90)
    fd(120)
    end_fill()

def legs():
    penup()
    #color('red')
    goto(33,-169)
    pendown()
    pensize(32)
    fd(43)
    penup()
    goto(130,-169)
    pendown()
    fd(43)
    penup()

def hands():
    home()
    pensize(30)
    goto(-18,-77)
    pendown()
    left(90)
    fd(65)
    penup()
    goto(179,77)
    pendown()
    fd(65)
    penup()
    fd(100)
    hideturtle()
    circle(100)
    circle(100,360,59)

hideturtle()

head()
body()
legs()
hands()
done()

Body:
For maximum control over the quality of the image, the best approach is to break an image up externally into separate GIF images and load them into cursors using the register_shape() and shape() methods.

However, if you really want to draw them, here's a rough example.  I'm not using 'boxes' but just drawing elements of the shape that can then be dragged around to produce a final drawing:

from turtle import *

ANTENNA_WIDTH = 5
ANTENNA_HEIGHT = 30
HEAD_RADIUS = 80

def head():

    begin_poly()

    setheading(90)
    circle(HEAD_RADIUS, 60)
    current_heading = heading()
    setheading(60)
    forward(ANTENNA_HEIGHT)
    backward(ANTENNA_HEIGHT)
    setheading(current_heading)
    circle(HEAD_RADIUS, 60)
    current_heading = heading()
    setheading(120)
    forward(ANTENNA_HEIGHT)
    backward(ANTENNA_HEIGHT)
    setheading(current_heading)
    circle(HEAD_RADIUS, 60)

    end_poly()

    register_shape("head", get_poly())

    reset()

BODY_HEIGHT = 120

def body():

    begin_poly()

    right(90)
    forward(BODY_HEIGHT)
    right(90)
    forward(HEAD_RADIUS * 2)
    right(90)
    forward(BODY_HEIGHT)

    end_poly()

    register_shape("body", get_poly())

    reset()

LEG_LENGTH = 43
LEG_WIDTH = 32

def legs():

    begin_poly()

    forward(LEG_WIDTH)
    setheading(-90)
    forward(LEG_LENGTH)
    circle(LEG_WIDTH / 2, 180)
    forward(LEG_LENGTH)
    setheading(0)

    forward(LEG_WIDTH)
    setheading(-90)
    forward(LEG_LENGTH)
    circle(LEG_WIDTH / 2, 180)
    forward(LEG_LENGTH)
    setheading(0)

    forward(LEG_WIDTH)

    end_poly()

    register_shape("legs", get_poly())

    reset()

ARM_WIDTH = 30
ARM_LENGTH = 65

def arm():

    begin_poly()

    setheading(90)
    circle(ARM_WIDTH / 2, 180)
    forward(ARM_LENGTH)
    circle(ARM_WIDTH / 2, 180)

    end_poly()

    register_shape("arm", get_poly())

    reset()

head()
head_turtle = Turtle("head")
head_turtle.color("green")
head_turtle.setheading(90)
head_turtle.penup()
head_turtle.goto(150, 150)

body()
body_turtle = Turtle("body")
body_turtle.color("green")
body_turtle.setheading(90)
body_turtle.penup()
body_turtle.goto(-150, -150)

legs()
legs_turtle = Turtle("legs")
legs_turtle.color("green")
legs_turtle.setheading(90)
legs_turtle.penup()
legs_turtle.goto(150, -150)

arm()
left_arm_turtle = Turtle("arm")
left_arm_turtle.color("green")
left_arm_turtle.setheading(90)
left_arm_turtle.penup()
left_arm_turtle.goto(-150, 150)

right_arm_turtle = Turtle("arm")
right_arm_turtle.color("green")
right_arm_turtle.setheading(90)
right_arm_turtle.penup()
right_arm_turtle.goto(0, 0)

hideturtle()

def drag_handler(turtle, x, y):
    turtle.ondrag(None)  # disable ondrag event inside drag_handler
    turtle.goto(x, y)
    turtle.ondrag(lambda x, y, turtle=turtle: drag_handler(turtle, x, y))

head_turtle.ondrag(lambda x, y: drag_handler(head_turtle, x, y))
body_turtle.ondrag(lambda x, y: drag_handler(body_turtle, x, y))
legs_turtle.ondrag(lambda x, y: drag_handler(legs_turtle, x, y))
left_arm_turtle.ondrag(lambda x, y: drag_handler(left_arm_turtle, x, y))
right_arm_turtle.ondrag(lambda x, y: drag_handler(right_arm_turtle, x, y))

mainloop()

Although the turtle documentation shows just using goto() as a drag event handler, you won't be happy with the result.  The above handler is just a goto() wrapped in code that disables and reenables the event so they don't stack up while you're dragging the element.

STARTING SCREEN

SCREEN AFTER DRAGGING


问:
How to make a square button
I have a button on my website and I want to make it square:

How do a make a square button and make it still act like a button so it changes a little bit when i scroll over it

here is my example: note that the button can't be clicked on

http://jsfiddle.net/HrUWm/

(what css will make this work?)
here is what i tried:

```<code><input class="butt" type="button" value="test"/>
.butt{ border: 1px outset blue;  background-color: lightBlue;}
</code>```

答:
An option I am using now (I'm using AngularJS & Bootstrap scripts)

HTML:

```<code><a href="#!login" class="btn">Log In</a>
</code>```

CSS:

```<code>padding: 40px 0px 40px 0px;
text-decoration: none;
width: 250px !important;
height: 250px !important;
</code>```

Title: How to make a square button

Body:
I have a button on my website and I want to make it square:

How do a make a square button and make it still act like a button so it changes a little bit when i scroll over it

here is my example: note that the button can't be clicked on

http://jsfiddle.net/HrUWm/

(what css will make this work?)
here is what i tried:

<input class="butt" type="button" value="test"/>
.butt{ border: 1px outset blue;  background-color: lightBlue;}

Body:
An option I am using now (I'm using AngularJS & Bootstrap scripts)

HTML:

<a href="#!login" class="btn">Log In</a>

CSS:

padding: 40px 0px 40px 0px;
text-decoration: none;
width: 250px !important;
height: 250px !important;


问:
java.lang.NoSuchMethodError: org.apache.spark.storage.BlockManager
I am getting the following error message while I am connecting to a kinesis stream.

```<code>java.lang.NoSuchMethodError: org.apache.spark.storage.BlockManager.get(Lorg/apache/spark/storage/BlockId;)Lscala/Option;
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.getBlockFromBlockManager$1(KinesisBackedBlockRDD.scala:104)
</code>```

My spark streaming code is,

```<code>sc = SparkContext(appName="PythonStreamingTest")
ssc = StreamingContext(sc, 10)
dstream = KinesisUtils.createStream(
    ssc, "PythonStreamingTest", "questions", "https://kinesis.us-west-2.amazonaws.com", "us-west-2", InitialPositionInStream.TRIM_HORIZON, 1)
dstream.foreachRDD(stream_rdd)

def stream_rdd(rdd):
    if not rdd.isEmpty():
        return rdd.foreach(classify)

def classify(ele):
    if ele!="":
        print ele
</code>```

Initially, the stream comes blank as it takes a while to connect to the Kinesis stream. But then all of a sudden, it breaks down the code.
The rest of the trace is,

```<code>17/04/02 17:52:00 ERROR Executor: Exception in task 0.0 in stage 1.0 (TID 1)
java.lang.NoSuchMethodError: org.apache.spark.storage.BlockManager.get(Lorg/apache/spark/storage/BlockId;)Lscala/Option;
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.getBlockFromBlockManager$1(KinesisBackedBlockRDD.scala:104)
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.compute(KinesisBackedBlockRDD.scala:117)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
</code>```

I submit my job using the following command,

```<code>spark-submit --jars spark-streaming-kinesis-asl-assembly_2.11-2.0.0.jar --driver-memory 5g Question_Type_Classification_testing_purpose/classifier_streaming.py
</code>```

I am running the code on a local machine. So if I am giving 5g of memory, the executor should work fine.
The same code works for Spark 1.6. Recently I changed to Spark 2.1 and I am not able to run this code. I updated my kinesis jar and Py4j as well.

I tested my code by writing a Kinesis consumer, and it gets the stream perfectly fine.

Can anyone please let me know what can be the possible issue? Is the empty stream creating an issue? If yes, why am I getting an empty stream while using Spark streaming? Any help is really appreciated.

答:
spark-streaming-kinesis-asl is Spark’s own internal library and is using Spark internal APIs (e.g., BlockManager.get). The method signature of BlockManager.get was changed in https://github.com/apache/spark/commit/29cfab3f1524c5690be675d24dda0a9a1806d6ff#diff-2b643ea78c1add0381754b1f47eec132L605 so you will see NoSuchMethodError if the Spark version is >= 2.0.1 but spark-streaming-kinesis-asl version is < 2.0.1.

Generally, because Spark doesn’t promise not breaking internal APIs between releases, you must use spark-streaming-kinesis-asl with the same version of Spark.

For latest Spark releases, the kinesis asl assembly jar was removed because of the potential license issue [1], hence you may not be able to find the assembly jar. However, you can use --packages org.apache.spark:spark-streaming-kinesis-asl_2.11:2.1.0 to add spark-streaming-kinesis-asl and its dependencies into the classpath automatically, rather than building the assembly jar by yourself.

[1] https://issues.apache.org/jira/browse/SPARK-17418

Body:
I am getting the following error message while I am connecting to a kinesis stream.

java.lang.NoSuchMethodError: org.apache.spark.storage.BlockManager.get(Lorg/apache/spark/storage/BlockId;)Lscala/Option;
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.getBlockFromBlockManager$1(KinesisBackedBlockRDD.scala:104)

My spark streaming code is,

sc = SparkContext(appName="PythonStreamingTest")
ssc = StreamingContext(sc, 10)
dstream = KinesisUtils.createStream(
    ssc, "PythonStreamingTest", "questions", "https://kinesis.us-west-2.amazonaws.com", "us-west-2", InitialPositionInStream.TRIM_HORIZON, 1)
dstream.foreachRDD(stream_rdd)

def stream_rdd(rdd):
    if not rdd.isEmpty():
        return rdd.foreach(classify)

def classify(ele):
    if ele!="":
        print ele

Initially, the stream comes blank as it takes a while to connect to the Kinesis stream. But then all of a sudden, it breaks down the code.
The rest of the trace is,

17/04/02 17:52:00 ERROR Executor: Exception in task 0.0 in stage 1.0 (TID 1)
java.lang.NoSuchMethodError: org.apache.spark.storage.BlockManager.get(Lorg/apache/spark/storage/BlockId;)Lscala/Option;
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.getBlockFromBlockManager$1(KinesisBackedBlockRDD.scala:104)
    at org.apache.spark.streaming.kinesis.KinesisBackedBlockRDD.compute(KinesisBackedBlockRDD.scala:117)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

I submit my job using the following command,

spark-submit --jars spark-streaming-kinesis-asl-assembly_2.11-2.0.0.jar --driver-memory 5g Question_Type_Classification_testing_purpose/classifier_streaming.py

I am running the code on a local machine. So if I am giving 5g of memory, the executor should work fine.
The same code works for Spark 1.6. Recently I changed to Spark 2.1 and I am not able to run this code. I updated my kinesis jar and Py4j as well.

I tested my code by writing a Kinesis consumer, and it gets the stream perfectly fine.

Can anyone please let me know what can be the possible issue? Is the empty stream creating an issue? If yes, why am I getting an empty stream while using Spark streaming? Any help is really appreciated.


问:
Why the image is not displayed in the imageItem?
I used the Nokia sample codes for Google Map. It has retrieveStaticImage method which loads and returns an Image. I them loaded the image to an ImageItem but I get an exception everytime..
Here are my codes...

Codes for GoogleMaps class

```<code>import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;

public class GoogleMaps implements Runnable{
    private static final String URL_UNRESERVED =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
        "abcdefghijklmnopqrstuvwxyz" +
        "0123456789-_.~";
    private static final char[] HEX = "0123456789ABCDEF".toCharArray();
    Image image;
    int width;
    int height;
    double lat;
    double lng;
    int zoom;
    String format;
    ImageItem imagecmpt;
    // these 2 properties will be used with map scrolling methods. You can remove them if not needed
    public static final int offset = 268435456;
    public static final double radius = offset / Math.PI;

    private String apiKey = null;

    public GoogleMaps(String key,int width, int height, double lat, double lng, int zoom,
            String format,ImageItem img) {
        this.width=width;
        this.height=height;
       this.lat=lat;
       this.lng=lng;
       this.zoom=zoom;
this.format=format;
        apiKey = key;

    }

    public double[] geocodeAddress(String address) throws Exception {
        byte[] res = loadHttpFile(getGeocodeUrl(address));
        String[] data = split(new String(res), ',');

        if (!data[0].equals("200")) {
            int errorCode = Integer.parseInt(data[0]);
            throw new Exception("Google Maps Exception: " + getGeocodeError(errorCode));
        }

        return new double[] {
                Double.parseDouble(data[2]), Double.parseDouble(data[3])
        };
    }

    public Image retrieveStaticImage() throws IOException {
        byte[] imageData = loadHttpFile(getMapUrl(width, height, lng, lat, zoom, format));
        System.out.println("Address is "+getMapUrl(width, height, lng, lat, zoom, format));
        for (int i=0;i<imageData.length;i++){
            System.out.println(imageData[i]);
        }
        return Image.createImage(imageData, 0, imageData.length);
    }

    private static String getGeocodeError(int errorCode) {
        switch (errorCode) {
        case 400:
            return "Bad request";
        case 500:
            return "Server error";
        case 601:
            return "Missing query";
        case 602:
            return "Unknown address";
        case 603:
            return "Unavailable address";
        case 604:
            return "Unknown directions";
        case 610:
            return "Bad API key";
        case 620:
            return "Too many queries";
        default:
            return "Generic error";
        }
    }

    private String getGeocodeUrl(String address) {
        return "http://maps.google.com/maps/geo?q=" + urlEncode(address) + "&output=csv&key="
                + apiKey;
    }

    private String getMapUrl(int width, int height, double lng, double lat, int zoom, String format) {
        return "http://maps.google.com/staticmap?center=" + lat + "," + lng + "&format="
                + format + "&zoom=" + zoom + "&size=" + width + "x" + height + "&key=" + apiKey;
    }

    private static String urlEncode(String str) {
        StringBuffer buf = new StringBuffer();
        byte[] bytes = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            dos.writeUTF(str);
            bytes = bos.toByteArray();
        } catch (IOException e) {
            // ignore
        }
        for (int i = 2; i < bytes.length; i++) {
            byte b = bytes[i];
            if (URL_UNRESERVED.indexOf(b) >= 0) {
                buf.append((char) b);
            } else {
                buf.append('%').append(HEX[(b >> 4) & 0x0f]).append(HEX[b & 0x0f]);
            }
        }
        return buf.toString();
    }

    private static byte[] loadHttpFile(String url) throws IOException {
        byte[] byteBuffer;

        HttpConnection hc = (HttpConnection) Connector.open(url);
        try {
            hc.setRequestMethod(HttpConnection.GET);
            InputStream is = hc.openInputStream();
            try {
                int len = (int) hc.getLength();
                if (len > 0) {
                    byteBuffer = new byte[len];
                    int done = 0;
                    while (done < len) {
                        done += is.read(byteBuffer, done, len - done);
                    }
                } else {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[512];
                    int count;
                    while ( (count = is.read(buffer)) >= 0 ) {
                        bos.write(buffer, 0, count);
                    }
                    byteBuffer = bos.toByteArray();
                }
            } finally {
                is.close();
            }
        } finally {
            hc.close();
        }

        return byteBuffer;
    }

    private static String[] split(String s, int chr) {
        Vector res = new Vector();

        int curr;
        int prev = 0;

        while ( (curr = s.indexOf(chr, prev)) >= 0 ) {
            res.addElement(s.substring(prev, curr));
            prev = curr + 1;
        }
        res.addElement(s.substring(prev));

        String[] splitted = new String[res.size()];
        res.copyInto(splitted);

        return splitted;
    }

    public void run() {
        try{
        //throw new UnsupportedOperationException("Not supported yet.");
        imagecmpt.setImage(retrieveStaticImage());
        }
        catch(Exception e){
            System.out.println("Error ......."+e);
        }
    }
}
</code>```

code for midlet

```<code>public void commandAction(Command command, Displayable displayable) {
        // write pre-action user code here
        if (displayable == form) {
            if (command == exitCommand) {
                // write pre-action user code here
                exitMIDlet();
                // write post-action user code here
            } else if (command == okCommand) {
                // write pre-action user code here

                // write post-action user code here

                GoogleMaps cMz=new GoogleMaps("ABQIAAAADEQoVqbqS5pT4ahHSLALyBT8PMUw5z7_OLJoE1lh2VQyfb-WOxTwS9t9mrSq_flhdPeVGOQrxXuCFQ",10, 10, 10, 10, 1, "roadmap", imageItem);

                Thread th=new Thread(cMz);
                th.run();
                Display display=getDisplay ();

            }
        }
        // write post-action user code here
    }
</code>```

My output:::

```<code>Starting emulator in execution mode
Running with storage root DefaultColorPhone
Running with locale: English_United States.1252
Running in the identified_third_party security domain
Warning: To avoid potential deadlock, operations that may block, such as
 networking, should be performed in a different thread than the
 commandAction() handler.
</code>```

I have used an external thread but yet it keeps telling me to use another thread..
How can I sort this out?

答:
Try </p>

```<code>new Thread(new Runnable(){
 GoogleMaps cMz=new GoogleMaps("ABQIAAAADEQoVqbqS5pT4ahHSLALyBT8PMUw5z7_OLJoE1lh2VQyfb-WOxTwS9t9mrSq_flhdPeVGOQrxXuCFQ",10, 10, 10, 10, 1, "roadmap", imageItem);

//put here action

}
).start();
</code>```

Body:
I used the Nokia sample codes for Google Map. It has retrieveStaticImage method which loads and returns an Image. I them loaded the image to an ImageItem but I get an exception everytime..
Here are my codes...

Codes for GoogleMaps class

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;

public class GoogleMaps implements Runnable{
    private static final String URL_UNRESERVED =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
        "abcdefghijklmnopqrstuvwxyz" +
        "0123456789-_.~";
    private static final char[] HEX = "0123456789ABCDEF".toCharArray();
    Image image;
    int width;
    int height;
    double lat;
    double lng;
    int zoom;
    String format;
    ImageItem imagecmpt;
    // these 2 properties will be used with map scrolling methods. You can remove them if not needed
    public static final int offset = 268435456;
    public static final double radius = offset / Math.PI;

    private String apiKey = null;

    public GoogleMaps(String key,int width, int height, double lat, double lng, int zoom,
            String format,ImageItem img) {
        this.width=width;
        this.height=height;
       this.lat=lat;
       this.lng=lng;
       this.zoom=zoom;
this.format=format;
        apiKey = key;

    }

    public double[] geocodeAddress(String address) throws Exception {
        byte[] res = loadHttpFile(getGeocodeUrl(address));
        String[] data = split(new String(res), ',');

        if (!data[0].equals("200")) {
            int errorCode = Integer.parseInt(data[0]);
            throw new Exception("Google Maps Exception: " + getGeocodeError(errorCode));
        }

        return new double[] {
                Double.parseDouble(data[2]), Double.parseDouble(data[3])
        };
    }

    public Image retrieveStaticImage() throws IOException {
        byte[] imageData = loadHttpFile(getMapUrl(width, height, lng, lat, zoom, format));
        System.out.println("Address is "+getMapUrl(width, height, lng, lat, zoom, format));
        for (int i=0;i<imageData.length;i++){
            System.out.println(imageData[i]);
        }
        return Image.createImage(imageData, 0, imageData.length);
    }

    private static String getGeocodeError(int errorCode) {
        switch (errorCode) {
        case 400:
            return "Bad request";
        case 500:
            return "Server error";
        case 601:
            return "Missing query";
        case 602:
            return "Unknown address";
        case 603:
            return "Unavailable address";
        case 604:
            return "Unknown directions";
        case 610:
            return "Bad API key";
        case 620:
            return "Too many queries";
        default:
            return "Generic error";
        }
    }

    private String getGeocodeUrl(String address) {
        return "http://maps.google.com/maps/geo?q=" + urlEncode(address) + "&output=csv&key="
                + apiKey;
    }

    private String getMapUrl(int width, int height, double lng, double lat, int zoom, String format) {
        return "http://maps.google.com/staticmap?center=" + lat + "," + lng + "&format="
                + format + "&zoom=" + zoom + "&size=" + width + "x" + height + "&key=" + apiKey;
    }

    private static String urlEncode(String str) {
        StringBuffer buf = new StringBuffer();
        byte[] bytes = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            dos.writeUTF(str);
            bytes = bos.toByteArray();
        } catch (IOException e) {
            // ignore
        }
        for (int i = 2; i < bytes.length; i++) {
            byte b = bytes[i];
            if (URL_UNRESERVED.indexOf(b) >= 0) {
                buf.append((char) b);
            } else {
                buf.append('%').append(HEX[(b >> 4) & 0x0f]).append(HEX[b & 0x0f]);
            }
        }
        return buf.toString();
    }

    private static byte[] loadHttpFile(String url) throws IOException {
        byte[] byteBuffer;

        HttpConnection hc = (HttpConnection) Connector.open(url);
        try {
            hc.setRequestMethod(HttpConnection.GET);
            InputStream is = hc.openInputStream();
            try {
                int len = (int) hc.getLength();
                if (len > 0) {
                    byteBuffer = new byte[len];
                    int done = 0;
                    while (done < len) {
                        done += is.read(byteBuffer, done, len - done);
                    }
                } else {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[512];
                    int count;
                    while ( (count = is.read(buffer)) >= 0 ) {
                        bos.write(buffer, 0, count);
                    }
                    byteBuffer = bos.toByteArray();
                }
            } finally {
                is.close();
            }
        } finally {
            hc.close();
        }

        return byteBuffer;
    }

    private static String[] split(String s, int chr) {
        Vector res = new Vector();

        int curr;
        int prev = 0;

        while ( (curr = s.indexOf(chr, prev)) >= 0 ) {
            res.addElement(s.substring(prev, curr));
            prev = curr + 1;
        }
        res.addElement(s.substring(prev));

        String[] splitted = new String[res.size()];
        res.copyInto(splitted);

        return splitted;
    }

    public void run() {
        try{
        //throw new UnsupportedOperationException("Not supported yet.");
        imagecmpt.setImage(retrieveStaticImage());
        }
        catch(Exception e){
            System.out.println("Error ......."+e);
        }
    }
}

code for midlet

public void commandAction(Command command, Displayable displayable) {
        // write pre-action user code here
        if (displayable == form) {
            if (command == exitCommand) {
                // write pre-action user code here
                exitMIDlet();
                // write post-action user code here
            } else if (command == okCommand) {
                // write pre-action user code here

                // write post-action user code here

                GoogleMaps cMz=new GoogleMaps("ABQIAAAADEQoVqbqS5pT4ahHSLALyBT8PMUw5z7_OLJoE1lh2VQyfb-WOxTwS9t9mrSq_flhdPeVGOQrxXuCFQ",10, 10, 10, 10, 1, "roadmap", imageItem);

                Thread th=new Thread(cMz);
                th.run();
                Display display=getDisplay ();

            }
        }
        // write post-action user code here
    }

My output:::

Starting emulator in execution mode
Running with storage root DefaultColorPhone
Running with locale: English_United States.1252
Running in the identified_third_party security domain
Warning: To avoid potential deadlock, operations that may block, such as
 networking, should be performed in a different thread than the
 commandAction() handler.

I have used an external thread but yet it keeps telling me to use another thread..
How can I sort this out?

Body:
Try

new Thread(new Runnable(){
 GoogleMaps cMz=new GoogleMaps("ABQIAAAADEQoVqbqS5pT4ahHSLALyBT8PMUw5z7_OLJoE1lh2VQyfb-WOxTwS9t9mrSq_flhdPeVGOQrxXuCFQ",10, 10, 10, 10, 1, "roadmap", imageItem);

//put here action

}
).start();


问:
Appengine devserver running on 2 ports
Upgraded my OS to Sierria, and installed JDK8, maven 3.3.9 and tried to run maven, and it throws an error. Going through appengine docs, it mentions "You can use Java 7 or Java 8, but you must use Java 7 bytecode level". So tried installing JDK7, but didn't work too. Tried to run on other ports, but the same problem occured.</p>

```<code>[INFO] <<< appengine-maven-plugin:1.9.48:devserver (default-cli) < package @ mark <<<
[INFO]
[INFO] --- appengine-maven-plugin:1.9.48:devserver (default-cli) @ mark ---
[INFO]
[INFO] Google App Engine Java SDK - Running Development Server
[INFO]
[INFO] Retrieving Google App Engine Java SDK from Maven
[INFO] Running /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/bin/java -XstartOnFirstThread -javaagent:/Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/lib/agent/appengine-agent.jar -Xbootclasspath/p:/Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/lib/override/appengine-dev-jdk-overrides.jar -Dappengine.fullscan.seconds=5 -classpath /Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/lib/appengine-tools-api.jar com.google.appengine.tools.development.DevAppServerMain --allow_remote_shutdown -p 8080 /Users/Raghu/git/site/target/mark-6
[INFO] objc[4320]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/bin/java (0x100e654c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x100f2e4e0). One of the two will be used. Which one is undefined.
[INFO] Apr 02, 2017 11:21:05 PM com.google.appengine.tools.development.SystemPropertiesManager setSystemProperties
[INFO] INFO: Overwriting system property key 'java.util.logging.config.file', value '/Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/config/sdk/logging.properties' with value 'WEB-INF/logging.properties' from '/Users/Raghu/git/site/target/mark-6/WEB-INF/appengine-web.xml'
[INFO] Apr 02, 2017 11:21:06 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
[INFO] Apr 02, 2017 5:51:06 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: jetty-6.1.x
[INFO] Apr 02, 2017 5:51:07 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: Started SelectChannelConnector@localhost:8080
[INFO] Apr 02, 2017 5:51:07 PM com.google.appengine.tools.development.JettyContainerService startHotDeployScanner
[INFO] INFO: Full scan of the web app in place every 5s.
[INFO] Apr 02, 2017 5:51:07 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: Module instance gamma is running at http://localhost:8080/
[INFO] Apr 02, 2017 5:51:07 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: The admin console is running at http://localhost:8080/_ah/admin
[INFO] Apr 02, 2017 5:51:07 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: jetty-6.1.x
[INFO] Apr 02, 2017 5:51:08 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: Started SelectChannelConnector@localhost:52747
[INFO] Apr 02, 2017 5:51:08 PM com.google.appengine.tools.development.JettyContainerService startHotDeployScanner
[INFO] INFO: Full scan of the web app in place every 5s.
[INFO] Apr 02, 2017 5:51:08 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: Module instance gamma instance 0 is running at http://localhost:52747/
[INFO] Apr 02, 2017 5:51:08 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: The admin console is running at http://localhost:52747/_ah/admin
[INFO] Apr 02, 2017 11:21:08 PM com.google.appengine.tools.development.DevAppServerImpl doStart
[INFO] INFO: Dev App Server is now running
[INFO] Apr 02, 2017 11:21:08 PM com.google.appengine.tools.development.InstanceHelper sendStartRequest
[INFO] WARNING: Got exception while performing /_ah/start request on server: 0.gamma, java.lang.NullPointerException: null
</code>```

答:
After spending some time on it, I had figured out that the problem was that I was using a backend instance B1 in appengine-web.xml with basic scaling. Solved it by using a Frontend instance F1 with automatic scaling and everything started to work fine. Since it was running locally, I thought appengine-web.xml wouldn't be considered, my bad.

In appengine-web.xml:

```<code><instance-class>F1</instance-class>
<automatic-scaling>
    <max-idle-instances>1</max-idle-instances>
    <min-pending-latency>automatic</min-pending-latency>
    <max-pending-latency>10ms</max-pending-latency>
    <max-concurrent-requests>5</max-concurrent-requests>
</automatic-scaling>
</code>```

Title: Appengine devserver running on 2 ports

Body:
Upgraded my OS to Sierria, and installed JDK8, maven 3.3.9 and tried to run maven, and it throws an error. Going through appengine docs, it mentions "You can use Java 7 or Java 8, but you must use Java 7 bytecode level". So tried installing JDK7, but didn't work too. Tried to run on other ports, but the same problem occured.

[INFO] <<< appengine-maven-plugin:1.9.48:devserver (default-cli) < package @ mark <<<
[INFO]
[INFO] --- appengine-maven-plugin:1.9.48:devserver (default-cli) @ mark ---
[INFO]
[INFO] Google App Engine Java SDK - Running Development Server
[INFO]
[INFO] Retrieving Google App Engine Java SDK from Maven
[INFO] Running /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/bin/java -XstartOnFirstThread -javaagent:/Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/lib/agent/appengine-agent.jar -Xbootclasspath/p:/Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/lib/override/appengine-dev-jdk-overrides.jar -Dappengine.fullscan.seconds=5 -classpath /Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/lib/appengine-tools-api.jar com.google.appengine.tools.development.DevAppServerMain --allow_remote_shutdown -p 8080 /Users/Raghu/git/site/target/mark-6
[INFO] objc[4320]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/bin/java (0x100e654c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x100f2e4e0). One of the two will be used. Which one is undefined.
[INFO] Apr 02, 2017 11:21:05 PM com.google.appengine.tools.development.SystemPropertiesManager setSystemProperties
[INFO] INFO: Overwriting system property key 'java.util.logging.config.file', value '/Users/Raghu/.m2/repository/com/google/appengine/appengine-java-sdk/1.9.48/appengine-java-sdk/appengine-java-sdk-1.9.48/config/sdk/logging.properties' with value 'WEB-INF/logging.properties' from '/Users/Raghu/git/site/target/mark-6/WEB-INF/appengine-web.xml'
[INFO] Apr 02, 2017 11:21:06 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
[INFO] Apr 02, 2017 5:51:06 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: jetty-6.1.x
[INFO] Apr 02, 2017 5:51:07 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: Started SelectChannelConnector@localhost:8080
[INFO] Apr 02, 2017 5:51:07 PM com.google.appengine.tools.development.JettyContainerService startHotDeployScanner
[INFO] INFO: Full scan of the web app in place every 5s.
[INFO] Apr 02, 2017 5:51:07 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: Module instance gamma is running at http://localhost:8080/
[INFO] Apr 02, 2017 5:51:07 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: The admin console is running at http://localhost:8080/_ah/admin
[INFO] Apr 02, 2017 5:51:07 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: jetty-6.1.x
[INFO] Apr 02, 2017 5:51:08 PM com.google.apphosting.utils.jetty.JettyLogger info
[INFO] INFO: Started SelectChannelConnector@localhost:52747
[INFO] Apr 02, 2017 5:51:08 PM com.google.appengine.tools.development.JettyContainerService startHotDeployScanner
[INFO] INFO: Full scan of the web app in place every 5s.
[INFO] Apr 02, 2017 5:51:08 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: Module instance gamma instance 0 is running at http://localhost:52747/
[INFO] Apr 02, 2017 5:51:08 PM com.google.appengine.tools.development.AbstractModule startup
[INFO] INFO: The admin console is running at http://localhost:52747/_ah/admin
[INFO] Apr 02, 2017 11:21:08 PM com.google.appengine.tools.development.DevAppServerImpl doStart
[INFO] INFO: Dev App Server is now running
[INFO] Apr 02, 2017 11:21:08 PM com.google.appengine.tools.development.InstanceHelper sendStartRequest
[INFO] WARNING: Got exception while performing /_ah/start request on server: 0.gamma, java.lang.NullPointerException: null

Body:
After spending some time on it, I had figured out that the problem was that I was using a backend instance B1 in appengine-web.xml with basic scaling. Solved it by using a Frontend instance F1 with automatic scaling and everything started to work fine. Since it was running locally, I thought appengine-web.xml wouldn't be considered, my bad.

In appengine-web.xml:

<instance-class>F1</instance-class>
<automatic-scaling>
    <max-idle-instances>1</max-idle-instances>
    <min-pending-latency>automatic</min-pending-latency>
    <max-pending-latency>10ms</max-pending-latency>
    <max-concurrent-requests>5</max-concurrent-requests>
</automatic-scaling>


问:
ngdbc.jar equivalent Maven repository
I am using ngdbc.jar to connect Java and HANA. Now I want to build a Web application. So I searched for the equivalent Maven repository but I could not find that one.

I found mostly for the cloud ones and finally found this one:

```<code>  <dependency>
    <groupId>com.sap.cloud</groupId>
    <artifactId>neo-java-web-api</artifactId>
    <version>1.53.18.2</version>
    <scope>provided</scope>
  </dependency>
</code>```

Can any one tell which repository I can use instead of ngdbc.jar? Any help is appreciated

答:
I tried to  install the jar file as a dependency by

```<code>install:install-file -Dfile=C:\ngdbc.jar -DgroupId=com.han.driver -DartifactId=hana -Dversion=1.0 -Dpackaging=jar
</code>```

in Maven which is pretty handy and good way.hope this helps someone dealing with custom jars.

ContentLicense: CC BY-SA 4.0

Title: ngdbc.jar equivalent Maven repository

Body:
I am using ngdbc.jar to connect Java and HANA. Now I want to build a Web application. So I searched for the equivalent Maven repository but I could not find that one.

I found mostly for the cloud ones and finally found this one:

  <dependency>
    <groupId>com.sap.cloud</groupId>
    <artifactId>neo-java-web-api</artifactId>
    <version>1.53.18.2</version>
    <scope>provided</scope>
  </dependency>

Can any one tell which repository I can use instead of ngdbc.jar? Any help is appreciated

Body:
I tried to  install the jar file as a dependency by

install:install-file -Dfile=C:\ngdbc.jar -DgroupId=com.han.driver -DartifactId=hana -Dversion=1.0 -Dpackaging=jar

in Maven which is pretty handy and good way.hope this helps someone dealing with custom jars.


问:
how would I pass a specific type of number in the command line?
I understand how to pass an integer through the command line, but how would I do this if I needed a specific range of integers?

For example I have a program that accepts a range of numbers and divides them by five. The number needs to be within 30-105, and must be a multiple of 5.

And if any number out of that range and is not a multiple of 5, there would be an error message.

How can I do this?

答:
You basically have to do three things:

Get all numbers from the command line

Check if they're valid

Print an error message if necessary

Let's get number 2 out of the way first, checking the validity.

```<code>bool isValid(int number) {
    return (number >= 30 && number <= 105 && number % 5 == 0);
}
</code>```

This function checks if the given number fits your criteria; greater than or equal to 30, lesser than or equal to 105, and divisible by 5. Now, we have to use that function to validate the arguments.

To do that, we have to loop over all of them and check if they are valid, aborting on the first error.

```<code>#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i != argc; ++i) {
        int number = atoi(argv[i]);
        if (!isValid(number)) {
            puts("Error!");
            break;
        } else {
            // do something
         }
     }
}
</code>```

If you want to keep the valid numbers, you'd have to store them in an array in the else-branch.

Edit:
Reading your comments made me think you don't want to get the numbers from the actual command line (as in ./myProgram 30 40 50) but from a prompt in the program itself.

Getting a single number at a time, we have to:

Print a prompt

Read a number

Check if it's valid

We can isolate that in a function, but to keep it short, I'll not do that and shamelessly put it in main.

```<code>#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    int number;

    while (true) {
        printf("Enter a number: ");
        scanf("%d", &number);

        if (isValid(number)) {
            break;
        } else {
            puts("Not a valid number!");
        }
    }

    // do something
}
</code>```

Body:
You basically have to do three things:

Get all numbers from the command line

Check if they're valid

Print an error message if necessary

Let's get number 2 out of the way first, checking the validity.

bool isValid(int number) {
    return (number >= 30 && number <= 105 && number % 5 == 0);
}

This function checks if the given number fits your criteria; greater than or equal to 30, lesser than or equal to 105, and divisible by 5. Now, we have to use that function to validate the arguments.

To do that, we have to loop over all of them and check if they are valid, aborting on the first error.

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i != argc; ++i) {
        int number = atoi(argv[i]);
        if (!isValid(number)) {
            puts("Error!");
            break;
        } else {
            // do something
         }
     }
}

If you want to keep the valid numbers, you'd have to store them in an array in the else-branch.

Edit:
Reading your comments made me think you don't want to get the numbers from the actual command line (as in ./myProgram 30 40 50) but from a prompt in the program itself.

Getting a single number at a time, we have to:

Print a prompt

Read a number

Check if it's valid

We can isolate that in a function, but to keep it short, I'll not do that and shamelessly put it in main.

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    int number;

    while (true) {
        printf("Enter a number: ");
        scanf("%d", &number);

        if (isValid(number)) {
            break;
        } else {
            puts("Not a valid number!");
        }
    }

    // do something
}


问:
transfer data from fragment A -> fragment B - > fragment C. When user click Back button, I want to return to fragment A and data
I'm a newbie in android developer. I have a question about transfer with 3 fragments.

I have 3 fragments (A - B - C). I want o transfer data from A -> B -> C.

In each the fragment, data was been changed.
When user click BACK BUTTON, user want to return A with the updated data.
How to return fragment A with the update data?
Thanks.

答: Use interface to achieve this. Implements interface in fragment and activity, as it's a good way to communicate between fragment through activity. Then send the data through interface and extract the data from it.</p>


问:
bash scripting: How to test list membership
(This is debian squeeze amd64)

I need to test if a file is a member of a list of files.
So long my (test) script is:

```<code>set -x
array=$( ls )
echo $array
FILE=log.out
# This line gives error!
if $FILE in $array
then   echo "success!"
else  echo "bad!"
fi
exit 0
</code>```

¿Any ideas?

Thanks for all the responses. To clarify: The script given is only an example, the actual problem is more complex. In the final solution, it will be done within a loop, so I need the file(name) to be tested for to be in a variable.

Thanks again. No my test-script works, and reads:
```</p>

<code>  in_list() {
       local search="$1"
       shift
       local list=("$@")
       for file in "${list[@]}" ; do
           [[ "$file" == "$search" ]] && return 0
       done
       return 1
    }
    #
    # set -x
    array=( * )  # Array of files in current dir
    # echo $array
    FILE="log.out"
    if in_list "$FILE" "${array[@]}"
    then   echo "success!"
    else  echo "bad!"
    fi
    exit 0
</code>```

答:
How about

```<code>in_list() {
    local search="$1"
    shift
    local list=("$@")
    for file in "${list[@]}" ; do
        [[ $file == $search ]] && return 0
    done
    return 1
}

if in_list log.out * ; then
    echo 'success!'
else
    echo 'bad!'
fi
</code>```

EDIT: made it a bit less idiotic.

EDIT #2:
Of course if all you're doing is looking in the current directory to see if a particular file is there, which is effectively what the above is doing, then you can just say

```<code>[ -e log.out ] && echo 'success!' || echo 'bad!'
</code>```

If you're actually doing something more complicated involving lists of files then this might not be sufficient.

Body:
(This is debian squeeze amd64)

I need to test if a file is a member of a list of files.
So long my (test) script is:

set -x
array=$( ls )
echo $array
FILE=log.out
# This line gives error!
if $FILE in $array
then   echo "success!"
else  echo "bad!"
fi
exit 0

¿Any ideas?

Thanks for all the responses. To clarify: The script given is only an example, the actual problem is more complex. In the final solution, it will be done within a loop, so I need the file(name) to be tested for to be in a variable.

Thanks again. No my test-script works, and reads:

  in_list() {
       local search="$1"
       shift
       local list=("$@")
       for file in "${list[@]}" ; do
           [[ "$file" == "$search" ]] && return 0
       done
       return 1
    }
    #
    # set -x
    array=( * )  # Array of files in current dir
    # echo $array
    FILE="log.out"
    if in_list "$FILE" "${array[@]}"
    then   echo "success!"
    else  echo "bad!"
    fi
    exit 0

Body:
How about

in_list() {
    local search="$1"
    shift
    local list=("$@")
    for file in "${list[@]}" ; do
        [[ $file == $search ]] && return 0
    done
    return 1
}

if in_list log.out * ; then
    echo 'success!'
else
    echo 'bad!'
fi

EDIT: made it a bit less idiotic.

EDIT #2:
Of course if all you're doing is looking in the current directory to see if a particular file is there, which is effectively what the above is doing, then you can just say

[ -e log.out ] && echo 'success!' || echo 'bad!'

If you're actually doing something more complicated involving lists of files then this might not be sufficient.