问:
ExecuteNonQuery: CommandText property has not been initialized in c#
I am trying to insert data from dynamically generated textbox of gridview in the database. however, I am getting the exception of the CommandText property has not been initialized cmd.executeNonQuery();

```<code>private void InsertRecords(StringCollection sc)
{
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
    foreach (string item in sc)
    {
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
        }

    }
    //  conn.Open();
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))

    {
        using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
        {
            connn.Open();
            //      cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            connn.Close();
        }
        // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
    }
}
</code>```

答:
You're not loading the first part of your query into the StringBuilder.  Try this:

```<code>private void InsertRecords(StringCollection sc)
{
    const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
    StringBuilder sb = new StringBuilder(sqlStatement);
    string[] splitItems = null;
    foreach (string item in sc)
    {
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
           sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
        }
    }
    //  conn.Open();
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))
    {
        using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
        {
            connn.Open();
            //      cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            connn.Close();
        }
        // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
    }
}
</code>```

EDIT - I've built a test database and debugged the following code.  It works for the test data I passed it.

```<code>    private void InsertRecords(StringCollection sc)
    {
        const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
        StringBuilder sb = new StringBuilder();

        foreach (string item in sc)
        {
            if (item.Contains(","))
            {
                var splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
            }

        }
        Console.WriteLine(sb.ToString());
        //  conn.Open();
        using (SqlConnection connn = new SqlConnection(ConfigurationManager.ConnectionStrings["whatever"].ConnectionString))

        {
            using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
            {
                connn.Open();
                cmd.ExecuteNonQuery();
                connn.Close();
            }
            // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
        }
    }
</code>```

I tested it as follows:

```<code>...
var collection = new StringCollection{"a,x", "b,y", "c,z"};

InsertRecords(collection);
</code>```

Execution of the database query to see data is as follows:

```<code>SELECT [Ingredients1]
  FROM [Ingredients_List]
</code>```

Results:

```<code>Ingredients1
------------
a
b
c
</code>```

Body:
I am trying to insert data from dynamically generated textbox of gridview in the database. however, I am getting the exception of the CommandText property has not been initialized cmd.executeNonQuery();

private void InsertRecords(StringCollection sc)
{
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
    foreach (string item in sc)
    {
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
        }

    }
    //  conn.Open();
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))

    {
        using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
        {
            connn.Open();
            //      cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            connn.Close();
        }
        // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
    }
}

Body:
You're not loading the first part of your query into the StringBuilder.  Try this:

private void InsertRecords(StringCollection sc)
{
    const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
    StringBuilder sb = new StringBuilder(sqlStatement);
    string[] splitItems = null;
    foreach (string item in sc)
    {
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
           sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
        }
    }
    //  conn.Open();
    using (SqlConnection connn = new SqlConnection(GetConnectionString()))
    {
        using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
        {
            connn.Open();
            //      cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            connn.Close();
        }
        // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
    }
}

EDIT - I've built a test database and debugged the following code.  It works for the test data I passed it.

    private void InsertRecords(StringCollection sc)
    {
        const string sqlStatement = "INSERT INTO Ingredients_List (Ingredients1) VALUES";
        StringBuilder sb = new StringBuilder();

        foreach (string item in sc)
        {
            if (item.Contains(","))
            {
                var splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems[0]);
            }

        }
        Console.WriteLine(sb.ToString());
        //  conn.Open();
        using (SqlConnection connn = new SqlConnection(ConfigurationManager.ConnectionStrings["whatever"].ConnectionString))

        {
            using (SqlCommand cmd = new SqlCommand(sb.ToString(), connn))
            {
                connn.Open();
                cmd.ExecuteNonQuery();
                connn.Close();
            }
            // Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
        }
    }

I tested it as follows:

...
var collection = new StringCollection{"a,x", "b,y", "c,z"};

InsertRecords(collection);

Execution of the database query to see data is as follows:

SELECT [Ingredients1]
  FROM [Ingredients_List]

Results:

Ingredients1
------------
a
b
c


来源: stackexchange

问:
DB2 rownum equivalent
I have the below query in Oracle which I want to replicate in DB2 which uses the random function and the rownum.

Oracle Query :

```<code>SELECT *
FROM  (
   SELECT *
   FROM db2admin.QUESTION_BANK
   WHERE type='PROCESS'
   ORDER BY dbms_random.value
) WHERE rownum <=?
</code>```

I got alternate for random function but nothing for rownum. Below is query in DB2,

```<code>SELECT *
FROM  (
  SELECT *
  FROM db2admin.QUESTION_BANK
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?
</code>```

The value for rownum is passed via PreparedStatement.

答:
You can use this:</p>

```<code>SELECT *
FROM db2admin.QUESTION_BANK
WHERE type = 'PROCESS'
ORDER BY RAND()
fetch first ? rows only;
</code>```

ContentLicense: CC BY-SA 3.0

Title: DB2 rownum equivalent

Body:
I have the below query in Oracle which I want to replicate in DB2 which uses the random function and the rownum.

Oracle Query :

SELECT *
FROM  (
   SELECT *
   FROM db2admin.QUESTION_BANK
   WHERE type='PROCESS'
   ORDER BY dbms_random.value
) WHERE rownum <=?

I got alternate for random function but nothing for rownum. Below is query in DB2,

SELECT *
FROM  (
  SELECT *
  FROM db2admin.QUESTION_BANK
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?

The value for rownum is passed via PreparedStatement.

Body:
You can use this:

SELECT *
FROM db2admin.QUESTION_BANK
WHERE type = 'PROCESS'
ORDER BY RAND()
fetch first ? rows only;


问:
in db2 , how to delete records from multiple tables
i've been trying many of the solutions found by googling, but none work with this seemingly simple task.

in db2, i want to delete PO and PO lines, based on PO vendor and PO date.

PO and PO lines are linked by PO number. (below don't work)

```<code>DELETE FROM po, po_lines
  WHERE po_lines.po_num = po.po_num
  AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE
</code>```

TIA!

答:
not necessary join, and you must use 2 query</p>

```<code>DELETE FROM po_lines pol
WHERE EXISTS
(
   SELECT * FROM po
   WHERE pol.po_num=po.po_num AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE
);

DELETE FROM po WHERE po.vendor = 'AAA' AND po.order_date = CURRENT DATE;
</code>```

Body:
i've been trying many of the solutions found by googling, but none work with this seemingly simple task.

in db2, i want to delete PO and PO lines, based on PO vendor and PO date.

PO and PO lines are linked by PO number. (below don't work)

DELETE FROM po, po_lines
  WHERE po_lines.po_num = po.po_num
  AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE

TIA!

Body:
not necessary join, and you must use 2 query

DELETE FROM po_lines pol
WHERE EXISTS
(
   SELECT * FROM po
   WHERE pol.po_num=po.po_num AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE
);

DELETE FROM po WHERE po.vendor = 'AAA' AND po.order_date = CURRENT DATE;


问:
How to generate auto increment ID and do not set to default when a program is closed and opened again in java?
I am generating the auto increment number as the code below.

```<code>public class CoachRegForm extends javax.swing.JFrame {

/**
 * Creates new form CoachRegForm
 */
   private static int counter = 10000;
    final private int coachId;

public CoachRegForm() {
    initComponents();
     coachId = counter++;
     String staffIDInString=new Integer(coachId).toString();
     CoachRegFormIDShowLab.setText(staffIDInString);
}
</code>```

It works within the system, but when I close the program and run again, it goes back to the default which is 10000.

Is there any method to carry the last number saved by the program to the next time I open the program?

答:
Your static counter field exists in the memory until your JVM shuts down (i.e., program end for standalone main() applications), so if you wanted to save and retrieve the counter value again, you need a persistent store like a database (preferable) or file system.

You can use Java API to connect to database (java.sql.* i.e., JDBC) to connect to database or file system API (i.e., java.io.*) &

Body:
I am generating the auto increment number as the code below.

public class CoachRegForm extends javax.swing.JFrame {

/**
 * Creates new form CoachRegForm
 */
   private static int counter = 10000;
    final private int coachId;

public CoachRegForm() {
    initComponents();
     coachId = counter++;
     String staffIDInString=new Integer(coachId).toString();
     CoachRegFormIDShowLab.setText(staffIDInString);
}

It works within the system, but when I close the program and run again, it goes back to the default which is 10000.

Is there any method to carry the last number saved by the program to the next time I open the program?


问:
JQuery Checking and Unchecking Checkboxes validations
I have some checkboxes in which one is select all and other child checkboxes are there

this is my html

```<code><label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" id="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" id="child">
</code>```

This is my JQuery Script of checking and unchecking

```<code> $('#parent').on('change', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('change', function () {
$('#parent').prop('checked', false);
 $('.child').not(this).prop('checked', false);
$(this).prop('checked',true);
});
</code>```

The select all works fine but the ('.child') on change the parent is unchecked and the child remains checked, i cant uncheck

I need a way to for once any child is checked the parent should be unchecked along with all other child elements but also I should be able to select multiple children

答:
You can use click instead of change. Also change the id="child" to class="child".

HTML:

```<code><label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" class="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" class="child">
</code>```

JS:

```<code> $('#parent').on('click', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('click', function () {
     console.log($('.child').is(':checked').length);

    if ($('.child:checked').length == 2) {
        $('#parent').prop('checked', true);
    } else {
        $('#parent').prop('checked', false);
    }

});
</code>```

 $('#parent').on('click', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('click', function () {

 if ($('.child:checked').length == 2) {
  $('#parent').prop('checked', true);
 } else {
  $('#parent').prop('checked', false);
 }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" class="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" class="child"></code>```

Body:
I have some checkboxes in which one is select all and other child checkboxes are there

this is my html

 Select All
<input type="checkbox" name="all" checked="" id="parent">
 Child 1
<input type="checkbox" name="child" checked="" id="child">
 Child 2
<input type="checkbox" name="child" checked="" id="child">

This is my JQuery Script of checking and unchecking

 $('#parent').on('change', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('change', function () {
$('#parent').prop('checked', false);
 $('.child').not(this).prop('checked', false);
$(this).prop('checked',true);
});

The select all works fine but the ('.child') on change the parent is unchecked and the child remains checked, i cant uncheck

I need a way to for once any child is checked the parent should be unchecked along with all other child elements but also I should be able to select multiple children

Body:
You can use click instead of change. Also change the id="child" to class="child".

HTML:

<label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" class="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" class="child">

JS:

 $('#parent').on('click', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('click', function () {
     console.log($('.child').is(':checked').length);

    if ($('.child:checked').length == 2) {
        $('#parent').prop('checked', true);
    } else {
        $('#parent').prop('checked', false);
    }

});

 $('#parent').on('click', function () {
    $('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('click', function () {

 if ($('.child:checked').length == 2) {
  $('#parent').prop('checked', true);
 } else {
  $('#parent').prop('checked', false);
 }

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" class="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" class="child">


问:
Setting enum value to random in Java
```<code>import java.util.*;
public enum Skills {
Random r= new Random();

//trying to use nextInt method in some case
SKILLS(r.nextInt(125)+25),
VEHICLE(r.nextInt(125)+25),
ACCURACY(),WEAPONS(23),REFLEX(),
STRATEGY(),CHARISMA(),
HACKING(r.nextInt(125)+25),
SPEED(r.nextInt(125)+25),
STEALTH(r.nextInt(125)+25);
//end of skills

private int value;
private Skills(int value){
    this.value=value;
}
public int getValue() {
    return value;
}
}
</code>```

I can't set the values of my enum to random. Later  I will give these skills to characters in my game. I can't use the nextInt method either. Why is that ? How to solve the problem and use this enum properly?

答:
It doesn't really make sense to use enum for this.  Remember that enum constants are singletons: all characters are going to be sharing the same single copy of each skill object, so all characters will have the same skill numbers.  That's probably not what you want.

It'd make more sense to just use a class with fields instead:

```<code>public class Skills {
    private int vehicleSkill;
    private int hackingSkill;
    // etc.

    public Skills(Random r) {
        this.vehicleSkill = r.nextInt(125)+25;
        this.hackingSkill = r.nextInt(125)+25;
        // etc.
    }

    public int getVehicleSkill() {
        return vehicleSkill;
    }

    public int getHackingSkill() {
        return hackingSkill;
    }

    // etc.
}
</code>```

That way you can create a separate Skills object for each character.

Title: Setting enum value to random in Java

Body:
import java.util.*;
public enum Skills {
Random r= new Random();

//trying to use nextInt method in some case
SKILLS(r.nextInt(125)+25),
VEHICLE(r.nextInt(125)+25),
ACCURACY(),WEAPONS(23),REFLEX(),
STRATEGY(),CHARISMA(),
HACKING(r.nextInt(125)+25),
SPEED(r.nextInt(125)+25),
STEALTH(r.nextInt(125)+25);
//end of skills

private int value;
private Skills(int value){
    this.value=value;
}
public int getValue() {
    return value;
}
}

I can't set the values of my enum to random. Later  I will give these skills to characters in my game. I can't use the nextInt method either. Why is that ? How to solve the problem and use this enum properly?

Body:
It doesn't really make sense to use enum for this.  Remember that enum constants are singletons: all characters are going to be sharing the same single copy of each skill object, so all characters will have the same skill numbers.  That's probably not what you want.

It'd make more sense to just use a class with fields instead:

public class Skills {
    private int vehicleSkill;
    private int hackingSkill;
    // etc.

    public Skills(Random r) {
        this.vehicleSkill = r.nextInt(125)+25;
        this.hackingSkill = r.nextInt(125)+25;
        // etc.
    }

    public int getVehicleSkill() {
        return vehicleSkill;
    }

    public int getHackingSkill() {
        return hackingSkill;
    }

    // etc.
}

That way you can create a separate Skills object for each character.


问:
BATCH "set" command issue
I want a code that can see if a 'set's exist or not.

Example:

```<code>@echo of
// Now the thing i want:
if not exist "%user%" (
goto :Register
)
:login
call Functions\user.bat
echo Hello %user%!
pause

:register
echo Register..
pause
</code>```

Now how do i get my batch file to check if %user% exist or not. %user% is not a folder in my script btw.

答:
```<code>if not exist "%user%"
</code>```

Tests whether a file or directory exists with the name contents of the variable user

```<code>if not defined user
</code>```

Tests whether the variable user has been set in the environment.

Title: BATCH "set" command issue

Body:
I want a code that can see if a 'set's exist or not.

Example:

@echo of
// Now the thing i want:
if not exist "%user%" (
goto :Register
)
:login
call Functions\user.bat
echo Hello %user%!
pause

:register
echo Register..
pause

Now how do i get my batch file to check if %user% exist or not. %user% is not a folder in my script btw.

Body:
if not exist "%user%"

Tests whether a file or directory exists with the name contents of the variable user

if not defined user

Tests whether the variable user has been set in the environment.


问:
Canvas : Difference between pixel values
How can I test if the pixel value at a point and another point are different in an image rendered on a canvas ??
Can I get a numerical difference between the pixel value at two different locations, say pixelat(x,y)-pixelat(x1,y1) = any number ??

I need to check difference between adjacent pixel values, and do some operation when the difference goes beyond a certain value..

答:
To get a pixel</p>

```<code>function getPixel(x,y){
    var data = ctx.getImageData(x,y,1,1).data;
    return {
       r : data[0], // pixel RGBA values
       g : data[1],
       b : data[2],
       a : data[3],
       raw : new Uint32Array(data.buffer)[0], // 32bit pixel value
    };
}
if(getPixel(10,10).raw !== getPixel(100,100).raw){
      // pixels are different
}
</code>```

Body:
To get a pixel

function getPixel(x,y){
    var data = ctx.getImageData(x,y,1,1).data;
    return {
       r : data[0], // pixel RGBA values
       g : data[1],
       b : data[2],
       a : data[3],
       raw : new Uint32Array(data.buffer)[0], // 32bit pixel value
    };
}
if(getPixel(10,10).raw !== getPixel(100,100).raw){
      // pixels are different
}


问:
Displaying % in Batch (Windows 10 Command Prompt)
I am writing a batch program that has a loading screen, because it has a lot of files to load,  anyway, I was trying to get it to display:

```<code>0%
</code>```

after runing the program, it only displayed:

```<code>0
</code>```

Any advice or solutions would help,
Thanks!

答: You shall display % in console by giving %% in your batch program.

Body:
I am writing a batch program that has a loading screen, because it has a lot of files to load,  anyway, I was trying to get it to display:

0%

after runing the program, it only displayed:

0

Any advice or solutions would help,
Thanks!


问:
How to manage git-like version control for a text file in Python without using git?
How to keep previous versions of a text file in a similar way to git? This is about user's configuration of an application and NOT about versioning code.

I am working with a file which is infrequently updated however need to keep an audit trail of any changes and be able to view previous versions of the file.

The two approaches to achieve this could be:

Create a git repository for the file

This would require the Python application through which the user updates the file would need to control the git repository and

make new commits as the file is changed.

Save the file with a timestamp each time the file is updated

This brings about a file management problem where files can be accidentally deleted, not backed up, etc.

What is the best way to manage versions of text files in Python?

The goal is to have one file which maintains the different versions of the text file.

答:
I would recommend a different approach using Git.  If the file is updated infrequently, have a process push the files to Git from the directory on a time interval (1 day?), something like:</p>

```<code>git add -u
git commit -m "File Audit" && git push
</code>```

Body:
I would recommend a different approach using Git.  If the file is updated infrequently, have a process push the files to Git from the directory on a time interval (1 day?), something like:

git add -u
git commit -m "File Audit" && git push


问:
Using a struct containing a borrowed parameter
I'm writing a simple game in Rust, which includes a Drawer, which is constructed once and then passed through many methods as a mutable reference:

```<code>pub struct Drawer<'a> {
    // ...
    renderer: Renderer<'a>,
    // ...
}

fn pause(drawer: &mut Drawer, events: &[Event]) {
    // ...
    drawer.draw_text(&TextPos::Centered, "Paused", 1);
    // ...
}
</code>```

I wanted to refactor my code to introduce a fluent interface for drawing text, such as:

```<code>drawer.text()
    .size(4)
    .centered()
    .draw("Paused");
</code>```

I did this by creating a TextDrawer struct, that contains a reference to the Drawer:

```<code>pub struct TextDrawer<'a, 'b: 'a> {
    pos: TextPos,
    size: u32,
    drawer: &'a mut Drawer<'b>,
}

impl<'a> Drawer<'a> {
     pub fn text(&mut self) -> TextDrawer {
        TextDrawer {
            pos: TextPos::At(0, 0),
            size: 1,
            drawer: self,
        }
    }
}
</code>```

I think the lifetimes I've put on the struct are correct (the reference must last as long as the Drawer itself).

However, my text method will not compile until I add explicit lifetimes. When I do, every method that calls text then demands explicit lifetimes, and so on. I'm surprised these lifetimes have to be stated: after all, they're all of the form fn foo<'a, 'b: 'a>(drawer: &mut'a Drawer<'b>). I had assumed before this point that this was already the inferred lifetime, since it was always necessary for the reference to last as long as the Drawer itself.

Is it necessary for me to put these explicit lifetimes all other my method signatures? Or can I avoid it in some other way?

答:
Thanks to the minimal example made by Lukas above, I realised I had simply got the lifetime parameters to my text method backwards.

My incorrect lifetimes:

```<code>impl<'a> Drawer<'a> {
    pub fn text<'b>(&'b mut self) -> TextDrawer<'a, 'b> {
        // omitted
    }
}
</code>```

The correct lifetimes:

```<code>impl<'a> Drawer<'a> {
    pub fn text<'b>(&'b mut self) -> TextDrawer<'b, 'a> {
        // omitted
    }
}
</code>```

After this, everything compiles without any further explicit lifetimes.

Body:
I'm writing a simple game in Rust, which includes a Drawer, which is constructed once and then passed through many methods as a mutable reference:

pub struct Drawer<'a> {
    // ...
    renderer: Renderer<'a>,
    // ...
}

fn pause(drawer: &mut Drawer, events: &[Event]) {
    // ...
    drawer.draw_text(&TextPos::Centered, "Paused", 1);
    // ...
}

I wanted to refactor my code to introduce a fluent interface for drawing text, such as:

drawer.text()
    .size(4)
    .centered()
    .draw("Paused");

I did this by creating a TextDrawer struct, that contains a reference to the Drawer:

pub struct TextDrawer<'a, 'b: 'a> {
    pos: TextPos,
    size: u32,
    drawer: &'a mut Drawer<'b>,
}

impl<'a> Drawer<'a> {
     pub fn text(&mut self) -> TextDrawer {
        TextDrawer {
            pos: TextPos::At(0, 0),
            size: 1,
            drawer: self,
        }
    }
}

I think the lifetimes I've put on the struct are correct (the reference must last as long as the Drawer itself).

However, my text method will not compile until I add explicit lifetimes. When I do, every method that calls text then demands explicit lifetimes, and so on. I'm surprised these lifetimes have to be stated: after all, they're all of the form fn foo<'a, 'b: 'a>(drawer: &mut'a Drawer<'b>). I had assumed before this point that this was already the inferred lifetime, since it was always necessary for the reference to last as long as the Drawer itself.

Is it necessary for me to put these explicit lifetimes all other my method signatures? Or can I avoid it in some other way?

Body:
Thanks to the minimal example made by Lukas above, I realised I had simply got the lifetime parameters to my text method backwards.

My incorrect lifetimes:

impl<'a> Drawer<'a> {
    pub fn text<'b>(&'b mut self) -> TextDrawer<'a, 'b> {
        // omitted
    }
}

The correct lifetimes:

impl<'a> Drawer<'a> {
    pub fn text<'b>(&'b mut self) -> TextDrawer<'b, 'a> {
        // omitted
    }
}

After this, everything compiles without any further explicit lifetimes.


问:
Visual Studio Code Formatting fail on save
I've started learning React Native.

I'm using Visual Studio Code as my editor.

I've set up the boiler plate and started the app. But whenever I change a .js file and hit save, VSCode is messing up all the formatting.

I thought I could sort this in the settings.json file but after googling for a while and playing around I can't find the correct setting.

Is this a bug or am I doing something wrong?

Setting file is default one:

UPDATE: I re-installed vscode. Then set up a basic js file with a react native tag and a html tag. I added in:

```<code>"editor.formatOnSave": false,
"javascript.format.enable": false
</code>```

To my settings.json file and the problem still occurs:

The problem is having tags in a js file, I just don't know how to tell vscode to ignore them?

答:
You should search for "format" in settings.json. You'll find a whole lot of TypeScript/JavaScript formatting tweaks in there, but the one that stands out to me is:

```<code>  // Defines space handling after opening and before closing non empty brackets.
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false
</code>```

Alternative, you're not a fan of formatting at all, you can turn it off entirely:

```<code>  // Enable/disable default JavaScript formatter.
  "javascript.format.enable": true,
</code>```

However, a lot of my formatting options come from language server extensions, so if you're using one for React Native specifically, be sure to check the attributes in settings.json, or the docs to see if there are any attributes you can add.

Body:
I've started learning React Native.

I'm using Visual Studio Code as my editor.

I've set up the boiler plate and started the app. But whenever I change a .js file and hit save, VSCode is messing up all the formatting.

I thought I could sort this in the settings.json file but after googling for a while and playing around I can't find the correct setting.

Is this a bug or am I doing something wrong?

Setting file is default one:

UPDATE: I re-installed vscode. Then set up a basic js file with a react native tag and a html tag. I added in:

"editor.formatOnSave": false,
"javascript.format.enable": false

To my settings.json file and the problem still occurs:

The problem is having tags in a js file, I just don't know how to tell vscode to ignore them?

Body:
You should search for "format" in settings.json. You'll find a whole lot of TypeScript/JavaScript formatting tweaks in there, but the one that stands out to me is:

  // Defines space handling after opening and before closing non empty brackets.
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false

Alternative, you're not a fan of formatting at all, you can turn it off entirely:

  // Enable/disable default JavaScript formatter.
  "javascript.format.enable": true,

However, a lot of my formatting options come from language server extensions, so if you're using one for React Native specifically, be sure to check the attributes in settings.json, or the docs to see if there are any attributes you can add.


问:
Converting function signature from compiler language to c++
Hey guys, I need to make a list of some functions that are listed in the linker output. The syntax i get is as follows:

```<code>int foo(int num,double dnum, Temp & temp) (in namespace "funcsns")
</code>```

Turns into:

```<code>.text._ZN7funcsns3fooEidRNS_4TempE
</code>```

(You might know it from the "undefined symbol" and some other linking errors that print functions names)

Now, i can write a script that somehow turns it into something readable but i wonder if there is a smart way of doing it.

Please share your ideas!

thanks.

答: The undname utility provided with visual studio (At least VC2005 that I'm currently using) does the same as c++filt for microsoft visual c++ </p>

ContentLicense: CC BY-SA 2.5

Body:
Hey guys, I need to make a list of some functions that are listed in the linker output. The syntax i get is as follows:

int foo(int num,double dnum, Temp & temp) (in namespace "funcsns")

Turns into:

.text._ZN7funcsns3fooEidRNS_4TempE

(You might know it from the "undefined symbol" and some other linking errors that print functions names)

Now, i can write a script that somehow turns it into something readable but i wonder if there is a smart way of doing it.

Please share your ideas!

thanks.


问:
Copy to clipboard in Node.js?
Is there a way you can copy to clipboard in Node.js? Any modules or ideas what so ever? I'm using Node.js on a desktop application. Hopefully that clears up why I want it to be able to achieve this.</p>

答:
Check out clipboardy. It lets you copy/paste cross-platform. It is more actively maintained than the copy-paste module mentioned in another answer and it fixes many of that module's issues.

const clipboardy = require('clipboardy');

// Copy
clipboardy.writeSync('');

// Paste
clipboardy.readSync();
//
```

Title: Copy to clipboard in Node.js?

ContentLicense: CC BY-SA 4.0


问:
NoMethodError: undefined method `pluck' for #<Model>
I am trying to fetch the email id from my User model by joining it with another model called Equipment. The association between two models is as follows:

```<code>class Equipment
  belongs_to :user
end

class User
  has_many :equipments
end
</code>```

The Equipment has a column named identifier
So at first I tried fetching the email of a user as follows.

```<code> @email = Equipment.joins(:user).where(identifier: "LID-0000061").pluck(:email)
</code>```

This worked and gave me the email of the user who added that equipment.

Now I am trying to fetch the email of last added equipment by doing following:

```<code>@email = Equipment.joins(:user).last.pluck(:email)
</code>```

I got:

```<code>NoMethodError: undefined method `pluck' for #<Equipment>
</code>```

My best guess is that I am doing it wrong. Can somebody please tell how do I pluck the email of that last equipment?

答:
the pluck method works for the ActiveRecord::Relation, not the model itself. when you add the last method, it returns a model instance, so directly visit it's column, no need to use pluck

try this:

```<code>@email = Equipment.joins(:user).last.user.email
</code>```

or

```<code>@email = Equipment.joins(:user).pluck(:email).last
</code>```

Body:
I am trying to fetch the email id from my User model by joining it with another model called Equipment. The association between two models is as follows:

class Equipment
  belongs_to :user
end

class User
  has_many :equipments
end

The Equipment has a column named identifier
So at first I tried fetching the email of a user as follows.

 @email = Equipment.joins(:user).where(identifier: "LID-0000061").pluck(:email)

This worked and gave me the email of the user who added that equipment.

Now I am trying to fetch the email of last added equipment by doing following:

@email = Equipment.joins(:user).last.pluck(:email)

I got:

NoMethodError: undefined method `pluck' for #<Equipment>

My best guess is that I am doing it wrong. Can somebody please tell how do I pluck the email of that last equipment?

Body:
the pluck method works for the ActiveRecord::Relation, not the model itself. when you add the last method, it returns a model instance, so directly visit it's column, no need to use pluck

try this:

@email = Equipment.joins(:user).last.user.email

or

@email = Equipment.joins(:user).pluck(:email).last


问:
VB.NET - Fill Specific Column DataGridView from Another Column
i have 2 DGV name dataListBarang and dataListTransaksi, i'm trying to fill dataListTransaksi spesific column called nama_barang from specific column in dataListBarang called nm_barang

my code so far

```<code>Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
        If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
            namaBarang = Me.dataListBarang.CurrentRow.Cells(0).Value.ToString
            dataListTransaksi.Columns(1).DataPropertyName = namaBarang
        End If
        dataListBarang.Refresh()
    End Sub
</code>```

when i double click on DGV dataListBarang, column nama_barang (on dataListTransaksi) will filled with value from column nm_barang on DGV dataListBarang, but its not working.

please help.

EDIT
what i'm trying to do is copy cell from current row when user double click on it then fill the first row on second DataGrid (dataGrid has columns with no data in it) in specific column.

note:

see the left dataGrid has data and the right dataGrid is empty

see the number!, when user double click, the value from 1 is copied to number 2

most of column in right dataGrid is manually input (except Nama Barang) and save to database

答:
What your picture shows is an empty DataGridView on the right. When you copy the cell from the left grid to the cell in the right grid as the picture shows, will have some problems. You will have to “Add” a new row first. Otherwise, subsequent double clicks from the user will simply overwrite the previous double click. The code below checks to see if the double click came from column 0 and if so simply adds a new row to the grid on the right. The value in column 0 is copied to the new row column 1. Hope I am not missing something.

```<code>Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
  Dim row As Integer = e.RowIndex
  Dim col As Integer = e.ColumnIndex
  If (col = 0) Then
    dataListTransaksi.Rows.Add("", dataListBarang.Rows(row).Cells(0).Value)
  End If
End Sub
</code>```

Update: If you do not know which column to copy but you know its name..

```<code>Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
  Dim row As Integer = e.RowIndex
  Dim col As Integer = e.ColumnIndex
  If (col = 0) Then
    Dim newRowIndex As Integer = dataListTransaksi.Rows.Add()
    dataListTransaksi.Rows(newRowIndex).Cells("MyColName").Value = dataListBarang.Rows(row).Cells(0).Value
  End If
End Sub
</code>```

Body:
i have 2 DGV name dataListBarang and dataListTransaksi, i'm trying to fill dataListTransaksi spesific column called nama_barang from specific column in dataListBarang called nm_barang

my code so far

Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
        If e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then
            namaBarang = Me.dataListBarang.CurrentRow.Cells(0).Value.ToString
            dataListTransaksi.Columns(1).DataPropertyName = namaBarang
        End If
        dataListBarang.Refresh()
    End Sub

when i double click on DGV dataListBarang, column nama_barang (on dataListTransaksi) will filled with value from column nm_barang on DGV dataListBarang, but its not working.

please help.

EDIT
what i'm trying to do is copy cell from current row when user double click on it then fill the first row on second DataGrid (dataGrid has columns with no data in it) in specific column.

note:

see the left dataGrid has data and the right dataGrid is empty

see the number!, when user double click, the value from 1 is copied to number 2

most of column in right dataGrid is manually input (except Nama Barang) and save to database

Body:
What your picture shows is an empty DataGridView on the right. When you copy the cell from the left grid to the cell in the right grid as the picture shows, will have some problems. You will have to “Add” a new row first. Otherwise, subsequent double clicks from the user will simply overwrite the previous double click. The code below checks to see if the double click came from column 0 and if so simply adds a new row to the grid on the right. The value in column 0 is copied to the new row column 1. Hope I am not missing something.

Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
  Dim row As Integer = e.RowIndex
  Dim col As Integer = e.ColumnIndex
  If (col = 0) Then
    dataListTransaksi.Rows.Add("", dataListBarang.Rows(row).Cells(0).Value)
  End If
End Sub

Update: If you do not know which column to copy but you know its name..

Private Sub dataListBarang_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataListBarang.CellContentDoubleClick
  Dim row As Integer = e.RowIndex
  Dim col As Integer = e.ColumnIndex
  If (col = 0) Then
    Dim newRowIndex As Integer = dataListTransaksi.Rows.Add()
    dataListTransaksi.Rows(newRowIndex).Cells("MyColName").Value = dataListBarang.Rows(row).Cells(0).Value
  End If
End Sub


问:
serialize/deserialize java 8 java.time with Jackson JSON mapper
How do I use Jackson JSON mapper with Java 8 LocalDateTime?

org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class java.time.LocalDateTime] from JSON String; no single-String constructor/factory method (through reference chain: MyDTO["field1"]->SubDTO["date"])

答:
If you are using Jersey then you need to add the Maven dependency (jackson-datatype-jsr310) as the others suggested and register your object mapper instance like so:

@Provider
public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {

  final ObjectMapper defaultObjectMapper;

  public JacksonObjectMapper() {
    defaultObjectMapper = createDefaultMapper();
  }

  @Override
  public ObjectMapper getContext(Class<?> type) {
    return defaultObjectMapper;
  }

  private static ObjectMapper createDefaultMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    return mapper;
  }
}
```

<p>When registering Jackson in your resources, you need to add this mapper like so:</p>

<pre class="lang-java prettyprint-override"><code>final ResourceConfig rc = new ResourceConfig().packages("<your package>");
rc
  .register(JacksonObjectMapper.class)
  .register(JacksonJaxbJsonProvider.class);
</code>```

Body:
If you are using Jersey then you need to add the Maven dependency (jackson-datatype-jsr310) as the others suggested and register your object mapper instance like so:

@Provider
public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {

  final ObjectMapper defaultObjectMapper;

  public JacksonObjectMapper() {
    defaultObjectMapper = createDefaultMapper();
  }

  @Override
  public ObjectMapper getContext(Class<?> type) {
    return defaultObjectMapper;
  }

  private static ObjectMapper createDefaultMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    return mapper;
  }
}

When registering Jackson in your resources, you need to add this mapper like so:

final ResourceConfig rc = new ResourceConfig().packages("<your package>");
rc
  .register(JacksonObjectMapper.class)
  .register(JacksonJaxbJsonProvider.class);


问:
How to do this in Laravel, subquery where in
How can I make this query in Laravel:

```<code>SELECT
    `p`.`id`,
    `p`.`name`,
    `p`.`img`,
    `p`.`safe_name`,
    `p`.`sku`,
    `p`.`productstatusid`
FROM `products` p
WHERE `p`.`id` IN (
    SELECT
        `product_id`
    FROM `product_category`
    WHERE `category_id` IN ('223', '15')
)
AND `p`.`active`=1
</code>```

I could also do this with a join, but I need this format for performance.

答:
```<code>Product::from('products as p')
->join('product_category as pc','p.id','=','pc.product_id')
->select('p.*')
->where('p.active',1)
->whereIn('pc.category_id', ['223', '15'])
->get();
</code>```

Body:
How can I make this query in Laravel:

SELECT
    `p`.`id`,
    `p`.`name`,
    `p`.`img`,
    `p`.`safe_name`,
    `p`.`sku`,
    `p`.`productstatusid`
FROM `products` p
WHERE `p`.`id` IN (
    SELECT
        `product_id`
    FROM `product_category`
    WHERE `category_id` IN ('223', '15')
)
AND `p`.`active`=1

I could also do this with a join, but I need this format for performance.


问:
iPhone In-App Purchase Store Kit error -1003 "Cannot connect to iTunes Store"
I've been working on adding in-app purchases and was able to create and test in-app purchases using Store Kit (yay!).  During testing, I exercised my app in a way which caused the app to crash mid purchase (so I guess the normal cycle of receiving paymentQueue:updatedTransactions and calling finishTransaction was interrupted).

Now I am unable to successfully complete any transactions and instead am getting only transactions with transactionState SKPaymentTransactionStateFailed when paymentQueue:updatedTransactions is called.

The transaction.error.code is -1003 and the transaction.error.localizedDescription is "Cannot connect to iTunes Store"!

I have tried removing all products from iTunesConnect, and rebuilt them using different identifiers but that did not help.  I have also tried using the App Store app to really connect to the real App Store and download some apps so I do have connectivity.  Finally, I have visited the Settings:Store app to make sure I am signed out of my normal app store account.

答:
In my case,
I tried everything in the internet, but nothing worked.

Apple actually broke the production payment system, and the sandbox. I just had to wait two days, and it started to work.


问:
Django allow user to edit their profile
How do I make a function that allows user to edit their own profile?

views.py

```<code>@login_required
def edit_user(request):
    if '_auth_user_id' in request.session:
        userId = request.session['_auth_user_id']
        userDetails = User.objects.get(pk=userId)
       if request.method == 'POST':
            form = UserProfileForm(request.POST, request.FILES)
            userDetails.first_name = request.POST['firstname']
            userDetails.last_name = request.POST['lastname']
            userDetails.email = request.POST['email']
            userDetails.zip = request.POST['zip']
            if form.is_valid():
                userDetails.save()
                return HttpResponseRedirect('/edit_user/')
        else:
            form = UserProfileForm()

    variables = RequestContext(request, {'form': form})
    return render_to_response('edit_user.html',variables,)
</code>```

forms.py

```<code>class UserProfileForm(forms.Form):
    email = forms.EmailField(label='Email', max_length=254)
    firstname = forms.CharField(label='First Name', max_length=20)
    lastname = forms.CharField(label='Last Name', max_length=20)
    zip = forms.CharField(label='Zipcode', max_length=5)
</code>```

edit_user.html

```<code><form class="form-signin" action="/edit_user/" method="post" enctype="multipart/form-data">{% csrf_token %}
                            {% csrf_token %}
                            {{ form.as_p }}
                            <button type="submit" class="btn btn-info"> Save Edits</button>
                        </form>
</code>```

It will not display the fields, it shows blank:
http://gyazo.com/48ee38b22434aae418cfe61accb00bd8.png

答:
My code:</p>

```<code>    def profile_edit(request, template_name='profile_edit.html'):
if request.method == 'POST':
    form = ProfileForm(data=request.POST, instance=request.user)
    if form.is_valid():
        user_profile = form.save(commit=False)
        user_profile.save()
        return redirect('index')
else:
    form = ProfileForm(instance=request.user)
return render(request, template_name,{'form': form})
</code>```

Title: Django allow user to edit their profile

Body:
How do I make a function that allows user to edit their own profile?

views.py

@login_required
def edit_user(request):
    if '_auth_user_id' in request.session:
        userId = request.session['_auth_user_id']
        userDetails = User.objects.get(pk=userId)
       if request.method == 'POST':
            form = UserProfileForm(request.POST, request.FILES)
            userDetails.first_name = request.POST['firstname']
            userDetails.last_name = request.POST['lastname']
            userDetails.email = request.POST['email']
            userDetails.zip = request.POST['zip']
            if form.is_valid():
                userDetails.save()
                return HttpResponseRedirect('/edit_user/')
        else:
            form = UserProfileForm()

    variables = RequestContext(request, {'form': form})
    return render_to_response('edit_user.html',variables,)

forms.py

class UserProfileForm(forms.Form):
    email = forms.EmailField(label='Email', max_length=254)
    firstname = forms.CharField(label='First Name', max_length=20)
    lastname = forms.CharField(label='Last Name', max_length=20)
    zip = forms.CharField(label='Zipcode', max_length=5)

edit_user.html

<form class="form-signin" action="/edit_user/" method="post" enctype="multipart/form-data">{% csrf_token %}
                            {% csrf_token %}
                            {{ form.as_p }}
                            <button type="submit" class="btn btn-info"> Save Edits</button>
                        </form>

It will not display the fields, it shows blank:
http://gyazo.com/48ee38b22434aae418cfe61accb00bd8.png

Body:
My code:

    def profile_edit(request, template_name='profile_edit.html'):
if request.method == 'POST':
    form = ProfileForm(data=request.POST, instance=request.user)
    if form.is_valid():
        user_profile = form.save(commit=False)
        user_profile.save()
        return redirect('index')
else:
    form = ProfileForm(instance=request.user)
return render(request, template_name,{'form': form})


问:
How to fetch json file in MEAN?
I am new in MEAN.I have json content inside database.Need to fetch the content and want to show at the front

Here is the json collection which I have taken from terminal

```<code>athira@athira-Inspiron-3558:~$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use ehsjson
switched to db ehsjson
> db.ehsjson.find()
{ "_id" : ObjectId("58ddfc8758749dac677fe0af"), "glossary" : { "title" : "example glossary", "GlossDiv" : { "title" : "S", "GlossList" : { "GlossEntry" : { "ID" : "SGML", "SortAs" : "SGML", "GlossTerm" : "Standard Generalized Markup Language", "Acronym" : "SGML", "Abbrev" : "ISO 8879:1986", "GlossDef" : { "para" : "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso" : [  "GML",  "XML" ] }, "GlossSee" : "markup" } } } } }
>
</code>```

Here is my code I have tried to fetch the data

```<code>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ehsjson');
var Employee = mongoose.model('Employee', mongoose.Schema({

glossary: {
    title: String,
    GlossDiv: {
        title: String,
        GlossList: {
            GlossEntry: {
                ID: String,
                SortAs: String,
                GlossTerm: String,
                Acronym: String,
                Abbrev: String,
                GlossDef: {
                    para: String,
                    GlossSeeAlso: Array
                },
                GlossSee: String
            }
        }
    }
}

}));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client'));

app.get('/api/employee', function(req, res){
    Employee.find(function(err, ehsjson)
    {
        console.log(ehsjson);
        if(err)
        {
            res.send(err);
            console.log("error"+err);
        }
        res.jsonp(ehsjson);
    });
     //res.jsonp(Employee.ehsjson());
});
</code>```

But its returning null object.

Please help to find out the mistakes

Thank you

答:
got it nothing it just add the collection name</p>

```<code>var Employee = mongoose.model('Employee', mongoose.Schema({
     glossary: {
        title: String,
        GlossDiv: {
            title: String,
            GlossList: {
                GlossEntry: {
                    ID: String,
                    SortAs: String,
                    GlossTerm: String,
                    Acronym: String,
                    Abbrev: String,
                    GlossDef: {
                        para: String,
                        GlossSeeAlso: Array,
                    },
                    GlossSee: String
                }
            }
        }
    }

    },{collection: 'ehsjson'}));
</code>```

Title: How to fetch json file in MEAN?

Body:
I am new in MEAN.I have json content inside database.Need to fetch the content and want to show at the front

Here is the json collection which I have taken from terminal

athira@athira-Inspiron-3558:~$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use ehsjson
switched to db ehsjson
> db.ehsjson.find()
{ "_id" : ObjectId("58ddfc8758749dac677fe0af"), "glossary" : { "title" : "example glossary", "GlossDiv" : { "title" : "S", "GlossList" : { "GlossEntry" : { "ID" : "SGML", "SortAs" : "SGML", "GlossTerm" : "Standard Generalized Markup Language", "Acronym" : "SGML", "Abbrev" : "ISO 8879:1986", "GlossDef" : { "para" : "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso" : [  "GML",  "XML" ] }, "GlossSee" : "markup" } } } } }
>

Here is my code I have tried to fetch the data

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/ehsjson');
var Employee = mongoose.model('Employee', mongoose.Schema({

glossary: {
    title: String,
    GlossDiv: {
        title: String,
        GlossList: {
            GlossEntry: {
                ID: String,
                SortAs: String,
                GlossTerm: String,
                Acronym: String,
                Abbrev: String,
                GlossDef: {
                    para: String,
                    GlossSeeAlso: Array
                },
                GlossSee: String
            }
        }
    }
}

}));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client'));

app.get('/api/employee', function(req, res){
    Employee.find(function(err, ehsjson)
    {
        console.log(ehsjson);
        if(err)
        {
            res.send(err);
            console.log("error"+err);
        }
        res.jsonp(ehsjson);
    });
     //res.jsonp(Employee.ehsjson());
});

But its returning null object.

Please help to find out the mistakes

Thank you

Body:
got it nothing it just add the collection name

var Employee = mongoose.model('Employee', mongoose.Schema({
     glossary: {
        title: String,
        GlossDiv: {
            title: String,
            GlossList: {
                GlossEntry: {
                    ID: String,
                    SortAs: String,
                    GlossTerm: String,
                    Acronym: String,
                    Abbrev: String,
                    GlossDef: {
                        para: String,
                        GlossSeeAlso: Array,
                    },
                    GlossSee: String
                }
            }
        }
    }

    },{collection: 'ehsjson'}));


问:
difference between SendOrPostCallback and Action in multithreaded environment?
I'm fairly new to working with threads. I was trying to set a DependencyProperty's value:

```<code>    public States State
    {
        get { return (States)GetValue(StateProperty); }
        set
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background,
                //(SendOrPostCallback)delegate { SetValue(StateProperty, value); }, //works
                (Action)(()=> SetValue(StateProperty, value)), //doesnt
                value);
        }
    }
    public static readonly DependencyProperty StateProperty =
        DependencyProperty.Register("State", typeof(States), typeof(FTPDownload), new UIPropertyMetadata(States.Idle));
</code>```

I realized the hard way that in the setter you have to use SendOrPostCallback (as it provides an argument when calling the method). it does NOT work with Action (because of the missing argument.  And, wpf is really a bitch about it, debugging and finding the cause of the TargetParameterCountException with "no source available" and no clue at all.

Why do I have to use SendOrPostCallback there? and how should I know that in this case this is the right one?  Because actually calling the setter works via:

```<code>Dispatcher.BeginInvoke((Action)(()=>State=States.Updating), null);
</code>```

and using the SendOrPostCallback instead of course results in a TargetParameterCountException..

Just wondering if seemingly inconsistent thing like that are just common knowledge? Feeling a bit lost here, at least since googling around with SendOrPostCallback, Action and BeginInvoke as keywords had no meaningful results.

答:
The relevant pieces of information:

1.The overload of Dispatcher.BeginInvoke that you are using is:

```<code>public DispatcherOperation BeginInvoke(
    DispatcherPriority priority,
    Delegate method,
    Object arg
)
</code>```

method:  A delegate to a method that takes one argument, which is pushed onto the Dispatcher event queue.

2.The SendOrPostCallBack delegate is declared as:

```<code>public delegate void SendOrPostCallback(object state)
</code>```

3.As for Action:

```<code>public delegate void Action()
</code>```

Clearly, the SendOrPostCallBack delegate is compatible since it takes a single argument but Action is not, since it is parameterless.

Of course, you can use the Action<T> delegate, which does take a single argument, if you prefer:

```<code>Dispatcher.BeginInvoke(DispatcherPriority.Background,
                        new Action<States>(arg => SetValue(StateProperty, arg)),
                        value);
</code>```

Alternatively, you can use a different overload of Dispatcher.BeginInvoke that expects an argument that is of a delegate-type that takes no arguments, and get the C# compiler to do the dirty work for you in the closure:

```<code>Dispatcher.BeginInvoke(DispatcherPriority.Background,
                        new Action(() => SetValue(StateProperty, value));
</code>```

Notice that value is a captured variable, so please be careful.

(Also, this answer doesn't deal with any thread-safety issues, only about the delegate signatures involved.)

Body:
I'm fairly new to working with threads. I was trying to set a DependencyProperty's value:

    public States State
    {
        get { return (States)GetValue(StateProperty); }
        set
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background,
                //(SendOrPostCallback)delegate { SetValue(StateProperty, value); }, //works
                (Action)(()=> SetValue(StateProperty, value)), //doesnt
                value);
        }
    }
    public static readonly DependencyProperty StateProperty =
        DependencyProperty.Register("State", typeof(States), typeof(FTPDownload), new UIPropertyMetadata(States.Idle));

I realized the hard way that in the setter you have to use SendOrPostCallback (as it provides an argument when calling the method). it does NOT work with Action (because of the missing argument.  And, wpf is really a bitch about it, debugging and finding the cause of the TargetParameterCountException with "no source available" and no clue at all.

Why do I have to use SendOrPostCallback there? and how should I know that in this case this is the right one?  Because actually calling the setter works via:

Dispatcher.BeginInvoke((Action)(()=>State=States.Updating), null);

and using the SendOrPostCallback instead of course results in a TargetParameterCountException..

Just wondering if seemingly inconsistent thing like that are just common knowledge? Feeling a bit lost here, at least since googling around with SendOrPostCallback, Action and BeginInvoke as keywords had no meaningful results.

Body:
The relevant pieces of information:

1.The overload of Dispatcher.BeginInvoke that you are using is:

public DispatcherOperation BeginInvoke(
    DispatcherPriority priority,
    Delegate method,
    Object arg
)

method:  A delegate to a method that takes one argument, which is pushed onto the Dispatcher event queue.

2.The SendOrPostCallBack delegate is declared as:

public delegate void SendOrPostCallback(object state)

3.As for Action:

public delegate void Action()

Clearly, the SendOrPostCallBack delegate is compatible since it takes a single argument but Action is not, since it is parameterless.

Of course, you can use the Action<T> delegate, which does take a single argument, if you prefer:

Dispatcher.BeginInvoke(DispatcherPriority.Background,
                        new Action<States>(arg => SetValue(StateProperty, arg)),
                        value);

Alternatively, you can use a different overload of Dispatcher.BeginInvoke that expects an argument that is of a delegate-type that takes no arguments, and get the C# compiler to do the dirty work for you in the closure:

Dispatcher.BeginInvoke(DispatcherPriority.Background,
                        new Action(() => SetValue(StateProperty, value));

Notice that value is a captured variable, so please be careful.

(Also, this answer doesn't deal with any thread-safety issues, only about the delegate signatures involved.)


问:
SpringMVC controller can not deal with the request

I follow the instruction from the book "Spring in action" in SprinvMVC chapter

When i run the tomcat server and try the demo it return error like:

HTTP Status 404 – Not Found

Type Status Report

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

enter image description here

I using macOS , tomcat9 , Intellij 2017.1 , jdk 1.9
and here is my code.

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>spitter</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spitter</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

spitter.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--static resources getting-->
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources"/>

<!--use annotations to create the mapping between-->
<!-- url and class deal with request(Controller) -->
<mvc:annotation-driven/>

<!--scan the component and auto regist as bean-->
<context:component-scan base-package="com.springmvc"/>

<!--Use this bean to map the jsp file according to the name return by Controller-->
<!--It will automatically add the prefix and suffix to the name string-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>
</code>```

controller:

```<code>package com.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
* Created by xwh on 29/3/2017.
*/
@Controller
  public class HomeController {
//    public static final int DEAFAULT_SPITTLES_PER_PAGE = 25;

public HomeController() {
    System.out.println("-------HomeController init-------");
}

@RequestMapping("/")
public String showHomePage() {

    System.out.println("-------showHomePage Method show-------");

    return "home";
  }
}
</code>```

And here is my directory pic.
enter image description here

答:
your contextConfigLocation file is spitter-servlet.xml?
In your web.xml file, you defined the context config file is applicationContext.xml. It means your configs in spitter.xml is not used.
try change the contextConfigLocation to /WEB-INF/spitter-servlet.xml</p>

Body:
I follow the instruction from the book "Spring in action" in SprinvMVC chapter

When i run the tomcat server and try the demo it return error like:

HTTP Status 404 – Not Found

Type Status Report

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

enter image description here

I using macOS , tomcat9 , Intellij 2017.1 , jdk 1.9
and here is my code.

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>spitter</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spitter</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

spitter.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:resources mapping="/resources/**" location="/WEB-INF/resources"/>

<mvc:annotation-driven/>

<context:component-scan base-package="com.springmvc"/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

controller:

package com.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
* Created by xwh on 29/3/2017.
*/
@Controller
  public class HomeController {
//    public static final int DEAFAULT_SPITTLES_PER_PAGE = 25;

public HomeController() {
    System.out.println("-------HomeController init-------");
}

@RequestMapping("/")
public String showHomePage() {

    System.out.println("-------showHomePage Method show-------");

    return "home";
  }
}

And here is my directory pic.
enter image description here


问:
ipython notebook clear all code
All I want to do is try some new codes in ipython notebook and I don't want to save it every time as its done automatically. Instead what I want is clear all the codes of ipython notebook along with reset of variables.

I want to do some coding and clear everything and start coding another set of codes without going to new python portion and without saving the current code.

Any shortcuts will be appreciated.

Note: I want to clear every cells code one time. All I want is an interface which appears when i create new python file, but I don't want to save my current code.

答:
In Jupyter, do the following to clear all cells:

Press Esc to enter command mode.

Hold Shift. Select the first and last cells to select all cells.*

Press d twice to delete all selected cells.

Alternatively, if you simply want to try out code, consider  running the ipython console, which is purely interactive in the REPL and does not require creating a new file.  In a command prompt, type:

```<code>> ipython
</code>```

Demo

Click outside the textbox to select a cell in command mode (thanks @moondra's).

Command Mode (Yes)

Edit Mode (No)

Title: ipython notebook clear all code

Body:
In Jupyter, do the following to clear all cells:

Press Esc to enter command mode.

Hold Shift. Select the first and last cells to select all cells.*

Press d twice to delete all selected cells.

Alternatively, if you simply want to try out code, consider  running the ipython console, which is purely interactive in the REPL and does not require creating a new file.  In a command prompt, type:

> ipython

Demo

Click outside the textbox to select a cell in command mode (thanks @moondra's).

Command Mode (Yes)

Edit Mode (No)


问:
Whats the use of creating a base theme and extending it to be used as your app theme
When I create a new app in my Android studio the app theme is like -

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Material">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

However google tutorials (like this) seems to create a base theme first and then create App theme extending it.

```<code><!-- Base application theme. -->
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#3F51B5</item>
    <!-- Light Indigo -->
    <item name="colorPrimaryDark">#3949AB</item>
    <!-- Dark Indigo -->
    <item name="colorAccent">#00B0FF</item>
    <!-- Blue -->
</style>
<style name="AppTheme" parent="AppTheme.Base"></style>
</code>```

I am wondering is there a good usecase for such a design or is it just modularization?

If it does hold a good use case Studio should incorporate it as well?

PS : I am using latest studio build from dev channel.

答:
For example if you want a certain theme to be the main theme of your app, you can set what you want to be the same for every activity, and then you can extend it and add for example different font size, button color, text color ecc, depending of want your activity needs. But the main theme is the same in any activity without any redundant code.

Hope this helps!

Body:
When I create a new app in my Android studio the app theme is like -

However google tutorials (like this) seems to create a base theme first and then create App theme extending it.

I am wondering is there a good usecase for such a design or is it just modularization?

If it does hold a good use case Studio should incorporate it as well?

PS : I am using latest studio build from dev channel.


问:
Can split recursion be done by hand?
I have this worksheet problem to work on, and I just don't see how it can be done by hand. Each method calls 2 more methods to run, so each one would call 2 more. I don't know how to keep track of any of it. I don't know how one would even find the answer besides putting it into Eclipse.</p>

```<code>static int fun(int x) {
    if(x < 1) {
        return 1;
    } else {
        return x + fun(x-1) + fun(x-2);
    }
}

public static void main(String[] args) {
    System.out.println(fun(4));
}
</code>```

答:
First of all "split recursion" is not a term that I have come across before.  And Google thinks that I'm asking about how to implement a split function using recursion; e.g. splitting strings into words.

If you are asking if you can perform that calculation by hand (i.e. work out fun(n) for some value of n), then the answer is obviously Yes.  You just need a large enough piece of paper and some patience1.

If you are asking if it is possible to come up with a "closed form" equation for fun(n) ... I suspect that the answer is yes.  However that's a Maths question not a programming question.  (Basically, you map the declaration of  fun to a recurrence relation ... and solve it.  In this case, it probably requires 1st year Uni maths skills.  Once you have the closed form, it will be easy to prove correct by induction.)

If you are asking if there is a faster program to compute fun(n) then the answer is Yes:

If you employ memoization, there is an O(N) solution.

If you can derive the closed form, there is an O(1) solution.

(I'm assuming you can use int or long arithmetic.)

1 - Actually, for large enough values of N, you should be able to compute fun(n) faster with a pencil and paper (and intelligence) than running that program.  The program has complexity (2^N) ... as written.

Title: Can split recursion be done by hand?

Body:
I have this worksheet problem to work on, and I just don't see how it can be done by hand. Each method calls 2 more methods to run, so each one would call 2 more. I don't know how to keep track of any of it. I don't know how one would even find the answer besides putting it into Eclipse.

static int fun(int x) {
    if(x < 1) {
        return 1;
    } else {
        return x + fun(x-1) + fun(x-2);
    }
}

public static void main(String[] args) {
    System.out.println(fun(4));
}


问:
How to initialize OnFragmentInteractionListener without onAttach(Context context) for use with FirebaseUI
I am trying to make my app (which uses com.firebase.ui and com.firebase.ui.auth) work on an old api level 15 (4.0.4) device.  First I use the manifest tag:

```<code> <uses-sdk tools:overrideLibrary="com.firebase.ui, com.firebase.ui.auth"/>
</code>```

but then I found that on the old device the onAttach(Context...) method was not getting called.

So I read some posts about it and this is what I came up with based on what I read:

```<code>  @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {

        Log.d(TAG, "onAttach Activity 1A "  );
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            setmListener(activity );
        }

    }

    private void setmListener(Context context){
        Log.d(TAG, "setmListener 1  "  );
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onAttach(Context context) {
        Log.d(TAG, "onAttach Context 1 "  );
        super.onAttach(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            setmListener(context);
        }
    }
</code>```

When the code runs on the old api 15 device the onAttach(Context context) method does not get called just the onAttach(Activity activity) method (same for an emulator running Lollipop).

```<code> D/StSt_MaxWListFrag: onAttach Activity 1A
 D/StSt_MaxWListFrag: setmListener 1
</code>```

But on the device with M both methods run but the setmListener only gets called once as expected:

```<code>D/StSt_MaxWListFrag: onAttach Context 1
D/StSt_MaxWListFrag: onAttach Activity 1A
D/StSt_MaxWListFrag: setmListener 1
</code>```

So - so far it seems to be working,  no problems so far.   I am just wondering if there is something I am missing here - is this approach going to cause me headaches down the road or is it bad practise - maybe inefficient?
Thanks for any insight!

答:
As you can see in docs, onAttach(Activity) is deprecated from API 23 upwards, instead onAttach(Context) is used. onAttach(Activity) won't call new onAttach(Context) automatically.

So, in order to support all versions of API and to perform attaching actions only once, you have to separate attach logics in a function and call that function from both callbacks performing a check:

```<code>@Override
public void onAttach(Context context) {
    super.onAttach(context);
    attached();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        attached();
    }
}
</code>```

Body:
I am trying to make my app (which uses com.firebase.ui and com.firebase.ui.auth) work on an old api level 15 (4.0.4) device.  First I use the manifest tag:

 <uses-sdk tools:overrideLibrary="com.firebase.ui, com.firebase.ui.auth"/>

but then I found that on the old device the onAttach(Context...) method was not getting called.

So I read some posts about it and this is what I came up with based on what I read:

  @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {

        Log.d(TAG, "onAttach Activity 1A "  );
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            setmListener(activity );
        }

    }

    private void setmListener(Context context){
        Log.d(TAG, "setmListener 1  "  );
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onAttach(Context context) {
        Log.d(TAG, "onAttach Context 1 "  );
        super.onAttach(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            setmListener(context);
        }
    }

When the code runs on the old api 15 device the onAttach(Context context) method does not get called just the onAttach(Activity activity) method (same for an emulator running Lollipop).

 D/StSt_MaxWListFrag: onAttach Activity 1A
 D/StSt_MaxWListFrag: setmListener 1

But on the device with M both methods run but the setmListener only gets called once as expected:

D/StSt_MaxWListFrag: onAttach Context 1
D/StSt_MaxWListFrag: onAttach Activity 1A
D/StSt_MaxWListFrag: setmListener 1

So - so far it seems to be working,  no problems so far.   I am just wondering if there is something I am missing here - is this approach going to cause me headaches down the road or is it bad practise - maybe inefficient?
Thanks for any insight!

Body:
As you can see in docs, onAttach(Activity) is deprecated from API 23 upwards, instead onAttach(Context) is used. onAttach(Activity) won't call new onAttach(Context) automatically.

So, in order to support all versions of API and to perform attaching actions only once, you have to separate attach logics in a function and call that function from both callbacks performing a check:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    attached();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        attached();
    }
}


问:
I keep getting a -1700 error
I am trying to write a script that will open finder, open the applications window and press command+a then command+o using this script but every time I try to run it the error code you can see comes up. What do I do?</p>

答:
The plus sign + is a mathematical operator and the enumerated constants cannot be added.

The syntax you are looking for is

```<code>tell application "System Events"
    keystroke "a" using {shift down, command down}
end tell
</code>```

Title: I keep getting a -1700 error

Body:
The plus sign + is a mathematical operator and the enumerated constants cannot be added.

The syntax you are looking for is

tell application "System Events"
    keystroke "a" using {shift down, command down}
end tell


问:
how to download zip file using php?
i want to download zip file which is uploaded on google drive.following is my html code for download,

```<code> <a class="tlClogo" href="https://drive.google.com/open?id=0BzJrMJ44NPAEV1ZIRmk4VTdxbG8" id="downloadThisPage"  oncontextmenu="return false;" download="myzip.zip"/>Click Here to download</a>
</code>```

this is javascript,

```<code><script type="text/javascript">
document.getElementById("downloadThisPage").href = window.location.toString();
</script>
</code>```

答:
No need to use javascript anchor tag will do the work. You just need to change the link like this.

FROM:

```<code><a class="tlClogo" href="https://drive.google.com/open?id=0BzJrMJ44NPAEV1ZIRmk4VTdxbG8" id="downloadThisPage"  oncontextmenu="return false;" download="myzip.zip"/>Click Here to download</a>
</code>```

TO:

```<code><a class="tlClogo" href="https://drive.google.com/uc?export=download&confirm=SYSo&id=0BzJrMJ44NPAEV1ZIRmk4VTdxbG8">Click Here to download</a>
</code>```

Title: how to download zip file using php?

Body:
i want to download zip file which is uploaded on google drive.following is my html code for download,

 Click Here to download

this is javascript,

Body:
No need to use javascript anchor tag will do the work. You just need to change the link like this.

FROM:

<a class="tlClogo" href="https://drive.google.com/open?id=0BzJrMJ44NPAEV1ZIRmk4VTdxbG8" id="downloadThisPage"  oncontextmenu="return false;" download="myzip.zip"/>Click Here to download</a>

TO:

<a class="tlClogo" href="https://drive.google.com/uc?export=download&confirm=SYSo&id=0BzJrMJ44NPAEV1ZIRmk4VTdxbG8">Click Here to download</a>


问:
Jackson databind working in IDE environment but not in jar
I am trying to use jackson databind using Maven. It works fine in my IDE environment (I'm using IntelliJ IDEA), but when I try to make a jar with it, it produces an error on startup and instantly crashes. Specifically, the error is this :

```<code>java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory
</code>```

This is specific to the JAR, and I don't know why it does that at all.
What did I do wrong ?

Here is the pom file :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.zam</groupId>
    <artifactId>jackson</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Make this jar executable -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <!-- Jar file entry point -->
                            <mainClass>me.Main</mainClass>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

And here is the Main object

```<code>package me;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

/**
 * Created by Martin on 31/03/2017.
 */
public class Main
{
    public static void main(String[] args)
    {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            User user = mapper.readValue(new File("user.yaml"), User.class);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

答: I'm not sure but you need to change <mainClass> to <MainClass> and set the scope for the dependency to compile like <scope>compile</scope> to add it directly to the jar file.

Body:
I am trying to use jackson databind using Maven. It works fine in my IDE environment (I'm using IntelliJ IDEA), but when I try to make a jar with it, it produces an error on startup and instantly crashes. Specifically, the error is this :

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

This is specific to the JAR, and I don't know why it does that at all.
What did I do wrong ?

Here is the pom file :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.zam</groupId>
    <artifactId>jackson</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>

                            <mainClass>me.Main</mainClass>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

And here is the Main object

package me;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

/**
 * Created by Martin on 31/03/2017.
 */
public class Main
{
    public static void main(String[] args)
    {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            User user = mapper.readValue(new File("user.yaml"), User.class);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


问:
Creating a list of lists from round robin not using a recipe
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

```<code>MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]
</code>```

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

答:
@Abhishek gurjar your code is giving a traceback with a TypeError. I think it is because of true division which outputs in float. It works if the expression len(l)/2 is inside an int() function. :) </p>

```<code>l = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']

half = int(len(l) / 2)
l1 = l[:half]
l2 = l[half:]
l3 = []
for i in range(half):
    l3 += [l1[i],l2[i]],
print l3
</code>```

Body:
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

Body:
@Abhishek gurjar your code is giving a traceback with a TypeError. I think it is because of true division which outputs in float. It works if the expression len(l)/2 is inside an int() function. :)

l = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']

half = int(len(l) / 2)
l1 = l[:half]
l2 = l[half:]
l3 = []
for i in range(half):
    l3 += [l1[i],l2[i]],
print l3


问:
How to Subset a column from function argument
```<code>data(mtcars)
sset <- function(column){
mtcars$column}
</code>```

Why does not this work? Basically, if I can select a column thus, I will be able to do a lot more. I know there are other ways to subset, but is this NOT workable at all?

Body:
data(mtcars)
sset <- function(column){
mtcars$column}

Why does not this work? Basically, if I can select a column thus, I will be able to do a lot more. I know there are other ways to subset, but is this NOT workable at all?

Body:
You should use [] for subsetting with variables and arguments:

sset <- function(column) {
   mtcars[,column]
}

sset("mpg")

#[1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4
#[17] 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4


问:
how can smallest floating point number be 2^(-126) , not 2^(-128)
Consider a 32 bit floating point number (IEEE 754) having 0-22 for mantissa(23 bits) , 23-30 for exponent(8 bits) , 31 for sign(1bit)

I want to find out the smallest positive number that can be stored.

I have been told answer is 1.18*10-38 which is approx 2-126

My analysis is as follows

if we put all zeroes in mantissa and put all ones in exponent then the decimal equivalent would be
 1.0 x 2-128 = 2.93 x 10-39

Where am I going wrong ?

Thanks

答:
Although 8 bits exponent means -127 to +128 but two case is reserved for special values (See here), so the most negative exponent is -126.

BTW, it's impossible to store -128 in 8 bits in Two's Complement system which is the base system used in exponent of IEEE 754.


答:
Easier solution: Declare an array big enough to hold the values of fun() up to the one you require. When fun(4) is asked for, you need an int[5]. Fill in hard coded values for the first two elements, then in a loop fill in the remaining entries using the formula. Now your result is in the last element.

A possible space requirement optimization: All the time through the loop you only need the last two and the current value, so you need not store all the values in an array of size x + 1.

Title: Can split recursion be done by hand?


问:
How do I print each individual array item as a template variable in Django?
I got a field in a Django modal as the following:

```<code>tags = models.CharField(null=True, blank=False, max_length=50)
</code>```

and within that field I have the value of:

```<code>['One', 'Two', 'Three']
</code>```

I'm currently trying to have it print out "One", "Two", and "Three" separately in a Django template using a for statement such as follows:

```<code>{% for tag in posts %}
    {{ tag }}
{% endfor %}
</code>```

But it seems to be printing each individual charter from the array instead of the word itself. I know I'm over looking something here. Can someone by any chance help me or point me in the right direction?

Thanks in advance.

答:
I hope in your tags field you have exactly like.

```<code>['One', 'Two', 'Three']
</code>```

You need to parse this string and pass it to the template. You should be able to access it as above. You can add a model method that does this for you. Ex:

```<code>class FooModel(models.Model):
    tags = models.CharField(null=True, blank=False, max_length=50)

    def tags_list(self):
        try:
            return eval(self.tags)
        except:
            return None
</code>```

Then in your template you can just do.

```<code>{% for tag in foo.tags_list %}
    {{ tag }}
{% endfor %}
</code>```

Body:
I got a field in a Django modal as the following:

tags = models.CharField(null=True, blank=False, max_length=50)

and within that field I have the value of:

['One', 'Two', 'Three']

I'm currently trying to have it print out "One", "Two", and "Three" separately in a Django template using a for statement such as follows:

{% for tag in posts %}
    {{ tag }}
{% endfor %}

But it seems to be printing each individual charter from the array instead of the word itself. I know I'm over looking something here. Can someone by any chance help me or point me in the right direction?

Thanks in advance.

Body:
I hope in your tags field you have exactly like.

['One', 'Two', 'Three']

You need to parse this string and pass it to the template. You should be able to access it as above. You can add a model method that does this for you. Ex:

class FooModel(models.Model):
    tags = models.CharField(null=True, blank=False, max_length=50)

    def tags_list(self):
        try:
            return eval(self.tags)
        except:
            return None

Then in your template you can just do.

{% for tag in foo.tags_list %}
    {{ tag }}
{% endfor %}