问:
When I try running this class in eclipse, another class gets executed
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :</p>

```<code>package deepToe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;

public class deepToe_2 extends JPanel {

JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];

public static void main(String[] args) {

    JFrame window = new JFrame("Tic Tac Toe");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new TicTacToe());
    window.setBounds(300,200,300,300);
    window.setVisible(true);
}

public deepToe_2()
{
  setLayout(new GridLayout(3,3));
  initializebuttons();
  toss();
}

public void toss(){
    Random ran = new Random();
    int r = ran.nextInt(2);
    if(r == 1){
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
    else {
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
}

public void deepToe() {
    if(alternate == 1) {
        buttons[4].setText("O");
    }else {
        int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
        for(int i = 0; i < 9; i++) {
            board = MotherBoard;
            if(board[i] == "") {
                board[i] = "O";
                moves[i] = evaluateBoard();
            }
        }
        int high = -999, final_move = -1;
        for(int j = 0; j < 9; j++) {
            if(moves[j] > high){
                high = moves[j];
                final_move = j;
            }
        }
        buttons[final_move].setText("O");
    }
    updateMotherBoard();
    if(!(checkResults())) alternate++;
}

public int evaluateBoard() {
    int x = 0;
    if(canSomeoneWin("O") != -1) x += 2;
    if(canSomeoneWin("X") != -1) x -= 2;
    return x;
}

public void updateMotherBoard() {
    for(int i = 0; i < 9; i++) {
        MotherBoard[i] = buttons[i].getText();
    }
}

public int canSomeoneWin(String c) {
    int x = 0, y = 1, z = 2;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x += 3;
        y += 3;
        z += 3;
    }
    x = 0; y = 3; z = 6;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x++;
        y++;
        z++;
    }
    x = 0; y = 4; z = 8;
    for(int j = 0; j < 2; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x = 2; z = 6;
    }
    return -1;

}

public void initializebuttons()
{
    for(int i = 0; i <= 8; i++)
    {
        buttons[i] = new JButton();
        buttons[i].setText("");
        buttons[i].addActionListener(new buttonListener());

        add(buttons[i]);
    }
    buttons[5].setText("X");

}

public class buttonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {

        JButton buttonClicked = (JButton)e.getSource();

        if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
            buttonClicked.setText("X");
            updateMotherBoard();
            if(!(checkResults())) {
                alternate++;
                deepToe();
            }
        }

    }
}

    public boolean checkResults(){
        if(checkForWin())
        {
            if(alternate%2 == 0)
                JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
            else
                JOptionPane.showConfirmDialog(null, "deepToe wins.");
            return true;
        }else{
            if(checkForDraw()){
                JOptionPane.showConfirmDialog(null, "Draw. Good game.");
                return true;
            }
        }
        return false;

    }

    public boolean checkForDraw() {
        boolean yes = true;
        for(int j = 0; j < 9; j++){
            if(buttons[j].getText().equals("")) yes = false;
        }
        return yes;
    }

    public boolean checkForWin()
    {
        if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
            return true;
        else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
            return true;
        else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
            return true;
        else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
            return true;
        else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
            return true;
        else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
            return true;
        else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
            return true;
        else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
            return true;
        else
            return false;

    }

    public boolean checkAdjacent(int a, int b)
    {
        if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
            return true;
        else
            return false;
    }

}
</code>```

答:
It probably IS running this class, but you are inserting the wrong panel in your frame:

```<code>window.getContentPane().add(new TicTacToe());
</code>```

it should be deepToe_2 like in

```<code>window.getContentPane().add(new deepToe_2());
</code>```

since there is no other reference to that class in the poseted code.

Just to be sure change the frame's title:

```<code>JFrame window = new JFrame("Deep Toe 2");  // or so
</code>```

I also would encourage you to (learn to) use the debugger, would b helpful to identify such problems...

Body:
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :

package deepToe;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;

public class deepToe_2 extends JPanel {

JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];

public static void main(String[] args) {

    JFrame window = new JFrame("Tic Tac Toe");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new TicTacToe());
    window.setBounds(300,200,300,300);
    window.setVisible(true);
}

public deepToe_2()
{
  setLayout(new GridLayout(3,3));
  initializebuttons();
  toss();
}

public void toss(){
    Random ran = new Random();
    int r = ran.nextInt(2);
    if(r == 1){
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
    else {
        JOptionPane.showMessageDialog(null, "deepToe goes First.");
        alternate++;
        deepToe();
    }
}

public void deepToe() {
    if(alternate == 1) {
        buttons[4].setText("O");
    }else {
        int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
        for(int i = 0; i < 9; i++) {
            board = MotherBoard;
            if(board[i] == "") {
                board[i] = "O";
                moves[i] = evaluateBoard();
            }
        }
        int high = -999, final_move = -1;
        for(int j = 0; j < 9; j++) {
            if(moves[j] > high){
                high = moves[j];
                final_move = j;
            }
        }
        buttons[final_move].setText("O");
    }
    updateMotherBoard();
    if(!(checkResults())) alternate++;
}

public int evaluateBoard() {
    int x = 0;
    if(canSomeoneWin("O") != -1) x += 2;
    if(canSomeoneWin("X") != -1) x -= 2;
    return x;
}

public void updateMotherBoard() {
    for(int i = 0; i < 9; i++) {
        MotherBoard[i] = buttons[i].getText();
    }
}

public int canSomeoneWin(String c) {
    int x = 0, y = 1, z = 2;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x += 3;
        y += 3;
        z += 3;
    }
    x = 0; y = 3; z = 6;
    for(int j = 0; j < 3; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x++;
        y++;
        z++;
    }
    x = 0; y = 4; z = 8;
    for(int j = 0; j < 2; j++){
        if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
        if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
        if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
        x = 2; z = 6;
    }
    return -1;

}

public void initializebuttons()
{
    for(int i = 0; i <= 8; i++)
    {
        buttons[i] = new JButton();
        buttons[i].setText("");
        buttons[i].addActionListener(new buttonListener());

        add(buttons[i]);
    }
    buttons[5].setText("X");

}

public class buttonListener implements ActionListener
{

    public void actionPerformed(ActionEvent e)
    {

        JButton buttonClicked = (JButton)e.getSource();

        if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
            buttonClicked.setText("X");
            updateMotherBoard();
            if(!(checkResults())) {
                alternate++;
                deepToe();
            }
        }

    }
}

    public boolean checkResults(){
        if(checkForWin())
        {
            if(alternate%2 == 0)
                JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
            else
                JOptionPane.showConfirmDialog(null, "deepToe wins.");
            return true;
        }else{
            if(checkForDraw()){
                JOptionPane.showConfirmDialog(null, "Draw. Good game.");
                return true;
            }
        }
        return false;

    }

    public boolean checkForDraw() {
        boolean yes = true;
        for(int j = 0; j < 9; j++){
            if(buttons[j].getText().equals("")) yes = false;
        }
        return yes;
    }

    public boolean checkForWin()
    {
        if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
            return true;
        else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
            return true;
        else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
            return true;
        else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
            return true;
        else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
            return true;
        else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
            return true;
        else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
            return true;
        else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
            return true;
        else
            return false;

    }

    public boolean checkAdjacent(int a, int b)
    {
        if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
            return true;
        else
            return false;
    }

}

Body:
It probably IS running this class, but you are inserting the wrong panel in your frame:

window.getContentPane().add(new TicTacToe());

it should be deepToe_2 like in

window.getContentPane().add(new deepToe_2());

since there is no other reference to that class in the poseted code.

Just to be sure change the frame's title:

JFrame window = new JFrame("Deep Toe 2");  // or so

I also would encourage you to (learn to) use the debugger, would b helpful to identify such problems...


来源: stackexchange

问:
lines in a file with comma
I would like to know how to create a sub file with a number of commas, for example.

123,abc,qwe,ert

123,456,abc,qwe,fgh

I want to create a file .txt with the line that has 4 commas. (123,456,abc,qwe,fgh).

I tried with this.

awk -F\, '{print NF-1}'

But only gives me the number of commas that each line has.

答:
four delimiters mean five fields, use as a condition, by default it will print the matching lines...</p>

```<code>awk -F, 'NF==5' file
</code>```

ContentLicense: CC BY-SA 3.0

Title: lines in a file with comma

Body:
four delimiters mean five fields, use as a condition, by default it will print the matching lines...

awk -F, 'NF==5' file


问:
Using the docs but completely confused... mongoose Model#save
I am trying to return specific status codes such as, 409 Conflict. I have used the Model#save docs

Edit: I am not trying to solve the error, it is deliberate.

According to the docs, there is three parameters on the callback: err, product, and numAffected.

EDIT: I wrote this code wrong and I edited. Either way, I got an excellent answer from Ryan.

```<code>  app.post('/skill', (req, res) => {
    const skill = new Skill({some_duplicate_object});
    skill.save((err, product, numAffected) => {
        console.log("Error: ", err);

    });
</code>```

NOT my console.log, in the Mocha test cli, I get an error:

```<code>(node:19760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): ValidationError: Path `name` is required.
</code>```

By playing around and shear luck, I did this: This is NOT in the mongoose docs and is my main reason for writing this post.

```<code>  app.post('/skill', (req, res) => {
    const skill = new Skill({});
    skill.save()
      .then((err, product, numAffected) => {
        console.log("Nothing displayed here");
    }, (err) => {
      console.log(err.errors);
    });
</code>```

Even though this is not in the docs, it shows the error I want. As someone that is REALLY trying to use official docs more, I find it so hard to understand what is really going on. Why does this work and if it is in the docs, where would this info be?

```<code>{ name:
   { MongooseError: Path `name` is required.
       at ValidatorError (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/error/validator.js:24:11)
       at validate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:706:13)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:752:11
       at Array.forEach (native)
       at SchemaString.SchemaType.doValidate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:712:19)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/document.js:1408:9
       at _combinedTickCallback (internal/process/next_tick.js:73:7)
       at process._tickCallback (internal/process/next_tick.js:104:9)
     message: 'Path `name` is required.',
     name: 'ValidatorError',
     properties:
      { type: 'required',
        message: 'Path `{PATH}` is required.',
        validator: [Function],
        path: 'name',
        value: undefined },
     kind: 'required',
     path: 'name',
     value: undefined,
     reason: undefined } }
</code>```

Extra info:

```<code>  "devDependencies": {
    "chai": "^3.5.0",
    "mocha": "^2.4.5",
    "request": "^2.81.0",
    "supertest": "^3.0.0"
  },
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "mongoose": "^4.9.2"
  }
</code>```

答:
You're not handling the promise rejection.

Change this:

```<code>.then((err, product, numAffected) => {
    console.log("Error: ", err);
});
</code>```

to this:

```<code>.then((result) => {
    console.log('Result:', result);
}).catch((error) => {
    console.log('Error:', error);
</code>```

Of course change what happens in the callbacks to whatever you need.

See this answer for more general info on unhandled rejection:

Should I refrain from handling Promise rejection asynchronously?

Body:
I am trying to return specific status codes such as, 409 Conflict. I have used the Model#save docs

Edit: I am not trying to solve the error, it is deliberate.

According to the docs, there is three parameters on the callback: err, product, and numAffected.

EDIT: I wrote this code wrong and I edited. Either way, I got an excellent answer from Ryan.

  app.post('/skill', (req, res) => {
    const skill = new Skill({some_duplicate_object});
    skill.save((err, product, numAffected) => {
        console.log("Error: ", err);

    });

NOT my console.log, in the Mocha test cli, I get an error:

(node:19760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): ValidationError: Path `name` is required.

By playing around and shear luck, I did this: This is NOT in the mongoose docs and is my main reason for writing this post.

  app.post('/skill', (req, res) => {
    const skill = new Skill({});
    skill.save()
      .then((err, product, numAffected) => {
        console.log("Nothing displayed here");
    }, (err) => {
      console.log(err.errors);
    });

Even though this is not in the docs, it shows the error I want. As someone that is REALLY trying to use official docs more, I find it so hard to understand what is really going on. Why does this work and if it is in the docs, where would this info be?

{ name:
   { MongooseError: Path `name` is required.
       at ValidatorError (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/error/validator.js:24:11)
       at validate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:706:13)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:752:11
       at Array.forEach (native)
       at SchemaString.SchemaType.doValidate (/home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/schematype.js:712:19)
       at /home/codeamend/Coding/projects/portfolio/work/CodeAmend.Com/backend/node_modules/mongoose/lib/document.js:1408:9
       at _combinedTickCallback (internal/process/next_tick.js:73:7)
       at process._tickCallback (internal/process/next_tick.js:104:9)
     message: 'Path `name` is required.',
     name: 'ValidatorError',
     properties:
      { type: 'required',
        message: 'Path `{PATH}` is required.',
        validator: [Function],
        path: 'name',
        value: undefined },
     kind: 'required',
     path: 'name',
     value: undefined,
     reason: undefined } }

Extra info:

  "devDependencies": {
    "chai": "^3.5.0",
    "mocha": "^2.4.5",
    "request": "^2.81.0",
    "supertest": "^3.0.0"
  },
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "mongoose": "^4.9.2"
  }

Body:
You're not handling the promise rejection.

Change this:

.then((err, product, numAffected) => {
    console.log("Error: ", err);
});

to this:

.then((result) => {
    console.log('Result:', result);
}).catch((error) => {
    console.log('Error:', error);

Of course change what happens in the callbacks to whatever you need.

See this answer for more general info on unhandled rejection:

Should I refrain from handling Promise rejection asynchronously?


问:
NoReverseMatch when trying to use get_absolute_url with custom template tag
I am making a calendar app which has a custom template tag that takes the python HTML template function and overlays objects from the Events model on the correct days. I am trying to get the displayed objects to have a link directly to an object detail/edit view and am trying to use get_absolute_url and to reverse render this view. This is necessary as the custom template tag doesn't load correctly if I try to hardcode {% url %} template tags into it for each event via a for loop. I have spent some hours looking through the other stack overflow questions with no luck and have even changed my reverse to the object ID rather than the title of the event. I am hoping this is just a small thing that I have overlooked but no sure.

view:

```<code>def home(request, month=None, year=None):
    if month == None:
        _date = datetime.now()
    else:
        _date = date(int(year), int(month), 1)
    title = "%s, %s" % (_date.strftime("%B"), _date.strftime("%Y"))

    return render(request, 'calendar.html', calendar(_date, title))
</code>```

url:

```<code>app_name = 'cal'
urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^newevent/$', views.newEvent, name='newevent'),
    url(r'^(?P<id>\d+)$/', views.viewEvent, name='viewevent'),
    url(r'^(?P<month>\d+)/(?P<year>\d+)$', views.home, name='another-month')
]
</code>```

HTML:

```<code>    <div>
      {% load calendarify %}
      <span id="calendarify">{% calendarify year month event_list %}</span>
    </div>
</code>```

Template tag:

```<code>def do_month_calendarify(parser, token):
    # Take the tag input from the template and format
    # Template syntax is {% calendarify year month %}
    try:
        tag_name, year, month, event_list = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            "%r tag requires three arguments" % token.contents.split()[0]
        )
    return CalendarifyNode(year, month, event_list)

class CalendarifyNode(template.Node):

    def __init__(self, year, month, event_list):
        try:
            self.year = template.Variable(year)
            self.month = template.Variable(month)
            self.event_list = template.Variable(event_list)
        except ValueError:
            raise template.TemplateSyntaxError

    def render(self, context):
        try:
            my_year = self.year.resolve(context)
            my_month = self.month.resolve(context)
            my_event_list = self.event_list.resolve(context)
            cal = EventCalendar(my_event_list)
            return cal.formatmonth(
                int(my_year), int(my_month))
        except ValueError:
            return "%s, %s, %s" % (my_month, my_year, my_event_list)

class EventCalendar(HTMLCalendar):
    # Use Python's HTMLCalendar and put user events over top
    def __init__(self, events):
        super(EventCalendar, self).__init__()
        self.events = self.group_by_day(events)

    def formatday(self, day, weekday):
        if day != 0:
            cssid = self.cssclasses[weekday]
            cssclass = "daybox"
            if date.today() == date(self.year, self.month, day):
                cssid += ' today'
            if day in self.events:
                cssid += ' filled'
                body = ['<ul>']
                for event in self.events[day]:
                    body.append('<li>')
                    body.append('<a href="%s">' % event.get_absolute_url())
                    body.append(esc(event.title))
                    body.append('</a></li>')
                body.append('</ul>')
                return self.day_cell(
                    cssclass, cssid, '<span class="dayNumber">%d</span> %s' % (
                        day, ''.join(body)))
            return self.day_cell(
                cssclass, cssid, '<span class="dayNumberNoReadings">%d</span>' % (day))
        return self.day_cell('nodaybox', 'noday', ' ')

    def formatmonth(self, year, month):
        self.year, self.month = year, month
        return super(EventCalendar, self).formatmonth(year, month)

    def group_by_day(self, events):
        field = lambda event: event.start_date.day
        return dict(
            [(day, list(items)) for day, items in groupby(events, field)]
        )

    def day_cell(self, cssclass, cssid, body):
        return '<td class="%s" id="%s">%s</td>' % (cssclass, cssid, body)

register.tag('calendarify', do_month_calendarify)
</code>```

Model:

```<code>class Events(models.Model):
    ...

    def get_absolute_url(self):
        return reverse('cal:viewEvent', args=[str(self.id)], current_app='cal')
</code>```

Sorry about the load of code posted. Any chance anyone knows what might have caused this issue?

Thanks in advance!

答:
This was caused by a typo/mismatch between the following:

```<code>url(r'^(?P<id>\d+)$/', views.viewEvent, name='viewevent'),
</code>```

name = viewevent

```<code>def get_absolute_url(self):
return reverse('cal:viewEvent', args=[str(self.id)],
current_app='cal')
</code>```

name = viewEvent

Once these were corrected it worked fine.

Body:
I am making a calendar app which has a custom template tag that takes the python HTML template function and overlays objects from the Events model on the correct days. I am trying to get the displayed objects to have a link directly to an object detail/edit view and am trying to use get_absolute_url and to reverse render this view. This is necessary as the custom template tag doesn't load correctly if I try to hardcode {% url %} template tags into it for each event via a for loop. I have spent some hours looking through the other stack overflow questions with no luck and have even changed my reverse to the object ID rather than the title of the event. I am hoping this is just a small thing that I have overlooked but no sure.

view:

def home(request, month=None, year=None):
    if month == None:
        _date = datetime.now()
    else:
        _date = date(int(year), int(month), 1)
    title = "%s, %s" % (_date.strftime("%B"), _date.strftime("%Y"))

    return render(request, 'calendar.html', calendar(_date, title))

url:

app_name = 'cal'
urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^newevent/$', views.newEvent, name='newevent'),
    url(r'^(?P<id>\d+)$/', views.viewEvent, name='viewevent'),
    url(r'^(?P<month>\d+)/(?P<year>\d+)$', views.home, name='another-month')
]

HTML:

      {% load calendarify %}
      {% calendarify year month event_list %}

Template tag:

def do_month_calendarify(parser, token):
    # Take the tag input from the template and format
    # Template syntax is {% calendarify year month %}
    try:
        tag_name, year, month, event_list = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            "%r tag requires three arguments" % token.contents.split()[0]
        )
    return CalendarifyNode(year, month, event_list)

class CalendarifyNode(template.Node):

    def __init__(self, year, month, event_list):
        try:
            self.year = template.Variable(year)
            self.month = template.Variable(month)
            self.event_list = template.Variable(event_list)
        except ValueError:
            raise template.TemplateSyntaxError

    def render(self, context):
        try:
            my_year = self.year.resolve(context)
            my_month = self.month.resolve(context)
            my_event_list = self.event_list.resolve(context)
            cal = EventCalendar(my_event_list)
            return cal.formatmonth(
                int(my_year), int(my_month))
        except ValueError:
            return "%s, %s, %s" % (my_month, my_year, my_event_list)

class EventCalendar(HTMLCalendar):
    # Use Python's HTMLCalendar and put user events over top
    def __init__(self, events):
        super(EventCalendar, self).__init__()
        self.events = self.group_by_day(events)

    def formatday(self, day, weekday):
        if day != 0:
            cssid = self.cssclasses[weekday]
            cssclass = "daybox"
            if date.today() == date(self.year, self.month, day):
                cssid += ' today'
            if day in self.events:
                cssid += ' filled'
                body = ['
']
                for event in self.events[day]:
                    body.append('
')
                    body.append('' % event.get_absolute_url())
                    body.append(esc(event.title))
                    body.append('
')
                body.append('
')
                return self.day_cell(
                    cssclass, cssid, '%d %s' % (
                        day, ''.join(body)))
            return self.day_cell(
                cssclass, cssid, '%d' % (day))
        return self.day_cell('nodaybox', 'noday', ' ')

    def formatmonth(self, year, month):
        self.year, self.month = year, month
        return super(EventCalendar, self).formatmonth(year, month)

    def group_by_day(self, events):
        field = lambda event: event.start_date.day
        return dict(
            [(day, list(items)) for day, items in groupby(events, field)]
        )

    def day_cell(self, cssclass, cssid, body):
        return '%s	' % (cssclass, cssid, body)

register.tag('calendarify', do_month_calendarify)

Model:

class Events(models.Model):
    ...

    def get_absolute_url(self):
        return reverse('cal:viewEvent', args=[str(self.id)], current_app='cal')

Sorry about the load of code posted. Any chance anyone knows what might have caused this issue?

Thanks in advance!

Body:
This was caused by a typo/mismatch between the following:

url(r'^(?P<id>\d+)$/', views.viewEvent, name='viewevent'),

name = viewevent

def get_absolute_url(self):
return reverse('cal:viewEvent', args=[str(self.id)],
current_app='cal')

name = viewEvent

Once these were corrected it worked fine.


问:
Missing files (404) in Ionic App only in iOS
I have an app I developed in Android. I installed a VM with Mac, and I'm testing it in iOS. The app worked perfectly in Android, but in iOS it is not. When I use 'ionic serve' or 'ionic serve --lab' the browser show a white screen, and in the console I get this errors (link of image below):

Console

Here is some code from the index.html:

```<code><link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="lib/ionic/css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/bluebird.min.js"></script>
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <script src="lib/ionic.cloud.min.js"></script>
    <script src="lib/ionic/js/ionic-modal-select.min.js"></script>
    <script src="lib/ionic/js/ionic-toast.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="js/ng-cordova.min.js"></script>
    <script src="cordova.js"></script>
</code>```

I'm really lost here because the exact same files works OK for Android.

答: Which error you are posted, not library error.Error coming from app.js file.If you dont mind create a new ionic app and replace your file in new app.it will works.</p>

Body:
I have an app I developed in Android. I installed a VM with Mac, and I'm testing it in iOS. The app worked perfectly in Android, but in iOS it is not. When I use 'ionic serve' or 'ionic serve --lab' the browser show a white screen, and in the console I get this errors (link of image below):

Console

Here is some code from the index.html:

<link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="lib/ionic/css/style.css" rel="stylesheet">

I'm really lost here because the exact same files works OK for Android.


问:
" Use of unassigned local variable" error for three local variables but not for the fourth local variable. Why?
For the following code in C#, why are the errors obtained: -

Error 1: Use of unassigned local variable circleArea

  Error 2: Use of unassigned local variable circleRadius

  Error 3: Use of unassigned local variable circleDiameter

but not for paramaterChoice; even though it also is an uninitialized local variable?

```<code>static void Main(string[] args)
{
    char paramaterChoice;
    double circleRadius, circleDiameter, circleArea;
    const double PI=3.14;

    Console.WriteLine("If you know the radius press r or R, If you know the diameter press d or D");
    paramaterChoice = Convert.ToChar(Console.ReadLine());

    switch (paramaterChoice)
    {
        case 'r':
        case 'R':
            Console.WriteLine("Enter the Radius of the Circle");
            circleRadius = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleRadius * circleRadius;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
        case 'd':
        case 'D':
            Console.WriteLine("Enter the Diameter of the Circle");
            circleDiameter = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleDiameter * circleDiameter / 4;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
    }

    // The error occurs on the next line:
    Console.WriteLine("Parameter: {0}, Radius: {1:f2}, Diameter: {2:f2}, Area: {3:f2}",
        paramaterChoice, circleRadius, circleDiameter, circleArea);

    Console.WriteLine("\nProgram Info: Calculates the Area of a circle");
}
</code>```

答:
As others have said, the reason you're getting the error is that not all your values are getting assigned before you use them. So you need to either initialize them when you declare them, or ensure that both values are assigned in each case statement (and include a default statement that assigns them).

There is an additional problem if the user does not enter a valid double for the radius/diameter input. What I like to do for collecting strongly typed information from the user is to write methods that take in a prompt string and return the strong type that you expect. Then, in that method, keep looping until the user enters a valid value.

For example:

```<code>/// <summary>
/// Gets a strongly typed (double) value from the Console
/// </summary>
/// <param name="prompt">The initial message to display to the user</param>
/// <returns>User input converted to a double</returns>
private static double GetDoubleFromUser(string prompt)
{
    double value;

    // Write the prompt text and get input from user
    Console.Write(prompt);
    string input = Console.ReadLine();

    // If input can't be converted to a double, keep trying
    while (!double.TryParse(input, out value))
    {
        Console.Write($"'{input}' is not a valid number. Please try again: ");
        input = Console.ReadLine();
    }

    // Input was successfully converted!
    return value;
}
</code>```

Then, you can use this in your code as in the example below. Notice that I also made a couple of other changes:

Get the user input using ReadKey. This reads in the key they pressed, and you don't have to worry about comparing upper or lower case.

Set the value for the item that the user didn't enter (either radius or diameter) in the switch cases.

Use the built-in Math properties/methods to get PI and to "square" the radius.

Set a bool variable called exit to true if the user doesn't enter a R or a D, and then check the value of this before displaying any output (that way we don't display output that they didn't enter, and allow the user to quit in an easy way).

For example:

```<code>private static void Main()
{
    double circleRadius = 0, circleDiameter = 0, circleArea = 0;
    bool exit = false;

    Console.Write("Press 'R' for radius, 'D' for diameter, or any other key to exit: ");
    ConsoleKeyInfo input = Console.ReadKey();
    Console.WriteLine();

    switch (input.Key)
    {
        case ConsoleKey.R:
            circleRadius = GetDoubleFromUser("Enter the radius of the circle: ");
            circleDiameter = circleRadius * 2;
            break;
        case ConsoleKey.D:
            circleDiameter = GetDoubleFromUser("Enter the diameter of the circle: ");
            circleRadius = circleDiameter / 2;
            break;
        default:
            exit = true;
            break;
    }

    if (exit)
    {
        Console.WriteLine("Program exiting.");
    }
    else
    {
        circleArea = Math.PI * Math.Pow(circleRadius, 2);

        Console.WriteLine("Input: {0}, Radius: {1:f2}, Diameter: {2:f2}, Area: {3:f2}",
            input.KeyChar, circleRadius, circleDiameter, circleArea);

        Console.WriteLine("\nProgram Info: Calculates the Area of a circle");
    }

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Body:
For the following code in C#, why are the errors obtained: -

Error 1: Use of unassigned local variable circleArea

  Error 2: Use of unassigned local variable circleRadius

  Error 3: Use of unassigned local variable circleDiameter

but not for paramaterChoice; even though it also is an uninitialized local variable?

static void Main(string[] args)
{
    char paramaterChoice;
    double circleRadius, circleDiameter, circleArea;
    const double PI=3.14;

    Console.WriteLine("If you know the radius press r or R, If you know the diameter press d or D");
    paramaterChoice = Convert.ToChar(Console.ReadLine());

    switch (paramaterChoice)
    {
        case 'r':
        case 'R':
            Console.WriteLine("Enter the Radius of the Circle");
            circleRadius = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleRadius * circleRadius;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
        case 'd':
        case 'D':
            Console.WriteLine("Enter the Diameter of the Circle");
            circleDiameter = Convert.ToDouble(Console.ReadLine());
            circleArea = PI * circleDiameter * circleDiameter / 4;
            //Console.WriteLine("Area of Cirle is: {0:f2}", circleArea);
            break;
    }

    // The error occurs on the next line:
    Console.WriteLine("Parameter: {0}, Radius: {1:f2}, Diameter: {2:f2}, Area: {3:f2}",
        paramaterChoice, circleRadius, circleDiameter, circleArea);

    Console.WriteLine("\nProgram Info: Calculates the Area of a circle");
}

Body:
As others have said, the reason you're getting the error is that not all your values are getting assigned before you use them. So you need to either initialize them when you declare them, or ensure that both values are assigned in each case statement (and include a default statement that assigns them).

There is an additional problem if the user does not enter a valid double for the radius/diameter input. What I like to do for collecting strongly typed information from the user is to write methods that take in a prompt string and return the strong type that you expect. Then, in that method, keep looping until the user enters a valid value.

For example:

/// <summary>
/// Gets a strongly typed (double) value from the Console
/// </summary>
/// <param name="prompt">The initial message to display to the user</param>
/// <returns>User input converted to a double</returns>
private static double GetDoubleFromUser(string prompt)
{
    double value;

    // Write the prompt text and get input from user
    Console.Write(prompt);
    string input = Console.ReadLine();

    // If input can't be converted to a double, keep trying
    while (!double.TryParse(input, out value))
    {
        Console.Write($"'{input}' is not a valid number. Please try again: ");
        input = Console.ReadLine();
    }

    // Input was successfully converted!
    return value;
}

Then, you can use this in your code as in the example below. Notice that I also made a couple of other changes:

Get the user input using ReadKey. This reads in the key they pressed, and you don't have to worry about comparing upper or lower case.

Set the value for the item that the user didn't enter (either radius or diameter) in the switch cases.

Use the built-in Math properties/methods to get PI and to "square" the radius.

Set a bool variable called exit to true if the user doesn't enter a R or a D, and then check the value of this before displaying any output (that way we don't display output that they didn't enter, and allow the user to quit in an easy way).

For example:

private static void Main()
{
    double circleRadius = 0, circleDiameter = 0, circleArea = 0;
    bool exit = false;

    Console.Write("Press 'R' for radius, 'D' for diameter, or any other key to exit: ");
    ConsoleKeyInfo input = Console.ReadKey();
    Console.WriteLine();

    switch (input.Key)
    {
        case ConsoleKey.R:
            circleRadius = GetDoubleFromUser("Enter the radius of the circle: ");
            circleDiameter = circleRadius * 2;
            break;
        case ConsoleKey.D:
            circleDiameter = GetDoubleFromUser("Enter the diameter of the circle: ");
            circleRadius = circleDiameter / 2;
            break;
        default:
            exit = true;
            break;
    }

    if (exit)
    {
        Console.WriteLine("Program exiting.");
    }
    else
    {
        circleArea = Math.PI * Math.Pow(circleRadius, 2);

        Console.WriteLine("Input: {0}, Radius: {1:f2}, Diameter: {2:f2}, Area: {3:f2}",
            input.KeyChar, circleRadius, circleDiameter, circleArea);

        Console.WriteLine("\nProgram Info: Calculates the Area of a circle");
    }

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}


问:
Is there a simple way to style text with gradients?
it is possible to style a background with gradients like:
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#eeeeee), color-stop(100%,#cccccc));

Is there a way to style text with gradients?I've been looking for sth like:
color-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#eeeeee), color-stop(100%,#cccccc));but wasn't able to find anything simple.

Thanks for your help.

答:
its not possible with pure CSS unless you use a image to cover the font:
http://www.webdesignerwall.com/tutorials/css-gradient-text-effect/
You could use the same technique but use a color to transparent gradient in the overlay element.

here is an example with pure CSS and an additional element: http://jsfiddle.net/Lub7z/

ContentLicense: CC BY-SA 2.5


问:
Xamarin listview outlining issues
I am trying to make a listview in Xamarin with 3 columns, having 1 imageview and 2 textviews. The imageview should be aligned to the left (working), the first textview should be in the middle, all aligned under each other, so that all first letters align. and the 3rd column should be all the way on the right and this is not working, the value of the 3rd column is directly set behind the text of the 2nd column.

The text should be centered verticaly in the row, but this is also not
  working although the android:gravity="center_vertical" is set.

My code :

Listview with everything wrong displayed as shown :

答:
Try this:</p>

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_item_menu"
    android:layout_width="fill_parent"
    android:layout_height="50dip">

    <ImageView
        android:id="@+id/layout_item_menu_image"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:src="@drawable/menu_image" />

    <TextView
        android:id="@+id/layout_item_menu_text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignBottom="@id/layout_item_menu_image"
        android:layout_marginRight="20dp"
        android:text="TEXT 2"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/layout_item_menu_text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/layout_item_menu_image"
        android:layout_toLeftOf="@id/layout_item_menu_text2"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:text="TEXT 1"
        android:textColor="#000000"
        android:textSize="18sp" />

</RelativeLayout>
</code>```

Title: Xamarin listview outlining issues

Body:
Try this:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_item_menu"
    android:layout_width="fill_parent"
    android:layout_height="50dip">

    <ImageView
        android:id="@+id/layout_item_menu_image"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:src="@drawable/menu_image" />

    <TextView
        android:id="@+id/layout_item_menu_text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignBottom="@id/layout_item_menu_image"
        android:layout_marginRight="20dp"
        android:text="TEXT 2"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/layout_item_menu_text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/layout_item_menu_image"
        android:layout_toLeftOf="@id/layout_item_menu_text2"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:text="TEXT 1"
        android:textColor="#000000"
        android:textSize="18sp" />

</RelativeLayout>


问:
Get information in two steps with javascript
I am trying to get some information from the user in two steps with javascript.
The user will provide this information by clicking on two different buttons.

I am struggling with the fact that the two actions (button clicks) will be triggered separately. Each time I will get a piece of information and I can do the magic only when I have both pieces.

This is what I tried (simplified to get to the core of my problem):

HTML

```<code><div class="container-1">
    <button class="my-btn" id="red">
        Color1
    </button>
    <button class="my-btn" id="green">
        Color2
    </button>
    <button class="my-btn" id="blue">
        Color3
    </button>
</div>
<hr>
<div class="container-2">
    <button class="my-btn" id="dog">
        Animal1
    </button>
    <button class="my-btn" id="cat">
        Animal2
    </button>
    <button class="my-btn" id="mouse">
        Animal3
    </button>
</div>
</code>```

javascript

```<code>sumUp = function(data) {
  first = data.btn1;
  second = data.btn2;
  alert('You chose a ' + first + ' ' + second);
};
$(".my-btn").click(function() {
  var val1 = $(this).attr('id');
  $(".container-2 .my-btn").click(function() {
    var val2 = $(this).attr('id');
  });
  var data = {
    btn1: val1,
    btn2: val2
  };
  sumUp(data);
});
</code>```

This jsfiddle will help to understand better what I am trying. It could be assumed that first the color would always be selected and then the animal.

In this example, I would just need to get the alert saying "You chose a red cat", or whatever combination depending on the buttons clicked.

What am I doing wrong and how could it be done?

答:
Here is my solution

```<code>   <div class="container-1">
    <button class="my-btn" id="red">
        Color1
    </button>
    <button class="my-btn" id="green">
        Color2
    </button>
    <button class="my-btn" id="blue">
        Color3
    </button>
</div>
<hr>
<div class="container-2">
    <button class="my-btn" id="dog">
        Animal1
    </button>
    <button class="my-btn" id="cat">
        Animal2
    </button>
    <button class="my-btn" id="mouse">
        Animal3
    </button>
</div>
</code>```

Javascript part

```<code> DATA={
    color:"",
  animal:""
}

sumUp = function(data){
    first = DATA.color;
    second = DATA.animal;
    if(DATA.color != "" && DATA.animal !=""){
        alert('You chose a ' + first + ' ' + second);
    }

};

$(".container-2 .my-btn").click(function() {
        DATA.animal = $(this).attr('id');
    sumUp(DATA)
});
$(".container-1 .my-btn").click(function() {
        DATA.color = $(this).attr('id');
    sumUp(DATA)
});
</code>```

Body:
I am trying to get some information from the user in two steps with javascript.
The user will provide this information by clicking on two different buttons.

I am struggling with the fact that the two actions (button clicks) will be triggered separately. Each time I will get a piece of information and I can do the magic only when I have both pieces.

This is what I tried (simplified to get to the core of my problem):

HTML

    <button class="my-btn" id="red">
        Color1
    </button>
    <button class="my-btn" id="green">
        Color2
    </button>
    <button class="my-btn" id="blue">
        Color3
    </button>

    <button class="my-btn" id="dog">
        Animal1
    </button>
    <button class="my-btn" id="cat">
        Animal2
    </button>
    <button class="my-btn" id="mouse">
        Animal3
    </button>

javascript

sumUp = function(data) {
  first = data.btn1;
  second = data.btn2;
  alert('You chose a ' + first + ' ' + second);
};
$(".my-btn").click(function() {
  var val1 = $(this).attr('id');
  $(".container-2 .my-btn").click(function() {
    var val2 = $(this).attr('id');
  });
  var data = {
    btn1: val1,
    btn2: val2
  };
  sumUp(data);
});

This jsfiddle will help to understand better what I am trying. It could be assumed that first the color would always be selected and then the animal.

In this example, I would just need to get the alert saying "You chose a red cat", or whatever combination depending on the buttons clicked.

What am I doing wrong and how could it be done?

Body:
Here is my solution

   <div class="container-1">
    <button class="my-btn" id="red">
        Color1
    </button>
    <button class="my-btn" id="green">
        Color2
    </button>
    <button class="my-btn" id="blue">
        Color3
    </button>
</div>
<hr>
<div class="container-2">
    <button class="my-btn" id="dog">
        Animal1
    </button>
    <button class="my-btn" id="cat">
        Animal2
    </button>
    <button class="my-btn" id="mouse">
        Animal3
    </button>
</div>

Javascript part

 DATA={
    color:"",
  animal:""
}

sumUp = function(data){
    first = DATA.color;
    second = DATA.animal;
    if(DATA.color != "" && DATA.animal !=""){
        alert('You chose a ' + first + ' ' + second);
    }

};

$(".container-2 .my-btn").click(function() {
        DATA.animal = $(this).attr('id');
    sumUp(DATA)
});
$(".container-1 .my-btn").click(function() {
        DATA.color = $(this).attr('id');
    sumUp(DATA)
});


问:
How to determine the downloading file type before it actually starts downloading using javascript?
I am developing a chrome extension, in which I need to determine the original type of the file, and stop the downloading if I encounter certain type of file.
To determine the file type I have the following code.How to put this code to select the downloading file before it actually downloads.

```<code> const xhr = new XMLHttpRequest();
 xhr.open('GET', 'unicorn.png');
 xhr.responseType = 'arraybuffer';

 xhr.onload = () => {
 fileType(new Uint8Array(this.response));
 //=> {ext: 'png', mime: 'image/png'}
 };

 xhr.send();
</code>```

File type should be determined using "magic numbers" not string matching.

答:
Set .responseType to "blob", check .type of Blob

```<code>  xhr.responseType = "blob";

  xhr.onload = () => {
     console.log(xhr.response.type)
  };
</code>```

Body:
I am developing a chrome extension, in which I need to determine the original type of the file, and stop the downloading if I encounter certain type of file.
To determine the file type I have the following code.How to put this code to select the downloading file before it actually downloads.

 const xhr = new XMLHttpRequest();
 xhr.open('GET', 'unicorn.png');
 xhr.responseType = 'arraybuffer';

 xhr.onload = () => {
 fileType(new Uint8Array(this.response));
 //=> {ext: 'png', mime: 'image/png'}
 };

 xhr.send();

File type should be determined using "magic numbers" not string matching.

Body:
Set .responseType to "blob", check .type of Blob

  xhr.responseType = "blob";

  xhr.onload = () => {
     console.log(xhr.response.type)
  };


问:
pipe example between multiple child-process in C
When I working on pipe() function in C, I have confused a bit. My aim is to transfer data between child processes. I want each child to take an input from fd[0] and write to fd[1]. My code is here, but I couldnt obtain any result. Where is the mistake? How can I imagine pipe?

```<code>    int main()
    {

    char *arr = malloc(sizeof(int));
    int num;
    int fd[2];
    char *piping = malloc(10*sizeof(char));
    char *word = malloc(10*sizeof(char));

    while(1)
    {
        printf("enter the number of child: ");
        fflush(stdout);
        fgets(arr, 10, stdin);

        printf("enter word: ");
        fflush(stdout);
        fgets(word, 10, stdin);

        num = atoi(arr);

        pipe(fd);
        for(int i = 0; i < num; i++)
        {
                if(!fork())
                {
                        read(0, piping, 10);
                        if(i != 0)
                        {
                            dup2(fd[0],0);
                        }
                        if(i != num-1)
                        {
                            dup2(fd[1],1);
                        }
                        write(1, piping, 10);
                }
                else
                    wait(0);
        }
    }
    return 0;
   }
</code>```

答:
The immediate problem is that each child process waits to read something from its standard input (not the pipe) before it proceeds, and you're not feeding any input (or at least not enough for all the children).  Perhaps you meant to perform the dup2(), when you perform it at all, prior to the read().

Although fixing that issue will probably let your program run to completion, the general strategy is flawed in at least these ways:

the parent wait()s for each child before starting the next one.  That creates two kinds of issues

you don't have any actual concurrency.  What, then, was the point of forking?

if the children were writing more output to the pipe then they would be at risk of filling its buffer and therefore blocking.  That would produce a deadlock, because the buffer will be drained only by the next child, which is not started until its predecessor terminates.

every pair of processes is using the same pipe for communication.  This only works at all because the parent serializes execution of the children (as discussed above).  Since such serialization has inherent problems, among other reasons, you ordinarily want each pipe to be dedicated to exactly one pair of processes.

Body:
When I working on pipe() function in C, I have confused a bit. My aim is to transfer data between child processes. I want each child to take an input from fd[0] and write to fd[1]. My code is here, but I couldnt obtain any result. Where is the mistake? How can I imagine pipe?

    int main()
    {

    char *arr = malloc(sizeof(int));
    int num;
    int fd[2];
    char *piping = malloc(10*sizeof(char));
    char *word = malloc(10*sizeof(char));

    while(1)
    {
        printf("enter the number of child: ");
        fflush(stdout);
        fgets(arr, 10, stdin);

        printf("enter word: ");
        fflush(stdout);
        fgets(word, 10, stdin);

        num = atoi(arr);

        pipe(fd);
        for(int i = 0; i < num; i++)
        {
                if(!fork())
                {
                        read(0, piping, 10);
                        if(i != 0)
                        {
                            dup2(fd[0],0);
                        }
                        if(i != num-1)
                        {
                            dup2(fd[1],1);
                        }
                        write(1, piping, 10);
                }
                else
                    wait(0);
        }
    }
    return 0;
   }


问:
How to map a custom file extension to mono?
I have mapped *.xyz extension to my own custom handler in asp.net and can run it on Windows asp.net.

How can I do the same thing on mono (Linux/Apache - ubuntu)?

I have this in my web.config:

```<code><httpHandlers><add path="*.xyz" verb="*" type="MyCustomHandler,...">...
</code>```

I also added similar things to mod_mono.conf and several other files but still I get

http 404 The resource cannot be found.

答:
If you have AutoConfiguration enabled then you need to add:

```<code>AddType application/x-asp-net .m
</code>```

to mod_mono.conf, where .m is your custom extension.

If you have AutoConfiguartion disabled the you need to add:

```<code>AddHandler mono .m
</code>```

to your httpd.conf.

Body:
I have mapped *.xyz extension to my own custom handler in asp.net and can run it on Windows asp.net.

How can I do the same thing on mono (Linux/Apache - ubuntu)?

I have this in my web.config:

<httpHandlers><add path="*.xyz" verb="*" type="MyCustomHandler,...">...

I also added similar things to mod_mono.conf and several other files but still I get

http 404 The resource cannot be found.

Body:
If you have AutoConfiguration enabled then you need to add:

AddType application/x-asp-net .m

to mod_mono.conf, where .m is your custom extension.

If you have AutoConfiguartion disabled the you need to add:

AddHandler mono .m

to your httpd.conf.


问:
How do you save a Git diff to a file in NetBeans?
I've cloned the repository for the project I'm on and opened it in NetBeans and made some changes and logged into the ReviewBoard site and now I need to upload a diff file for others on the project to see my changes. When I click in NetBeans' menu bar on Team->Diff, I can see a diff between my working copy and my Head, which is what I want to diff. I can see the textual version if I want as well by clicking on the textual tab in the diff window. What I don't see is where I can click to save this diff as a .diff file that ReviewBoard wants me to upload. An image of my screen as I graphically diff:

答:
I've been able to save a patch file by first opening the diff window in the IDE:

```<code>Team -> Diff -> Diff to Head
</code>```

Then, when the diff is selected in the editor:

```<code>Team -> Patches -> Export Uncommited Changes
</code>```

(NetBeans 8.2)

Body:
I've been able to save a patch file by first opening the diff window in the IDE:

Team -> Diff -> Diff to Head

Then, when the diff is selected in the editor:

Team -> Patches -> Export Uncommited Changes

(NetBeans 8.2)


问:
array to pointpairlist (ZedGraph)
I'm trying to display some data using ZedGraph. The data was read in from a file, which is then stored in an array called heart_rate[x] which I'm trying to pass to the point pair list, however, it won't accept the string array. After searching, I assume it needs to be converted to double first. I've tried this but with no luck.

Here is the code that creates the array by reading data from a file. Ideally I don't want to change this, as I have other arrays written the same way, and this would require an entire program re-write.

```<code>                for (x = 0; x < hrm_data.Length; x = x + 6)
                {
                    heart_rate.Add(hrm_data[x]);
                }
</code>```

Here is where I set up ZedGraph, obviously missing code to pass the array to the point pair list.

```<code>            GraphPane myPane = z_graph.GraphPane;
            myPane.Title = "HRM Data";
            myPane.XAxis.Title = "Time";
            myPane.YAxis.Title = "Readings";
            PointPairList heart_rate_list = new PointPairList();
            LineItem heart_rate_curve = myPane.AddCurve("Heart Rate", heart_rate_list, Color.Red, SymbolType.Diamond);
            z_graph.AxisChange();
</code>```

EDIT

Here is an example of the file I'm reading in. The first column of data is heart rate readings, Using the for loop I am only selecting the first column and adding that to the array

```<code>91 43 56 78 45 78
91 43 56 78 45 78
91 43 56 78 45 78
91 43 56 78 45 78
</code>```

EDIT 2

Thankyou for all the help, I really appreciate it, however, I think I'm confusing everyone with what I'm asking for. This is a student project and I know some fellow students have done this that could help out.

答:
yes as you have mentioned the code is incomplete .

```<code>  PointPairList heart_rate_list = new PointPairList();
</code>```

since you have defined the list but you forgot you to set the parameters for it .Basically (x,y) ..thus you have to input all your array value as one of the parameters of x or y .Just make a loop to insert the value of array using foreach.
//taking  int x as time  for seconds add using

```<code>        foreach(int value in heart_rate)
       {        y=value;
         heart_rate_list.Add(x,y)
        };
</code>```

//now add it to the curve as you have done above

Title: array to pointpairlist (ZedGraph)

Body:
I'm trying to display some data using ZedGraph. The data was read in from a file, which is then stored in an array called heart_rate[x] which I'm trying to pass to the point pair list, however, it won't accept the string array. After searching, I assume it needs to be converted to double first. I've tried this but with no luck.

Here is the code that creates the array by reading data from a file. Ideally I don't want to change this, as I have other arrays written the same way, and this would require an entire program re-write.

                for (x = 0; x < hrm_data.Length; x = x + 6)
                {
                    heart_rate.Add(hrm_data[x]);
                }

Here is where I set up ZedGraph, obviously missing code to pass the array to the point pair list.

            GraphPane myPane = z_graph.GraphPane;
            myPane.Title = "HRM Data";
            myPane.XAxis.Title = "Time";
            myPane.YAxis.Title = "Readings";
            PointPairList heart_rate_list = new PointPairList();
            LineItem heart_rate_curve = myPane.AddCurve("Heart Rate", heart_rate_list, Color.Red, SymbolType.Diamond);
            z_graph.AxisChange();

EDIT

Here is an example of the file I'm reading in. The first column of data is heart rate readings, Using the for loop I am only selecting the first column and adding that to the array

91 43 56 78 45 78
91 43 56 78 45 78
91 43 56 78 45 78
91 43 56 78 45 78

EDIT 2

Thankyou for all the help, I really appreciate it, however, I think I'm confusing everyone with what I'm asking for. This is a student project and I know some fellow students have done this that could help out.

Body:
yes as you have mentioned the code is incomplete .

  PointPairList heart_rate_list = new PointPairList();

since you have defined the list but you forgot you to set the parameters for it .Basically (x,y) ..thus you have to input all your array value as one of the parameters of x or y .Just make a loop to insert the value of array using foreach.
//taking  int x as time  for seconds add using

        foreach(int value in heart_rate)
       {        y=value;
         heart_rate_list.Add(x,y)
        };

//now add it to the curve as you have done above

ContentLicense: CC BY-SA 4.0


答:
There is a ton wrong with this. Forget about all the pipe stuff for now and just look at the forking. The code looks like this:

```<code>for(int i = 0; i < num; i++)
{
    if (!fork())
    {
        // in child do something
    }
    else
        wait(0);
}
</code>```

The parent goes into the loop, creates the first child and waits for it.

The first child goes into the second iteration of the loop, creates a child and waits for it

The first child's child goes into the third iteration of the loop, creates a child and waits for it.

and so on until we have an ancestor chain of num - 1 parents and children. The num - 1'th child simply exits, which means its parent will stop waiting and go on to the next iteration of the loop. It too will exit, so the num-2'th child will stop waiting, but it still has an iteration of the loop to go, so it creates another child and waits for it.

You are creating vastly more children then you probably want because you have forgotten that parent and child both carry on executing the same code after the fork. You probably want the if part of the if ... else to contain exit(0); as its last statement.

However, your problems are not over there. In the if part, you first try to read from stdin which means that all of your many child processes will block waiting on input from the terminal.

The dup stuff is currently pointless. Apart form the fact that you don't dup the read end of the pipe to stdin until after you have read stdin, when you fork you still have access to the pipe unless you call exec so why not use it directly. The child that writes can write directly to fd[1] and the child that reads can read directly from fd[0].

Title: pipe example between multiple child-process in C

Body:
There is a ton wrong with this. Forget about all the pipe stuff for now and just look at the forking. The code looks like this:

for(int i = 0; i < num; i++)
{
    if (!fork())
    {
        // in child do something
    }
    else
        wait(0);
}

The parent goes into the loop, creates the first child and waits for it.

The first child goes into the second iteration of the loop, creates a child and waits for it

The first child's child goes into the third iteration of the loop, creates a child and waits for it.

and so on until we have an ancestor chain of num - 1 parents and children. The num - 1'th child simply exits, which means its parent will stop waiting and go on to the next iteration of the loop. It too will exit, so the num-2'th child will stop waiting, but it still has an iteration of the loop to go, so it creates another child and waits for it.

You are creating vastly more children then you probably want because you have forgotten that parent and child both carry on executing the same code after the fork. You probably want the if part of the if ... else to contain exit(0); as its last statement.

However, your problems are not over there. In the if part, you first try to read from stdin which means that all of your many child processes will block waiting on input from the terminal.

The dup stuff is currently pointless. Apart form the fact that you don't dup the read end of the pipe to stdin until after you have read stdin, when you fork you still have access to the pipe unless you call exec so why not use it directly. The child that writes can write directly to fd[1] and the child that reads can read directly from fd[0].


问:
Is there a true single-pair shortest path algorithm?
I came across this term today "single-pair shortest path problem". I was wondering if a single-pair shortest path algorithm exists for weighted graphs. My reasoning might be flawed, but I imagine that if you want to find the shortest path between A and Z, you absolutely have to know the shortest path from A to B, C, D, ... Y.

If you do not know the latter you can not be sure that your path is in fact the shortest one. Thus for me any shortest path algorithm has to compute the shortest path from A to every other vertex in the graph, in order to get the shortest path from A to Z.

Is this correct?

PS: If yes, any research paper properly proving this?

答:
For non-negative weighted edges graph problem Dijkstra itself solves given problem.

A quote from wiki

The algorithm exists in many variants; Dijkstra's original variant
  found the shortest path between two nodes, but a more common variant
  fixes a single node as the "source" node and finds shortest paths from
  the source to all other nodes in the graph, producing a shortest-path
  tree.

Consider following pseudo code from wiki:

```<code> 1  function Dijkstra(Graph, source):
 2
 3      create vertex set Q
 4
 5      for each vertex v in Graph:             // Initialization
 6          dist[v] ← INFINITY                  // Unknown distance from source to v
 7          prev[v] ← UNDEFINED                 // Previous node in optimal path from source
 8          add v to Q                          // All nodes initially in Q (unvisited nodes)
 9
10      dist[source] ← 0                        // Distance from source to source
11
12      while Q is not empty:
13          u ← vertex in Q with min dist[u]    // Node with the least distance will be selected first
14          remove u from Q
15
16          for each neighbor v of u:           // where v is still in Q.
17              alt ← dist[u] + length(u, v)
18              if alt < dist[v]:               // A shorter path to v has been found
19                  dist[v] ← alt
20                  prev[v] ← u
21
22      return dist[], prev[]
</code>```

with each new iteration of while (12), first step it to pick the vertex u with shortest distance from the remaining set Q (13) and then that vertex is removed from the Q (14) notifying that shortest distance to u has been achieved. If u is your destination then you can halt without considering further edges.

Note that all vertices were used but not all edges and shortest path to all vertices was not yet found.

Body:
For non-negative weighted edges graph problem Dijkstra itself solves given problem.

A quote from wiki

The algorithm exists in many variants; Dijkstra's original variant
  found the shortest path between two nodes, but a more common variant
  fixes a single node as the "source" node and finds shortest paths from
  the source to all other nodes in the graph, producing a shortest-path
  tree.

Consider following pseudo code from wiki:

 1  function Dijkstra(Graph, source):
 2
 3      create vertex set Q
 4
 5      for each vertex v in Graph:             // Initialization
 6          dist[v] ← INFINITY                  // Unknown distance from source to v
 7          prev[v] ← UNDEFINED                 // Previous node in optimal path from source
 8          add v to Q                          // All nodes initially in Q (unvisited nodes)
 9
10      dist[source] ← 0                        // Distance from source to source
11
12      while Q is not empty:
13          u ← vertex in Q with min dist[u]    // Node with the least distance will be selected first
14          remove u from Q
15
16          for each neighbor v of u:           // where v is still in Q.
17              alt ← dist[u] + length(u, v)
18              if alt < dist[v]:               // A shorter path to v has been found
19                  dist[v] ← alt
20                  prev[v] ← u
21
22      return dist[], prev[]

with each new iteration of while (12), first step it to pick the vertex u with shortest distance from the remaining set Q (13) and then that vertex is removed from the Q (14) notifying that shortest distance to u has been achieved. If u is your destination then you can halt without considering further edges.

Note that all vertices were used but not all edges and shortest path to all vertices was not yet found.


问:
Substitution for INTERSECT in phpMyAdmin
I'm trying to use an intersect query on phpMyAdmin but obviously it doesn't supports INTERSECT, at least I'm pretty sure it doesn't. This is the query I'm trying to use, but what is another way I could put it to where I don't use INTERSECT?

```<code>SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83649
INTERSECT
SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83677
ORDER BY cust_lname, cust_fname;
</code>```

答:
You're right, MySQL doesn't support INTERSECT.

```<code>SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code)
WHERE employee_id IN (83649, 83677)
GROUP BY cust_code, cust_fname, cust_lname
HAVING COUNT(DISTINCT employee_id) = 2
</code>```

Update: MySQL 8.0.31 (released 2022-10-11) supports INTERSECT. See https://lefred.be/content/intersect-and-except-in-mysql-8-0/

Body:
I'm trying to use an intersect query on phpMyAdmin but obviously it doesn't supports INTERSECT, at least I'm pretty sure it doesn't. This is the query I'm trying to use, but what is another way I could put it to where I don't use INTERSECT?

SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83649
INTERSECT
SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83677
ORDER BY cust_lname, cust_fname;

Body:
You're right, MySQL doesn't support INTERSECT.

SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code)
WHERE employee_id IN (83649, 83677)
GROUP BY cust_code, cust_fname, cust_lname
HAVING COUNT(DISTINCT employee_id) = 2

Update: MySQL 8.0.31 (released 2022-10-11) supports INTERSECT. See https://lefred.be/content/intersect-and-except-in-mysql-8-0/


问:
PHP - Issue with pcntl in PHP 7.0+. Potential bug
I have encountered an issue with the pcntl signal handling i PHP 7.0+. The problem is that alarms aren't getting scheduled in some cases.

The following example works in PHP 5.6 but neither in PHP 7.0 or 7.1.

file.php

```<code>require_once('file2.php');

declare(ticks = 1);

// Add an alarm listener
pcntl_signal(SIGALRM, function() {
    var_dump("Triggered");

    // Re-schedule the alarm
    pcntl_alarm(5);
});

// Schedule the initial alarm
pcntl_alarm(5);

test();
</code>```

file2.php

```<code>function test() {
    while(true) {
        sleep(2);
    }
}
</code>```

Snippet working in both PHP 5.6 and 7.0+. If we combine the code into one file then it is working.

```<code>declare(ticks = 1);

// Add a alarm listener
pcntl_signal(SIGALRM, function() {
    var_dump("here");

    // Re-schedule the alarm to be triggered
    pcntl_alarm(5);
});

// Set the initial alarm
pcntl_alarm(5);

function test() {
    while(true) {
        sleep(2);
    }
}

test();
</code>```

答:
The issue is related to https://bugs.php.net/bug.php?id=71448#1463246578.

pcntl_async_signals() which was introduced in 7.1 solves the issue.

Body:
I have encountered an issue with the pcntl signal handling i PHP 7.0+. The problem is that alarms aren't getting scheduled in some cases.

The following example works in PHP 5.6 but neither in PHP 7.0 or 7.1.

file.php

require_once('file2.php');

declare(ticks = 1);

// Add an alarm listener
pcntl_signal(SIGALRM, function() {
    var_dump("Triggered");

    // Re-schedule the alarm
    pcntl_alarm(5);
});

// Schedule the initial alarm
pcntl_alarm(5);

test();

file2.php

function test() {
    while(true) {
        sleep(2);
    }
}

Snippet working in both PHP 5.6 and 7.0+. If we combine the code into one file then it is working.

declare(ticks = 1);

// Add a alarm listener
pcntl_signal(SIGALRM, function() {
    var_dump("here");

    // Re-schedule the alarm to be triggered
    pcntl_alarm(5);
});

// Set the initial alarm
pcntl_alarm(5);

function test() {
    while(true) {
        sleep(2);
    }
}

test();


问:
How to convert the values of a Map of List to a single List
How is the best (efficient and simple) way to convert the values of a Map<Object1, List<Object2>> to a List<Object2>. Should I simply iterate over all entries and adAll the items to a list?

答:
Just found it:</p>

```<code> List<Object2> list = myMap.values()
                           .stream()
                           .flatMap(item -> item.stream())
                           .collect(Collectors.toList()));
</code>```

Body:
Just found it:

 List<Object2> list = myMap.values()
                           .stream()
                           .flatMap(item -> item.stream())
                           .collect(Collectors.toList()));


问:
Using Typescript, Type guard and reflection to validate objects against types
I am trying to DRY, by using ES6, Typescript, I have created an interface, call it IUser which has properties.

What is the best way to know if an object conforms to the interface at runtime?

How can I get a list of the errors? The IDE knows which properties are missing, why I can't?

I have seen examples using reflection and other techniques which test one property at a time. But there must be a way to easily know if an object implements all properties, and if not which ones.

IKnowing that some properties are optional '?' and we know the type, this should be possible!

```<code>type IUser = {
    name: string
    age?: number
    gender: string | any
}

// Assume this object gets created at runtime.
let john = {
    name: "John"
}

let errors = ValidateThis(john, IUser)
// Return something like this ["Error: Missing value gender", "Warning: Missing optional value age"]
</code>```

I don't want to specify each property, so there must be a way to iterate the type properties.

I don't want to use any of the existing npm projects I found which force me to create, yet a separate schema file or use a class.

答: This doesn't exist. You should use one of the existing NPM projects, or write yet another.</p>

Body:
I am trying to DRY, by using ES6, Typescript, I have created an interface, call it IUser which has properties.

What is the best way to know if an object conforms to the interface at runtime?

How can I get a list of the errors? The IDE knows which properties are missing, why I can't?

I have seen examples using reflection and other techniques which test one property at a time. But there must be a way to easily know if an object implements all properties, and if not which ones.

IKnowing that some properties are optional '?' and we know the type, this should be possible!

type IUser = {
    name: string
    age?: number
    gender: string | any
}

// Assume this object gets created at runtime.
let john = {
    name: "John"
}

let errors = ValidateThis(john, IUser)
// Return something like this ["Error: Missing value gender", "Warning: Missing optional value age"]

I don't want to specify each property, so there must be a way to iterate the type properties.

I don't want to use any of the existing npm projects I found which force me to create, yet a separate schema file or use a class.


答:
Try using this node module file-type . This should serve your purpose
https://www.npmjs.com/package/file-type</p>

Title: How to determine the downloading file type before it actually starts downloading using javascript?


问:
Why am I getting a UNIQUE Constraint Failure in my SQLite3 table
I have been searching StackOverflow, SQLite.com, and Google for help, but haven't found what I'm looking for yet.

I need to combine two older tables into one new table, but the PRIMARY KEY and UNIQUE constraints seem to be fighting with each other (I am getting a Constraint Failed error once it gets to the INSERT statement).  The script will run if I remove the UNIQUE constraint, but then I have duplicate CamIndex records.

```<code>CREATE TABLE tmpTable(
RowID      INTEGER   PRIMARY KEY AUTOINCREMENT,
CamIndex   INTEGER   UNIQUE NOT NULL,
LenIndex   INTEGER   NOT NULL,
CamDesc    TEXT,
LenDesc    TEXT
);

INSERT INTO tmpTable(
CamIndex,
LenIndex,
CamDesc,
LenDesc
)

SELECT
TblA.CAM_INDEX,
TblB.LEN_INDEX,
TblA.CAM_DESC,
TblB.LEN_DESC

FROM TblA
LEFT JOIN TblB on TblA.CAM_INDEX = TblB.CAM_INDEX;
</code>```

How do I make the CamIndex column UNIQUE and keep RowID as Primary key?

This didn't work either:

```<code>CREATE TABLE tmpTable(
RowID      INTEGER   PRIMARY KEY AUTOINCREMENT,
CamIndex   INTEGER   NOT NULL,
LenIndex   INTEGER   NOT NULL,
CamDesc    TEXT,
LenDesc    TEXT,
UNIQUE(CamIndex)
);
</code>```

I'm using SQLite so I can't add the UNIQUE constraint with the ALTER Table statement.

答:
Your assumption about the uniqueness of your data is invalid.  Given what you had remarked in the comments, the result of your SELECT statement produces the same CamIndex for different combinations of LenIndex, CamDesc, or LenDesc.  Given that, you cannot place a unique constraint on CamIndex.

You will need to reevaluate your SELECT query to ensure that you're not getting bogus values from it before you can constrain your table.

Body:
I have been searching StackOverflow, SQLite.com, and Google for help, but haven't found what I'm looking for yet.

I need to combine two older tables into one new table, but the PRIMARY KEY and UNIQUE constraints seem to be fighting with each other (I am getting a Constraint Failed error once it gets to the INSERT statement).  The script will run if I remove the UNIQUE constraint, but then I have duplicate CamIndex records.

CREATE TABLE tmpTable(
RowID      INTEGER   PRIMARY KEY AUTOINCREMENT,
CamIndex   INTEGER   UNIQUE NOT NULL,
LenIndex   INTEGER   NOT NULL,
CamDesc    TEXT,
LenDesc    TEXT
);

INSERT INTO tmpTable(
CamIndex,
LenIndex,
CamDesc,
LenDesc
)

SELECT
TblA.CAM_INDEX,
TblB.LEN_INDEX,
TblA.CAM_DESC,
TblB.LEN_DESC

FROM TblA
LEFT JOIN TblB on TblA.CAM_INDEX = TblB.CAM_INDEX;

How do I make the CamIndex column UNIQUE and keep RowID as Primary key?

This didn't work either:

CREATE TABLE tmpTable(
RowID      INTEGER   PRIMARY KEY AUTOINCREMENT,
CamIndex   INTEGER   NOT NULL,
LenIndex   INTEGER   NOT NULL,
CamDesc    TEXT,
LenDesc    TEXT,
UNIQUE(CamIndex)
);

I'm using SQLite so I can't add the UNIQUE constraint with the ALTER Table statement.


问:
Asp.net MVC Authentication issue
I created two different asp.net MVC application using the default template, and launches the two simultaneously, when I login with site a, and refresh site b, site b tries to use the login detail of site a. How do I stop it?</p>

答:
Authentication is persisted via cookies and cookies are domain-bound. All cookies tied to the domain will be sent to a request to that domain, regardless of how many actual websites there are in the mix. Although you haven't specified, you're most likely in development and loading the sites under different localhost ports. It's important to know that a different port is not enough to prevent cookies from being shared. In all cases, when developing locally, the domain will be localhost and cookies will be shared between all sites running on localhost.

You have a couple of options. The simplest option is to simply customize the auth cookie name for each site. If you're using ASP.NET Identity, just add the following property to your cookie auth config:

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    ...
    CookieName = "foo",
});
</code>```

If the two sites use different auth cookies (based on the name), it won't matter if they both receive both; they'll only look at the one that belongs to them.

The second option is to use something other than localhost. For example, you can make use of something like localtest.me. It's a domain that has been helpfully set up to redirect all subdomains to localhost. That way you can test your sites via something like site1.localtest.me:12345 and site2.localtest.met:54321 (notice that the ports will be the same as they were with just localhost). However, since these are now different domains, the cookies will no longer be shared. However, doing this requires making changes to IIS Express' ApplicationHost.config file, and you could potentially mess something up if you're not careful. It also will be confined to your specific machine, so any other developers would need to make the same change on their machines. Changing the cookie name will be universally applied.

Title: Asp.net MVC Authentication issue

Body:
Authentication is persisted via cookies and cookies are domain-bound. All cookies tied to the domain will be sent to a request to that domain, regardless of how many actual websites there are in the mix. Although you haven't specified, you're most likely in development and loading the sites under different localhost ports. It's important to know that a different port is not enough to prevent cookies from being shared. In all cases, when developing locally, the domain will be localhost and cookies will be shared between all sites running on localhost.

You have a couple of options. The simplest option is to simply customize the auth cookie name for each site. If you're using ASP.NET Identity, just add the following property to your cookie auth config:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    ...
    CookieName = "foo",
});

If the two sites use different auth cookies (based on the name), it won't matter if they both receive both; they'll only look at the one that belongs to them.

The second option is to use something other than localhost. For example, you can make use of something like localtest.me. It's a domain that has been helpfully set up to redirect all subdomains to localhost. That way you can test your sites via something like site1.localtest.me:12345 and site2.localtest.met:54321 (notice that the ports will be the same as they were with just localhost). However, since these are now different domains, the cookies will no longer be shared. However, doing this requires making changes to IIS Express' ApplicationHost.config file, and you could potentially mess something up if you're not careful. It also will be confined to your specific machine, so any other developers would need to make the same change on their machines. Changing the cookie name will be universally applied.


问:
How to sign AAR Artifacts in Android?
I'm currently developing a .AAR android library and I would like to sign the released artifacts with my own key, so that I can determine if a fake aar with the same name and functionality has been released by mine or not.

Notice 1 :

I want to be able to check the authenticity of my library programmatically, even if a fakely-cooked one, is forging just part of the functionality of my aar file.

Notice 2 :

I am not going to publish this aar into maven, sonatype or any other public repository. So I'm going to sign it for a typical release flow like signing an apk file.

答:
You can generate it by execute:

```<code>./gradlew assembleRelease
</code>```

Or from gradle menu, on the right side of the Android Studio, select YourLibraryProject->Tasks->Build->AssembleRelease.

But of course you need to add the signing key in your library project. Please read at Sign Your App

Title: How to sign AAR Artifacts in Android?

Body:
You can generate it by execute:

./gradlew assembleRelease

Or from gradle menu, on the right side of the Android Studio, select YourLibraryProject->Tasks->Build->AssembleRelease.

But of course you need to add the signing key in your library project. Please read at Sign Your App


问:
Can you use math calculations on two alias columns in MySQL?
I want to do this:

```<code>SELECT SUM(currentbalance) AS 'current', SUM(principal) AS 'prin', 'current' + 'prin' AS 'total'
FROM dbase
</code>```

This doesn't work. I've also tried:

```<code>SELECT sum(currentbalance) AS 'current', sum(principal) AS 'prin', (SELECT 'current') + (SELECT 'prin') AS 'total'
FROM dbase
</code>```

@juergen-d @fqhv

Both answers worked perfectly. I thought that would be enough for me to understand how to add it to my current query. How can I implement this inside this query? I need to divide the "file_principal" by the "total_cash_cleared"? Thanks in Advance.

```<code>SELECT a.portfolio
       ,a.dateplaced
       ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
       ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
       ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
FROM dbase a
LEFT JOIN payments b
ON a.filenumber = b.filenumber
GROUP BY a.portfolio
ORDER BY STR_TO_DATE(a.dateplaced, '%m/%d/%Y') DESC
</code>```

I tried to add this in a comment but it was too long so I edited this post sorry.

答:
You can't reuse aliases in the same SELECT clause</p>

```<code>SELECT SUM(currentbalance) AS 'current',
       SUM(principal) AS 'prin',
       SUM(currentbalance + principal) AS 'total'
FROM dbase
</code>```

Body:
I want to do this:

SELECT SUM(currentbalance) AS 'current', SUM(principal) AS 'prin', 'current' + 'prin' AS 'total'
FROM dbase

This doesn't work. I've also tried:

SELECT sum(currentbalance) AS 'current', sum(principal) AS 'prin', (SELECT 'current') + (SELECT 'prin') AS 'total'
FROM dbase

@juergen-d @fqhv

Both answers worked perfectly. I thought that would be enough for me to understand how to add it to my current query. How can I implement this inside this query? I need to divide the "file_principal" by the "total_cash_cleared"? Thanks in Advance.

SELECT a.portfolio
       ,a.dateplaced
       ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
       ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
       ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
FROM dbase a
LEFT JOIN payments b
ON a.filenumber = b.filenumber
GROUP BY a.portfolio
ORDER BY STR_TO_DATE(a.dateplaced, '%m/%d/%Y') DESC

I tried to add this in a comment but it was too long so I edited this post sorry.

Body:
You can't reuse aliases in the same SELECT clause

SELECT SUM(currentbalance) AS 'current',
       SUM(principal) AS 'prin',
       SUM(currentbalance + principal) AS 'total'
FROM dbase


答:
You aren't the first person to ask for this. Interfaces don't exist at runtime, because TS fully erases all type information during compilation.

However, ECMAScript has standards-tracked a reflection API, and TypeScript is on-board with it. Your best bet for accomplishing this is to use experimentalDecoratorMetadata to automatically decorate your classes with type information, and then use the reflection API at runtime to validate. (Ctrl-f and search for experimentalDecoratorMetadata).

Title: Using Typescript, Type guard and reflection to validate objects against types


问:
Install cx_Oracle for Python
Am on Debian 5, I've been trying to install cx_oracle module for python without any success. First, I installed oracle-xe-client and its dependency (followed tutorial in the following link here).

Then, I used the scripts in /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/bin to populate environment variables such as PATH, ORACLE_HOME and NLS_LANG.

Once, this was completed, I tried to run:

```<code>sudo easy_install cx_oracle
</code>```

But I keep getting the following error:

```<code>Searching for cx-oracle
Reading http://pypi.python.org/simple/cx_oracle/
Reading http://cx-oracle.sourceforge.net
Reading http://starship.python.net/crew/atuining
Best match: cx-Oracle 5.0.4
Downloading http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4.tar.gz?download
Processing cx_Oracle-5.0.4.tar.gz
Running cx_Oracle-5.0.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-xsylvG/cx_Oracle-5.0.4/egg-dist-tmp-8KoqIx
error: cannot locate an Oracle software installation
</code>```

Any idea what I missed here?

答:
Thanks Burhan Khalid. Your advice to make a a soft link make my installation finally work.

To recap:

You need both the basic version and the SDK version of instant client

You need to set both LD_LIBRARY_PATH and ORACLE_HOME

You need to create a soft link (ln -s libclntsh.so.12.1 libclntsh.so in my    case)

None of this is documented anywhere, which is quite unbelievable and quite frustrating. I spent over 3 hours yesterday with failed builds because I didn't know to create a soft link.

Title: Install cx_Oracle for Python

Body:
Am on Debian 5, I've been trying to install cx_oracle module for python without any success. First, I installed oracle-xe-client and its dependency (followed tutorial in the following link here).

Then, I used the scripts in /usr/lib/oracle/xe/app/oracle/product/10.2.0/client/bin to populate environment variables such as PATH, ORACLE_HOME and NLS_LANG.

Once, this was completed, I tried to run:

sudo easy_install cx_oracle

But I keep getting the following error:

Searching for cx-oracle
Reading http://pypi.python.org/simple/cx_oracle/
Reading http://cx-oracle.sourceforge.net
Reading http://starship.python.net/crew/atuining
Best match: cx-Oracle 5.0.4
Downloading http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4.tar.gz?download
Processing cx_Oracle-5.0.4.tar.gz
Running cx_Oracle-5.0.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-xsylvG/cx_Oracle-5.0.4/egg-dist-tmp-8KoqIx
error: cannot locate an Oracle software installation

Any idea what I missed here?


问:
How to let my web-user-control determine automatically the url of the page where it's placed
```<code>        <asp:HyperLink
        ID="hyper1"
        runat="server"
        NavigateUrl='<%#string.Format("~/PLayer.aspx?ID={0}&Type={1}",Eval("arrange_by_id"),Eval("value"))%>'><%# Eval("value")%></asp:HyperLink>
</code>```

I've implemented this string format in my NavigateUrl to pass a dynamic querystring depending on the clicked item!

but you see the first part in the string format where it says "~/PLayer.aspx" i want the user control to automatically change this part according to where it's placed!

答:
how about this:</p>

```<code>NavigateUrl='<%#string.Format("{2}?ID={0}&Type={1}",
     Eval("arrange_by_id"),Eval("value"), Page.ResolveUrl("~/Palyer.aspx"))%>'
</code>```

Body:
        <asp:HyperLink
        ID="hyper1"
        runat="server"
        NavigateUrl='<%#string.Format("~/PLayer.aspx?ID={0}&Type={1}",Eval("arrange_by_id"),Eval("value"))%>'><%# Eval("value")%></asp:HyperLink>

I've implemented this string format in my NavigateUrl to pass a dynamic querystring depending on the clicked item!

but you see the first part in the string format where it says "~/PLayer.aspx" i want the user control to automatically change this part according to where it's placed!

Body:
how about this:

NavigateUrl='<%#string.Format("{2}?ID={0}&Type={1}",
     Eval("arrange_by_id"),Eval("value"), Page.ResolveUrl("~/Palyer.aspx"))%>'


问:
How to collapse a codename one accordion component programmatically?
How to collapse a codename one accordion component programmatically?

In my App, I have an accordion that expands a body container with some radio buttons. I want to collapse (Close) the  body automatically when a radio button is selected.

Adding more details about the problem:

My intention is create a  component that has same behavior of a ComboBox, but using Accodion component as base class.
I wrote a minimal use case that reproduce the problem and you can get its source file here MyApplication.java.
This code implements Steve Hanna answer.I suppose. And it didn't work for me.

 Running this code is simple.
Just create a CodeName One project and replace the MyApplication.java file generated by CodeName One Wizard and run the project (I use Netbeans IDE).
I put inside Radio Button action  the command to collapse the component as you can see at lines 271 til 280. But it didn't work.

答:
In the radio button's action listener, check if it's not selected and then call collapse(bodyContainer) on the accordion.

EDIT: There was a bug in Accordion that caused collapse() to work incorrectly.  This has now been fixed, and will be available in the next plugin update.

See this sample to see correct usage.

Note that after calling collapse(component), you should call the Accordion's animateLayout() method so that the change is shown.