问:
How does the static keyword affect thread safety and why?
Take the following examples:

```<code>List<MyObject> objects = new List<MyObject();
</code>```

Example #1:

```<code>static class MyClass1
{
    static void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}
</code>```

Example #2:

```<code>class MyClass2
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}
</code>```

Example #3:

```<code>static MyClass3 myClass3 = new MyClass3();
class MyClass3
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}
</code>```

and then calling

```<code> Task.Factory.StartNew(() =>
 {
    MyClass1.MyMember(objects);
 });
</code>```

or

```<code> MyClass2 myClass2 = new MyClass2();
 Task.Factory.StartNew(() =>
 {
    myClass2.MyMember(objects);
 });
</code>```

or

```<code> static MyClass3 myClass3 = new MyClass3();
 Task.Factory.StartNew(() =>
 {
    myClass3.MyMember(objects);
 });
</code>```

Assuming that the application will only have one of these examples, and that the Task is called multiple times simultaneously.

You could think of this as a console app where List<MyObject> objects is instantiated in the Main(), same goes for the tasks, called in Main() multiple times simultaneously.

答:
For Example #1 to work, you would have to have

```<code>static class MyClass1
{
    static List<MyObject> objects = new List<MyObject();
    static void MyMember() { objects.Add(new MyObject); }
}
</code>```

in order for MyMember to access objects. Since there is only ever a single instance of a static class'es data members (which must all be static since a static class cannot be constructed (it's not dynamically allocated on the heap like a reference variable, but instead allocated in a separate, "global", memory area) and therefore have instance variables), this would not be thread safe.

Body:
Take the following examples:

List<MyObject> objects = new List<MyObject();

Example #1:

static class MyClass1
{
    static void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}

Example #2:

class MyClass2
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}

Example #3:

static MyClass3 myClass3 = new MyClass3();
class MyClass3
{
    void MyMember(List<MyObject> objects) { objects.Add(new MyObject); }
}

and then calling

 Task.Factory.StartNew(() =>
 {
    MyClass1.MyMember(objects);
 });

or

 MyClass2 myClass2 = new MyClass2();
 Task.Factory.StartNew(() =>
 {
    myClass2.MyMember(objects);
 });

or

 static MyClass3 myClass3 = new MyClass3();
 Task.Factory.StartNew(() =>
 {
    myClass3.MyMember(objects);
 });

Assuming that the application will only have one of these examples, and that the Task is called multiple times simultaneously.

You could think of this as a console app where List<MyObject> objects is instantiated in the Main(), same goes for the tasks, called in Main() multiple times simultaneously.

Body:
For Example #1 to work, you would have to have

static class MyClass1
{
    static List<MyObject> objects = new List<MyObject();
    static void MyMember() { objects.Add(new MyObject); }
}

in order for MyMember to access objects. Since there is only ever a single instance of a static class'es data members (which must all be static since a static class cannot be constructed (it's not dynamically allocated on the heap like a reference variable, but instead allocated in a separate, "global", memory area) and therefore have instance variables), this would not be thread safe.


来源: stackexchange

问:
LINQ .equals() and string variables
Not sure why this query returns no results (note that CUSTOMERs is from an Oracle database):

```<code>string zip = "12345"
string state = "MA"

var result = from x in CUSTOMERs
             where x.STATE.Equals(state) || x.ZIP.Equals(zip)
             select x;
</code>```

But this one does?

```<code>var result = from x in CUSTOMERs
             where x.STATE.Equals("MA") || x.ZIP.Equals("12345")
             select x;
</code>```

答:
Following is my understanding, you are using a Oracle data connector in the LinqPad, which allows you to Query a Customers Table, now since you are running an IQueryable<T> Linq Query, which unlike Linq to Objects, execute at the remote data source and takes an Expression tree in the form Expression<Func<T,bool>. It is not able to bind the values when supply a variable instead of actual hard coded value. Issue with binding values is purely due to the way it expects and parse the Expression tree internally.

To verify my point, check the signature of CUSTOMERs.Where in the Fluent syntax and it would be taking an expression tree instead of Func<T,bool> required by the Linq2Objects

ContentLicense: CC BY-SA 3.0

Title: LINQ .equals() and string variables

Body:
Not sure why this query returns no results (note that CUSTOMERs is from an Oracle database):

string zip = "12345"
string state = "MA"

var result = from x in CUSTOMERs
             where x.STATE.Equals(state) || x.ZIP.Equals(zip)
             select x;

But this one does?

var result = from x in CUSTOMERs
             where x.STATE.Equals("MA") || x.ZIP.Equals("12345")
             select x;


问:
Why was function overloading added to C++?
I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?

What went across the mind of the language designer at that time?

答:
Try to come up with a comfortable way to construct objects if it weren't for function overloading.

```<code>std::string foo = "bar";
std::vector< std::string > myStringVector;
myStringVector.push_back( std::string() );
myStringVector.push_back( std::string( "hello" ) );
myStringVector.push_back( std::string( foo ) );
</code>```

A nonsense example, of course, but it illustrates the point.

Another point would be template programming. You could not come up with generic templates if you had to have a different function name for each parameter type.

ContentLicense: CC BY-SA 2.5

Body:
Try to come up with a comfortable way to construct objects if it weren't for function overloading.

std::string foo = "bar";
std::vector< std::string > myStringVector;
myStringVector.push_back( std::string() );
myStringVector.push_back( std::string( "hello" ) );
myStringVector.push_back( std::string( foo ) );

A nonsense example, of course, but it illustrates the point.

Another point would be template programming. You could not come up with generic templates if you had to have a different function name for each parameter type.


问:
javascript countdown echoing wrong time
i want this my javascript code to to be able to be reading 3 hours countdown and also redirect to a new page after the countdown is complete

```<code><script type="text/javascript">
// properties
var count = 0;
var counter = null;

window.onload = function() {
initCounter();
};

function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will  run it every 1 second
}

function setLocalStorage(key, val) {
if (window.localStorage) {
  window.localStorage.setItem(key, val);
}

return val;
}

function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}

function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
  clearInterval(counter);
  return;
}

var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;

document.getElementById("timer").innerHTML = hours +  "hours "  + minutes  +  "minutes and "   + seconds +  "  seconds left to complete this   transaction"; // watch for spelling
 }
</script>
<div id="timer"></div>
</code>```

please help me make it better by making it been able to countdown to three hour and also redirect to another page after the countdown is complete

答:
You didn't properly set total time. You set it to 16 minutes instead of 3 hours. Here is the working code (try it on JSFiddle):

```<code>var time = 60 * 60 * 3;
var div = document.getElementById("timer");
var t = Date.now();

var loop = function(){
  var dt = (Date.now() - t) * 1e-3;

  if(dt > time){
    doWhateverHere();
  }else{
    dt = time - dt;
    div.innerHTML = `Hours: ${dt / 3600 | 0}, Minutes: ${dt / 60 % 60 | 0}, Seconds: ${dt % 60 | 0}`;
  }

  requestAnimationFrame(loop);
};

loop();
</code>```

Also, do not use setInterval and setTimeout for precise timing. These functions are volatile. Use Date.now() instead.

Title: javascript countdown echoing wrong time

Body:
i want this my javascript code to to be able to be reading 3 hours countdown and also redirect to a new page after the countdown is complete

please help me make it better by making it been able to countdown to three hour and also redirect to another page after the countdown is complete

Body:
You didn't properly set total time. You set it to 16 minutes instead of 3 hours. Here is the working code (try it on JSFiddle):

var time = 60 * 60 * 3;
var div = document.getElementById("timer");
var t = Date.now();

var loop = function(){
  var dt = (Date.now() - t) * 1e-3;

  if(dt > time){
    doWhateverHere();
  }else{
    dt = time - dt;
    div.innerHTML = `Hours: ${dt / 3600 | 0}, Minutes: ${dt / 60 % 60 | 0}, Seconds: ${dt % 60 | 0}`;
  }

  requestAnimationFrame(loop);
};

loop();

Also, do not use setInterval and setTimeout for precise timing. These functions are volatile. Use Date.now() instead.


答:
It seems that there is a bug with the Date/Time format of the first column (Timestamp). If you convert the first column to character, it should work.
So, you may change your first column to

```<code>q1[,1] <- as.character(q1[,1])
</code>```

and try again...

Title: Error in printing data.frame in excel using XLSX package in R

Body:
The dataframe is visible with out any error. But when the same is printed using write.xlsx fucnction of the package XLSX, it gives the error.

Error in .jcall(cell, "V", "setCellValue", value) :
  method setCellValue with signature ([D)V not found.

The dput of the data.frame looks like:

Timestamp         qs          pqs        logqs         es         p_imp      dep    r_dep       agg_rtn
               (time)      (dbl)        (dbl)        (dbl)      (dbl)         (dbl)    (dbl)    (dbl)         (dbl)
1 2015-05-04 09:29:59 0.05788732 0.0007478696 0.0007478545 0.09633803 -0.0446830986 3533.518 274079.9 -0.0006432937
2 2015-05-04 10:00:00 0.04948394 0.0006362707 0.0006362707 0.07586009  0.0088016055 2416.431 187953.1  0.0000000000
3 2015-05-04 10:30:00 0.05554795 0.0007142532 0.0007142532 0.06417808 -0.0002739726 3245.574 252422.0  0.0000000000
4 2015-05-04 10:59:59 0.04863014 0.0006194244 0.0006194244 0.08434442  0.0024951076 3563.401 279503.9  0.0000000000
5 2015-05-04 11:30:00 0.05761986 0.0007319037 0.0007319037 0.07851027  0.0154965753 2010.943 158429.1 -0.0006339144
6 2015-05-04 12:00:00 0.04957627 0.0006285051 0.0006285051 0.07025424  0.0070762712 1819.908 143546.0  0.0000000000
Variables not shown: vol_30_sum (dbl), vol_30_mean (dbl), p_return_sqr (dbl), p_return_mean (dbl), Lim_or_out (dbl),
  closing_price (dbl), closing_vol (dbl)

Kindly help in resolving this error.

Body:
It seems that there is a bug with the Date/Time format of the first column (Timestamp). If you convert the first column to character, it should work.
So, you may change your first column to

q1[,1] <- as.character(q1[,1])

and try again...


问:
Pic16f818 - set trisa regiter as digital inputs for those bits: RB5 RB6 RB7
I am trying to set RB0 - 7 as digital inputs on my PIC16F818 microcontroller. In order to do that I used the following config:

```<code>void config() {
    //cmcon = 0x07;     // Sets all IO pins to digital
    trisa = 0xFF;       // Set porta as inputs
    trisb = 0x00;       // Set portb as outputs
    adcon1 = 0x07;  // For PIC16F84A comment the line above and uncomment this statement
    portb = 0x00;       // Reset value of portb (portb = 0)
    _CONFIG  & _CP_OFF & _LVP_OFF & _CPD_OFF & _DEBUG_OFF & _MCLR_OFF & _INTRC_IO & _WRT_ENABLE_OFF  & _PWRTE_OFF;

}
</code>```

I test this setting by mapping my porta (8 switch block) to portb (8 bit led block), switches 0 - 4 are working correctly, but switches 5-7 are not responding, however bits are set internally by some other PIC functions and output: (b5)0 (b6)0 (b7)1.

答:
This is a common issue people have when using Microchip controllers. There are many places on stackexchange where the mantra is: "write to LATx, read from PORTx"

PORTx gives you the current state of the port.

LATX is the output latch.

During initialization, you should set up the values of TRISx, ANSELx (analogue selection), CNPUx/CNPDx (pull up/down) for every port.

Body:
I am trying to set RB0 - 7 as digital inputs on my PIC16F818 microcontroller. In order to do that I used the following config:

void config() {
    //cmcon = 0x07;     // Sets all IO pins to digital
    trisa = 0xFF;       // Set porta as inputs
    trisb = 0x00;       // Set portb as outputs
    adcon1 = 0x07;  // For PIC16F84A comment the line above and uncomment this statement
    portb = 0x00;       // Reset value of portb (portb = 0)
    _CONFIG  & _CP_OFF & _LVP_OFF & _CPD_OFF & _DEBUG_OFF & _MCLR_OFF & _INTRC_IO & _WRT_ENABLE_OFF  & _PWRTE_OFF;

}

I test this setting by mapping my porta (8 switch block) to portb (8 bit led block), switches 0 - 4 are working correctly, but switches 5-7 are not responding, however bits are set internally by some other PIC functions and output: (b5)0 (b6)0 (b7)1.


问:
I'm trying to understand this c# code how would it work in python
I'm trying to understand this c# code:

```<code>sum += (myName[i]) * Math.Pow(i+5,i+1);
</code>```

how would this work in python?

答:
You can also use the math module:

```<code>import math   # This will import math module

sum = 0
myName = [1,2,3,4,5]

i = 3 # array index
sum += (myName[i]) * math.pow(i+5,i+1)

print sum
</code>```

Working fiddle: http://www.codeskulptor.org/#user42_xxRNH8VUra_0.py

Body:
I'm trying to understand this c# code:

sum += (myName[i]) * Math.Pow(i+5,i+1);

how would this work in python?

Body:
You can also use the math module:

import math   # This will import math module

sum = 0
myName = [1,2,3,4,5]

i = 3 # array index
sum += (myName[i]) * math.pow(i+5,i+1)

print sum

Working fiddle: http://www.codeskulptor.org/#user42_xxRNH8VUra_0.py


问:
Android OrmLite Foreign Key / Foreign Collection
On my recent project on Android Im using OrmLite to model one-to-many relations as well as simple one-to-one relations.
Ive noticed that with one-to-many relations,  the child holds the foreign key reference to the parent in the database. Still when loading the parent object OrmLite knows what to do and loads the collection of child elements which is, of course, the desired behavior.

However, with simple one-to-one relationships, the parent object seems to be required holding the foreign key column in order to achieve the same behavior.

So the actual question: Is it possible to have OrmLite loading the child objects in one-to-one relations when the foreign key is only set in the child, as it is the standard behavior with one-to-many relations?

Here is some example code:

```<code>@DatabaseTable
public class Parent
{

@DatabaseField(foreign = true)
private Child1 child1;

@ForeignCollectionField
private Collection<Child2> children2;

}
</code>```

So in child 1 and 2 I need to have the reference to the Parent like this:

```<code> public class Child1 / Child2
{

    @DatabaseField(foreign = true)
    private Parent parent;
}
</code>```

So when saving a child2 I simply set

```<code>child2.setParent(parent);
child2Dao.create(child2)
</code>```

But in order to arrive at the same behavior when querying the parent including the child1 and child2 I would have to save the relationship the other way around:

```<code>parent.setChild1(child1)
parentDao.create(parent)
</code>```

This is very inconvenient as I want either child1/child2 both holding the foreign key of the parent or the other way around. But a mixture seems somewhat ugly!

Any ideas how to achieve that?

Ive searched for answers to that question here but couldnt find one. In case it is a duplicate, Im sorry!

Thank you very much!

Edit:

To be more precisely:
Is it possible to set the Foreign Key in my child1 table and still be able to obtain child1 when querying for the Parent. ORMLite does it automagically for the foreign collection of child2. I want the same behavior for child1.
But when I set

```<code>child1.setParent(parent);
child1Dao.create(child1);
</code>```

and then make a query

```<code>Parent parent = parentDao.queryForId(1)
</code>```

only child2 is obtained since the Parent Table does not have a reference (foreign key) to the child1. Only child1 has a reference to the parent.

So: I want either have OrmLite automatically update the parent foreign key column or tell Ormlite to still obtain child1 even though no foreign key is set in the parent (as this is exactly the case with the collection of child2).
Is this somehow possible? Or not?

I hope this is not too confusing :) Im totally aware that it would be simpler to just set the foreign key in the parent. But I really dislike that approach as I will end up with some children having a foreign key of the parent and some that do not.

Thank you very much

答:
According to ORMLite documentation, the DatabaseField is, by default, with canBeNull = true. So, it is not necessary to set the Parent when creating a Child1. To obtain the Childs in the Parent and vice-versa, you can set foreignAutoRefresh = true.

If you want to leave the foreign key column in only one table, maybe you can achieve that by setting maxForeignAutoRefreshLevel = 1.

Body:
On my recent project on Android Im using OrmLite to model one-to-many relations as well as simple one-to-one relations.
Ive noticed that with one-to-many relations,  the child holds the foreign key reference to the parent in the database. Still when loading the parent object OrmLite knows what to do and loads the collection of child elements which is, of course, the desired behavior.

However, with simple one-to-one relationships, the parent object seems to be required holding the foreign key column in order to achieve the same behavior.

So the actual question: Is it possible to have OrmLite loading the child objects in one-to-one relations when the foreign key is only set in the child, as it is the standard behavior with one-to-many relations?

Here is some example code:

@DatabaseTable
public class Parent
{

@DatabaseField(foreign = true)
private Child1 child1;

@ForeignCollectionField
private Collection<Child2> children2;

}

So in child 1 and 2 I need to have the reference to the Parent like this:

 public class Child1 / Child2
{

    @DatabaseField(foreign = true)
    private Parent parent;
}

So when saving a child2 I simply set

child2.setParent(parent);
child2Dao.create(child2)

But in order to arrive at the same behavior when querying the parent including the child1 and child2 I would have to save the relationship the other way around:

parent.setChild1(child1)
parentDao.create(parent)

This is very inconvenient as I want either child1/child2 both holding the foreign key of the parent or the other way around. But a mixture seems somewhat ugly!

Any ideas how to achieve that?

Ive searched for answers to that question here but couldnt find one. In case it is a duplicate, Im sorry!

Thank you very much!

Edit:

To be more precisely:
Is it possible to set the Foreign Key in my child1 table and still be able to obtain child1 when querying for the Parent. ORMLite does it automagically for the foreign collection of child2. I want the same behavior for child1.
But when I set

child1.setParent(parent);
child1Dao.create(child1);

and then make a query

Parent parent = parentDao.queryForId(1)

only child2 is obtained since the Parent Table does not have a reference (foreign key) to the child1. Only child1 has a reference to the parent.

So: I want either have OrmLite automatically update the parent foreign key column or tell Ormlite to still obtain child1 even though no foreign key is set in the parent (as this is exactly the case with the collection of child2).
Is this somehow possible? Or not?

I hope this is not too confusing :) Im totally aware that it would be simpler to just set the foreign key in the parent. But I really dislike that approach as I will end up with some children having a foreign key of the parent and some that do not.

Thank you very much


问:
scroll view issue Android
I am adding layouts programmatically.I have added a scrollview as a parent layout and a combination of horizontal and vertical linearlayouts when I add a list view in the scrollview I am getting an issue that my UI is not taking full screen although the listview height is set to fill parent .There is a blank space added at the bottom and the height of the listview gets very small .I haven't find the reason why it's happening, is it a bug in android for scrollview ?</p>

答: fill_parent won't work.  Try setting android:fillViewport="true".

Title: scroll view issue Android


问:
Function not writing to txt file
I have a program that uses various structs and functions to read information into a struct from an output file, do something with it, and write to an output file if a condition is met. Everything is working properly, except the function that's supposed to write to the output file isn't doing so. I'm required to have a function that writes to the output file, so doing it in main isn't an option.

edit: The function to write to the output file is at the very bottom.
another edit: I only need information written to the output file if the subscription is expired (so if customer.custInfo.monthsLeft==0).

Here's my code:

```<code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <climits>

using namespace std;

struct subscriberName{
    string firstName;
    string lastName;
    int custId;
};

struct address{
    string street;
    string city;
    string state;
    int zip_code;
};

struct date{
    string month;
    int day;
    int year;
};

struct renewal_information{
    int monthsLeft;
    date lastNoticeSent;
};

struct subscriber{
    subscriberName custName;
    address custAddress;
    renewal_information custInfo;
};

void openInFile(ifstream&);
void openOutFile(ofstream&);
subscriber recordIn(ifstream&, subscriber&, address&, date&, int&,     int&);
void expired(subscriber&, ofstream&);

int main() {
    ifstream inFile;
    ofstream outFile;
    openInFile(inFile);
    openOutFile(outFile);
    subscriber customer;
    address custAddress;
    date custDate;
    int currentLine=0, numProcessed=0, numExpired=0;

    while (!inFile.eof()){
        recordIn(inFile, customer, custAddress, custDate, currentLine,     numProcessed);

        if (customer.custInfo.monthsLeft==0) {
            expired(customer, outFile);
            numExpired++;
        }
    }
    cout<<endl<<string(47, '-')<<endl<<"Number of subscribers     processed: "<<numProcessed
        <<endl<<"The number of expired subscriptions is: "    <<numExpired<<endl
        <<string(47, '-')<<endl<<endl;

    inFile.close();
    outFile.close();
    return 0;
}

void openInFile(ifstream& inFile){
    string inFileName;
    do{
        cout<<"Enter input file name: ";
        cin>>inFileName;
        cout<<inFileName<<endl;
        inFile.open(inFileName.c_str());
    }
    while (!inFile);
    if (inFile.fail()){
        cout<<"input file failed to open\n";
        inFile.clear();
    } else
        cout<<inFileName<<" opened successfully\n";
}

void openOutFile(ofstream&){
    string outFileName;
    ofstream outFile;
    do{
        cout<<"Enter output file name: ";
        cin>>outFileName;
        cout<<outFileName<<endl;
        outFile.open(outFileName.c_str());
    }
    while (!outFile);
    if (outFile.fail()){
        cout<<"output file failed to open\n";
        outFile.clear();
    } else
        cout<<outFileName<<" opened successfully\n";
}

subscriber recordIn(ifstream& inFile, subscriber& customer, address&     custAddress, date& custDate, int& currentLine, int& numProcessed){
    inFile.ignore(currentLine, '\n');

    getline(inFile, customer.custName.firstName, '\n');

    if (inFile.eof()){
        return customer;
    }
    else {
        getline(inFile, customer.custName.lastName, '\n');
        inFile >> customer.custName.custId;
        cout << "==> Processing Customer ID: " <<     customer.custName.custId << endl;
        numProcessed++;

        inFile.ignore(INT_MAX, '\n');
        getline(inFile, customer.custAddress.street, '\n');
        getline(inFile, customer.custAddress.city, '\n');
        getline(inFile, customer.custAddress.state, '\n');
        inFile >> customer.custAddress.zip_code;
        inFile >> customer.custInfo.monthsLeft;
        inFile >> customer.custInfo.lastNoticeSent.month;
        inFile >> customer.custInfo.lastNoticeSent.day;
        inFile >> customer.custInfo.lastNoticeSent.year;

        currentLine = currentLine + 11;
    }
    return customer;
}

void expired(subscriber& customer, ofstream& outFile){
    while (customer.custInfo.monthsLeft==0) {
        outFile << customer.custName.firstName;
        outFile << customer.custName.lastName;
        outFile << customer.custName.custId;
        outFile << customer.custAddress.street;
        outFile << customer.custAddress.city;
        outFile << customer.custAddress.state;
        outFile << customer.custAddress.zip_code;
        outFile << customer.custInfo.monthsLeft;
        outFile << customer.custInfo.lastNoticeSent.month;
        outFile << customer.custInfo.lastNoticeSent.day;
        outFile << customer.custInfo.lastNoticeSent.year;
        customer.custInfo.monthsLeft=-1;
        outFile.flush();
    }
}
</code>```

答:
In this code

```<code>void openOutFile(ofstream&){
    string outFileName;
    ofstream outFile;
    ...
}
</code>```

outFile should be the parameter of openOutFile and not a local variable, otherwise the call to openOutFile(outFile); does not return with an open stream outFile.

Title: Function not writing to txt file

Body:
I have a program that uses various structs and functions to read information into a struct from an output file, do something with it, and write to an output file if a condition is met. Everything is working properly, except the function that's supposed to write to the output file isn't doing so. I'm required to have a function that writes to the output file, so doing it in main isn't an option.

edit: The function to write to the output file is at the very bottom.
another edit: I only need information written to the output file if the subscription is expired (so if customer.custInfo.monthsLeft==0).

Here's my code:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <climits>

using namespace std;

struct subscriberName{
    string firstName;
    string lastName;
    int custId;
};

struct address{
    string street;
    string city;
    string state;
    int zip_code;
};

struct date{
    string month;
    int day;
    int year;
};

struct renewal_information{
    int monthsLeft;
    date lastNoticeSent;
};

struct subscriber{
    subscriberName custName;
    address custAddress;
    renewal_information custInfo;
};

void openInFile(ifstream&);
void openOutFile(ofstream&);
subscriber recordIn(ifstream&, subscriber&, address&, date&, int&,     int&);
void expired(subscriber&, ofstream&);

int main() {
    ifstream inFile;
    ofstream outFile;
    openInFile(inFile);
    openOutFile(outFile);
    subscriber customer;
    address custAddress;
    date custDate;
    int currentLine=0, numProcessed=0, numExpired=0;

    while (!inFile.eof()){
        recordIn(inFile, customer, custAddress, custDate, currentLine,     numProcessed);

        if (customer.custInfo.monthsLeft==0) {
            expired(customer, outFile);
            numExpired++;
        }
    }
    cout<<endl<<string(47, '-')<<endl<<"Number of subscribers     processed: "<<numProcessed
        <<endl<<"The number of expired subscriptions is: "    <<numExpired<<endl
        <<string(47, '-')<<endl<<endl;

    inFile.close();
    outFile.close();
    return 0;
}

void openInFile(ifstream& inFile){
    string inFileName;
    do{
        cout<<"Enter input file name: ";
        cin>>inFileName;
        cout<<inFileName<<endl;
        inFile.open(inFileName.c_str());
    }
    while (!inFile);
    if (inFile.fail()){
        cout<<"input file failed to open\n";
        inFile.clear();
    } else
        cout<<inFileName<<" opened successfully\n";
}

void openOutFile(ofstream&){
    string outFileName;
    ofstream outFile;
    do{
        cout<<"Enter output file name: ";
        cin>>outFileName;
        cout<<outFileName<<endl;
        outFile.open(outFileName.c_str());
    }
    while (!outFile);
    if (outFile.fail()){
        cout<<"output file failed to open\n";
        outFile.clear();
    } else
        cout<<outFileName<<" opened successfully\n";
}

subscriber recordIn(ifstream& inFile, subscriber& customer, address&     custAddress, date& custDate, int& currentLine, int& numProcessed){
    inFile.ignore(currentLine, '\n');

    getline(inFile, customer.custName.firstName, '\n');

    if (inFile.eof()){
        return customer;
    }
    else {
        getline(inFile, customer.custName.lastName, '\n');
        inFile >> customer.custName.custId;
        cout << "==> Processing Customer ID: " <<     customer.custName.custId << endl;
        numProcessed++;

        inFile.ignore(INT_MAX, '\n');
        getline(inFile, customer.custAddress.street, '\n');
        getline(inFile, customer.custAddress.city, '\n');
        getline(inFile, customer.custAddress.state, '\n');
        inFile >> customer.custAddress.zip_code;
        inFile >> customer.custInfo.monthsLeft;
        inFile >> customer.custInfo.lastNoticeSent.month;
        inFile >> customer.custInfo.lastNoticeSent.day;
        inFile >> customer.custInfo.lastNoticeSent.year;

        currentLine = currentLine + 11;
    }
    return customer;
}

void expired(subscriber& customer, ofstream& outFile){
    while (customer.custInfo.monthsLeft==0) {
        outFile << customer.custName.firstName;
        outFile << customer.custName.lastName;
        outFile << customer.custName.custId;
        outFile << customer.custAddress.street;
        outFile << customer.custAddress.city;
        outFile << customer.custAddress.state;
        outFile << customer.custAddress.zip_code;
        outFile << customer.custInfo.monthsLeft;
        outFile << customer.custInfo.lastNoticeSent.month;
        outFile << customer.custInfo.lastNoticeSent.day;
        outFile << customer.custInfo.lastNoticeSent.year;
        customer.custInfo.monthsLeft=-1;
        outFile.flush();
    }
}

Body:
In this code

void openOutFile(ofstream&){
    string outFileName;
    ofstream outFile;
    ...
}

outFile should be the parameter of openOutFile and not a local variable, otherwise the call to openOutFile(outFile); does not return with an open stream outFile.


答:
The code below works</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication49
{

    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(FeatureCollection));
            StreamReader reader = new StreamReader(FILENAME);
            FeatureCollection collection =  (FeatureCollection)serializer.Deserialize(reader);

        }
    }
    [XmlRoot(ElementName = "FeatureCollection", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
    public class FeatureCollection
    {
        [XmlElement(ElementName = "metadata", Namespace = "http://namespaces.os.uk/product/1.0")]
        public Metadata metadata  { get; set;}
        [XmlElement(ElementName = "featureMember", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
        public FeatureMember featureMember { get; set; }
    }
    [XmlRoot(ElementName = "metadata", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
    public class Metadata
    {
    }
    [XmlRoot(ElementName = "featureMember", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
    public class FeatureMember
    {
        [XmlElement(ElementName = "TurnRestriction", Namespace = "http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0", IsNullable = false)]
        public TurnRestriction turnRestriction { get; set; }
    }
    [XmlRoot(ElementName = "TurnRestriction", Namespace = "http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0", IsNullable = false)]
    public class TurnRestriction
    {
        [XmlElement(ElementName = "identifier", Namespace = "http://www.opengis.net/gml/3.2", IsNullable = false)]
        public Identifier identifier { get; set; }

        [XmlElement(ElementName = "networkRef", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
        public NetworkRef[] networkRef { get; set; }
    }
    [XmlRoot(ElementName = "identifier", Namespace = "http://www.opengis.net/gml/3.2", IsNullable = false)]
    public class Identifier
    {
    }
    [XmlRoot(ElementName = "networkRef", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0", IsNullable = false)]
    public class NetworkRef
    {
        [XmlElement("LinkReference", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
        public LinkReference linkReference { get; set; }
    }
   [XmlRoot(ElementName = "LinkReference", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0", IsNullable = false)]
    public class LinkReference
    {
        [XmlElement("element", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
        public Element element { get; set; }
    }
    [XmlRoot(ElementName = "element", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0", IsNullable = false)]
    public class Element
    {
    }

}
</code>```

Title: Deserialize just read the first item

Body:
I have the following xml elemnt:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<os:FeatureCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:hwtn="http://namespaces.os.uk/mastermap/highwaysWaterTransportNetwork/1.0" xmlns:net="http://inspire.ec.europa.eu/schemas/net/4.0" xmlns:base="http://inspire.ec.europa.eu/schemas/base/3.3" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gss="http://www.isotc211.org/2005/gss" xmlns:gts="http://www.isotc211.org/2005/gts" xmlns:gsr="http://www.isotc211.org/2005/gsr" xmlns:gn="http://inspire.ec.europa.eu/schemas/gn/4.0" xmlns:tn-w="http://inspire.ec.europa.eu/schemas/tn-w/4.0" xmlns:tn="http://inspire.ec.europa.eu/schemas/tn/4.0" xmlns:gmlxbt="http://www.opengis.net/gml/3.3/xbt" xmlns:os="http://namespaces.os.uk/product/1.0" xmlns:highway="http://namespaces.os.uk/mastermap/highwayNetwork/2.0" xmlns:base2="http://inspire.ec.europa.eu/schemas/base2/2.0" xmlns:ad="http://inspire.ec.europa.eu/schemas/ad/4.0" xmlns:au="http://inspire.ec.europa.eu/schemas/au/4.0" xmlns:bu-base="http://inspire.ec.europa.eu/schemas/bu-base/4.0" xmlns:sc="http://www.interactive-instruments.de/ShapeChange/AppInfo" xmlns:cp="http://inspire.ec.europa.eu/schemas/cp/4.0" xmlns:am="http://inspire.ec.europa.eu/schemas/am/4.0" xmlns:su-core="http://inspire.ec.europa.eu/schemas/su-core/4.0" xmlns:gmlexr="http://www.opengis.net/gml/3.3/exr" xmlns:tn-ro="http://inspire.ec.europa.eu/schemas/tn-ro/4.0" xmlns:network="http://namespaces.os.uk/mastermap/generalNetwork/2.0" xmlns:ram="http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0" xsi:schemaLocation="http://namespaces.os.uk/mastermap/highwaysWaterTransportNetwork/1.0 https://www.ordnancesurvey.co.uk/xml/schema/highwaysnetwork/1.0/HighwaysWaterTransportNetwork.xsd http://namespaces.os.uk/mastermap/highwayNetwork/2.0 https://www.ordnancesurvey.co.uk/xml/schema/highwaysnetwork/2.0/LinearHighwayNetwork.xsd http://namespaces.os.uk/product/1.0 https://www.ordnancesurvey.co.uk/xml/schema/product/1.0/OSProduct.xsd http://namespaces.os.uk/mastermap/generalNetwork/2.0 https://www.ordnancesurvey.co.uk/xml/schema/network/2.0/generalNetwork.xsd http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0 https://www.ordnancesurvey.co.uk/xml/schema/highwaysnetwork/2.0/RoutingAndAssetManagement.xsd" gml:id="OS_HIGHWAYS">
<os:metadata xlink:href="https://www.ordnancesurvey.co.uk/xml/products/Highways.xml"/>
  <os:featureMember>
    <ram:TurnRestriction gml:id="osgb4000000031265199">
      <gml:identifier codeSpace="http://inspire.jrc.ec.europa.eu/ids">http://data.os.uk/id/4000000031265199</gml:identifier>
      <net:networkRef>
        <net:LinkReference>
          <net:element xlink:href="#osgb4000000030462832"/>
          <net:applicableDirection xlink:title="in opposite direction" xlink:href="http://inspire.ec.europa.eu/codelist/LinkDirectionValue/inOppositeDirection"/>
        </net:LinkReference>
      </net:networkRef>
      <net:networkRef>
        <net:LinkReference>
          <net:element xlink:href="#osgb4000000030462831"/>
          <net:applicableDirection xlink:title="in opposite direction" xlink:href="http://inspire.ec.europa.eu/codelist/LinkDirectionValue/inOppositeDirection"/>
        </net:LinkReference>
      </net:networkRef>
      <net:inspireId>
        <base:Identifier>
          <base:localId>4000000031265199</base:localId>
          <base:namespace>http://data.os.uk/</base:namespace>
        </base:Identifier>
      </net:inspireId>
      <net:beginLifespanVersion>2016-06-17T00:00:00.000</net:beginLifespanVersion>
      <tn:validFrom nilReason="unknown" xsi:nil="true"/>
      <ram:restriction codeSpace="http://www.os.uk/xml/codelists/highways/TurnRestrictionValue.xml">No Turn</ram:restriction>
      <ram:reasonForChange codeSpace="http://www.os.uk/xml/codelists/ChangeTypeValue.xml">New</ram:reasonForChange>
    </ram:TurnRestriction>
  </os:featureMember>
</os:FeatureCollection>

and C# class is

[XmlArray(Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
[XmlArrayItem("LinkReference", IsNullable = false)]
public networkRefLinkReference[] networkRef {get; set;}

which has been created by XSD /c.

But When I use XmlSerializer.Deserialize to transfer XML to object, it just loads one networkRef.

I have changed the first attribute to the following and it does not work too.

[XmlArray("networkRef", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]

================== Edited ====== Add new class structure based on  jdweng comment but still not getting result.

      [System.CodeDom.Compiler.GeneratedCode("xsd", "4.6.1055.0")]
[System.Serializable]
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(AnonymousType = true, Namespace = "http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0")]
[XmlRoot(Namespace = "http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0", IsNullable = false)]
public class TurnRestriction
{
    [XmlElement(Namespace = "http://www.opengis.net/gml/3.2", IsNullable = true)]
    public identifier identifier { get; set; }

    [XmlElement("networkRef", IsNullable = true)]
    public NetworkRef[] NetworkRefs { get; set; }

    [XmlElement(Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
    public inspireId inspireId { get; set; }

    [XmlElement("restriction", IsNullable = true)]
    public TurnRestrictionRestriction[] Restriction { get; set; }

    public string id { get; set; }
}

 [System.CodeDom.Compiler.GeneratedCode("xsd", "4.6.1055.0")]
    [System.Serializable]
    [System.Diagnostics.DebuggerStepThrough]
    [System.ComponentModel.DesignerCategory("code")]
    [XmlType(AnonymousType = true, Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
    [XmlRoot(Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0", IsNullable = false)]
    public class networkRef
    {
        [XmlElement("LinkReference")]
        public networkRefLinkReference LinkReference { get; set; }
    }

Body:
The code below works

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication49
{

    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(FeatureCollection));
            StreamReader reader = new StreamReader(FILENAME);
            FeatureCollection collection =  (FeatureCollection)serializer.Deserialize(reader);

        }
    }
    [XmlRoot(ElementName = "FeatureCollection", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
    public class FeatureCollection
    {
        [XmlElement(ElementName = "metadata", Namespace = "http://namespaces.os.uk/product/1.0")]
        public Metadata metadata  { get; set;}
        [XmlElement(ElementName = "featureMember", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
        public FeatureMember featureMember { get; set; }
    }
    [XmlRoot(ElementName = "metadata", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
    public class Metadata
    {
    }
    [XmlRoot(ElementName = "featureMember", Namespace = "http://namespaces.os.uk/product/1.0", IsNullable = false)]
    public class FeatureMember
    {
        [XmlElement(ElementName = "TurnRestriction", Namespace = "http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0", IsNullable = false)]
        public TurnRestriction turnRestriction { get; set; }
    }
    [XmlRoot(ElementName = "TurnRestriction", Namespace = "http://namespaces.os.uk/mastermap/routingAndAssetManagement/2.0", IsNullable = false)]
    public class TurnRestriction
    {
        [XmlElement(ElementName = "identifier", Namespace = "http://www.opengis.net/gml/3.2", IsNullable = false)]
        public Identifier identifier { get; set; }

        [XmlElement(ElementName = "networkRef", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
        public NetworkRef[] networkRef { get; set; }
    }
    [XmlRoot(ElementName = "identifier", Namespace = "http://www.opengis.net/gml/3.2", IsNullable = false)]
    public class Identifier
    {
    }
    [XmlRoot(ElementName = "networkRef", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0", IsNullable = false)]
    public class NetworkRef
    {
        [XmlElement("LinkReference", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
        public LinkReference linkReference { get; set; }
    }
   [XmlRoot(ElementName = "LinkReference", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0", IsNullable = false)]
    public class LinkReference
    {
        [XmlElement("element", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0")]
        public Element element { get; set; }
    }
    [XmlRoot(ElementName = "element", Namespace = "http://inspire.ec.europa.eu/schemas/net/4.0", IsNullable = false)]
    public class Element
    {
    }

}


问:
Can I give an intermediate string to fetch from mysql table which values has that string in middle?
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

```<code>Select *
from orders
where date = "%03%"
</code>```

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?

答:
In MySQL, "%" matches zero or more characters, while "_" matches exactly one character. Thus, you would want to match against "__03%" or "__03____".

Furthermore, you must use "LIKE" instead of "=" in order to handle wildcards (and use a backslash to escape any literal instances of said characters).

See https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html for more information

Body:
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

Select *
from orders
where date = "%03%"

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?


问:
How to call ListView adapter's getItem(i) from Activity
I have a ListView adapter:

```<code>public class CartList extends BaseAdapter {
    // ...
    @Override
    public long getItemId(int i) { return i; }
    // ...

}
</code>```

And I have this activity:

```<code>public class ListActivity extends AppCompatActivity {
    ListView lv_list;
    static ArrayList<CartEntity> lista1 = new ArrayList<CartEntity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // my_code;
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final int pos = position;
                CartEntity item = CartList.getItem(pos);
            }
        });
    }
</code>```

That shows this error:

Non-static method 'getItem(int)' cannot be referenced from a static
  context

How Can i call the method to get selected item?
Without 'getItem' line works fine, but i need the object.

答:
You have not created a CartList, you are trying to use the method without an actual CartList object created, so the list will be empty.  You need to instantiate it and assign a CartList object to a variable somewhere in your class.

For Example:

```<code>public class ListActivity extends AppCompatActivity {
    private CartList mCartList = new CartList();
</code>```

The problem is, mCartList may still be empty.  You need to be sure it has data.  I would also learn what access modifiers in Java and Object Oriented Programming do, such as Public, Private, Protected, Static, etc.

Body:
I have a ListView adapter:

public class CartList extends BaseAdapter {
    // ...
    @Override
    public long getItemId(int i) { return i; }
    // ...

}

And I have this activity:

public class ListActivity extends AppCompatActivity {
    ListView lv_list;
    static ArrayList<CartEntity> lista1 = new ArrayList<CartEntity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // my_code;
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final int pos = position;
                CartEntity item = CartList.getItem(pos);
            }
        });
    }

That shows this error:

Non-static method 'getItem(int)' cannot be referenced from a static
  context

How Can i call the method to get selected item?
Without 'getItem' line works fine, but i need the object.

Body:
You have not created a CartList, you are trying to use the method without an actual CartList object created, so the list will be empty.  You need to instantiate it and assign a CartList object to a variable somewhere in your class.

For Example:

public class ListActivity extends AppCompatActivity {
    private CartList mCartList = new CartList();

The problem is, mCartList may still be empty.  You need to be sure it has data.  I would also learn what access modifiers in Java and Object Oriented Programming do, such as Public, Private, Protected, Static, etc.


问:
How to send Firebase email confirmation on signup?
So, I have enabled email/password in the dev console and everything is working fine. Except that I should be getting a confirmation email to the email I inputted, but I'm not getting it. I thought it does it automatically, but apparently it doesn't.

Method for signup:

```<code>public void signUp(View v) {
    String email = emailET.getText().toString();
    String password = passwordET.getText().toString();
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d("AD", "createUserWithEmail: " + task.isSuccessful() + task.getException());
                    if (!task.isSuccessful()) {
                        createDialogSignUpError(
                                getApplicationContext().getResources().getString(R.string.signUpFailedET),
                                getApplicationContext().getResources().getString(R.string.signUpFailedEM),
                                getApplicationContext().getResources().getString(android.R.string.ok));
                        Toast.makeText(SignUp.this, task.getException().toString(), Toast.LENGTH_LONG).show();
                    } else if (task.isSuccessful()) {
                        Toast.makeText(SignUp.this, "Registration Successful.", Toast.LENGTH_SHORT).show();
                    }
                }
            });

}
</code>```

It should be sending, but sadly it's not. I've read somewhere on SO that you need to add a method or something to send the email, and it's missing in the docs, but that wasn't Java.

Edit

According to here, it is only supported in iOS and web. Which is pretty surprising, since after all, android IS Google, and Google is Firebase. So is it possible even with creating a custom sent email?

Edit 2: To be more clear, does Android have an Email sender like C#. That would be the best solution if there isn't an API for this.

答:
Now according to the updated firebase documentation

Here is how to send a verification mail to the user that in your case is after creating the account and letting the user to log-in then send him/her a notification that he have to verify the account and then the next login is blocked until he/she didn't verify (I think this is better than making the user is forced to open his email first)

Send a user a verification email

You can send an address verification email to a user with the
  sendEmailVerification method. For example:

```<code>FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.sendEmailVerification()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Email sent.");
                }
            }
        });
</code>```

Body:
So, I have enabled email/password in the dev console and everything is working fine. Except that I should be getting a confirmation email to the email I inputted, but I'm not getting it. I thought it does it automatically, but apparently it doesn't.

Method for signup:

public void signUp(View v) {
    String email = emailET.getText().toString();
    String password = passwordET.getText().toString();
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d("AD", "createUserWithEmail: " + task.isSuccessful() + task.getException());
                    if (!task.isSuccessful()) {
                        createDialogSignUpError(
                                getApplicationContext().getResources().getString(R.string.signUpFailedET),
                                getApplicationContext().getResources().getString(R.string.signUpFailedEM),
                                getApplicationContext().getResources().getString(android.R.string.ok));
                        Toast.makeText(SignUp.this, task.getException().toString(), Toast.LENGTH_LONG).show();
                    } else if (task.isSuccessful()) {
                        Toast.makeText(SignUp.this, "Registration Successful.", Toast.LENGTH_SHORT).show();
                    }
                }
            });

}

It should be sending, but sadly it's not. I've read somewhere on SO that you need to add a method or something to send the email, and it's missing in the docs, but that wasn't Java.

Edit

According to here, it is only supported in iOS and web. Which is pretty surprising, since after all, android IS Google, and Google is Firebase. So is it possible even with creating a custom sent email?

Edit 2: To be more clear, does Android have an Email sender like C#. That would be the best solution if there isn't an API for this.

Body:
Now according to the updated firebase documentation

Here is how to send a verification mail to the user that in your case is after creating the account and letting the user to log-in then send him/her a notification that he have to verify the account and then the next login is blocked until he/she didn't verify (I think this is better than making the user is forced to open his email first)

Send a user a verification email

You can send an address verification email to a user with the
  sendEmailVerification method. For example:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.sendEmailVerification()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Email sent.");
                }
            }
        });


问:
iOS UIView - Different rounding radius for each of the 4 corners
How can I set a completely different rounding radius for each of the 4 corners of a UIView?

UIBezierPath allows me to set ONE value for one or more specific corners, but not a different value for each corner.

I think in theory it should be possible with a custom CGPath but I'm unable to implement it.

答:
Give this a try - you can paste it directly into a Playground page and see how it works:

```<code>import UIKit
import PlaygroundSupport

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

class VariableCornerRadiusView: UIView  {

    var upperLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var upperRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    func layoutMask() -> Void {

        var pt = CGPoint.zero

        let myBezier = UIBezierPath()

        pt.x = upperLeftCornerRadius
        pt.y = 0

        myBezier.move(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = 0

        myBezier.addLine(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = upperRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperRightCornerRadius, startAngle: CGFloat(270.degreesToRadians), endAngle: CGFloat(0.degreesToRadians), clockwise: true)

        pt.x = bounds.width
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addLine(to: pt)

        pt.x = bounds.width - lowerRightCornerRadius
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerRightCornerRadius, startAngle: CGFloat(0.degreesToRadians), endAngle: CGFloat(90.degreesToRadians), clockwise: true)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height

        myBezier.addLine(to: pt)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height - lowerLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerLeftCornerRadius, startAngle: CGFloat(90.degreesToRadians), endAngle: CGFloat(180.degreesToRadians), clockwise: true)

        pt.x = 0
        pt.y = upperLeftCornerRadius

        myBezier.addLine(to: pt)

        pt.x = upperLeftCornerRadius
        pt.y = upperLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperLeftCornerRadius, startAngle: CGFloat(180.degreesToRadians), endAngle: CGFloat(270.degreesToRadians), clockwise: true)

        myBezier.close()

        let maskForPath = CAShapeLayer()
        maskForPath.path = myBezier.cgPath
        layer.mask = maskForPath

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutMask()
    }

}

var testSize = CGSize(width: 200, height: 200)

// set up an orange view to hold it...
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 260))

containerView.backgroundColor = UIColor.orange

// create a VariableCornerRadiusView, just a little smaller than the container view
let TestView = VariableCornerRadiusView(frame: containerView.bounds.insetBy(dx: 20, dy: 20))

// set different radius for each corner
TestView.upperLeftCornerRadius = 20.0
TestView.upperRightCornerRadius = 40.0
TestView.lowerRightCornerRadius = 60.0
TestView.lowerLeftCornerRadius = 80.0

// give it a blue background
TestView.backgroundColor = UIColor.blue

// add it to the container
containerView.addSubview(TestView)

// show it
PlaygroundPage.current.liveView = containerView
</code>```

Result should look like this:

Edit another approach... Using a filled shape layer (instead of a mask) and a shadow:

```<code>import UIKit
import PlaygroundSupport

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

class VariableCornerRadiusShadowView: UIView  {

    var upperLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var upperRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var fillColor: UIColor = .white {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowColor: UIColor = .black {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowOffset: CGSize = CGSize(width: 0.0, height: 2.0) {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowOpacity: Float = 0.5 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowRadius: CGFloat = 8.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    let theShapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    func commonInit() -> Void {
        layer.addSublayer(theShapeLayer)
    }

    func layoutShape() -> Void {

        var pt = CGPoint.zero

        let myBezier = UIBezierPath()

        pt.x = upperLeftCornerRadius
        pt.y = 0

        myBezier.move(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = 0

        myBezier.addLine(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = upperRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperRightCornerRadius, startAngle: CGFloat(270.degreesToRadians), endAngle: CGFloat(0.degreesToRadians), clockwise: true)

        pt.x = bounds.width
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addLine(to: pt)

        pt.x = bounds.width - lowerRightCornerRadius
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerRightCornerRadius, startAngle: CGFloat(0.degreesToRadians), endAngle: CGFloat(90.degreesToRadians), clockwise: true)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height

        myBezier.addLine(to: pt)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height - lowerLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerLeftCornerRadius, startAngle: CGFloat(90.degreesToRadians), endAngle: CGFloat(180.degreesToRadians), clockwise: true)

        pt.x = 0
        pt.y = upperLeftCornerRadius

        myBezier.addLine(to: pt)

        pt.x = upperLeftCornerRadius
        pt.y = upperLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperLeftCornerRadius, startAngle: CGFloat(180.degreesToRadians), endAngle: CGFloat(270.degreesToRadians), clockwise: true)

        myBezier.close()

        theShapeLayer.path = myBezier.cgPath
        theShapeLayer.fillColor = fillColor.cgColor

        layer.shadowRadius = shadowRadius
        layer.shadowOffset = shadowOffset
        layer.shadowOpacity = shadowOpacity
        layer.shadowColor = shadowColor.cgColor

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutShape()
    }

}

var testSize = CGSize(width: 200, height: 200)

// set up an orange "container" view to hold it...
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 260))

containerView.backgroundColor = UIColor.white

let sampleView = VariableCornerRadiusShadowView(frame: containerView.bounds.insetBy(dx: 20, dy: 20))

// set different radius for each corner
sampleView.upperLeftCornerRadius = 20.0
sampleView.upperRightCornerRadius = 40.0
sampleView.lowerRightCornerRadius = 60.0
sampleView.lowerLeftCornerRadius = 80.0

// if we want to adjust defaults
//sampleView.fillColor = .green
//sampleView.shadowOffset = CGSize(width: 2, height: 4)
//sampleView.shadowRadius = 4  // not quite so "fuzzy"
//sampleView.shadowOpacity = 0.8

// add view to container
containerView.addSubview(sampleView)

// show it
PlaygroundPage.current.liveView = containerView
</code>```

Result with "default" properties:

Result with properties changed to:

```<code>.fillColor = .green
.shadowOffset = CGSize(width: 2, height: 4)
.shadowRadius = 4  // not quite so "fuzzy"
.shadowOpacity = 0.8
</code>```

Edit 2 -

This version is now @IBDesignable, with some properties renamed to show better in IB. Also added border width and color:

```<code>@IBDesignable
class VariableCornerRadiusShadowView: UIView  {

    @IBInspectable
    var radTopLeft:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var radTopRright:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var radBotLeft:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var radBotRright:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var fillColor: UIColor = .white {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var borderColor: UIColor = .clear {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var borderWidth: CGFloat = 0.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowColor: UIColor = .black {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowXOffset: CGFloat = 0.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowYOffset: CGFloat = 0.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowOpacity: Float = 0.5 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowRadius: CGFloat = 8.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    let theShapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    override func prepareForInterfaceBuilder() {
        commonInit()
    }

    func commonInit() -> Void {
        backgroundColor = .clear
        layer.addSublayer(theShapeLayer)
    }

    func layoutShape() -> Void {

        var pt = CGPoint.zero

        let myBezier = UIBezierPath()

        pt.x = radTopLeft
        pt.y = 0

        myBezier.move(to: pt)

        pt.x = bounds.width - radTopRright
        pt.y = 0

        myBezier.addLine(to: pt)

        pt.x = bounds.width - radTopRright
        pt.y = radTopRright

        myBezier.addArc(withCenter: pt, radius: radTopRright, startAngle: .pi * 1.5, endAngle: 0, clockwise: true)

        pt.x = bounds.width
        pt.y = bounds.height - radBotRright

        myBezier.addLine(to: pt)

        pt.x = bounds.width - radBotRright
        pt.y = bounds.height - radBotRright

        myBezier.addArc(withCenter: pt, radius: radBotRright, startAngle: 0, endAngle: .pi * 0.5, clockwise: true)

        pt.x = radBotLeft
        pt.y = bounds.height

        myBezier.addLine(to: pt)

        pt.x = radBotLeft
        pt.y = bounds.height - radBotLeft

        myBezier.addArc(withCenter: pt, radius: radBotLeft, startAngle: .pi * 0.5, endAngle: .pi, clockwise: true)

        pt.x = 0
        pt.y = radTopLeft

        myBezier.addLine(to: pt)

        pt.x = radTopLeft
        pt.y = radTopLeft

        myBezier.addArc(withCenter: pt, radius: radTopLeft, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)

        myBezier.close()

        theShapeLayer.path = myBezier.cgPath
        theShapeLayer.fillColor = fillColor.cgColor

        theShapeLayer.strokeColor = borderColor.cgColor
        theShapeLayer.lineWidth = borderWidth

        layer.shadowRadius = shadowRadius
        layer.shadowOffset = CGSize(width: shadowXOffset, height: shadowYOffset)
        layer.shadowOpacity = shadowOpacity
        layer.shadowColor = shadowColor.cgColor

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutShape()
    }

}
</code>```

Body:
Give this a try - you can paste it directly into a Playground page and see how it works:

import UIKit
import PlaygroundSupport

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

class VariableCornerRadiusView: UIView  {

    var upperLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var upperRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    func layoutMask() -> Void {

        var pt = CGPoint.zero

        let myBezier = UIBezierPath()

        pt.x = upperLeftCornerRadius
        pt.y = 0

        myBezier.move(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = 0

        myBezier.addLine(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = upperRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperRightCornerRadius, startAngle: CGFloat(270.degreesToRadians), endAngle: CGFloat(0.degreesToRadians), clockwise: true)

        pt.x = bounds.width
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addLine(to: pt)

        pt.x = bounds.width - lowerRightCornerRadius
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerRightCornerRadius, startAngle: CGFloat(0.degreesToRadians), endAngle: CGFloat(90.degreesToRadians), clockwise: true)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height

        myBezier.addLine(to: pt)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height - lowerLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerLeftCornerRadius, startAngle: CGFloat(90.degreesToRadians), endAngle: CGFloat(180.degreesToRadians), clockwise: true)

        pt.x = 0
        pt.y = upperLeftCornerRadius

        myBezier.addLine(to: pt)

        pt.x = upperLeftCornerRadius
        pt.y = upperLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperLeftCornerRadius, startAngle: CGFloat(180.degreesToRadians), endAngle: CGFloat(270.degreesToRadians), clockwise: true)

        myBezier.close()

        let maskForPath = CAShapeLayer()
        maskForPath.path = myBezier.cgPath
        layer.mask = maskForPath

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutMask()
    }

}

var testSize = CGSize(width: 200, height: 200)

// set up an orange view to hold it...
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 260))

containerView.backgroundColor = UIColor.orange

// create a VariableCornerRadiusView, just a little smaller than the container view
let TestView = VariableCornerRadiusView(frame: containerView.bounds.insetBy(dx: 20, dy: 20))

// set different radius for each corner
TestView.upperLeftCornerRadius = 20.0
TestView.upperRightCornerRadius = 40.0
TestView.lowerRightCornerRadius = 60.0
TestView.lowerLeftCornerRadius = 80.0

// give it a blue background
TestView.backgroundColor = UIColor.blue

// add it to the container
containerView.addSubview(TestView)

// show it
PlaygroundPage.current.liveView = containerView

Result should look like this:

Edit another approach... Using a filled shape layer (instead of a mask) and a shadow:

import UIKit
import PlaygroundSupport

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

class VariableCornerRadiusShadowView: UIView  {

    var upperLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var upperRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerLeftCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var lowerRightCornerRadius:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var fillColor: UIColor = .white {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowColor: UIColor = .black {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowOffset: CGSize = CGSize(width: 0.0, height: 2.0) {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowOpacity: Float = 0.5 {
        didSet {
            self.setNeedsLayout()
        }
    }

    var shadowRadius: CGFloat = 8.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    let theShapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    func commonInit() -> Void {
        layer.addSublayer(theShapeLayer)
    }

    func layoutShape() -> Void {

        var pt = CGPoint.zero

        let myBezier = UIBezierPath()

        pt.x = upperLeftCornerRadius
        pt.y = 0

        myBezier.move(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = 0

        myBezier.addLine(to: pt)

        pt.x = bounds.width - upperRightCornerRadius
        pt.y = upperRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperRightCornerRadius, startAngle: CGFloat(270.degreesToRadians), endAngle: CGFloat(0.degreesToRadians), clockwise: true)

        pt.x = bounds.width
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addLine(to: pt)

        pt.x = bounds.width - lowerRightCornerRadius
        pt.y = bounds.height - lowerRightCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerRightCornerRadius, startAngle: CGFloat(0.degreesToRadians), endAngle: CGFloat(90.degreesToRadians), clockwise: true)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height

        myBezier.addLine(to: pt)

        pt.x = lowerLeftCornerRadius
        pt.y = bounds.height - lowerLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: lowerLeftCornerRadius, startAngle: CGFloat(90.degreesToRadians), endAngle: CGFloat(180.degreesToRadians), clockwise: true)

        pt.x = 0
        pt.y = upperLeftCornerRadius

        myBezier.addLine(to: pt)

        pt.x = upperLeftCornerRadius
        pt.y = upperLeftCornerRadius

        myBezier.addArc(withCenter: pt, radius: upperLeftCornerRadius, startAngle: CGFloat(180.degreesToRadians), endAngle: CGFloat(270.degreesToRadians), clockwise: true)

        myBezier.close()

        theShapeLayer.path = myBezier.cgPath
        theShapeLayer.fillColor = fillColor.cgColor

        layer.shadowRadius = shadowRadius
        layer.shadowOffset = shadowOffset
        layer.shadowOpacity = shadowOpacity
        layer.shadowColor = shadowColor.cgColor

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutShape()
    }

}

var testSize = CGSize(width: 200, height: 200)

// set up an orange "container" view to hold it...
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 260))

containerView.backgroundColor = UIColor.white

let sampleView = VariableCornerRadiusShadowView(frame: containerView.bounds.insetBy(dx: 20, dy: 20))

// set different radius for each corner
sampleView.upperLeftCornerRadius = 20.0
sampleView.upperRightCornerRadius = 40.0
sampleView.lowerRightCornerRadius = 60.0
sampleView.lowerLeftCornerRadius = 80.0

// if we want to adjust defaults
//sampleView.fillColor = .green
//sampleView.shadowOffset = CGSize(width: 2, height: 4)
//sampleView.shadowRadius = 4  // not quite so "fuzzy"
//sampleView.shadowOpacity = 0.8

// add view to container
containerView.addSubview(sampleView)

// show it
PlaygroundPage.current.liveView = containerView

Result with "default" properties:

Result with properties changed to:

.fillColor = .green
.shadowOffset = CGSize(width: 2, height: 4)
.shadowRadius = 4  // not quite so "fuzzy"
.shadowOpacity = 0.8

Edit 2 -

This version is now @IBDesignable, with some properties renamed to show better in IB. Also added border width and color:

@IBDesignable
class VariableCornerRadiusShadowView: UIView  {

    @IBInspectable
    var radTopLeft:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var radTopRright:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var radBotLeft:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var radBotRright:CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var fillColor: UIColor = .white {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var borderColor: UIColor = .clear {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var borderWidth: CGFloat = 0.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowColor: UIColor = .black {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowXOffset: CGFloat = 0.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowYOffset: CGFloat = 0.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowOpacity: Float = 0.5 {
        didSet {
            self.setNeedsLayout()
        }
    }

    @IBInspectable
    var shadowRadius: CGFloat = 8.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    let theShapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    override func prepareForInterfaceBuilder() {
        commonInit()
    }

    func commonInit() -> Void {
        backgroundColor = .clear
        layer.addSublayer(theShapeLayer)
    }

    func layoutShape() -> Void {

        var pt = CGPoint.zero

        let myBezier = UIBezierPath()

        pt.x = radTopLeft
        pt.y = 0

        myBezier.move(to: pt)

        pt.x = bounds.width - radTopRright
        pt.y = 0

        myBezier.addLine(to: pt)

        pt.x = bounds.width - radTopRright
        pt.y = radTopRright

        myBezier.addArc(withCenter: pt, radius: radTopRright, startAngle: .pi * 1.5, endAngle: 0, clockwise: true)

        pt.x = bounds.width
        pt.y = bounds.height - radBotRright

        myBezier.addLine(to: pt)

        pt.x = bounds.width - radBotRright
        pt.y = bounds.height - radBotRright

        myBezier.addArc(withCenter: pt, radius: radBotRright, startAngle: 0, endAngle: .pi * 0.5, clockwise: true)

        pt.x = radBotLeft
        pt.y = bounds.height

        myBezier.addLine(to: pt)

        pt.x = radBotLeft
        pt.y = bounds.height - radBotLeft

        myBezier.addArc(withCenter: pt, radius: radBotLeft, startAngle: .pi * 0.5, endAngle: .pi, clockwise: true)

        pt.x = 0
        pt.y = radTopLeft

        myBezier.addLine(to: pt)

        pt.x = radTopLeft
        pt.y = radTopLeft

        myBezier.addArc(withCenter: pt, radius: radTopLeft, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)

        myBezier.close()

        theShapeLayer.path = myBezier.cgPath
        theShapeLayer.fillColor = fillColor.cgColor

        theShapeLayer.strokeColor = borderColor.cgColor
        theShapeLayer.lineWidth = borderWidth

        layer.shadowRadius = shadowRadius
        layer.shadowOffset = CGSize(width: shadowXOffset, height: shadowYOffset)
        layer.shadowOpacity = shadowOpacity
        layer.shadowColor = shadowColor.cgColor

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutShape()
    }

}

ContentLicense: CC BY-SA 4.0


问:
Django Channels doesn't run basic test case
I'm trying to test my consumers with the testing framework from django channels, but even a basic test doesn't seem to work

This is what my test case looks like:

```<code>from channels import Channel
from channels.test import ChannelTestCase, HttpClient, apply_routes
from rci.consumers import Demultiplexer
from rosbridge.consumers import OtherWebSocketConsumer

class ChannelTestCase(ChannelTestCase):

    def test_channel(self):
        client = HttpClient()
        client.send_and_consume('websocket.connect', '/new/') # <--- here's the error
        self.assertIsNone(client.receive())
</code>```

This is my routing:

```<code>http_routing = [
    route("http.request", admin.site.urls, path=r"^/admin/", method=r"^$"),
    #...and so on
]

channel_routing = [Demultiplexer.as_route(path=r"^/sock/")]
</code>```

This is my consumer:

```<code>class Demultiplexer(WebsocketDemultiplexer):
    channel_session_user = True

   consumers = {
       "rosbridge": ROSWebSocketConsumer,
       "setting": SettingsConsumer,
 }
</code>```

This gives me the following error:

ERROR: test_ros_channel
  (robot_configuration_interface.tests.unit.test_channels.ROSChannelTestCase)
  ---------------------------------------------------------------------- Traceback (most recent call last):   File
  "/home/cjds/development/robot_configuration_interface/robot_configuration_interface/tests/unit/test_channels.py", line 36, in test_ros_channel
      client.send_and_consume('websocket.connect', '/new/')   File "/usr/local/lib/python2.7/dist-packages/channels/test/http.py", line
  94, in send_and_consume
      self.send(channel, content, text, path)   File "/usr/local/lib/python2.7/dist-packages/channels/test/http.py", line
  79, in send
      content.setdefault('reply_channel', self.reply_channel) AttributeError: 'str' object has no attribute 'setdefault'

I'm trying to follow this tutorial here:

http://channels.readthedocs.io/en/stable/testing.html#clients

答:
channels 1.x

You are calling send_and_consume with two positional arguments which results in effect in this call (which is exactly why there happens an error during execution in this line):

```<code># AGAIN this is wrong code this is what is written in the question
# only difference is the naming of the (previously positional) arguments
client.send_and_consume(channel='websocket.connect', content='/new/')
</code>```

and here is the explanation why there is an error:

However, the implementation of send_and_consume expects content to be a dictionary:

```<code>def send_and_consume(self, channel, content={}, text=None, path='/', fail_on_none=True, check_accept=True):
        """
        Reproduce full life cycle of the message
        """
        self.send(channel, content, text, path)
        return self.consume(channel, fail_on_none=fail_on_none, check_accept=check_accept)
</code>```

Implementation code taken from: https://github.com/django/channels/blob/master/channels/test/http.py#L92

channels 2.x

See https://channels.readthedocs.io/en/latest/topics/testing.html, as mentioned in the comment by Paul Whipp.

Body:
I'm trying to test my consumers with the testing framework from django channels, but even a basic test doesn't seem to work

This is what my test case looks like:

from channels import Channel
from channels.test import ChannelTestCase, HttpClient, apply_routes
from rci.consumers import Demultiplexer
from rosbridge.consumers import OtherWebSocketConsumer

class ChannelTestCase(ChannelTestCase):

    def test_channel(self):
        client = HttpClient()
        client.send_and_consume('websocket.connect', '/new/') # <--- here's the error
        self.assertIsNone(client.receive())

This is my routing:

http_routing = [
    route("http.request", admin.site.urls, path=r"^/admin/", method=r"^$"),
    #...and so on
]

channel_routing = [Demultiplexer.as_route(path=r"^/sock/")]

This is my consumer:

class Demultiplexer(WebsocketDemultiplexer):
    channel_session_user = True

   consumers = {
       "rosbridge": ROSWebSocketConsumer,
       "setting": SettingsConsumer,
 }

This gives me the following error:

ERROR: test_ros_channel
  (robot_configuration_interface.tests.unit.test_channels.ROSChannelTestCase)
  ---------------------------------------------------------------------- Traceback (most recent call last):   File
  "/home/cjds/development/robot_configuration_interface/robot_configuration_interface/tests/unit/test_channels.py", line 36, in test_ros_channel
      client.send_and_consume('websocket.connect', '/new/')   File "/usr/local/lib/python2.7/dist-packages/channels/test/http.py", line
  94, in send_and_consume
      self.send(channel, content, text, path)   File "/usr/local/lib/python2.7/dist-packages/channels/test/http.py", line
  79, in send
      content.setdefault('reply_channel', self.reply_channel) AttributeError: 'str' object has no attribute 'setdefault'

I'm trying to follow this tutorial here:

http://channels.readthedocs.io/en/stable/testing.html#clients

Body:
channels 1.x

You are calling send_and_consume with two positional arguments which results in effect in this call (which is exactly why there happens an error during execution in this line):

# AGAIN this is wrong code this is what is written in the question
# only difference is the naming of the (previously positional) arguments
client.send_and_consume(channel='websocket.connect', content='/new/')

and here is the explanation why there is an error:

However, the implementation of send_and_consume expects content to be a dictionary:

def send_and_consume(self, channel, content={}, text=None, path='/', fail_on_none=True, check_accept=True):
        """
        Reproduce full life cycle of the message
        """
        self.send(channel, content, text, path)
        return self.consume(channel, fail_on_none=fail_on_none, check_accept=check_accept)

Implementation code taken from: https://github.com/django/channels/blob/master/channels/test/http.py#L92

channels 2.x

See https://channels.readthedocs.io/en/latest/topics/testing.html, as mentioned in the comment by Paul Whipp.


问:
Query returning records with duplicate data because of the wrong data in one of the columns
I have a record of an employee but my query is returning 2 records of this employee because the address column is different between the 2. How can solve this problem? Is it something that can be done? EMP_ID, CUS_LAST_NAME, CUS_FIRST_NAME, and GUARDIAN_ADDRESS are from 3 separate tables.

Example:

```<code>ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street Apt 1

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street
</code>```

答:
The quick and dirty way with max():

```<code>select id, emp_id, emp_last_name, emp_first_name, max(address) as address
from employees
group by id, emp_id, emp_last_name, emp_first_name
</code>```

Alternative using: top with ties

```<code>select top 1 with ties
    id, emp_id, emp_last_name, emp_first_name, address
from employees
order by row_number() over (partition by emp_id order by address desc)
</code>```

rextester demo for both: http://rextester.com/EGGA75008

Body:
I have a record of an employee but my query is returning 2 records of this employee because the address column is different between the 2. How can solve this problem? Is it something that can be done? EMP_ID, CUS_LAST_NAME, CUS_FIRST_NAME, and GUARDIAN_ADDRESS are from 3 separate tables.

Example:

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street Apt 1

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street

Body:
The quick and dirty way with max():

select id, emp_id, emp_last_name, emp_first_name, max(address) as address
from employees
group by id, emp_id, emp_last_name, emp_first_name

Alternative using: top with ties

select top 1 with ties
    id, emp_id, emp_last_name, emp_first_name, address
from employees
order by row_number() over (partition by emp_id order by address desc)

rextester demo for both: http://rextester.com/EGGA75008


问:
Can AWS Cognito adminCreateUser send a temporary password?
The Amazon Cognito adminCreateUser documentation on TemporaryPassword states:

This parameter is not required. If you do not specify a value, Amazon
  Cognito generates one for you.

How does the user ever get it?  At first I thought it would get emailed to the user, but that doesn't seem to be the case.  Then I thought maybe it would come back in the response.  Nope.

Here's the code I'm calling in my node JS Lambda function:

```<code>adminCreateUser(
{
    "UserPoolId": "us-east-1_XXXXXXXX",
    "Username": "roger__mailinator.com",
    "DesiredDeliveryMediums": [
        "EMAIL"
    ],
    "ForceAliasCreation": false,
    "MessageAction": "SUPPRESS",
    "UserAttributes": [
        {
            "Name": "given_name",
            "Value": "Rodger"
        },
        {
            "Name": "family_name",
            "Value": "Ribbit"
        },
        {
            "Name": "name",
            "Value": "Rodger Ribbit"
        },
        {
            "Name": "email",
            "Value": "roger@mailinator.com"
        },
        {
            "Name": "custom:title",
            "Value": "Animation Designer"
        },
        {
            "Name": "custom:company",
            "Value": "76"
        }
    ]
}, function(error, data) {
    if (error) {
      console.log("Error adding user to cognito: " + error, error.stack);
      //...
    } else {
      console.log("Received back from cognito: " + JSON.stringify(data));
      //...
    }
  });
</code>```

and here's the response I get:

```<code>Received back from cognito:
{
    "User": {
        "Username": "roger__mailinator.com",
        "Attributes": [
            {
                "Name": "custom:title",
                "Value": "Animation Designer"
            },
            {
                "Name": "sub",
                "Value": "1cd612a0-0da0-4e7b-84c7-30570fab80a9"
            },
            {
                "Name": "name",
                "Value": "Rodger Ribbit"
            },
            {
                "Name": "given_name",
                "Value": "Rodger"
            },
            {
                "Name": "family_name",
                "Value": "Ribbit"
            },
            {
                "Name": "email",
                "Value": "roger@mailinator.com"
            },
            {
                "Name": "custom:company",
                "Value": "76"
            }
        ],
        "UserCreateDate": "2017-03-30T18:31:34.283Z",
        "UserLastModifiedDate": "2017-03-30T18:31:34.283Z",
        "Enabled": true,
        "UserStatus": "FORCE_CHANGE_PASSWORD"
    }
}
</code>```

Where does the password go?  Are we supposed to guess it? :-)

答:
I think it's because you are passing "MessageAction": "SUPPRESS". That would suppress the sending of the email.

The temporary password is emailed to the user and he needs to reset it upon the first login.

Body:
The Amazon Cognito adminCreateUser documentation on TemporaryPassword states:

This parameter is not required. If you do not specify a value, Amazon
  Cognito generates one for you.

How does the user ever get it?  At first I thought it would get emailed to the user, but that doesn't seem to be the case.  Then I thought maybe it would come back in the response.  Nope.

Here's the code I'm calling in my node JS Lambda function:

adminCreateUser(
{
    "UserPoolId": "us-east-1_XXXXXXXX",
    "Username": "roger__mailinator.com",
    "DesiredDeliveryMediums": [
        "EMAIL"
    ],
    "ForceAliasCreation": false,
    "MessageAction": "SUPPRESS",
    "UserAttributes": [
        {
            "Name": "given_name",
            "Value": "Rodger"
        },
        {
            "Name": "family_name",
            "Value": "Ribbit"
        },
        {
            "Name": "name",
            "Value": "Rodger Ribbit"
        },
        {
            "Name": "email",
            "Value": "roger@mailinator.com"
        },
        {
            "Name": "custom:title",
            "Value": "Animation Designer"
        },
        {
            "Name": "custom:company",
            "Value": "76"
        }
    ]
}, function(error, data) {
    if (error) {
      console.log("Error adding user to cognito: " + error, error.stack);
      //...
    } else {
      console.log("Received back from cognito: " + JSON.stringify(data));
      //...
    }
  });

and here's the response I get:

Received back from cognito:
{
    "User": {
        "Username": "roger__mailinator.com",
        "Attributes": [
            {
                "Name": "custom:title",
                "Value": "Animation Designer"
            },
            {
                "Name": "sub",
                "Value": "1cd612a0-0da0-4e7b-84c7-30570fab80a9"
            },
            {
                "Name": "name",
                "Value": "Rodger Ribbit"
            },
            {
                "Name": "given_name",
                "Value": "Rodger"
            },
            {
                "Name": "family_name",
                "Value": "Ribbit"
            },
            {
                "Name": "email",
                "Value": "roger@mailinator.com"
            },
            {
                "Name": "custom:company",
                "Value": "76"
            }
        ],
        "UserCreateDate": "2017-03-30T18:31:34.283Z",
        "UserLastModifiedDate": "2017-03-30T18:31:34.283Z",
        "Enabled": true,
        "UserStatus": "FORCE_CHANGE_PASSWORD"
    }
}

Where does the password go?  Are we supposed to guess it? :-)


问:
BOT for company use
I have a BOT that answers questions for sales people, but I need to make sure that only users in my company's Azure Active Directory are able to access the BOT.  Is there a way to only allow Skype for business users and authorize based on their access token?

Thanks

Terry

答:
You can authenticate your bot's users against their corporate AAD account using a library like botauth.

Here's an example bot. https://github.com/MicrosoftDX/botauth/blob/master/examples/aadv2/app.js

Title: BOT for company use


问:
How to set time to 24 hour format in Calendar
I need to set the time on the current date. The time string is always in 24 hour format but the result I get is wrong:

```<code>  SimpleDateFormat df = new SimpleDateFormat("kk:mm");
  Date d1 = df.parse("10:30");
  Calendar c1 = Calendar.getInstance();
  c1.set(Calendar.HOUR, d1.getHours());
  c1.set(Calendar.MINUTE, d1.getMinutes());
</code>```

The date should be today's date and the time set to 10:30. Instead the time in c1 ends up being 22:30. How can I force the calendar control to recognize my time is 24 hour format?

EDIT:
If I just do this:

```<code>Calendar c1 = Calendar.getInstance();
c1.set(Calendar.HOUR, 10);
c1.set(Calendar.MINUTE, 30);
</code>```

This gives me the same result. Why?

答:
tl;dr

```<code>LocalTime.parse( "10:30" )  // Parsed as 24-hour time.
</code>```

java.time

Avoid the troublesome old date-time classes such as Date and Calendar that are now supplanted by the java.time classes.

LocalTime

The java.time classes provide a way to represent the time-of-day without a date and without a time zone: LocalTime

```<code>LocalTime lt = LocalTime.of( 10 , 30 );  // 10:30 AM.
LocalTime lt = LocalTime.of( 22 , 30 );  // 22:30 is 10:30 PM.
</code>```

ISO 8601

The java.time classes use standard ISO 8601 formats by default when generating and parsing strings. These formats use 24-hour time.

```<code>String output = lt.toString();
</code>```

LocalTime.of( 10 , 30 ).toString() : 10:30

LocalTime.of( 22 , 30 ).toString() : 22:30

So parsing 10:30 will be interpreted as 10:30 AM.

```<code>LocalTime lt = LocalTime.parse( "10:30" );  // 10:30 AM.
</code>```

DateTimeFormatter

If you need to generate or parse strings in 12-hour click format with AM/PM, use the DateTimeFormatter class. Tip: make a habit of specifying a Locale.

Body:
I need to set the time on the current date. The time string is always in 24 hour format but the result I get is wrong:

  SimpleDateFormat df = new SimpleDateFormat("kk:mm");
  Date d1 = df.parse("10:30");
  Calendar c1 = Calendar.getInstance();
  c1.set(Calendar.HOUR, d1.getHours());
  c1.set(Calendar.MINUTE, d1.getMinutes());

The date should be today's date and the time set to 10:30. Instead the time in c1 ends up being 22:30. How can I force the calendar control to recognize my time is 24 hour format?

EDIT:
If I just do this:

Calendar c1 = Calendar.getInstance();
c1.set(Calendar.HOUR, 10);
c1.set(Calendar.MINUTE, 30);

This gives me the same result. Why?

Body:
tl;dr

LocalTime.parse( "10:30" )  // Parsed as 24-hour time.

java.time

Avoid the troublesome old date-time classes such as Date and Calendar that are now supplanted by the java.time classes.

LocalTime

The java.time classes provide a way to represent the time-of-day without a date and without a time zone: LocalTime

LocalTime lt = LocalTime.of( 10 , 30 );  // 10:30 AM.
LocalTime lt = LocalTime.of( 22 , 30 );  // 22:30 is 10:30 PM.

ISO 8601

The java.time classes use standard ISO 8601 formats by default when generating and parsing strings. These formats use 24-hour time.

String output = lt.toString();

LocalTime.of( 10 , 30 ).toString() : 10:30

LocalTime.of( 22 , 30 ).toString() : 22:30

So parsing 10:30 will be interpreted as 10:30 AM.

LocalTime lt = LocalTime.parse( "10:30" );  // 10:30 AM.

DateTimeFormatter

If you need to generate or parse strings in 12-hour click format with AM/PM, use the DateTimeFormatter class. Tip: make a habit of specifying a Locale.


问:
How to detect number of CPU cores in Crystal?
How do you detect the number of CPU cores in crystal?

In Go you can do runtime.NumCPU() and in Node.js you can do os.cpus(). Is there something similar in Crystal?

答:
The last time I checked (admittedly that was long ago) there was no direct way to do that, but you can get access to this information through the command line. I ended up combining multiple of these answers for redundancy.</p>

```<code>THREADS = `getconf _NPROCESSORS_ONLN || nproc --all || grep -c '^processor' /proc/cpuinfo`.to_i
</code>```

Body:
The last time I checked (admittedly that was long ago) there was no direct way to do that, but you can get access to this information through the command line. I ended up combining multiple of these answers for redundancy.

THREADS = `getconf _NPROCESSORS_ONLN || nproc --all || grep -c '^processor' /proc/cpuinfo`.to_i