问:
boost::iostreams decompression returns an empty stream
I have a seemingly basic issue that I've been tackling for the past couple of days and can't seem to find an answer for. I have read multiple answers for similar issues, but none seems to work for me.

I have been simply trying to use boost's compression / decompression functions, but I figure I must be using it incorrectly. My goal is quite simple - create a string, compress it and write to file, read the compressed file, decompress it and print to std::cout (or any other stream for that matter).
I used the following code:

```<code>// write files
std::stringstream str;
str << "SampleString";

std::ofstream outFile_raw("rawFile");
std::ofstream outFile_comp("compressedFile);

boost::iostreams::filtering_istream filteredString;
filteredString.push(boost::iostreams::zlib_compressor());
filteredString.push(str);

boost::iostreams::copy(str, outFile_raw);
boost::iostreams::copy(filteredString, outFile_comp);

\\read files
std::ifstream inFile_raw("rawFile");
std::ifstream inFile_comp("compressedFile);

boost::iostreams::filtering_istream filteredInput;
filteredInput.push(boost::iostreams::zlib_decompressor());
filteredInput.push(inFile_comp);

boost::iostreams::copy(inFile_raw, std::cout);
boost::iostreams::copy(filteredInput, std::cout);
</code>```

The writing phase works as it should - two files are created, one with an expected size (stringLength bytes), and a smaller one.
Upon reading, for some reason only the raw file is read successfully, while the compressed one prints nothing.

I have tried several methods in order to debug this issue:

Getting the stream length with seekg and tellg, in order to verify that the stream is indeed empty

using stream << filteredStream.rdbuf(); instead of boost::iostreams::copy

Using filtering_istreambuf insteaf of filtering_istream (what is the difference? When should I use each one?)

Using other compression algorithms, such as gzip and bzip2.

Adding inFile_comp.close();  before and after pushing it to the filtering stream (One approach does not help, the other yields an iostream stream error exception.

I feel like there is a basic concept I am missing, can anyone please help me figure it out?

EDIT: After further investigating the issue, I have come to an interesting situation- During zlib and gzip compression, the entire process is completed successfully for a small file (~5KB, which is compressed to ~200 bytes), yet an "iostream stream error" exception is thrown for a larger file (~55MB, compressed to ~320KB).

For bzip2 compression, the exception is thrown in both cases. Could it have something to do with the decompressor buffer size?
I am getting pretty hopeless at this stage..

Thank you all in advance!

答:
You're using str twice. After using it the first time it is at end-of-stream, so nothing will be read the second time.

Besides this, either explicitly flush your streams and buffers, or limit the scope of the objects so it happens automatically:

Live On Coliru

```<code>#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <fstream>
#include <iostream>
#include <sstream>

int main() {
    // write files
    {
        std::stringstream str("SampleString");
        std::ofstream outFile_raw("rawFile");
        boost::iostreams::copy(str, outFile_raw);
    }
    {
        std::stringstream str("SampleString");
        std::ofstream outFile_comp("compressedFile");

        boost::iostreams::filtering_istream filteredString;
        filteredString.push(boost::iostreams::zlib_compressor());
        filteredString.push(str);

        boost::iostreams::copy(filteredString, outFile_comp);

        outFile_comp.flush();
        outFile_comp.close();
    }

    //read files
    {
        std::ifstream inFile_raw("rawFile");
        boost::iostreams::copy(inFile_raw, std::cout << "\n inFile_raw: ");
    }
    {
        std::ifstream inFile_comp("compressedFile");

        boost::iostreams::filtering_istream filteredInput;
        filteredInput.push(boost::iostreams::zlib_decompressor());
        filteredInput.push(inFile_comp);

        boost::iostreams::copy(filteredInput, std::cout << "\n filteredInput: ");
    }
}
</code>```

Prints:

```<code> inFile_raw: SampleString
 filteredInput: SampleString
</code>```

Body:
I have a seemingly basic issue that I've been tackling for the past couple of days and can't seem to find an answer for. I have read multiple answers for similar issues, but none seems to work for me.

I have been simply trying to use boost's compression / decompression functions, but I figure I must be using it incorrectly. My goal is quite simple - create a string, compress it and write to file, read the compressed file, decompress it and print to std::cout (or any other stream for that matter).
I used the following code:

// write files
std::stringstream str;
str << "SampleString";

std::ofstream outFile_raw("rawFile");
std::ofstream outFile_comp("compressedFile);

boost::iostreams::filtering_istream filteredString;
filteredString.push(boost::iostreams::zlib_compressor());
filteredString.push(str);

boost::iostreams::copy(str, outFile_raw);
boost::iostreams::copy(filteredString, outFile_comp);

\\read files
std::ifstream inFile_raw("rawFile");
std::ifstream inFile_comp("compressedFile);

boost::iostreams::filtering_istream filteredInput;
filteredInput.push(boost::iostreams::zlib_decompressor());
filteredInput.push(inFile_comp);

boost::iostreams::copy(inFile_raw, std::cout);
boost::iostreams::copy(filteredInput, std::cout);

The writing phase works as it should - two files are created, one with an expected size (stringLength bytes), and a smaller one.
Upon reading, for some reason only the raw file is read successfully, while the compressed one prints nothing.

I have tried several methods in order to debug this issue:

Getting the stream length with seekg and tellg, in order to verify that the stream is indeed empty

using stream << filteredStream.rdbuf(); instead of boost::iostreams::copy

Using filtering_istreambuf insteaf of filtering_istream (what is the difference? When should I use each one?)

Using other compression algorithms, such as gzip and bzip2.

Adding inFile_comp.close();  before and after pushing it to the filtering stream (One approach does not help, the other yields an iostream stream error exception.

I feel like there is a basic concept I am missing, can anyone please help me figure it out?

EDIT: After further investigating the issue, I have come to an interesting situation- During zlib and gzip compression, the entire process is completed successfully for a small file (~5KB, which is compressed to ~200 bytes), yet an "iostream stream error" exception is thrown for a larger file (~55MB, compressed to ~320KB).

For bzip2 compression, the exception is thrown in both cases. Could it have something to do with the decompressor buffer size?
I am getting pretty hopeless at this stage..

Thank you all in advance!

Body:
You're using str twice. After using it the first time it is at end-of-stream, so nothing will be read the second time.

Besides this, either explicitly flush your streams and buffers, or limit the scope of the objects so it happens automatically:

Live On Coliru

#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <fstream>
#include <iostream>
#include <sstream>

int main() {
    // write files
    {
        std::stringstream str("SampleString");
        std::ofstream outFile_raw("rawFile");
        boost::iostreams::copy(str, outFile_raw);
    }
    {
        std::stringstream str("SampleString");
        std::ofstream outFile_comp("compressedFile");

        boost::iostreams::filtering_istream filteredString;
        filteredString.push(boost::iostreams::zlib_compressor());
        filteredString.push(str);

        boost::iostreams::copy(filteredString, outFile_comp);

        outFile_comp.flush();
        outFile_comp.close();
    }

    //read files
    {
        std::ifstream inFile_raw("rawFile");
        boost::iostreams::copy(inFile_raw, std::cout << "\n inFile_raw: ");
    }
    {
        std::ifstream inFile_comp("compressedFile");

        boost::iostreams::filtering_istream filteredInput;
        filteredInput.push(boost::iostreams::zlib_decompressor());
        filteredInput.push(inFile_comp);

        boost::iostreams::copy(filteredInput, std::cout << "\n filteredInput: ");
    }
}

Prints:

 inFile_raw: SampleString
 filteredInput: SampleString


来源: stackexchange

问:
Sorting csv file by one field
Trying to write a program that sorts a csv file with 5 "fields" using compareTo, and I've got the code working to import the csv file into an arrayList, among a couple of other things.
That said, I'm completely stuck on what code I need to actually sort the populated arrayList.

Here is my code:

```<code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Student implements Comparable<Student>{

public static final String CSV_PATH = "unsortedList.csv";
public static int studentID, mark;
public static String fName, lName, grade;
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    readAllLinesFromFile(CSV_PATH);
}

public static ArrayList<String> readAllLinesFromFile(String path) throws IOException{

    FileReader fileReader = new FileReader(path);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while( (line = bufferedReader.readLine()) != null){
        aList.add(line);
    }
    bufferedReader.close();
    System.out.print(aList);

    return aList;

}

public static void writeAllLinesToFile(String path, ArrayList<String> aList) throws IOException {
    //ArrayList<String> aList = new ArrayList<String>();
    FileWriter fileWriter = new FileWriter(path, append);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    for (String line : aList){
        printWriter.printf("%s" + "%n", line);
    }
    printWriter.close();
}

public Student(int studentID, String fName, String lName, int mark, String grade) {
    super();
    this.studentID = studentID;
    this.fName = fName;
    this.lName = lName;
    this.mark = mark;
    this.grade = grade;
}

public int getStudentID() {
    return studentID;
}

public String getfName() {
    return fName;
}

public String getlName() {
    return lName;
}

public int getMark() {
    return mark;
}

public String getGrade() {
    return grade;
}

public int compareTo (Student s) {

    if (this.mark == s.mark) {
        return this.fName.compareTo(s.fName);
    } else {
        return (s.mark - this.mark) > 0 ? 1 : -1;
    }
}
}
</code>```

And here is an example of the contents of the CSV:

```<code>StudentID,FirstName,LastName,FinalMark,FinalGrade
123464,John,Guest,77,P
123456,Dianne,Smith,76,P
122364,Stacey,Hobbs,58,P
123472,Laura,Taylor,67,P
123461,Lazarus,Wonton,42,F
123468,Nola,Emirate,50,P
</code>```

Any help is greatly appreciated!

答:
You need to implement the Comparable interface for your Student. According to javadoc compareTo needs to return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. So you don't have to return either -1 or 0 or 1:

```<code>class Student implements Comparable<Student> {

    private int studentID;
    private String fName;
    private String lName;
    private int mark;
    private String grade;

    public Student(int studentID, String fName, String lName, int mark, String grade) {
        this.studentID = studentID;
        this.fName = fName;
        this.lName = lName;
        this.mark = mark;
        this.grade = grade;
    }

    @Override
    public int compareTo(Student o) {
        return o.mark - this.mark; // DESC
    }

    @Override
    public String toString() {
        return studentID + "," + fName + "," + lName + "," + mark + "," + grade;
    }
}
</code>```

And your code eventually might look like this:

```<code>import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        File input = new File("mycvs.cvs");
        File output = new File("sorted.cvs");
        Main m = new Main();
        List<Student> students = m.sort(input, 2);
        m.write(output, students);
    }

    private void write(File output, List<Student> students) throws IOException {
        Path path = Paths.get(output.toURI());
        List<String> listStudents = new ArrayList<>(students.size());
        for (Student s: students) {
            listStudents.add(s.toString());
        }
        Files.write(path, listStudents);
    }

    private List<Student> sort(File f, int columnToSort) throws IOException {
        Path path = Paths.get(f.toURI());
        List<String> allLines = Files.readAllLines(path);
        List<Student> students = new ArrayList<>(allLines.size());
        for (int i = 1; i < allLines.size(); i++) {
            String line = allLines.get(i);
            String[] columns = line.split(",");
            Student s = new Student(Integer.parseInt(columns[0]), columns[1], columns[2], Integer.parseInt(columns[3]), columns[4]);
            students.add(s);
        }
        Collections.sort(students);
        return students;
    }
}

class Student implements Comparable<Student> {

    private int studentID;
    private String fName;
    private String lName;
    private int mark;
    private String grade;

    public Student(int studentID, String fName, String lName, int mark, String grade) {
        this.studentID = studentID;
        this.fName = fName;
        this.lName = lName;
        this.mark = mark;
        this.grade = grade;
    }

    @Override
    public int compareTo(Student o) {
        return o.mark - this.mark; // DESC
    }

    @Override
    public String toString() {
        return studentID + "," + fName + "," + lName + "," + mark + "," + grade;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sorting csv file by one field

Body:
Trying to write a program that sorts a csv file with 5 "fields" using compareTo, and I've got the code working to import the csv file into an arrayList, among a couple of other things.
That said, I'm completely stuck on what code I need to actually sort the populated arrayList.

Here is my code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Student implements Comparable<Student>{

public static final String CSV_PATH = "unsortedList.csv";
public static int studentID, mark;
public static String fName, lName, grade;
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    readAllLinesFromFile(CSV_PATH);
}

public static ArrayList<String> readAllLinesFromFile(String path) throws IOException{

    FileReader fileReader = new FileReader(path);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while( (line = bufferedReader.readLine()) != null){
        aList.add(line);
    }
    bufferedReader.close();
    System.out.print(aList);

    return aList;

}

public static void writeAllLinesToFile(String path, ArrayList<String> aList) throws IOException {
    //ArrayList<String> aList = new ArrayList<String>();
    FileWriter fileWriter = new FileWriter(path, append);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    for (String line : aList){
        printWriter.printf("%s" + "%n", line);
    }
    printWriter.close();
}

public Student(int studentID, String fName, String lName, int mark, String grade) {
    super();
    this.studentID = studentID;
    this.fName = fName;
    this.lName = lName;
    this.mark = mark;
    this.grade = grade;
}

public int getStudentID() {
    return studentID;
}

public String getfName() {
    return fName;
}

public String getlName() {
    return lName;
}

public int getMark() {
    return mark;
}

public String getGrade() {
    return grade;
}

public int compareTo (Student s) {

    if (this.mark == s.mark) {
        return this.fName.compareTo(s.fName);
    } else {
        return (s.mark - this.mark) > 0 ? 1 : -1;
    }
}
}

And here is an example of the contents of the CSV:

StudentID,FirstName,LastName,FinalMark,FinalGrade
123464,John,Guest,77,P
123456,Dianne,Smith,76,P
122364,Stacey,Hobbs,58,P
123472,Laura,Taylor,67,P
123461,Lazarus,Wonton,42,F
123468,Nola,Emirate,50,P

Any help is greatly appreciated!

Body:
You need to implement the Comparable interface for your Student. According to javadoc compareTo needs to return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. So you don't have to return either -1 or 0 or 1:

class Student implements Comparable<Student> {

    private int studentID;
    private String fName;
    private String lName;
    private int mark;
    private String grade;

    public Student(int studentID, String fName, String lName, int mark, String grade) {
        this.studentID = studentID;
        this.fName = fName;
        this.lName = lName;
        this.mark = mark;
        this.grade = grade;
    }

    @Override
    public int compareTo(Student o) {
        return o.mark - this.mark; // DESC
    }

    @Override
    public String toString() {
        return studentID + "," + fName + "," + lName + "," + mark + "," + grade;
    }
}

And your code eventually might look like this:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        File input = new File("mycvs.cvs");
        File output = new File("sorted.cvs");
        Main m = new Main();
        List<Student> students = m.sort(input, 2);
        m.write(output, students);
    }

    private void write(File output, List<Student> students) throws IOException {
        Path path = Paths.get(output.toURI());
        List<String> listStudents = new ArrayList<>(students.size());
        for (Student s: students) {
            listStudents.add(s.toString());
        }
        Files.write(path, listStudents);
    }

    private List<Student> sort(File f, int columnToSort) throws IOException {
        Path path = Paths.get(f.toURI());
        List<String> allLines = Files.readAllLines(path);
        List<Student> students = new ArrayList<>(allLines.size());
        for (int i = 1; i < allLines.size(); i++) {
            String line = allLines.get(i);
            String[] columns = line.split(",");
            Student s = new Student(Integer.parseInt(columns[0]), columns[1], columns[2], Integer.parseInt(columns[3]), columns[4]);
            students.add(s);
        }
        Collections.sort(students);
        return students;
    }
}

class Student implements Comparable<Student> {

    private int studentID;
    private String fName;
    private String lName;
    private int mark;
    private String grade;

    public Student(int studentID, String fName, String lName, int mark, String grade) {
        this.studentID = studentID;
        this.fName = fName;
        this.lName = lName;
        this.mark = mark;
        this.grade = grade;
    }

    @Override
    public int compareTo(Student o) {
        return o.mark - this.mark; // DESC
    }

    @Override
    public String toString() {
        return studentID + "," + fName + "," + lName + "," + mark + "," + grade;
    }
}


问:
Background image not showing in browser
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

```

Thanks in advance

答:
On adding the mydiv container to your html, I can see the background-image being shown. Also please provide the correct path for the background-image: url() in your css code.

Refer code for more info:

body {
  background-image: url('http://www.gettyimages.com/gi-resources/images/Embed/new/embed2.jpg');
  height: 100%;
  width: 100%;
  background-repeat: no-repeat;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <div class="header">

    <div class="container">

      <div class="logo">
        <h1>Lusofly Virtual</h1>
      </div>

      <div class="nav">
        <ul>
          <li>HOME</li>
          <li>COMMUNITY</li>
          <li>CONTACT</li>
          <li>PILOT AREA</li>
        </ul>
      </div>
      <div id="mydiv"></div>
    </div>
  </div>
</body></code>```

Title: Background image not showing in browser

Body:
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

Thanks in advance

Body:
On adding the mydiv container to your html, I can see the background-image being shown. Also please provide the correct path for the background-image: url() in your css code.

Refer code for more info:

body {
  background-image: url('http://www.gettyimages.com/gi-resources/images/Embed/new/embed2.jpg');
  height: 100%;
  width: 100%;
  background-repeat: no-repeat;
  background-size: cover;
}

<body>

  <div class="header">

    <div class="container">

      <div class="logo">
        <h1><a href="#">Lusofly Virtual</a></h1>
      </div>

      <div class="nav">
        <ul>
          <li><a href="#">HOME</a></li>
          <li><a href="#">COMMUNITY</a></li>
          <li><a href="#">CONTACT</a></li>
          <li><a href="#">PILOT AREA</a></li>
        </ul>
      </div>
      <div id="mydiv"></div>
    </div>
  </div>
</body>


问:
Delete item from a pivot table
I try to delete an item form a pivot query , and i'm not sure if i do the right method .

Here my view with some "football stades" for a structure (club)

structure can have many stades and stades have many structures

here my model Stade :

```<code>public function structures()
    {
        return $this->belongsToMany('App\Structure');
    }
</code>```

here my model Structure :

```<code> public function stades(){

        return $this->belongsToMany('App\Stade');

    }
</code>```

My pivot table is like:

```<code>structure_id
stade_id

@foreach($club->stades as $stade)
                        <tr>
                            <th>{{$stade->lb_nom}}</th>
                            <th>{{$stade->adresse_stade}}</th>
                            <th>{{$stade->ville_stade}}</th>
                            <th>{{$stade->cd_post_stade}}</th>
                            <th>{{$stade->tel_stade}}</th>
                            <th>
                                {{ Form::open(['method' => 'DELETE', 'route' => ['club.stade.destroy', $club->id , $stade->id ]]) }}
                                {{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
                                {{ Form::close() }}

                            </th>
                        </tr>
                        @endforeach
</code>```

I can insert a new stade to a structure without any problems

```<code> public function store(Request $request , $id){

    $stade_structure = new ClubStade;

    $structure =  Structure::findOrFail($id);

    $stade_structure->structure_id = $structure->id;

    $stade_structure->stade_id = $request->input('stade_id');

    $stade_structure->save();

        return back()->with('status', "Un nouveau stade à été ajouté pour votre Club ! ");
    }
</code>```

but now i would like to detach or delete the record from the table . do i need to make a delete function ?

thanks a lot in advance

答:
detach() is what you're looking for:

This will delete item only from pivot table.

If you want to delete relating model then you have to use delete method.
Click here for more detail

Title: Delete item from a pivot table

Body:
I try to delete an item form a pivot query , and i'm not sure if i do the right method .

Here my view with some "football stades" for a structure (club)

structure can have many stades and stades have many structures

here my model Stade :

public function structures()
    {
        return $this->belongsToMany('App\Structure');
    }

here my model Structure :

 public function stades(){

        return $this->belongsToMany('App\Stade');

    }

My pivot table is like:

structure_id
stade_id

@foreach($club->stades as $stade)

                            {{$stade->lb_nom}}
                            {{$stade->adresse_stade}}
                            {{$stade->ville_stade}}
                            {{$stade->cd_post_stade}}
                            {{$stade->tel_stade}}

                                {{ Form::open(['method' => 'DELETE', 'route' => ['club.stade.destroy', $club->id , $stade->id ]]) }}
                                {{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
                                {{ Form::close() }}

                        @endforeach

I can insert a new stade to a structure without any problems

 public function store(Request $request , $id){

    $stade_structure = new ClubStade;

    $structure =  Structure::findOrFail($id);

    $stade_structure->structure_id = $structure->id;

    $stade_structure->stade_id = $request->input('stade_id');

    $stade_structure->save();

        return back()->with('status', "Un nouveau stade à été ajouté pour votre Club ! ");
    }

but now i would like to detach or delete the record from the table . do i need to make a delete function ?

thanks a lot in advance


问:
Linq - how to replace a lists property with value from another list where both keys are equal
I have 2 lists groupoptions and dataIndicator

```<code>class groupoptions{
  ...
  GroupName string
}

class dataIndicator{
  ...
 HeaderID int
 IndicatorDescription
}
</code>```

currently my groupname possible values are 4 or 5 or 11

first i want to get all dataindicators where headerid  is equal to GroupName, then replace those GroupNames with dataindicator's IndicatorDescription

What would be the Linq syntax for this?

UPDATE

using join

```<code>var newList = from first in dataIndicator
                      join second in groupedoptions
                      on first.HeaderID.ToString() equals second.GroupName
                      select new { first,second };
</code>```

What next?
PROBLEM: i want to do it inside a constructor that is being created inside a Linq Select

```<code>var list = xyz.Select(x => new groupoptions(){
   GroupName = x.Key.ToString();
 })
</code>```

答:
Here's a non-linq example:</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var groupOptions = new List<GroupOption>();
            groupOptions.Add(new GroupOption { GroupName = 4.ToString() });
            groupOptions.Add(new GroupOption { GroupName = 5.ToString() });
            groupOptions.Add(new GroupOption { GroupName = 11.ToString() });

            var dataIndicators = new List<DataIndicator>();
            dataIndicators.Add(new DataIndicator { HeaderID = 4, IndicatorDescription = "four" });
            dataIndicators.Add(new DataIndicator { HeaderID = 99, IndicatorDescription = "ninetynine" });
            dataIndicators.Add(new DataIndicator { HeaderID = 100, IndicatorDescription = "onehundred" });

            Console.WriteLine("Before:");
            PrintGroupOptions(groupOptions);

            foreach (var dataIndicator in dataIndicators)
            {
                foreach (var groupOption in groupOptions)
                {
                    if (dataIndicator.HeaderID.ToString() == groupOption.GroupName)
                    {
                        groupOption.GroupName = dataIndicator.IndicatorDescription;
                    }
                }
            }

            Console.WriteLine("After:");
            PrintGroupOptions(groupOptions);
        }

        static void PrintGroupOptions(List<GroupOption> groupOptions)
        {
            groupOptions.ToList().ForEach(g => Console.WriteLine(g));
        }
    }

    class GroupOption
    {
        public string GroupName { get; set; }
        public override string ToString()
        {
            return GroupName;
        }
    }

    class DataIndicator
    {
        public int HeaderID { get; set; }
        public string IndicatorDescription { get; set; }
    }
}
</code>```

Body:
I have 2 lists groupoptions and dataIndicator

class groupoptions{
  ...
  GroupName string
}

class dataIndicator{
  ...
 HeaderID int
 IndicatorDescription
}

currently my groupname possible values are 4 or 5 or 11

first i want to get all dataindicators where headerid  is equal to GroupName, then replace those GroupNames with dataindicator's IndicatorDescription

What would be the Linq syntax for this?

UPDATE

using join

var newList = from first in dataIndicator
                      join second in groupedoptions
                      on first.HeaderID.ToString() equals second.GroupName
                      select new { first,second };

What next?
PROBLEM: i want to do it inside a constructor that is being created inside a Linq Select

var list = xyz.Select(x => new groupoptions(){
   GroupName = x.Key.ToString();
 })

Body:
Here's a non-linq example:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var groupOptions = new List<GroupOption>();
            groupOptions.Add(new GroupOption { GroupName = 4.ToString() });
            groupOptions.Add(new GroupOption { GroupName = 5.ToString() });
            groupOptions.Add(new GroupOption { GroupName = 11.ToString() });

            var dataIndicators = new List<DataIndicator>();
            dataIndicators.Add(new DataIndicator { HeaderID = 4, IndicatorDescription = "four" });
            dataIndicators.Add(new DataIndicator { HeaderID = 99, IndicatorDescription = "ninetynine" });
            dataIndicators.Add(new DataIndicator { HeaderID = 100, IndicatorDescription = "onehundred" });

            Console.WriteLine("Before:");
            PrintGroupOptions(groupOptions);

            foreach (var dataIndicator in dataIndicators)
            {
                foreach (var groupOption in groupOptions)
                {
                    if (dataIndicator.HeaderID.ToString() == groupOption.GroupName)
                    {
                        groupOption.GroupName = dataIndicator.IndicatorDescription;
                    }
                }
            }

            Console.WriteLine("After:");
            PrintGroupOptions(groupOptions);
        }

        static void PrintGroupOptions(List<GroupOption> groupOptions)
        {
            groupOptions.ToList().ForEach(g => Console.WriteLine(g));
        }
    }

    class GroupOption
    {
        public string GroupName { get; set; }
        public override string ToString()
        {
            return GroupName;
        }
    }

    class DataIndicator
    {
        public int HeaderID { get; set; }
        public string IndicatorDescription { get; set; }
    }
}


问:
Laravel 5: Bulk insertion in mongo DB showing error
I am using jenssegers package in Laravel 5 for mongodb.
I am inserting multiple data in below described way and data is inserted successfully in mongodb but then it through error before the script completes.

```<code>$AllTrans=array();
$AllTrans[]=array("InvoiceID"=>1,"Amount"=>50);
$AllTrans[]=array("InvoiceID"=>2,"Amount"=>150);

$mongo_connnection->collection('invoices')->insert($AllTrans);
</code>```

Here is the error:

```<code>MongoException in Collection.php line 42:
No write ops were included in the batch
</code>```

But i can not figure out problem, I have tried passing option like   array('multi' => true) with insert query but it was not working.

答:
It will work great with bulk addition, this way, you just need to create on array and pass it to it.</p>

```<code>$temp = [
            [
                'item'=> "envelopes"
            ],
            [
                'item'=> "envelopesas"
            ],
            [
                'item'=> "lala"
            ]
        ];

        $userData = DB::table('log')->raw( function ( $collection ) use ($temp) {

            return $collection->insertMany($temp);
        });
</code>```

Body:
I am using jenssegers package in Laravel 5 for mongodb.
I am inserting multiple data in below described way and data is inserted successfully in mongodb but then it through error before the script completes.

$AllTrans=array();
$AllTrans[]=array("InvoiceID"=>1,"Amount"=>50);
$AllTrans[]=array("InvoiceID"=>2,"Amount"=>150);

$mongo_connnection->collection('invoices')->insert($AllTrans);

Here is the error:

MongoException in Collection.php line 42:
No write ops were included in the batch

But i can not figure out problem, I have tried passing option like   array('multi' => true) with insert query but it was not working.

Body:
It will work great with bulk addition, this way, you just need to create on array and pass it to it.

$temp = [
            [
                'item'=> "envelopes"
            ],
            [
                'item'=> "envelopesas"
            ],
            [
                'item'=> "lala"
            ]
        ];

        $userData = DB::table('log')->raw( function ( $collection ) use ($temp) {

            return $collection->insertMany($temp);
        });


问:
iOS -- require OpenGL ES 2.0 for upgrade?
The first version of my app runs on all iOS devices. I'm considering releasing an upgrade which will only work on devices which support OpenGL ES 2.0. Is that as simple as changing the UIRequiredDeviceCapabilities in info.plist? If I do this, what will users on the old devices see when they try to upgrade? Or will they even be notified that there's an upgrade available?

And lastly, just want to double-check that this will work, that it's possible to change the device requirements for different versions of my app.

答: I would not restrict app via UIRequiredDeviceCapabilities unless you do not want app installed. I would not restrict and check at runtime and then use new features conditionally. </p>

ContentLicense: CC BY-SA 2.5


问:
How to generate Angular4 javascript es6 scaffold app
Is there any possibility to easy generate Angular 4 (or Angular 2) app that uses ES6 JavaScript instead of TypeScript? I maybe unaware and maybe it works out of the box, but as I've checked angular-cli and angular documentation there's no information how it's possible.</p>

答:
Here you go. This uses Ang4, Babel, WebPack 2, has all the updated related packages (required for WP2 etc.) etc. Follow the instructions in README.md (basically, pull it down, run "npm install", then "npm run serve", which fires up the webpack dev server/watcher). Router config and all that set up, couple of scrap components in there and whatnot as basic samples.

Probably the most interesting thing is the package.json file. Anybody that knows Angular2 from scratch could just grab that.

Not thoroughly tested, but seems to just work. Post if anything looks broken and I try to fix.

https://github.com/tcoz/ang2-babel-webpack/tree/angular4


问:
about xpath when using scrapy
xpath sentences:

```<code>item['title'] = response.xpath('//span[@class="title"]/text()').extract_first()
item['content'] = response.xpath('//div[@class="content"]').extract_first()
</code>```

results：

```<code>{
'title': '\t史蒂芬霍金',
'content': '<div class="content"><div>能够在过去这么多年的时间里研究并学习宇宙学<br>\r\n对我来说意义非凡</div></div>'
}
</code>```

questions：

1、How to remove \t in title field?

2、How to remove

 in content field?(the children nodes can not be removed.)

答:
You can use Python's strip() for title:

```<code>item['title'] = response.xpath(
                    '//span[@class="title"]/text()').extract_first().strip()
</code>```

And you can chain your selector with XPath's string() or normalize-space() for content:

```<code>item['content'] = response.xpath(
                      '//div[@class="content"]').xpath('string(.)').extract_first()
</code>```

Title: about xpath when using scrapy

Body:
xpath sentences:

item['title'] = response.xpath('//span[@class="title"]/text()').extract_first()
item['content'] = response.xpath('//div[@class="content"]').extract_first()

results：

{
'title': '\t史蒂芬霍金',
'content': '

能够在过去这么多年的时间里研究并学习宇宙学
\r\n对我来说意义非凡

'
}

questions：

1、How to remove \t in title field?

2、How to remove

 in content field?(the children nodes can not be removed.)

Body:
You can use Python's strip() for title:

item['title'] = response.xpath(
                    '//span[@class="title"]/text()').extract_first().strip()

And you can chain your selector with XPath's string() or normalize-space() for content:

item['content'] = response.xpath(
                      '//div[@class="content"]').xpath('string(.)').extract_first()


问:
C# - Custom TabControl Class Memory Leak onHover
```<code>#region CustomTabControl - Leak

public class cTabControl : TabControl
{

    #region Remove Padding
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x1300 + 40)
        {
            lparamrect rc = (lparamrect)m.GetLParam(typeof(lparamrect));
            rc.Left -= 4;
            rc.Right += 4;
            rc.Top -= 2;
            rc.Bottom += 4;
            Marshal.StructureToPtr(rc, m.LParam, true);
        }
        base.WndProc(ref m);
    }
    internal struct lparamrect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
    #endregion

    //Variables;
    private Rectangle Rect;
    private int _OverIndex = -1;
    private int OverIndex
    {
        get { return _OverIndex; }
        set
        {
            _OverIndex = value;
            Invalidate();
        }
    }

    //Default Settings;
    public cTabControl()
    {
        DoubleBuffered = true;
        Alignment = TabAlignment.Left;
        SizeMode = TabSizeMode.Fixed;
        ItemSize = new Size(30, 32);
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
    }

    protected override void OnControlAdded(ControlEventArgs e)
    {
        base.OnControlAdded(e);
        e.Control.BackColor = Settings.Default.TabBackgroundColor;
        e.Control.ForeColor = ColorFromHex("#FFFFFF");
        e.Control.Font = new Font("Kozuka Gothic Pro B", 9);
    }

    protected override void OnPaint(PaintEventArgs e)
    {

        //Set the Graphics Variable;
        Graphics G = e.Graphics;

        //Raise the Paint event;
        base.OnPaint(e);

        //Dynamically Darken the Parent's Color slightly;
        Color DarkParentColor = default(Color);
        if (ColorContrast(Parent.BackColor) == Color.White)
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.01), (float)1.2);
        }
        else
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.1), (float)0.35);
        }

        //Set the Tab's Background Color to the Darkened Parent's Color;
        G.Clear(DarkParentColor);

        //For Each Tab;
        for (int i = 0; i <= TabPages.Count - 1; i++)
        {

            if ((string)TabPages[i].Tag != "Hidden")
            {

                // Get the Tab's Rectangle Sizing
                Rect = GetTabRect(i);
                float x = Convert.ToSingle((Rect.X + (Rect.Height - 10)) - (Rect.Height / 2));
                float y = Convert.ToSingle((Rect.Y + (Rect.Height - 10)) - (Rect.Height / 2));

                // If the user is hovering over the tab
                if (!(OverIndex == -1))
                {
                    using (SolidBrush sb = new SolidBrush(Color.FromArgb(9, Color.Black)))
                    {
                        //Draw the Hover Background;
                        G.FillRectangle(sb, new Rectangle(GetTabRect(OverIndex).X, GetTabRect(OverIndex).Y, GetTabRect(OverIndex).Width, GetTabRect(OverIndex).Height));
                    }
                }
                else
                {
                    using (SolidBrush sb = new SolidBrush(DarkParentColor))
                    {
                        // Set the Background Color to the Darkened Parent's Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, Rect.Width + 6, Rect.Height));
                    }
                }

                // If its the selected tab
                if (SelectedIndex == i)
                {
                    using (SolidBrush sb = new SolidBrush(Settings.Default.HighlightColor), sb2 = new SolidBrush(Color.FromArgb(30, Color.Black)))
                    {
                        // Set the Selected Indicator to the Highlight Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, 2, Rect.Height));
                        //Draw the Hover Background;
                        G.FillRectangle(sb2, new Rectangle(Rect.X, Rect.Y, Rect.Width, Rect.Height));
                    }
                }

                //Set Render Quality;
                G.TextRenderingHint = TextRenderingHint.AntiAlias;

                if ((!ReferenceEquals(Tag, "TextOnly")))
                {
                    if (!(SelectedIndex == i))
                    {
                        using (Graphics gfx = Graphics.FromImage(new Bitmap(GetTabIcon(i).Width, GetTabIcon(i).Height)))
                        {
                            ColorMatrix matrix = new ColorMatrix();
                            matrix.Matrix33 = (float)0.5;
                            ImageAttributes attributes = new ImageAttributes();
                            attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            G.DrawImage(GetTabIcon(i), new Rectangle(Convert.ToInt32(x), Convert.ToInt32(y), 20, 20), 0, 0, GetTabIcon(i).Width, GetTabIcon(i).Height, GraphicsUnit.Pixel, attributes);
                        }
                    }
                    else if (SelectedIndex == i)
                    {
                        using (Image ti = GetTabIcon(i))
                        {
                            G.DrawImage(ti, new Rectangle(Convert.ToInt32(x) + 1, Convert.ToInt32(y), 20, 20));
                        }
                    }
                }
                else
                {
                    dynamic TabProperties = TabPages[i];
                    StringFormat sf = new StringFormat();
                    sf.LineAlignment = StringAlignment.Center;
                    using (Font f = new Font(LoadFont(Resources.Roboto_Medium), 10f))
                    using (SolidBrush sb = new SolidBrush(TabProperties.ForeColor))
                    {
                        G.DrawString(TabProperties.Text, f, sb, x + 2, Convert.ToSingle(Rect.Y + (Rect.Height / 2)), sf);
                    }
                }

            }

        }

    }

    protected override void OnSelecting(TabControlCancelEventArgs e)
    {
        base.OnSelecting(e);

        if ((e.TabPage != null))
        {
            if (!string.IsNullOrEmpty(Convert.ToString(e.TabPage.Tag)))
            {
                e.Cancel = true;
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        for (int I = 0; I <= TabPages.Count - 1; I++)
        {
            if (GetTabRect(I).Contains(e.Location) & string.IsNullOrEmpty(Convert.ToString(TabPages[I].Tag)))
            {
                OverIndex = I;
                break; // TODO: might not be correct. Was : Exit For
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        OverIndex = -1;
    }

}

#endregion
</code>```

I have this custom tab control class that is more modern and is left aligned rather than top aligned. It works, but there's a huge memory leak issue with it. I'm using MouseMove to be able to get the mouse location and then cross match it with the tabs, but even if I leave my mouse still or move in more to the middle of the tab for example, it will obviously execute millions of times, this then causes huge spikes in memory usage.

Is there any way around this?

Process Memory Diagnostic

答: It seems that the reason it was happening was because for TextOnly, it was loading Roboto using a LoadFont gdi32.dll, and it for some reason made it need to use a ton of resources to load it, removing all of LoadFont() completely and then adding using() on the GetTabIcon()'s Bitmaps made it fully stable!</p>

Body:
#region CustomTabControl - Leak

public class cTabControl : TabControl
{

    #region Remove Padding
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x1300 + 40)
        {
            lparamrect rc = (lparamrect)m.GetLParam(typeof(lparamrect));
            rc.Left -= 4;
            rc.Right += 4;
            rc.Top -= 2;
            rc.Bottom += 4;
            Marshal.StructureToPtr(rc, m.LParam, true);
        }
        base.WndProc(ref m);
    }
    internal struct lparamrect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
    #endregion

    //Variables;
    private Rectangle Rect;
    private int _OverIndex = -1;
    private int OverIndex
    {
        get { return _OverIndex; }
        set
        {
            _OverIndex = value;
            Invalidate();
        }
    }

    //Default Settings;
    public cTabControl()
    {
        DoubleBuffered = true;
        Alignment = TabAlignment.Left;
        SizeMode = TabSizeMode.Fixed;
        ItemSize = new Size(30, 32);
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
    }

    protected override void OnControlAdded(ControlEventArgs e)
    {
        base.OnControlAdded(e);
        e.Control.BackColor = Settings.Default.TabBackgroundColor;
        e.Control.ForeColor = ColorFromHex("#FFFFFF");
        e.Control.Font = new Font("Kozuka Gothic Pro B", 9);
    }

    protected override void OnPaint(PaintEventArgs e)
    {

        //Set the Graphics Variable;
        Graphics G = e.Graphics;

        //Raise the Paint event;
        base.OnPaint(e);

        //Dynamically Darken the Parent's Color slightly;
        Color DarkParentColor = default(Color);
        if (ColorContrast(Parent.BackColor) == Color.White)
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.01), (float)1.2);
        }
        else
        {
            DarkParentColor = ControlPaint.Light(ControlPaint.Dark(Parent.BackColor, (float)0.1), (float)0.35);
        }

        //Set the Tab's Background Color to the Darkened Parent's Color;
        G.Clear(DarkParentColor);

        //For Each Tab;
        for (int i = 0; i <= TabPages.Count - 1; i++)
        {

            if ((string)TabPages[i].Tag != "Hidden")
            {

                // Get the Tab's Rectangle Sizing
                Rect = GetTabRect(i);
                float x = Convert.ToSingle((Rect.X + (Rect.Height - 10)) - (Rect.Height / 2));
                float y = Convert.ToSingle((Rect.Y + (Rect.Height - 10)) - (Rect.Height / 2));

                // If the user is hovering over the tab
                if (!(OverIndex == -1))
                {
                    using (SolidBrush sb = new SolidBrush(Color.FromArgb(9, Color.Black)))
                    {
                        //Draw the Hover Background;
                        G.FillRectangle(sb, new Rectangle(GetTabRect(OverIndex).X, GetTabRect(OverIndex).Y, GetTabRect(OverIndex).Width, GetTabRect(OverIndex).Height));
                    }
                }
                else
                {
                    using (SolidBrush sb = new SolidBrush(DarkParentColor))
                    {
                        // Set the Background Color to the Darkened Parent's Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, Rect.Width + 6, Rect.Height));
                    }
                }

                // If its the selected tab
                if (SelectedIndex == i)
                {
                    using (SolidBrush sb = new SolidBrush(Settings.Default.HighlightColor), sb2 = new SolidBrush(Color.FromArgb(30, Color.Black)))
                    {
                        // Set the Selected Indicator to the Highlight Color
                        G.FillRectangle(sb, new Rectangle(Rect.X, Rect.Y, 2, Rect.Height));
                        //Draw the Hover Background;
                        G.FillRectangle(sb2, new Rectangle(Rect.X, Rect.Y, Rect.Width, Rect.Height));
                    }
                }

                //Set Render Quality;
                G.TextRenderingHint = TextRenderingHint.AntiAlias;

                if ((!ReferenceEquals(Tag, "TextOnly")))
                {
                    if (!(SelectedIndex == i))
                    {
                        using (Graphics gfx = Graphics.FromImage(new Bitmap(GetTabIcon(i).Width, GetTabIcon(i).Height)))
                        {
                            ColorMatrix matrix = new ColorMatrix();
                            matrix.Matrix33 = (float)0.5;
                            ImageAttributes attributes = new ImageAttributes();
                            attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            G.DrawImage(GetTabIcon(i), new Rectangle(Convert.ToInt32(x), Convert.ToInt32(y), 20, 20), 0, 0, GetTabIcon(i).Width, GetTabIcon(i).Height, GraphicsUnit.Pixel, attributes);
                        }
                    }
                    else if (SelectedIndex == i)
                    {
                        using (Image ti = GetTabIcon(i))
                        {
                            G.DrawImage(ti, new Rectangle(Convert.ToInt32(x) + 1, Convert.ToInt32(y), 20, 20));
                        }
                    }
                }
                else
                {
                    dynamic TabProperties = TabPages[i];
                    StringFormat sf = new StringFormat();
                    sf.LineAlignment = StringAlignment.Center;
                    using (Font f = new Font(LoadFont(Resources.Roboto_Medium), 10f))
                    using (SolidBrush sb = new SolidBrush(TabProperties.ForeColor))
                    {
                        G.DrawString(TabProperties.Text, f, sb, x + 2, Convert.ToSingle(Rect.Y + (Rect.Height / 2)), sf);
                    }
                }

            }

        }

    }

    protected override void OnSelecting(TabControlCancelEventArgs e)
    {
        base.OnSelecting(e);

        if ((e.TabPage != null))
        {
            if (!string.IsNullOrEmpty(Convert.ToString(e.TabPage.Tag)))
            {
                e.Cancel = true;
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        for (int I = 0; I <= TabPages.Count - 1; I++)
        {
            if (GetTabRect(I).Contains(e.Location) & string.IsNullOrEmpty(Convert.ToString(TabPages[I].Tag)))
            {
                OverIndex = I;
                break; // TODO: might not be correct. Was : Exit For
            }
            else
            {
                OverIndex = -1;
            }
        }

    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        OverIndex = -1;
    }

}

#endregion

I have this custom tab control class that is more modern and is left aligned rather than top aligned. It works, but there's a huge memory leak issue with it. I'm using MouseMove to be able to get the mouse location and then cross match it with the tabs, but even if I leave my mouse still or move in more to the middle of the tab for example, it will obviously execute millions of times, this then causes huge spikes in memory usage.

Is there any way around this?

Process Memory Diagnostic


问:
Double Quote Problem after Saving an INI file with Zend_Config
I got a problem when I want to write and save an INI file. I use Zend_Config_Ini to handle this procedure.

The problem is I always got 'Double Quote' in the value for every line that use integer or number afer saving process. Here is the example

The original application.ini file

```<code>resources.session.use_only_cookies = 1
resources.session.remember_me_seconds = 86400
</code>```

After I run these lines of code

```<code>$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini',
                                      null,
                                      array('skipExtends'        => true,
                                            'allowModifications' => true));

        // Modify a value
$config->production->resources->db->adapter = 'foobar';

        // Write the config file
$writer = new Zend_Config_Writer_Ini(array('config' => $config,
                                           'filename' => APPLICATION_PATH . '/configs/application.ini'));
$writer->write();
</code>```

The application.ini lines become

```<code>resources.session.use_only_cookies = "1"  //double quote appears T_T
resources.session.remember_me_seconds = "86400"  //double quote appears T_T
</code>```

What I want is the integer value must still remain the same (without double quotes).

Anyone can help me to solve this problem?

Thank you very much in advance

答:
Anyway,

In my solution, I had to remove some lines of code in Zend. The file that I changed was \Zend\Config\Writer\Ini.php for method _prepareValue() in line 150 to be like below

```<code>   protected function _prepareValue($value)
    {
        /*
         I comment it

         if (is_integer($value) || is_float($value)) {
            return $value;
        } elseif (is_bool($value)) {
            return ($value ? 'true' : 'false');
        } else {
            return '"' . addslashes($value) .  '"';
        }*/

        return $value; // my line
    }
</code>```

just comment the original code of Zend and just pass and return $value.

So, by changing this file I never get any double quote anymore for string, boolean or even number. This is that what I want. :)

Thank you everyone.

Body:
I got a problem when I want to write and save an INI file. I use Zend_Config_Ini to handle this procedure.

The problem is I always got 'Double Quote' in the value for every line that use integer or number afer saving process. Here is the example

The original application.ini file

resources.session.use_only_cookies = 1
resources.session.remember_me_seconds = 86400

After I run these lines of code

$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini',
                                      null,
                                      array('skipExtends'        => true,
                                            'allowModifications' => true));

        // Modify a value
$config->production->resources->db->adapter = 'foobar';

        // Write the config file
$writer = new Zend_Config_Writer_Ini(array('config' => $config,
                                           'filename' => APPLICATION_PATH . '/configs/application.ini'));
$writer->write();

The application.ini lines become

resources.session.use_only_cookies = "1"  //double quote appears T_T
resources.session.remember_me_seconds = "86400"  //double quote appears T_T

What I want is the integer value must still remain the same (without double quotes).

Anyone can help me to solve this problem?

Thank you very much in advance

Body:
Anyway,

In my solution, I had to remove some lines of code in Zend. The file that I changed was \Zend\Config\Writer\Ini.php for method _prepareValue() in line 150 to be like below

   protected function _prepareValue($value)
    {
        /*
         I comment it

         if (is_integer($value) || is_float($value)) {
            return $value;
        } elseif (is_bool($value)) {
            return ($value ? 'true' : 'false');
        } else {
            return '"' . addslashes($value) .  '"';
        }*/

        return $value; // my line
    }

just comment the original code of Zend and just pass and return $value.

So, by changing this file I never get any double quote anymore for string, boolean or even number. This is that what I want. :)

Thank you everyone.


问:
How to delay jquery step function response
I m using jQuery-step library with a form combining the formvalidation.js . i want to delay below method response until ajax complete.

i want to send return true/false when ajax complete.

```<code>onStepChanging: function (e, currentIndex, newIndex) {

    var fv = $stepForm.data('formValidation'), // FormValidation instance
        // The current step container
        $container = $stepForm.find('section[data-step="' + currentIndex + '"]');

    // Validate the container
    fv.validateContainer($container);
    var isValidStep = fv.isValidContainer($container);
    if (isValidStep === false || isValidStep === null) {
        // Do not jump to the next step
        return false;
    }
    if (isValidStep === true) {
        //call ajax here
        //wait for ajax to complete then move to next or keep
    }
    return true; //-> i want to delay this

},
</code>```

答:
In your case:

```<code>function submitForm($stepForm) {
    return new Promise((resolve, reject) =>{
      $.ajax({
        type: 'POST',
        url: 'http://' + location.host + "/ajax",
        dataType: 'JSON',
        data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
        /* Resolving true on success, you could also return a json object if you need the response */
        success: () => { resolve(true); },
        /* Rejecting the promise in case of an error */
        error: () => { reject(false) }
     })
  })
}
</code>```

Then:

```<code>onStepChanging: function (e, currentIndex, newIndex) {
  if (isValidStep === true) {
       submitForm($stepForm)
       .then( /*...Do whatever you want ..*/)
       .catch( console.log );
  }
</code>```

Body:
I m using jQuery-step library with a form combining the formvalidation.js . i want to delay below method response until ajax complete.

i want to send return true/false when ajax complete.

onStepChanging: function (e, currentIndex, newIndex) {

    var fv = $stepForm.data('formValidation'), // FormValidation instance
        // The current step container
        $container = $stepForm.find('section[data-step="' + currentIndex + '"]');

    // Validate the container
    fv.validateContainer($container);
    var isValidStep = fv.isValidContainer($container);
    if (isValidStep === false || isValidStep === null) {
        // Do not jump to the next step
        return false;
    }
    if (isValidStep === true) {
        //call ajax here
        //wait for ajax to complete then move to next or keep
    }
    return true; //-> i want to delay this

},

Body:
In your case:

function submitForm($stepForm) {
    return new Promise((resolve, reject) =>{
      $.ajax({
        type: 'POST',
        url: 'http://' + location.host + "/ajax",
        dataType: 'JSON',
        data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
        /* Resolving true on success, you could also return a json object if you need the response */
        success: () => { resolve(true); },
        /* Rejecting the promise in case of an error */
        error: () => { reject(false) }
     })
  })
}

Then:

onStepChanging: function (e, currentIndex, newIndex) {
  if (isValidStep === true) {
       submitForm($stepForm)
       .then( /*...Do whatever you want ..*/)
       .catch( console.log );
  }


问:
aggregate function calls cannot be nested postgresql
I get "aggregate function calls cannot be nested" error from PostgreSQL. I tried different bunch of things but could not solve.

```<code>select c.*, (
             select sum((count(distinct product_id))/2)
             from page_views
             where product_id in (c.p1, c.p2)
             group by user_id, session_id
             having count(distinct product_id) > 1
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;
</code>```

Thanks!

答:
You can just use subselect to get nested aggregate functions, like this:</p>

```<code>select c.*, (SELECT sum(count_column) FROM (
                 select (count(distinct product_id))/2 AS count_column
                 from page_views
                 where product_id in (c.p1, c.p2)
                 group by user_id, session_id
                 having count(distinct product_id) > 1
               ) sub_q
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;
</code>```

Body:
I get "aggregate function calls cannot be nested" error from PostgreSQL. I tried different bunch of things but could not solve.

select c.*, (
             select sum((count(distinct product_id))/2)
             from page_views
             where product_id in (c.p1, c.p2)
             group by user_id, session_id
             having count(distinct product_id) > 1
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;

Thanks!

Body:
You can just use subselect to get nested aggregate functions, like this:

select c.*, (SELECT sum(count_column) FROM (
                 select (count(distinct product_id))/2 AS count_column
                 from page_views
                 where product_id in (c.p1, c.p2)
                 group by user_id, session_id
                 having count(distinct product_id) > 1
               ) sub_q
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;


问:
How to exclude dates from a table when searching between two dates?
I have created a query where it can search between two dates to calculate working days excluding bank holidays.

I have created a table with dates inside of bank holidays

How can i create a query where when searching between the two dates, it excludes the dates within the table?

Here is what i have so far...

```<code> DECLARE @StartDate DATETIME
   DECLARE @EndDate DATETIME
-- Calculate the calendar working days below INCLUDING BH
--YEAR/MONTH/DATE
    SET @StartDate = '2016/09/01'
    SET @EndDate = '2016/09/30'
    SELECT
       (DATEDIFF(dd, @StartDate, @EndDate) + 1)
      -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
      -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
       DECLARE @TotalDays INT, @WorkDays INT
       SET @TotalDays = (DATEDIFF(dd, @StartDate, @EndDate) +1)
       print @TotalDays
</code>```

答:
You can calculate between two dates by manipulating this</p>

```<code>DECLARE @sql VARCHAR(500),
@Region VARCHAR(100) = 'COLUMN2', --It can be Column1, Column2.....
@StartDate DATETIME = '2016-04-10',
@EndDate DATETIME = '2016-04-15'

SET @sql = '
    SELECT
    COUNT(' + @Region + ')
    FROM  bankholidays
    WHERE ' + @Region + ' BETWEEN ''' + CAST(@StartDate AS VARCHAR) + ''' AND ''' + CAST(@EndDate AS VARCHAR) + ''''

EXEC (@SQL)
</code>```

Body:
I have created a query where it can search between two dates to calculate working days excluding bank holidays.

I have created a table with dates inside of bank holidays

How can i create a query where when searching between the two dates, it excludes the dates within the table?

Here is what i have so far...

 DECLARE @StartDate DATETIME
   DECLARE @EndDate DATETIME
-- Calculate the calendar working days below INCLUDING BH
--YEAR/MONTH/DATE
    SET @StartDate = '2016/09/01'
    SET @EndDate = '2016/09/30'
    SELECT
       (DATEDIFF(dd, @StartDate, @EndDate) + 1)
      -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
      -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
       DECLARE @TotalDays INT, @WorkDays INT
       SET @TotalDays = (DATEDIFF(dd, @StartDate, @EndDate) +1)
       print @TotalDays

Body:
You can calculate between two dates by manipulating this

DECLARE @sql VARCHAR(500),
@Region VARCHAR(100) = 'COLUMN2', --It can be Column1, Column2.....
@StartDate DATETIME = '2016-04-10',
@EndDate DATETIME = '2016-04-15'

SET @sql = '
    SELECT
    COUNT(' + @Region + ')
    FROM  bankholidays
    WHERE ' + @Region + ' BETWEEN ''' + CAST(@StartDate AS VARCHAR) + ''' AND ''' + CAST(@EndDate AS VARCHAR) + ''''

EXEC (@SQL)


问:
Keras 2DConvolution produces unlogical output tensor - 32x32 image becomes 32xN feature maps, instead of 32x32xN
According to my understanding, a 2D-Convolution applies N filters to an input image, producing N new "images" (=feature maps).

If we neglect stride/subsampling, a 32x32 image becomes a Nx32x32 tensor after 2D-Convolution with N channels:

However, in Keras, a 32x32 input produces a 32xN output. So, my question is, how is the dimensional reduction applied? Is there another hidden layer involved in this step?

And if so, isn't the network losing its ability to view the image as it is - namely a 2D-entity?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This code can reproduce my above claims:

```<code>inputs = Input(shape=(1, 32, 32,))
shared = Convolution2D(nb_filter=10, nb_row=8, nb_col=8, subsample=(1, 1), border_mode='same', activation='relu')(inputs)
print("1 => ", inputs.shape)
print("2 => ", shared.shape)
</code>```

It produces - as we apply 10 filters (==N) to a 32x32 grayscale image

1 =>  (?, 1, 32, 32)

2 =>  (?, 1, 32, 10)

Where ? is the unspecified batch size and 1 is the amount of input-channels (would be 3 for RGB, is 1 for Grayscale).

The input has a shape of 32x32, as expected.
But then, the output of the convolution has 32xN dimensions instead of 32x32xN

答:
It may be because of input format order.

From Keras docs Conv2D takes this param

data_format: A string, one of channels_last (default) or
  channels_first. The ordering of the dimensions in the inputs.
  channels_last corresponds to inputs with shape  (batch, height, width,
  channels) while channels_first corresponds to inputs with shape
  (batch, channels, height, width). It defaults to the image_data_format
  value found in your Keras config file at ~/.keras/keras.json. If you
  never set it, then it will be "channels_last".

So your (1, 32, 32) is actually a 1x32 image with 32 channels. Switch to (32, 32, 1) or set the data_format argument to channels_first.

More info on changing the default behavior: https://keras.io/backend/
You can use keras.backend.image_data_format() to get your setting and set_image_data_format(data_format) to set either channels_first or channels_last.

There is this setting because Theano and TF handle dimension ordering differently and it depends on the backed you're using.

Body:
According to my understanding, a 2D-Convolution applies N filters to an input image, producing N new "images" (=feature maps).

If we neglect stride/subsampling, a 32x32 image becomes a Nx32x32 tensor after 2D-Convolution with N channels:

However, in Keras, a 32x32 input produces a 32xN output. So, my question is, how is the dimensional reduction applied? Is there another hidden layer involved in this step?

And if so, isn't the network losing its ability to view the image as it is - namely a 2D-entity?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This code can reproduce my above claims:

inputs = Input(shape=(1, 32, 32,))
shared = Convolution2D(nb_filter=10, nb_row=8, nb_col=8, subsample=(1, 1), border_mode='same', activation='relu')(inputs)
print("1 => ", inputs.shape)
print("2 => ", shared.shape)

It produces - as we apply 10 filters (==N) to a 32x32 grayscale image

1 =>  (?, 1, 32, 32)

2 =>  (?, 1, 32, 10)

Where ? is the unspecified batch size and 1 is the amount of input-channels (would be 3 for RGB, is 1 for Grayscale).

The input has a shape of 32x32, as expected.
But then, the output of the convolution has 32xN dimensions instead of 32x32xN


问:
I am getting an error while creating a simple RDD in Spark
I am using Jupyter notebook and just started to learn Apache spark, but getting an error while creating a simple RDD:

```<code>sc.parallelize([2, 3, 4]).count()
</code>```

the error is : parallelize() missing 1 required positional argument: 'c'
This happens for every kind like if I try textFile(""), I get that a positional argument is missing. I have the sparkcontext as sc, can someone please help me with this.

答:
```<code>rdd = sc.parallelize([2, 3, 4])
c = rdd.count()
</code>```

The count() method return a long type value not rdd.

Body:
I am using Jupyter notebook and just started to learn Apache spark, but getting an error while creating a simple RDD:

sc.parallelize([2, 3, 4]).count()

the error is : parallelize() missing 1 required positional argument: 'c'
This happens for every kind like if I try textFile(""), I get that a positional argument is missing. I have the sparkcontext as sc, can someone please help me with this.

Body:
rdd = sc.parallelize([2, 3, 4])
c = rdd.count()

The count() method return a long type value not rdd.


答:
You have to define a Spark context and the number of slices for parallelization. For example:

```<code>import pyspark as sp

nSlices = 10
sc = sp.SparkContext(appName='myApp')
rdd = sc.parallelize([2,3,4],nSlices)

# [...]
sc.close()
</code>```

And don't forget to call your program using spark-submit

Title: I am getting an error while creating a simple RDD in Spark

Body:
You have to define a Spark context and the number of slices for parallelization. For example:

import pyspark as sp

nSlices = 10
sc = sp.SparkContext(appName='myApp')
rdd = sc.parallelize([2,3,4],nSlices)

# [...]
sc.close()

And don't forget to call your program using spark-submit


问:
Including SVG contents in Laravel 5 Blade template
What is the best way to include the contents of an SVG file (located in the assets folder) in a Laravel 5 blade template?

I don't want to use image/object/embed tags, this should be an inline SVG for reasons of speed.

I know I could use <?php file_get_contents("file.svg") ?> but is there a better way specific to Laravel/Blade?

Edit: to clarify, the method should work with all SVG files, including the one below.

<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
<path stroke="red" fill="#00f" d="M10 10h100v100H10z"/>
</svg>
```

答:
Similar to the accepted answer but a bit cleaner (imo).

Use the laravel directive to extend blade, like so (in your App Service Provider, as outlined here):

```<code>    \Blade::directive('svg', function($arguments) {
        // Funky madness to accept multiple arguments into the directive
        list($path, $class) = array_pad(explode(',', trim($arguments, "() ")), 2, '');
        $path = trim($path, "' ");
        $class = trim($class, "' ");

        // Create the dom document as per the other answers
        $svg = new \DOMDocument();
        $svg->load(public_path($path));
        $svg->documentElement->setAttribute("class", $class);
        $output = $svg->saveXML($svg->documentElement);

        return $output;
    });
</code>```

Then use it in your blade like so:

```<code>        <div class="Login__image Login__cloud">
            @svg('cloud.svg', 'Cloud')
        </div>
</code>```

Body:
Similar to the accepted answer but a bit cleaner (imo).

Use the laravel directive to extend blade, like so (in your App Service Provider, as outlined here):

    \Blade::directive('svg', function($arguments) {
        // Funky madness to accept multiple arguments into the directive
        list($path, $class) = array_pad(explode(',', trim($arguments, "() ")), 2, '');
        $path = trim($path, "' ");
        $class = trim($class, "' ");

        // Create the dom document as per the other answers
        $svg = new \DOMDocument();
        $svg->load(public_path($path));
        $svg->documentElement->setAttribute("class", $class);
        $output = $svg->saveXML($svg->documentElement);

        return $output;
    });

Then use it in your blade like so:

        <div class="Login__image Login__cloud">
            @svg('cloud.svg', 'Cloud')
        </div>


问:
Angular Filter throws Error: [$injector:unpr]
I am working on an project and need to modify some code to resolve an error
Filter:

```<code>(function () {
    'use strict';

    angular.module('myApp').filter('filter1', ['$filter', firstFilter]);
    angular.module('myApp').filter('filter2', ['$filter', secondFilter]);

    function firstFilter($filter) {
        return function (element) {
            //code
        };
    }

    function secondFilter($filter) {
        return function (element) {
            //code
        };
    }
})();
</code>```

This only appears to happen with the minified version.

It look a lot like Angular directive throws Error: [$injector:unpr]
but the code is already injecting $filter.

What do i miss in this situation.

答:
I added your code in a plunker (all console errors fixed) and I think you could be getting [$injector:nomod] instead.

It occurs when you don't specify angular.module('myApp', []) the emtpy array describing dependencies. Check for that. To retrieve a reference to the same module for further configuration, you can call angular.module without the array argument.

Also, you have a typo in firstFilter function declaration which was misspelled as firtstFilter

Body:
I am working on an project and need to modify some code to resolve an error
Filter:

(function () {
    'use strict';

    angular.module('myApp').filter('filter1', ['$filter', firstFilter]);
    angular.module('myApp').filter('filter2', ['$filter', secondFilter]);

    function firstFilter($filter) {
        return function (element) {
            //code
        };
    }

    function secondFilter($filter) {
        return function (element) {
            //code
        };
    }
})();

This only appears to happen with the minified version.

It look a lot like Angular directive throws Error: [$injector:unpr]
but the code is already injecting $filter.

What do i miss in this situation.


问:
How to disable sorting in NSTableVIew?
I have a an NSTableView when ever I click on a specific header column the data in the table get reversed or sort upside down. I have checked NSTableView as well as NSTableColumn but couldn't find any method that disables this. I would be obliged if anyone can help in disabling this sorting on clicking on the header of a particular column.

答:
Sorting of the NSTableView is done by its sortDescriptors, see here.

An NSTableColumn uses its sortDescriptorPrototype (see here) to generate the sort descriptor of the NSTableView, depending on how many times you clicked the column header, etc.

If you use dataSource to manage the data, then the sort descriptor is communicated via the delegate method tableView:sortDescriptorsDidChange:, see here. You just need to ignore the change message to stop sorting.

If you use Cocoa bindings to manage the data, the sort descriptor is generated by the table column and set to the NSArrayController. To stop it, just open the inspector of the binding of the table column, select value, and uncheck "Creates Sort Descriptor."

Title: How to disable sorting in NSTableVIew?


问:
Recursive Function Call : Powershell (Scope?)
Having trouble getting my menus to work. I would like to make a menu class, but I'm stuck with v2. Each time I enter "1" at the "Main Menu", it will simply re-present me with the main menu instead of re-entering the function with the new $menuType.

```<code>function presentMenu{
param ([string]$menuType)

if($menuType = "Main"){
     Write-Host "MAIN MENU: 1.) Add Scanner 2.) Remove Scanner 3.) Lookup Scanner Config 4.) Exit"
     $command = Read-Host
     ##DEBUG## write-host $menuType

     if ($command -eq 1){
         presentMenu("addScaner")
     }
     elseif ($command -eq 2){

     }
     elseif ($command -eq 3){

     }
     elseif ($command -eq 4){
        exit
     }
     elseif ($command -eq 5){
        exit
     }
    else{
        presentMenu("Main")
    }
  }

elseif($menuType = "addScanner"){
    Write-Host "ADD SCANNER: 1.) From File 2.) From Input 3.) Back  4.) Exit"
    $command = Read-Host
    if ($command -eq 1){
        addScannerController("File")
    }
    if ($command -eq 2){
        addScannerController("Input")
    }
    if ($command -eq 3){
        presentMenu("Main")
    }
    if ($command -eq 4){
        exit
    }
    else{
        presentMenu("addScanner")
    }
  }
}

try{
presentMenu("Main")
}
catch{
  Write-Error $_.Exception.ToString()
  Read-Host -Prompt "The above error occurred. Press Enter to exit."
}
</code>```

The expected outcome when you enter "1" at the main menu, would be that you are presented with the "addScanner" menu. This really seems like a scope issue to me, but I can't seem to figure out how to correct it?

答:
You are using = to compare the parameter, you need to use -eq.

You also have a typo, missing an n in addScanner.

Here's a stripped down example:

```<code>function presentMenu
{
    param ([string]$menuType)
    if($menuType -eq "Main")
    {
         Write-Host "MAIN MENU: 1.) Add Scanner 2.) Remove Scanner 3.) Lookup Scanner Config 4.) Exit"
         $command = Read-Host
         if ($command -eq 1)
         {
             presentMenu addScanner
         }
    }
    elseif($menuType -eq "addScanner")
    {
        Write-Host "ADD SCANNER: 1.) From File 2.) From Input 3.) Back  4.) Exit"
        $command = Read-Host
        if ($command -eq 1)
        {
            Write-Host "Scanner added"
        }
    }
}

presentMenu Main
</code>```

Body:
Having trouble getting my menus to work. I would like to make a menu class, but I'm stuck with v2. Each time I enter "1" at the "Main Menu", it will simply re-present me with the main menu instead of re-entering the function with the new $menuType.

function presentMenu{
param ([string]$menuType)

if($menuType = "Main"){
     Write-Host "MAIN MENU: 1.) Add Scanner 2.) Remove Scanner 3.) Lookup Scanner Config 4.) Exit"
     $command = Read-Host
     ##DEBUG## write-host $menuType

     if ($command -eq 1){
         presentMenu("addScaner")
     }
     elseif ($command -eq 2){

     }
     elseif ($command -eq 3){

     }
     elseif ($command -eq 4){
        exit
     }
     elseif ($command -eq 5){
        exit
     }
    else{
        presentMenu("Main")
    }
  }

elseif($menuType = "addScanner"){
    Write-Host "ADD SCANNER: 1.) From File 2.) From Input 3.) Back  4.) Exit"
    $command = Read-Host
    if ($command -eq 1){
        addScannerController("File")
    }
    if ($command -eq 2){
        addScannerController("Input")
    }
    if ($command -eq 3){
        presentMenu("Main")
    }
    if ($command -eq 4){
        exit
    }
    else{
        presentMenu("addScanner")
    }
  }
}

try{
presentMenu("Main")
}
catch{
  Write-Error $_.Exception.ToString()
  Read-Host -Prompt "The above error occurred. Press Enter to exit."
}

The expected outcome when you enter "1" at the main menu, would be that you are presented with the "addScanner" menu. This really seems like a scope issue to me, but I can't seem to figure out how to correct it?

Body:
You are using = to compare the parameter, you need to use -eq.

You also have a typo, missing an n in addScanner.

Here's a stripped down example:

function presentMenu
{
    param ([string]$menuType)
    if($menuType -eq "Main")
    {
         Write-Host "MAIN MENU: 1.) Add Scanner 2.) Remove Scanner 3.) Lookup Scanner Config 4.) Exit"
         $command = Read-Host
         if ($command -eq 1)
         {
             presentMenu addScanner
         }
    }
    elseif($menuType -eq "addScanner")
    {
        Write-Host "ADD SCANNER: 1.) From File 2.) From Input 3.) Back  4.) Exit"
        $command = Read-Host
        if ($command -eq 1)
        {
            Write-Host "Scanner added"
        }
    }
}

presentMenu Main


问:
When you double-click on the widget is thrown

When I do double-click on the widget is thrown:

Uncaught TypeError: Cannot read property 'focusable' of undefined

I have grid with widget column

```<code>text:'blabala'
flex: 1.8,
xtype: 'widgetcolumn',
dataIndex: 'attachment',
stopSelection: false,

widget: {
            xtype: 'panel',
            layout: 'hbox',
            padding: 5,
            border: 0,
            bodyStyle: 'background:transparent',
            flex: 1,
            header: false,
            items: [{
                xtype: 'panel',
                flex: 1,
                bodyStyle: 'background:#d7d7d7;border-radius:16px',
                layout: 'hbox',
                items: [

                    {
                        xtype: 'button',
                        cls: 'attach-btn-divers',
                        padding: '10 0 10 5',
                        textAlign: 'left',
                        flex: 1,
                    }, {
                        xtype: 'button',
                        cls: 'attach-btn-divers attach-btn-divers-cancel',
                        padding: '10 5 10 0',
                        iconCls: 'x-fa fa-close',
                        handler: 'onDetachDiver',
                        width: 20,
                    },
                ]
            }, {
                xtype: 'combolabel',
                forceSelection: true,
                store: {
                    type: 'divingAttachmentStore'
                },
                displayField: 'value',
                valueField: 'value',
                autoSelect: true,
                queryCaching: false,
                queryMode: 'remote',

                listConfig: {
                    loadMask: false
                },
                flex: 1,
                listeners: {
                    specialkey: 'onEditAttachment',
                    focusLeave: 'onFocusLeaveAttachment',
                    beforequery: 'onBeforeQueryAttachment'
                }
            },
            ]

        },
        onWidgetAttach: 'onWidgetAttachAttachment',
</code>```

 When editing, combos are displayed

 In the normal view, a panel with buttons is displayed

 if empty cell, then combos are displayed with empty text. When you click on the combo, a list drops but with an error

Update 29.03.2017

If the edit plugin is removed, then there is no error.
Reproduced:
https://fiddle.sencha.com/#view/editor&fiddle/1t1v

答:
Resolved. I defined an empty editor to the widgetcolumn

```<code> editor:{},
</code>```

and the problem disappeared.

Body:
When I do double-click on the widget is thrown:

Uncaught TypeError: Cannot read property 'focusable' of undefined

I have grid with widget column

text:'blabala'
flex: 1.8,
xtype: 'widgetcolumn',
dataIndex: 'attachment',
stopSelection: false,

widget: {
            xtype: 'panel',
            layout: 'hbox',
            padding: 5,
            border: 0,
            bodyStyle: 'background:transparent',
            flex: 1,
            header: false,
            items: [{
                xtype: 'panel',
                flex: 1,
                bodyStyle: 'background:#d7d7d7;border-radius:16px',
                layout: 'hbox',
                items: [

                    {
                        xtype: 'button',
                        cls: 'attach-btn-divers',
                        padding: '10 0 10 5',
                        textAlign: 'left',
                        flex: 1,
                    }, {
                        xtype: 'button',
                        cls: 'attach-btn-divers attach-btn-divers-cancel',
                        padding: '10 5 10 0',
                        iconCls: 'x-fa fa-close',
                        handler: 'onDetachDiver',
                        width: 20,
                    },
                ]
            }, {
                xtype: 'combolabel',
                forceSelection: true,
                store: {
                    type: 'divingAttachmentStore'
                },
                displayField: 'value',
                valueField: 'value',
                autoSelect: true,
                queryCaching: false,
                queryMode: 'remote',

                listConfig: {
                    loadMask: false
                },
                flex: 1,
                listeners: {
                    specialkey: 'onEditAttachment',
                    focusLeave: 'onFocusLeaveAttachment',
                    beforequery: 'onBeforeQueryAttachment'
                }
            },
            ]

        },
        onWidgetAttach: 'onWidgetAttachAttachment',

 When editing, combos are displayed

 In the normal view, a panel with buttons is displayed

 if empty cell, then combos are displayed with empty text. When you click on the combo, a list drops but with an error

Update 29.03.2017

If the edit plugin is removed, then there is no error.
Reproduced:
https://fiddle.sencha.com/#view/editor&fiddle/1t1v

Body:
Resolved. I defined an empty editor to the widgetcolumn

 editor:{},

and the problem disappeared.


问:
jQuery selector to get form by name
I have the following HTML:

```<code><form name="frmSave">...</form>
</code>```

Just to know, I am not able to modify the HTML in order to add an id or something else.

This is what I tried to get the form element by it's name:

```<code>var frm = $('form[name="frmSave"]');

console.log(frm);
</code>```

(but I believe the above code will try to get a children element with the frmSave name inside the form which is not what I need).

How can I achieve this, is it possible to get the form by just the name and using a selector?

Update:

I was doing the wrong way in my original code (I was using a space aka "combinator" in the selector) and not in the code snippet from here so jQuery was trying to get any children element with the name needed and I was asking myself what was wrong since nothing was returned.

The accepted answer gives a better explanation about this so a little space could change everything - I will sleep properly next time :-)

答:
For detecting if the form is present, I'm using </p>

```<code>if($('form[name="frmSave"]').length > 0) {
    //do something
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: jQuery selector to get form by name

Body:
I have the following HTML:

<form name="frmSave">...</form>

Just to know, I am not able to modify the HTML in order to add an id or something else.

This is what I tried to get the form element by it's name:

var frm = $('form[name="frmSave"]');

console.log(frm);

(but I believe the above code will try to get a children element with the frmSave name inside the form which is not what I need).

How can I achieve this, is it possible to get the form by just the name and using a selector?

Update:

I was doing the wrong way in my original code (I was using a space aka "combinator" in the selector) and not in the code snippet from here so jQuery was trying to get any children element with the name needed and I was asking myself what was wrong since nothing was returned.

The accepted answer gives a better explanation about this so a little space could change everything - I will sleep properly next time :-)

Body:
For detecting if the form is present, I'm using

if($('form[name="frmSave"]').length > 0) {
    //do something
}


问:
Java: Method always returns same result
I'm supposed to write a program for my programming class in High School. The program asks the user to input a time in seconds, and calculates the falling distance using the common formula d = 1/2 * g * t ^ 2. D is the distance (result), g equals 9.8 and t is the time the user entered. We are supposed to call the method 10 times for some reason. Here's my problem: The method always returns the same result (4.9 in the first iteration), no matter what the user's input for time was. What am I doing wrong?</p>

```<code>import javax.swing.JOptionPane;
public class fallingDistance {

    public static void main(String[] args){

        String input;
        double time;

        input = JOptionPane.showInputDialog("Enter the time in seconds: ");
        time = Double.parseDouble(input);
        System.out.println(time);
        for(int x=1; x<=10; x++){
            JOptionPane.showMessageDialog(null, "The falling distance is: " + calculate(x) + "m.");
        }

    }

    public static double calculate(double time){
        double g = 9.8, a=0.5;
        double distance = (a*g) * (Math.pow(time, 2.0));
        JOptionPane.showMessageDialog(null, distance);
        return (distance);
    }
}
</code>```

答: You are passing in x to the calculate method. Try passing in time instead.

Title: Java: Method always returns same result

Body:
I'm supposed to write a program for my programming class in High School. The program asks the user to input a time in seconds, and calculates the falling distance using the common formula d = 1/2 * g * t ^ 2. D is the distance (result), g equals 9.8 and t is the time the user entered. We are supposed to call the method 10 times for some reason. Here's my problem: The method always returns the same result (4.9 in the first iteration), no matter what the user's input for time was. What am I doing wrong?

import javax.swing.JOptionPane;
public class fallingDistance {

    public static void main(String[] args){

        String input;
        double time;

        input = JOptionPane.showInputDialog("Enter the time in seconds: ");
        time = Double.parseDouble(input);
        System.out.println(time);
        for(int x=1; x<=10; x++){
            JOptionPane.showMessageDialog(null, "The falling distance is: " + calculate(x) + "m.");
        }

    }

    public static double calculate(double time){
        double g = 9.8, a=0.5;
        double distance = (a*g) * (Math.pow(time, 2.0));
        JOptionPane.showMessageDialog(null, distance);
        return (distance);
    }
}


问:
Creating stored procedures in mysql
what is wrong in this code

```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);

    select concat('#GNC', '3') into main_id;  #error shows here

    declare m1 int;
    declare m2 int;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
END
</code>```

It is giving error like missing end. if I remove the if statement it works fine.

答:
You are almost there :) the only problem I see is all your declarations are not at the beginning of your logic and you are not using delimiter as mentioned by @Alvaro; try this:

```<code>DELIMITER $$

CREATE PROCEDURE `diff`()
  BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);
    declare m1 INT;
    declare m2 int;

    select concat('#GNC', '3') into main_id;

     select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
      TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
  END $$
</code>```

Title: Creating stored procedures in mysql

Body:
what is wrong in this code

CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);

    select concat('#GNC', '3') into main_id;  #error shows here

    declare m1 int;
    declare m2 int;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
END

It is giving error like missing end. if I remove the if statement it works fine.

Body:
You are almost there :) the only problem I see is all your declarations are not at the beginning of your logic and you are not using delimiter as mentioned by @Alvaro; try this:

DELIMITER $$

CREATE PROCEDURE `diff`()
  BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);
    declare m1 INT;
    declare m2 int;

    select concat('#GNC', '3') into main_id;

     select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
      TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
  END $$


问:
Convert float64 column to datetime pandas
I have the following pandas DataFrame column dfA['TradeDate']:

```<code>0     20100329.0
1     20100328.0
2     20100329.0
...
</code>```

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')
</code>```

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

```<code>dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')
</code>```

It returns: must be a Str and not Series.

答:
You can use to_datetime with a custom format on a string representation of the values:

```<code>import pandas as pd
pd.to_datetime(pd.Series([20100329.0, 20100328.0, 20100329.0]).astype(str), format='%Y%m%d.0')
</code>```

Body:
I have the following pandas DataFrame column dfA['TradeDate']:

0     20100329.0
1     20100328.0
2     20100329.0
...

and I wish to transform it to a datetime.

Based on another tread on SO, I convert it first to a string and then apply the strptime function.

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')

However this returns the error that my format is incorrect (ValueError).

An issue that I spotted is that the column is not properly to string, but to an object.

When I try:

dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')

It returns: must be a Str and not Series.

Body:
You can use to_datetime with a custom format on a string representation of the values:

import pandas as pd
pd.to_datetime(pd.Series([20100329.0, 20100328.0, 20100329.0]).astype(str), format='%Y%m%d.0')