问:
How to copy data values separated with `:` from multiple text file to csv with respected headers with python?
Trying to copy text next to variables like type, number, name from text file to csv with following form:

```<code>Type      Name     Phone     email     Mailing Address
</code>```

I Have lots of text file in this form:

```<code>Type: zxyz
Number: 34567892
Name: xyzzzxx, yuw
Phone Number: 000-000-0000
Email Address: any@gmail.com
Mailing Address: bla bla bla
</code>```

I am unable to copy text next to search string from text file and write it into csv file.

答:
You can convert the contents of one file to a dictionary like this:

```<code>with open('file.txt') as f:
    d = dict(line.strip().split(': ') for line in f)
</code>```

Then write the dictionary to a CSV file using csv.DictWriter:

```<code>import csv

fieldnames = ['Type', 'Name', 'Phone Number', 'Email Address', 'Mailing Address']
filenames = ['a.txt', 'b.txt', 'c.txt']

with open('out.csv', 'w') as outfile:
    writer = csv.DictWriter(outfile, fieldnames)
    writer.writerheader()
    for filename in filenames:
        with open(filename) as f:
            d = dict(line.strip().split(': ') for line in f)
            writer.writerow(d)
</code>```

This will copy all of the data from the input files to a single CSV file. If you want to exclude some fields adjust the fieldnames and remove the unwanted fields from the dictionary prior to calling writerow(). You can also rename the fields by changing the field name in both fieldnames and the dictionary.

Body:
Trying to copy text next to variables like type, number, name from text file to csv with following form:

Type      Name     Phone     email     Mailing Address

I Have lots of text file in this form:

Type: zxyz
Number: 34567892
Name: xyzzzxx, yuw
Phone Number: 000-000-0000
Email Address: any@gmail.com
Mailing Address: bla bla bla

I am unable to copy text next to search string from text file and write it into csv file.

Body:
You can convert the contents of one file to a dictionary like this:

with open('file.txt') as f:
    d = dict(line.strip().split(': ') for line in f)

Then write the dictionary to a CSV file using csv.DictWriter:

import csv

fieldnames = ['Type', 'Name', 'Phone Number', 'Email Address', 'Mailing Address']
filenames = ['a.txt', 'b.txt', 'c.txt']

with open('out.csv', 'w') as outfile:
    writer = csv.DictWriter(outfile, fieldnames)
    writer.writerheader()
    for filename in filenames:
        with open(filename) as f:
            d = dict(line.strip().split(': ') for line in f)
            writer.writerow(d)

This will copy all of the data from the input files to a single CSV file. If you want to exclude some fields adjust the fieldnames and remove the unwanted fields from the dictionary prior to calling writerow(). You can also rename the fields by changing the field name in both fieldnames and the dictionary.


来源: stackexchange

问:
dropzone and jquery load method
I have this code for dropzone. It works. Then on complete event it has to load a php file. I am not able to pass the content of a variable. It has an id that i need to fetch data from a database. Here the code:

```<code>Dropzone.options.myform = {
  maxFilesize:5,
  maxFiles: 1,
  acceptedFiles: ".jpeg,.jpg,.png,.gif",
  addRemoveLinks: true,
  previewsContainer: "#div_preview",
  dictDefaultMessage: "Premi per caricare le foto",
  params: '#hiddenId',
  init: function() {
    this.hiddenFileInput.removeAttribute('multiple');
  },
  complete: function(file) {
    var a = $("#hiddenId").val();
    alert(a);
    $('#div_preview').show();
    $("#div_preview").html("");
    $("#div_preview").load('php/load_cover_auto.php',{'id': '<?php echo $a; ?>' });
  }
};
</code>```

with firebug i get this reply from the server:

```<code>id<?php echo $a; ?>
</code>```

I tried also to pass variable in this way but with no luck:

```<code>$("#div_preview").load('php/load_cover_auto.php?id=a');
</code>```

What am i doing wrong?

答:
This line is wrong:

```<code>$("#div_preview").load('php/load_cover_auto.php',{'id': '<?php echo $a; ?>'
</code>```

Change it to:

```<code>$("#div_preview").load('php/load_cover_auto.php',{'id': a});
</code>```

Because you want to get and pass the value of the jquery variable.

ContentLicense: CC BY-SA 3.0

Title: dropzone and jquery load method

Body:
I have this code for dropzone. It works. Then on complete event it has to load a php file. I am not able to pass the content of a variable. It has an id that i need to fetch data from a database. Here the code:

Dropzone.options.myform = {
  maxFilesize:5,
  maxFiles: 1,
  acceptedFiles: ".jpeg,.jpg,.png,.gif",
  addRemoveLinks: true,
  previewsContainer: "#div_preview",
  dictDefaultMessage: "Premi per caricare le foto",
  params: '#hiddenId',
  init: function() {
    this.hiddenFileInput.removeAttribute('multiple');
  },
  complete: function(file) {
    var a = $("#hiddenId").val();
    alert(a);
    $('#div_preview').show();
    $("#div_preview").html("");
    $("#div_preview").load('php/load_cover_auto.php',{'id': '<?php echo $a; ?>' });
  }
};

with firebug i get this reply from the server:

id<?php echo $a; ?>

I tried also to pass variable in this way but with no luck:

$("#div_preview").load('php/load_cover_auto.php?id=a');

What am i doing wrong?

Body:
This line is wrong:

$("#div_preview").load('php/load_cover_auto.php',{'id': '<?php echo $a; ?>'

Change it to:

$("#div_preview").load('php/load_cover_auto.php',{'id': a});

Because you want to get and pass the value of the jquery variable.


问:
asp.net MVC parameter not passed
In my controller I do have this endpoint:

```<code>async Task<FileResult> DownloadSelection(AssignedDatabaseSelection selection)
</code>```

And my HTML looks like:

```<code>@if (Model.AssignedDatabaseSelections.Any())
{
    <table>
        @foreach (var selection in Model.AssignedDatabaseSelections)
        {
            <tr>
                <td>@selection.DisplayName</td>
                <td width="10%">
                    @Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home", selection, null)
                </td>
            </tr>
        }
    </table>
}
</code>```

Now I wanted to add another parameter to my controller method:

```<code>async Task<FileResult> DownloadSelection(AssignedDatabaseSelection selection, DownloadFormat format)
</code>```

And

```<code>@if (Model.AssignedDatabaseSelections.Any())
{
    <table>
        @foreach (var selection in Model.AssignedDatabaseSelections)
        {
            <tr>
                <td>@selection.DisplayName</td>
                <td width="10%">
                    @Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home", new {selection = selection, Format = DownloadFormat.CSV}, null)
                </td>
                <td width="10%">
                    @Html.ActionLink(Strings.ExcelLabel, "DownloadSelection", "Home", new  { selection = selection, Format = DownloadFormat.CSV }, null)
                </td>
            </tr>
        }
    </table>
}
</code>```

When I make an inspect elements I got this:

```<code><a href="/Home/DownloadSelection?selection=System.Data.Entity.DynamicProxies.AssignedDatabaseSele_D02B1D7B1220921CC4150FAA016EB8BFD5692B52C49949B0ECB80AA2F98E7355&Format=CSV">Excel</a>
</code>```

Now, the format is filled, but the selection is always null. What am I missing?

答:
Here is an example of how to create a link with properties from an object. I am including the code of creating a new Employee within the view but this can/should be in the model:

```<code>@{ var emp = new Employee { Name = "Tom", Age = 44 }; }
@Html.ActionLink("Test", "Test2", "Account", new {Name = emp.Name, Age = emp.Age }, null)
</code>```

Please note how I am passing each property of the Employee into the anonymous object for the route values.

The above link will work with this action. The DefaultModeBinder will take the names from the query string in the link and assign it to the properties of the Employee and pass it to the action below:

```<code>public ActionResult Test2(Employee emp)
{
    return null;
}
</code>```

Title: asp.net MVC parameter not passed

Body:
In my controller I do have this endpoint:

async Task<FileResult> DownloadSelection(AssignedDatabaseSelection selection)

And my HTML looks like:

@if (Model.AssignedDatabaseSelections.Any())
{

        @foreach (var selection in Model.AssignedDatabaseSelections)
        {

                @selection.DisplayName

                    @Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home", selection, null)

        }

}

Now I wanted to add another parameter to my controller method:

async Task<FileResult> DownloadSelection(AssignedDatabaseSelection selection, DownloadFormat format)

And

@if (Model.AssignedDatabaseSelections.Any())
{

        @foreach (var selection in Model.AssignedDatabaseSelections)
        {

                @selection.DisplayName

                    @Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home", new {selection = selection, Format = DownloadFormat.CSV}, null)

                    @Html.ActionLink(Strings.ExcelLabel, "DownloadSelection", "Home", new  { selection = selection, Format = DownloadFormat.CSV }, null)

        }

}

When I make an inspect elements I got this:

Excel

Now, the format is filled, but the selection is always null. What am I missing?

Body:
Here is an example of how to create a link with properties from an object. I am including the code of creating a new Employee within the view but this can/should be in the model:

@{ var emp = new Employee { Name = "Tom", Age = 44 }; }
@Html.ActionLink("Test", "Test2", "Account", new {Name = emp.Name, Age = emp.Age }, null)

Please note how I am passing each property of the Employee into the anonymous object for the route values.

The above link will work with this action. The DefaultModeBinder will take the names from the query string in the link and assign it to the properties of the Employee and pass it to the action below:

public ActionResult Test2(Employee emp)
{
    return null;
}


答:
In you first example, the 3rd parameter is a complex object (typeof AssignedDatabaseSelections) and the method will correctly serialize each property of your object to a query string. Note that it only works because your object contains only simple properties.

In the second example, your creating a new object containing a complex object. The ActionLink() method (and all methods that generate route/query string values) call the .ToString() method on each property in the object (hence you get the name of the class) and do not do recursion.

If you want to pass back all properties of the AssignedDatabaseSelections object plus another property, you need to generate a new object containing each property of AssignedDatabaseSelections, for example (assuming it contains properties ID and Name)

```<code>@Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home",
    new { ID = selection.ID, Name = selection.Name, ......, Format = DownloadFormat.CSV }, null)
</code>```

Note that if AssignedDatabaseSelections contains a lot of properties and/or larger values, you risk exceeding the query string limit and throwing an exception. A better approach is just to pass the ID property of the AssignedDatabaseSelection and get the object again in the GET method if you need other properties of it.

```<code>@Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home",
    new { ID = selection.ID, Format = DownloadFormat.CSV }, null)
</code>```

Title: asp.net MVC parameter not passed

Body:
In you first example, the 3rd parameter is a complex object (typeof AssignedDatabaseSelections) and the method will correctly serialize each property of your object to a query string. Note that it only works because your object contains only simple properties.

In the second example, your creating a new object containing a complex object. The ActionLink() method (and all methods that generate route/query string values) call the .ToString() method on each property in the object (hence you get the name of the class) and do not do recursion.

If you want to pass back all properties of the AssignedDatabaseSelections object plus another property, you need to generate a new object containing each property of AssignedDatabaseSelections, for example (assuming it contains properties ID and Name)

@Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home",
    new { ID = selection.ID, Name = selection.Name, ......, Format = DownloadFormat.CSV }, null)

Note that if AssignedDatabaseSelections contains a lot of properties and/or larger values, you risk exceeding the query string limit and throwing an exception. A better approach is just to pass the ID property of the AssignedDatabaseSelection and get the object again in the GET method if you need other properties of it.

@Html.ActionLink(Strings.CsvLabel, "DownloadSelection", "Home",
    new { ID = selection.ID, Format = DownloadFormat.CSV }, null)


问:
Passing Member Function Pointers Between Modules
Just a curiosity question!  This seems to suggest that member function pointers are in fact different sizes pending compiler and compile options used, and this seems to suggest that function pointers are passed just fine between modules, so what about member function pointers?  I mean with all the hassles that are already presented in passing data between modules it would seem rather silly to even attempt this?  Or what about scenarios involving static libraries?  If two different compilers are used am I wrong to assume that any scenario involving the passing of a member function pointer would be fruitless?</p>

答: If you use two different compilers, then unless they have compatible ABI (application binary interface), you cannot sensibly mix-and-match any object code created by them, whether or not member function pointers are involved.</p>

ContentLicense: CC BY-SA 2.5


问:
Create instance for list of data types - Haskell
I feel like this should be really easy, but i am stuck at this point for quite some time.

Is it possible in haskell to create an instance of a type class for a list of certain data types?

What i want to achieve is the following.

```<code>class Rename a where
    findSub :: a -> a

-- A 'normal' instance would look like this
instance Rename Atom where
    findSub ......

-- Now i want to acchieve something like this
instance Rename ([] Atom) where
    findSub ......
</code>```

How ever when i write this i get the following error:

```<code>* Illegal instance declaration for `Rename [Atom]'
        (All instance types must be of the form (T a1 ... an)
         where a1 ... an are *distinct type variables*,
         and each type variable appears at most once in the instance head.
         Use FlexibleInstances if you want to disable this.)
    * In the instance declaration for `Rename ([] Atom)'
Failed, modules loaded: none.
</code>```

I would like to know how to fix this and why this is not allowed.

Thanks in advance.

答:
It just requires a language extension, since this form of instance is not technically allowed by the Haskell 98 standard.  When the error message says to enable an extension, usually just do it[1]. FlexibleInstances is a very common and accepted extension, so just put

```<code>{-# LANGUAGE FlexibleInstances #-}
</code>```

at the top of the file.

Alternatively, often times such instances can be defined "recursively", in which case you don't need the extension, but besides that you get more instances for free, and more guarantees because the type is more general. See if you can define

```<code>instance (Rename a) => Rename [a] where
    findSub ...
</code>```

instead, using only the fact that a is a Rename rather than it being specifically an Atom.  When you can define instances this way, it is a good sign that your design is on the right track.

[1] There are a few exceptions, such as UndecidableInstances or IncoherentInstances, which sometimes indicates that you have a wrong idea about how typeclass resolution works.

Body:
I feel like this should be really easy, but i am stuck at this point for quite some time.

Is it possible in haskell to create an instance of a type class for a list of certain data types?

What i want to achieve is the following.

class Rename a where
    findSub :: a -> a

-- A 'normal' instance would look like this
instance Rename Atom where
    findSub ......

-- Now i want to acchieve something like this
instance Rename ([] Atom) where
    findSub ......

How ever when i write this i get the following error:

* Illegal instance declaration for `Rename [Atom]'
        (All instance types must be of the form (T a1 ... an)
         where a1 ... an are *distinct type variables*,
         and each type variable appears at most once in the instance head.
         Use FlexibleInstances if you want to disable this.)
    * In the instance declaration for `Rename ([] Atom)'
Failed, modules loaded: none.

I would like to know how to fix this and why this is not allowed.

Thanks in advance.

Body:
It just requires a language extension, since this form of instance is not technically allowed by the Haskell 98 standard.  When the error message says to enable an extension, usually just do it[1]. FlexibleInstances is a very common and accepted extension, so just put

{-# LANGUAGE FlexibleInstances #-}

at the top of the file.

Alternatively, often times such instances can be defined "recursively", in which case you don't need the extension, but besides that you get more instances for free, and more guarantees because the type is more general. See if you can define

instance (Rename a) => Rename [a] where
    findSub ...

instead, using only the fact that a is a Rename rather than it being specifically an Atom.  When you can define instances this way, it is a good sign that your design is on the right track.

[1] There are a few exceptions, such as UndecidableInstances or IncoherentInstances, which sometimes indicates that you have a wrong idea about how typeclass resolution works.


问:
Error when I try to post to database. I am trying to calculate GPA
I am getting this error "ErrorException in scoresheetController.php line 259:
Object of class Illuminate\Database\Eloquent\Collection could not be converted to int" when I want to post the following into the database. Kindly find the code below.

```<code> <?php

    namespace App\Http\Controllers;

    use App\Http\Requests\scoresheetRequest;
    use App\Scoresheet;
    use App\StudentCourse;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Input;
    use DB;
    use Excel;
    use Illuminate\Database\Eloquent\Collection;

    class scoresheetController extends Controller
    {
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth');
        }

        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            $scoresheet = Scoresheet::select('id', 'code', 'stud_id', 'term', 'year', 'CA_Score', 'exam_score', 'total', 'grade')->get();

            return view('admin.results')->with('scoresheet', $scoresheet);
        }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function create()
        {
            //
        }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function store(scoresheetRequest $request)
        {
            //dd($request ->all());

            $scoresheet = new Scoresheet();

            $crdthr = StudentCourse::select('student_courses')
                                    ->join('scoresheets', 'student_courses.stud_id', '=', 'scoresheets.stud_id')
                                    ->select('student_courses.credit_hrs')
                                    ->get();

            //Calculate total
            $total  = $request['CA_Score'] + $request['exam_score'];

            //Calculate the grade
            switch ($grade = $total) {
                case $total >=93 && $total==100:
                   $grade =  "A+";
                    break;
                case $total>=85:
                    $grade = "A";
                    break;
                case $total >=77:
                    $grade = "B+";
                    break;
                case $total >=70:
                    $grade = "B";
                    break;
                case $total >=60:
                    $grade = "C";
                    break;
                case $total >=55:
                    $grade = "D+";
                    break;
                case $total >=50:
                    $grade = "D";
                    break;
                case $total <50:
                    $grade = "F";
                    break;
            }

            //Check for grade equivalent
            switch ($digit = $grade) {
                case $grade == "A+":
                    $digit =  "4.00";
                    break;
                case $grade == "A":
                    $digit =  "3.75";
                    break;
                case $grade == "B+":
                    $digit =  "3.50";
                    break;
                case $grade == "B":
                    $digit =  "3.00";
                    break;
                case $grade == "C+":
                    $digit =  "2.50";
                    break;
                case $grade == "C":
                    $digit =  "2.00";
                    break;
                case $grade == "D+":
                    $digit =  "1.50";
                    break;
                case $grade == "D":
                    $digit =  "1.00";
                    break;
                case $grade == "F":
                    $digit =  "0.00";
                    break;
            }

            //Calculate mini wgt
            $gpa = $digit * $crdthr;

            $scoresheet->code = $request['code'];
            $scoresheet->stud_id = $request['stud_id'];
            $scoresheet->term = $request['term'];
            $scoresheet->year = $request['year'];
            $scoresheet->CA_Score = $request['CA_Score'];
            $scoresheet->exam_score = $request['exam_score'];
            $scoresheet->total = $total;
            $scoresheet->grade = $grade;
            $scoresheet->grade_digit = $digit;
            $scoresheet->mini_wgt = $gpa;

            //dd($gpa);
            if ($scoresheet->save()){
                flash($request['name'].' successfully saved.')->success();
                /*echo 'saved';*/
            }else{
                flash($request['name'].' not saved.')->error();
                /*echo 'Not saved';*/
            }

            return redirect()->back();
        }

        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function show($id)
        {
            //
        }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {
            $scoresheet =Scoresheet::findOrFail($id);

            return view('admin.result_edit') ->with('scoresheet', $scoresheet);
        }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function update(Request $request, $id)
        {
            $scoresheet = Scoresheet::findOrFail($id);

            $crdthr = StudentCourse::select('student_courses')
                ->join('scoresheets', 'student_courses.stud_id', '=', 'scoresheets.stud_id')
                ->select('student_courses.credit_hrs')
                ->get();

            $total = $request['CA_Score'] + $request['exam_score'];

            //Calculate the grade
            switch ($grade = $total) {
                case $total >=93 && $total==100:
                    $grade =  "A+";
                    break;
                case $total>=85:
                    $grade = "A";
                    break;
                case $total >=77:
                    $grade = "B+";
                    break;
                case $total >=70:
                    $grade = "B";
                    break;
                case $total >=60:
                    $grade = "C";
                    break;
                case $total >=55:
                    $grade = "D+";
                    break;
                case $total >=50:
                    $grade = "D";
                    break;
                case $total <50:
                    $grade = "F";
                    break;
            }

            //Check for grade equivalent
            switch ($digit = $grade) {
                case $grade == "A+":
                    $digit =  "4.00";
                    break;
                case $grade == "A":
                    $digit =  "3.75";
                    break;
                case $grade == "B+":
                    $digit =  "3.50";
                    break;
                case $grade == "B":
                    $digit =  "3.00";
                    break;
                case $grade == "C+":
                    $digit =  "2.50";
                    break;
                case $grade == "C":
                    $digit =  "2.00";
                    break;
                case $grade == "D+":
                    $digit =  "1.50";
                    break;
                case $grade == "D":
                    $digit =  "1.00";
                    break;
                case $grade == "F":
                    $digit =  "0.00";
                    break;
            }

            //Calculate mini wgt
            $gpa = $digit * $crdthr;

            $scoresheet->code = $request['code'];
            $scoresheet->stud_id = $request['stud_id'];
            $scoresheet->term = $request['term'];
            $scoresheet->year = $request['year'];
            $scoresheet->CA_Score = $request['CA_Score'];
            $scoresheet->exam_score = $request['exam_score'];
            $scoresheet->total = $total;
            $scoresheet->grade = $grade;
            $scoresheet->grade_digit = $digit;
            $scoresheet->mini_wgt = $gpa;

            if ($scoresheet->save()){
                flash($request['name'].' successfully saved.')->success();
                /*echo 'saved';*/
            }else{
                flash($request['name'].' not saved.')->error();
                /*echo 'Not saved';*/
            }

            return redirect() ->to('/scoresheet');
        }

        /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function destroy($id)
        {
            $scoresheet = Scoresheet::findOrFail($id);

            if (Scoresheet::destroy($id)){
                flash ('deleted successfully')->success();
            }else{
                flash ('failed to delete')->warning();
            }

            return redirect()->back();
        }

    }
</code>```

I would be glad if assistance can be given as soon as possible.

答:
Since $crdthr is a Collection object, you can print it to see the data format in there. Usually, you can get the data you are looking for as $crdthr[0]-> credit_hrs

```<code>$gpa = $digit * $crdthr[0]->credit_hrs;
</code>```

Body:
I am getting this error "ErrorException in scoresheetController.php line 259:
Object of class Illuminate\Database\Eloquent\Collection could not be converted to int" when I want to post the following into the database. Kindly find the code below.

 <?php

    namespace App\Http\Controllers;

    use App\Http\Requests\scoresheetRequest;
    use App\Scoresheet;
    use App\StudentCourse;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Input;
    use DB;
    use Excel;
    use Illuminate\Database\Eloquent\Collection;

    class scoresheetController extends Controller
    {
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth');
        }

        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            $scoresheet = Scoresheet::select('id', 'code', 'stud_id', 'term', 'year', 'CA_Score', 'exam_score', 'total', 'grade')->get();

            return view('admin.results')->with('scoresheet', $scoresheet);
        }

        /**
         * Show the form for creating a new resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function create()
        {
            //
        }

        /**
         * Store a newly created resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function store(scoresheetRequest $request)
        {
            //dd($request ->all());

            $scoresheet = new Scoresheet();

            $crdthr = StudentCourse::select('student_courses')
                                    ->join('scoresheets', 'student_courses.stud_id', '=', 'scoresheets.stud_id')
                                    ->select('student_courses.credit_hrs')
                                    ->get();

            //Calculate total
            $total  = $request['CA_Score'] + $request['exam_score'];

            //Calculate the grade
            switch ($grade = $total) {
                case $total >=93 && $total==100:
                   $grade =  "A+";
                    break;
                case $total>=85:
                    $grade = "A";
                    break;
                case $total >=77:
                    $grade = "B+";
                    break;
                case $total >=70:
                    $grade = "B";
                    break;
                case $total >=60:
                    $grade = "C";
                    break;
                case $total >=55:
                    $grade = "D+";
                    break;
                case $total >=50:
                    $grade = "D";
                    break;
                case $total <50:
                    $grade = "F";
                    break;
            }

            //Check for grade equivalent
            switch ($digit = $grade) {
                case $grade == "A+":
                    $digit =  "4.00";
                    break;
                case $grade == "A":
                    $digit =  "3.75";
                    break;
                case $grade == "B+":
                    $digit =  "3.50";
                    break;
                case $grade == "B":
                    $digit =  "3.00";
                    break;
                case $grade == "C+":
                    $digit =  "2.50";
                    break;
                case $grade == "C":
                    $digit =  "2.00";
                    break;
                case $grade == "D+":
                    $digit =  "1.50";
                    break;
                case $grade == "D":
                    $digit =  "1.00";
                    break;
                case $grade == "F":
                    $digit =  "0.00";
                    break;
            }

            //Calculate mini wgt
            $gpa = $digit * $crdthr;

            $scoresheet->code = $request['code'];
            $scoresheet->stud_id = $request['stud_id'];
            $scoresheet->term = $request['term'];
            $scoresheet->year = $request['year'];
            $scoresheet->CA_Score = $request['CA_Score'];
            $scoresheet->exam_score = $request['exam_score'];
            $scoresheet->total = $total;
            $scoresheet->grade = $grade;
            $scoresheet->grade_digit = $digit;
            $scoresheet->mini_wgt = $gpa;

            //dd($gpa);
            if ($scoresheet->save()){
                flash($request['name'].' successfully saved.')->success();
                /*echo 'saved';*/
            }else{
                flash($request['name'].' not saved.')->error();
                /*echo 'Not saved';*/
            }

            return redirect()->back();
        }

        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function show($id)
        {
            //
        }

        /**
         * Show the form for editing the specified resource.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {
            $scoresheet =Scoresheet::findOrFail($id);

            return view('admin.result_edit') ->with('scoresheet', $scoresheet);
        }

        /**
         * Update the specified resource in storage.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function update(Request $request, $id)
        {
            $scoresheet = Scoresheet::findOrFail($id);

            $crdthr = StudentCourse::select('student_courses')
                ->join('scoresheets', 'student_courses.stud_id', '=', 'scoresheets.stud_id')
                ->select('student_courses.credit_hrs')
                ->get();

            $total = $request['CA_Score'] + $request['exam_score'];

            //Calculate the grade
            switch ($grade = $total) {
                case $total >=93 && $total==100:
                    $grade =  "A+";
                    break;
                case $total>=85:
                    $grade = "A";
                    break;
                case $total >=77:
                    $grade = "B+";
                    break;
                case $total >=70:
                    $grade = "B";
                    break;
                case $total >=60:
                    $grade = "C";
                    break;
                case $total >=55:
                    $grade = "D+";
                    break;
                case $total >=50:
                    $grade = "D";
                    break;
                case $total <50:
                    $grade = "F";
                    break;
            }

            //Check for grade equivalent
            switch ($digit = $grade) {
                case $grade == "A+":
                    $digit =  "4.00";
                    break;
                case $grade == "A":
                    $digit =  "3.75";
                    break;
                case $grade == "B+":
                    $digit =  "3.50";
                    break;
                case $grade == "B":
                    $digit =  "3.00";
                    break;
                case $grade == "C+":
                    $digit =  "2.50";
                    break;
                case $grade == "C":
                    $digit =  "2.00";
                    break;
                case $grade == "D+":
                    $digit =  "1.50";
                    break;
                case $grade == "D":
                    $digit =  "1.00";
                    break;
                case $grade == "F":
                    $digit =  "0.00";
                    break;
            }

            //Calculate mini wgt
            $gpa = $digit * $crdthr;

            $scoresheet->code = $request['code'];
            $scoresheet->stud_id = $request['stud_id'];
            $scoresheet->term = $request['term'];
            $scoresheet->year = $request['year'];
            $scoresheet->CA_Score = $request['CA_Score'];
            $scoresheet->exam_score = $request['exam_score'];
            $scoresheet->total = $total;
            $scoresheet->grade = $grade;
            $scoresheet->grade_digit = $digit;
            $scoresheet->mini_wgt = $gpa;

            if ($scoresheet->save()){
                flash($request['name'].' successfully saved.')->success();
                /*echo 'saved';*/
            }else{
                flash($request['name'].' not saved.')->error();
                /*echo 'Not saved';*/
            }

            return redirect() ->to('/scoresheet');
        }

        /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return \Illuminate\Http\Response
         */
        public function destroy($id)
        {
            $scoresheet = Scoresheet::findOrFail($id);

            if (Scoresheet::destroy($id)){
                flash ('deleted successfully')->success();
            }else{
                flash ('failed to delete')->warning();
            }

            return redirect()->back();
        }

    }

I would be glad if assistance can be given as soon as possible.

Body:
Since $crdthr is a Collection object, you can print it to see the data format in there. Usually, you can get the data you are looking for as $crdthr[0]-> credit_hrs

$gpa = $digit * $crdthr[0]->credit_hrs;


问:
Using PHPMailer without gmail account
I wanted to test locally sending mails via PHPMailer (Symfony3 framework), but on the internet i see only configurations for gmail accounts. Is it possible to not configure any external server to send mails for testing locally?</p>

答: Yes it is possible, but I would not recommend it. You can look up the mx for a domain and send directly to it using PHPMailer without any particular problems, however, PHPMailer is not an MTA, so you would be much better off using a local mail server to accept your message and deliver it asynchronously. The actual code is much the same as for Gmail, you just need to do the mx lookup first, set that as the Host and send to it without authentication on port 25.

Title: Using PHPMailer without gmail account


问:
My tcp client using spring integration not able to get response
I have created tcp client using spring integration I am able to receive  response for my send message . But when I uses  localDateTime.now() to log time I am not able to receive the response of send message . I know this can be solved using time setting to make thread wait. As I am new to spring integration So kindly help me how to do it.

```<code>@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Test
{

    protected final Log logger = LogFactory.getLog(this.getClass());

    // **************** Client **********************************************
    @Bean
    public MessageChannel replyChannel()
    {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel sendChannel()
    {
        MessageChannel directChannel = new DirectChannel();
        return directChannel;
    }

    @EnableIntegration
    @IntegrationComponentScan
    @Configuration
    public static class config
    {
        @MessagingGateway(defaultRequestChannel = "sendChannel", defaultReplyChannel = "replyChannel")
        public interface Gateway
        {

            String Send(String in);

        }
    }

    @Bean
    AbstractClientConnectionFactory tcpNetClientConnectionFactory()
    {
        AbstractClientConnectionFactory tcpNetClientConnectionFactory = new TcpNetClientConnectionFactory("localhost",
                9999);
        tcpNetClientConnectionFactory.setSerializer(new UCCXImprovedSerializer());
        tcpNetClientConnectionFactory.setDeserializer(new UCCXImprovedSerializer());
        tcpNetClientConnectionFactory.setSingleUse(true);

        tcpNetClientConnectionFactory.setMapper(new TcpMessageMapper());
        return tcpNetClientConnectionFactory;
    }

    @Bean
    @ServiceActivator(inputChannel = "sendChannel")
    TcpOutboundGateway tcpOutboundGateway()
    {
        TcpOutboundGateway tcpOutboundGateway = new TcpOutboundGateway();
        tcpOutboundGateway.setConnectionFactory(tcpNetClientConnectionFactory());
        tcpOutboundGateway.setReplyChannel(replyChannel());
        return tcpOutboundGateway;
    }

    public static void main(String args[])
    {
        // new LegaServer();
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Test.class, args);
        String temp = applicationContext.getBean(Gateway.class).Send("kksingh");
        System.out.println(LocalDateTime.now()+"output" + temp);

        applicationContext.stop();

    }
}
</code>```

My custom serialzer and deserialser UCCXImprovedSerializerclass
after updating as per @Garry

```<code> public class UCCXImprovedSerializer implements Serializer<String>, Deserializer<String>
{
     @Override
    public String deserialize(InputStream initialStream) throws IOException
    {

        System.out.println("deserialzier called");
        StringBuilder sb = new StringBuilder();
        try (BufferedReader rdr = new BufferedReader(new InputStreamReader(initialStream)))
        {
            for (int c; (c = rdr.read()) != -1;)
            {
                sb.append((char) c);

            }
        }
        return sb.toString();
    }

    @Override
    public void serialize(String msg, OutputStream os) throws IOException
    {
        System.out.println(msg + "---serialize---" + Thread.currentThread().getName() + "");
        os.write(msg.getBytes());
    }
   }
</code>```

My server at port 9999 code

```<code>   try
        {
            clientSocket = echoServer.accept();
            System.out.println("client connection established..");
            is = new DataInputStream(clientSocket.getInputStream());
            os = new PrintStream(clientSocket.getOutputStream());
            String tempString = "kksingh";
            byte[] tempStringByte = tempString.getBytes();
            byte[] temp = new byte[tempString.getBytes().length];
            while (true)
            {
                is.read(temp);
                System.out.println(new String(temp) + "--received msg is--- " + LocalDateTime.now());
                System.out.println(LocalDateTime.now() + "sending value");
                os.write(tempStringByte);
                break;
            }
        } catch (IOException e)
        {
            System.out.println(e);
        }
    }
</code>```

My log file for tcp client

```<code>2017-06-04 23:10:14.771  INFO 15568 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started org.springframework.integration.endpoint.EventDrivenConsumer@1f12e153
kksingh---serialize---main
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
2017-06-04 23:10:14.812 ERROR 15568 --- [pool-1-thread-1] o.s.i.ip.tcp.TcpOutboundGateway          : Cannot correlate response - no pending reply for localhost:9999:57622:bc98ee29-8957-47bd-bd8a-f734c3ec3f9d
2017-06-04T23:10:14.809output
2017-06-04 23:10:14.821  INFO 15568 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
</code>```

My log file for server side

```<code>client connection established..
kksingh--received msg is--- 2017-06-04T23:10:14.899
2017-06-04T23:10:14.899sending value
</code>```

when I removed the localdatetime.now() from server and tcpclient  I am able to get response as outputkksingh

```<code>o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-06-05 12:46:32.494  INFO 29076 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'application.errorChannel' has 1 subscriber(s).
2017-06-05 12:46:32.495  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-06-05 12:46:32.746  INFO 29076 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-05 12:46:32.753  INFO 29076 --- [           main] o.s.i.samples.tcpclientserver.Test       : Started Test in 2.422 seconds (JVM running for 2.716)
2017-06-05 12:46:32.761  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {bridge:null} as a subscriber to the 'replyChannel' channel
2017-06-05 12:46:32.762  INFO 29076 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'application.replyChannel' has 1 subscriber(s).
2017-06-05 12:46:32.763  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started org.springframework.integration.endpoint.EventDrivenConsumer@1f12e153
kksingh---serialize---main
pool-1-thread-1---deserialize----kksingh
outputkksingh
2017-06-05 12:46:32.837  INFO 29076 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2017-06-05 12:46:32.839  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Removing {bridge:null} as a subscriber to the 'replyChannel' channel
2017-06-05 12:46:32.839  INFO 29076 --- [
</code>```

答:
Your deserializer is deserializing multiple packets...

```<code>pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
</code>```

Which produces 4 reply messsages; the gateway can only handle one reply which is why you see that ERROR message.

You deserializer needs to be smarter than just capturing "available" bytes. You need something in the message to indicate the end of the data (or close the socket to indicate the end).

Body:
I have created tcp client using spring integration I am able to receive  response for my send message . But when I uses  localDateTime.now() to log time I am not able to receive the response of send message . I know this can be solved using time setting to make thread wait. As I am new to spring integration So kindly help me how to do it.

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Test
{

    protected final Log logger = LogFactory.getLog(this.getClass());

    // **************** Client **********************************************
    @Bean
    public MessageChannel replyChannel()
    {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel sendChannel()
    {
        MessageChannel directChannel = new DirectChannel();
        return directChannel;
    }

    @EnableIntegration
    @IntegrationComponentScan
    @Configuration
    public static class config
    {
        @MessagingGateway(defaultRequestChannel = "sendChannel", defaultReplyChannel = "replyChannel")
        public interface Gateway
        {

            String Send(String in);

        }
    }

    @Bean
    AbstractClientConnectionFactory tcpNetClientConnectionFactory()
    {
        AbstractClientConnectionFactory tcpNetClientConnectionFactory = new TcpNetClientConnectionFactory("localhost",
                9999);
        tcpNetClientConnectionFactory.setSerializer(new UCCXImprovedSerializer());
        tcpNetClientConnectionFactory.setDeserializer(new UCCXImprovedSerializer());
        tcpNetClientConnectionFactory.setSingleUse(true);

        tcpNetClientConnectionFactory.setMapper(new TcpMessageMapper());
        return tcpNetClientConnectionFactory;
    }

    @Bean
    @ServiceActivator(inputChannel = "sendChannel")
    TcpOutboundGateway tcpOutboundGateway()
    {
        TcpOutboundGateway tcpOutboundGateway = new TcpOutboundGateway();
        tcpOutboundGateway.setConnectionFactory(tcpNetClientConnectionFactory());
        tcpOutboundGateway.setReplyChannel(replyChannel());
        return tcpOutboundGateway;
    }

    public static void main(String args[])
    {
        // new LegaServer();
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Test.class, args);
        String temp = applicationContext.getBean(Gateway.class).Send("kksingh");
        System.out.println(LocalDateTime.now()+"output" + temp);

        applicationContext.stop();

    }
}

My custom serialzer and deserialser UCCXImprovedSerializerclass
after updating as per @Garry

 public class UCCXImprovedSerializer implements Serializer<String>, Deserializer<String>
{
     @Override
    public String deserialize(InputStream initialStream) throws IOException
    {

        System.out.println("deserialzier called");
        StringBuilder sb = new StringBuilder();
        try (BufferedReader rdr = new BufferedReader(new InputStreamReader(initialStream)))
        {
            for (int c; (c = rdr.read()) != -1;)
            {
                sb.append((char) c);

            }
        }
        return sb.toString();
    }

    @Override
    public void serialize(String msg, OutputStream os) throws IOException
    {
        System.out.println(msg + "---serialize---" + Thread.currentThread().getName() + "");
        os.write(msg.getBytes());
    }
   }

My server at port 9999 code

   try
        {
            clientSocket = echoServer.accept();
            System.out.println("client connection established..");
            is = new DataInputStream(clientSocket.getInputStream());
            os = new PrintStream(clientSocket.getOutputStream());
            String tempString = "kksingh";
            byte[] tempStringByte = tempString.getBytes();
            byte[] temp = new byte[tempString.getBytes().length];
            while (true)
            {
                is.read(temp);
                System.out.println(new String(temp) + "--received msg is--- " + LocalDateTime.now());
                System.out.println(LocalDateTime.now() + "sending value");
                os.write(tempStringByte);
                break;
            }
        } catch (IOException e)
        {
            System.out.println(e);
        }
    }

My log file for tcp client

2017-06-04 23:10:14.771  INFO 15568 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started org.springframework.integration.endpoint.EventDrivenConsumer@1f12e153
kksingh---serialize---main
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
2017-06-04 23:10:14.812 ERROR 15568 --- [pool-1-thread-1] o.s.i.ip.tcp.TcpOutboundGateway          : Cannot correlate response - no pending reply for localhost:9999:57622:bc98ee29-8957-47bd-bd8a-f734c3ec3f9d
2017-06-04T23:10:14.809output
2017-06-04 23:10:14.821  INFO 15568 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0

My log file for server side

client connection established..
kksingh--received msg is--- 2017-06-04T23:10:14.899
2017-06-04T23:10:14.899sending value

when I removed the localdatetime.now() from server and tcpclient  I am able to get response as outputkksingh

o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-06-05 12:46:32.494  INFO 29076 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'application.errorChannel' has 1 subscriber(s).
2017-06-05 12:46:32.495  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-06-05 12:46:32.746  INFO 29076 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-05 12:46:32.753  INFO 29076 --- [           main] o.s.i.samples.tcpclientserver.Test       : Started Test in 2.422 seconds (JVM running for 2.716)
2017-06-05 12:46:32.761  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {bridge:null} as a subscriber to the 'replyChannel' channel
2017-06-05 12:46:32.762  INFO 29076 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'application.replyChannel' has 1 subscriber(s).
2017-06-05 12:46:32.763  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started org.springframework.integration.endpoint.EventDrivenConsumer@1f12e153
kksingh---serialize---main
pool-1-thread-1---deserialize----kksingh
outputkksingh
2017-06-05 12:46:32.837  INFO 29076 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2017-06-05 12:46:32.839  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Removing {bridge:null} as a subscriber to the 'replyChannel' channel
2017-06-05 12:46:32.839  INFO 29076 --- [

Body:
Your deserializer is deserializing multiple packets...

pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----

Which produces 4 reply messsages; the gateway can only handle one reply which is why you see that ERROR message.

You deserializer needs to be smarter than just capturing "available" bytes. You need something in the message to indicate the end of the data (or close the socket to indicate the end).


问:
Display simple markup in a Label in Delphi
I am currently displaying some text in a TLabel. I would now like to emphasise certain words within the text by displaying them in bold or perhaps italic. What is the recommended way to do this in Delphi? Is there a TLabel-like component that can display simple HTML or markup?
I am imagining some code like this:

```<code>label.text:='This information is <b>important</b>';
</code>```

I am using Delphi 2010

答:
Some ideas:

Have a look at TLinkLabel in ExtCtrls.
It lets you add links.. it paints the linked part underlined. Maybe you can steal the code and add support for other tags like    ?

You can use a TRichEdit component.. It's not HTML as you describe, but it should do the trick of formatting your text.

Use TjanMarkupLabel from this page.
"TjanMarkupLabel is a TGraphicControl descendant that renders its Text property in HTML style. Supported tags: Bold, Italic, Underline, Font (face, size and color) and Break."

Body:
I am currently displaying some text in a TLabel. I would now like to emphasise certain words within the text by displaying them in bold or perhaps italic. What is the recommended way to do this in Delphi? Is there a TLabel-like component that can display simple HTML or markup?
I am imagining some code like this:

label.text:='This information is important';

I am using Delphi 2010

Body:
Some ideas:

Have a look at TLinkLabel in ExtCtrls.
It lets you add links.. it paints the linked part underlined. Maybe you can steal the code and add support for other tags like <b> <i> <strong> <em>?

You can use a TRichEdit component.. It's not HTML as you describe, but it should do the trick of formatting your text.

Use TjanMarkupLabel from this page.
"TjanMarkupLabel is a TGraphicControl descendant that renders its Text property in HTML style. Supported tags: Bold, Italic, Underline, Font (face, size and color) and Break."


问:
Learn Python the Hard Way ex4
I'm recently follow learn python the hard way to ex4 and a bit confused about it. I use python3.5.2
This is what I typed in my editor and it worked well:

but when I open the file through terminal, it turned out like this:

('There are', 100, 'cars available')
('There are only', 30, 'drivers available')
('There will be', 70, 'empty cars today.')
('we can transport', 90, 'to carpool today.')
('we need to put about', 3, 'in each car.')
```

<p>The result I expect is:</p>

<pre class="lang-none prettyprint-override"><code>There are 100 cars available without the symbols.
</code>```

答: If you are on Windows, and you have multiple python versions installed, which you obviously do, use the py console command to run the version you want.  Start with py -h.  If you have exactly 2.7 and 3.5 installed, py -2 will run 2.7 and py -3 will run 3.5.

Title: Learn Python the Hard Way ex4

Body:
I'm recently follow learn python the hard way to ex4 and a bit confused about it. I use python3.5.2
This is what I typed in my editor and it worked well:

but when I open the file through terminal, it turned out like this:

('There are', 100, 'cars available')
('There are only', 30, 'drivers available')
('There will be', 70, 'empty cars today.')
('we can transport', 90, 'to carpool today.')
('we need to put about', 3, 'in each car.')

The result I expect is:

There are 100 cars available without the symbols.


问:
How is lookup table data declared and initialized in SQLAlchemy?

Motivation

Take a trivial example where a column of data needs to be represented by an enumerated type in SQL:

```<code>+------------------------------------------+
| user                                     |
+----+------+-----+------------------------+
| id | name | age | relationship_status_id |
+----+------+-----+------------------------+
| 1  | John | 27  | 3                      |
| 2  | Mary | 77  | 1                      |
| 3  | Jack | 40  | 4                      |
+----+------+-----+------------------------+

+---------------------+
| relationship_status |
+----+----------------+
| id | name           |
+----+----------------+
| 1  | married        |
| 2  | widowed        |
| 3  | single         |
| 4  | divorced       |
+----+----------------+
</code>```

Defining (declaring) the tables themselves in SQLAlchemy is relatively straightforward:

```<code>from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)
    relationship_status_id = Column(Integer, ForeignKey('relationship_status.id'))

class RelationshipStatus(Base):
    __tablename__ = 'relationship_status'

    id = Column(Integer, primary_key=True)
    name = Column(String)
</code>```

When initializing the database, tables can be created with a Base.metadata.create_all(engine) directive. The user table would be filled during the application's running lifetime; however, the relationship_status lookup table's data remains constant, and it seems appropriate to "declare" this data along with the table definition.

Yet persisting data to a table naturally requires a session, and unlike the table definitions themselves, SQLAlchemy does not seem to offer any declarative construct for "expected rows" in a given table (naturally, since the majority of tables in any application are like user with dynamic data).

Problem

Using SQLAlchemy, how can one declare both the schema and data of a lookup table before application runtime? Ideally, the solution would involve the creation of some Enum-like construct containing the data that other parts of the application could reference.

Research

The creator of SQLAlchemy proposed the enum recipe. The only apparent downside of such a solution is that one must rely on the enum datatype within the DBMS being used. For the scope of this question, a DBMS-independent lookup table solution is preferred.

A related alternative also proposed by SQLAlchemy's creator is the unique object recipe. Such an implementation ensures that the rows returned by lookup table queries remain without duplicates, but a session object is still required to make any declarations or requests--blurring the separation of concerns between database definition and implementation. Furthermore, clients would all simply need to "just know" what rows to ask for rather than having some sort of enum (within Python) for reference.

The root of the issue may be conceptual rather than tied to SQLAlchemy or Python. In either case, any advice would be much appreciated.

答:
First, I'd argue that in most situations, data that is constant and known at application development time is not generally a good fit for storing in a database.  I'd use either a DBMS-based enumeration or a Python-based enumeration and a check constraint to guarantee that each row in the users table had a valid relationship status.
Since you said you're not going to do that, it sounds like you're looking for a way to trigger some inserts at the time that your relationship_status table is created.
I've adapted the after_create example to insert something into a table instead of altering the table.  You should be able to adapt this to go insert your relationship status values.</p>

```<code>from sqlalchemy import event
from sqlalchemy import Table, Column, Metadata, Integer

m = MetaData()
some_table = Table('some_table', m, Column('data', Integer))

def after_create(target, connection, **kw):
    connection.execute("insert into  %s values ('1','single');" %
                            (target.name))

event.listen(some_table, "after_create", after_create)
</code>```

Body:
Motivation

Take a trivial example where a column of data needs to be represented by an enumerated type in SQL:

+------------------------------------------+
| user                                     |
+----+------+-----+------------------------+
| id | name | age | relationship_status_id |
+----+------+-----+------------------------+
| 1  | John | 27  | 3                      |
| 2  | Mary | 77  | 1                      |
| 3  | Jack | 40  | 4                      |
+----+------+-----+------------------------+

+---------------------+
| relationship_status |
+----+----------------+
| id | name           |
+----+----------------+
| 1  | married        |
| 2  | widowed        |
| 3  | single         |
| 4  | divorced       |
+----+----------------+

Defining (declaring) the tables themselves in SQLAlchemy is relatively straightforward:

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)
    relationship_status_id = Column(Integer, ForeignKey('relationship_status.id'))

class RelationshipStatus(Base):
    __tablename__ = 'relationship_status'

    id = Column(Integer, primary_key=True)
    name = Column(String)

When initializing the database, tables can be created with a Base.metadata.create_all(engine) directive. The user table would be filled during the application's running lifetime; however, the relationship_status lookup table's data remains constant, and it seems appropriate to "declare" this data along with the table definition.

Yet persisting data to a table naturally requires a session, and unlike the table definitions themselves, SQLAlchemy does not seem to offer any declarative construct for "expected rows" in a given table (naturally, since the majority of tables in any application are like user with dynamic data).

Problem

Using SQLAlchemy, how can one declare both the schema and data of a lookup table before application runtime? Ideally, the solution would involve the creation of some Enum-like construct containing the data that other parts of the application could reference.

Research

The creator of SQLAlchemy proposed the enum recipe. The only apparent downside of such a solution is that one must rely on the enum datatype within the DBMS being used. For the scope of this question, a DBMS-independent lookup table solution is preferred.

A related alternative also proposed by SQLAlchemy's creator is the unique object recipe. Such an implementation ensures that the rows returned by lookup table queries remain without duplicates, but a session object is still required to make any declarations or requests--blurring the separation of concerns between database definition and implementation. Furthermore, clients would all simply need to "just know" what rows to ask for rather than having some sort of enum (within Python) for reference.

The root of the issue may be conceptual rather than tied to SQLAlchemy or Python. In either case, any advice would be much appreciated.

Body:
First, I'd argue that in most situations, data that is constant and known at application development time is not generally a good fit for storing in a database.  I'd use either a DBMS-based enumeration or a Python-based enumeration and a check constraint to guarantee that each row in the users table had a valid relationship status.
Since you said you're not going to do that, it sounds like you're looking for a way to trigger some inserts at the time that your relationship_status table is created.
I've adapted the after_create example to insert something into a table instead of altering the table.  You should be able to adapt this to go insert your relationship status values.

from sqlalchemy import event
from sqlalchemy import Table, Column, Metadata, Integer

m = MetaData()
some_table = Table('some_table', m, Column('data', Integer))

def after_create(target, connection, **kw):
    connection.execute("insert into  %s values ('1','single');" %
                            (target.name))

event.listen(some_table, "after_create", after_create)


问:
Xcode Build Succeeded but not run on iPhone/Simulator
I am facing a little strange problem with Xcode, that is when I run my app is Xcode shows Succeeded but my app does not run automatically on iPhone or Simulator. I have to manually click on app icon then it runs. I have already tried all the solutions I could find. I have tried the following points:

Adding in armv6

Restarting xcode

Restarting device/simulator

Removing device from the organizer then adding it back.

Restarting Mac Book Pro.

Cleaning project and rebuilding

Check plist

Check target

Check product>edit scheme > select run option (and info tab) ==> all is fine there

Please note I am using these frameworks via pods name are:

```<code>pod 'IQKeyboardManager'
pod 'GooglePlacePicker'
pod 'Firebase/Messaging'
pod 'Google'
pod 'Google/SignIn'
pod 'FBSDKCoreKit'
pod 'FBSDKShareKit'
pod 'FBSDKLoginKit'
</code>```

The app does not run automatically even after Xcode show Build succeeded on simulator/iPhone.

答: There is one more possible problem that I can think of and that is, you're using a developer account on this project that is not trusted/verified on your iphone. After running your app for once on this device. Go to Settings > General > Device Management. Then select the developer account that you have used to build this app and finally tap "trust".</p>

Body:
I am facing a little strange problem with Xcode, that is when I run my app is Xcode shows Succeeded but my app does not run automatically on iPhone or Simulator. I have to manually click on app icon then it runs. I have already tried all the solutions I could find. I have tried the following points:

Adding in armv6

Restarting xcode

Restarting device/simulator

Removing device from the organizer then adding it back.

Restarting Mac Book Pro.

Cleaning project and rebuilding

Check plist

Check target

Check product>edit scheme > select run option (and info tab) ==> all is fine there

Please note I am using these frameworks via pods name are:

pod 'IQKeyboardManager'
pod 'GooglePlacePicker'
pod 'Firebase/Messaging'
pod 'Google'
pod 'Google/SignIn'
pod 'FBSDKCoreKit'
pod 'FBSDKShareKit'
pod 'FBSDKLoginKit'

The app does not run automatically even after Xcode show Build succeeded on simulator/iPhone.


问:
Error, pygame.image.load, unable to resolve
To start, this seems to be a common issue for folks but the resolves which have helped them have been little help to myself. Preliminaries, I am running Raspbian w/Pixel on the RaspberryPi3B. I have read all relevant pygame documentation on the matter along with other resources. Here is the link to the doc; https://www.pygame.org/docs/ref/image.html#pygame.image.load .

I have re-installed everything using the shell:

```<code>$ sudo apt-get install mercurial

$ hg clone https://bitbucket.org/pygame/pygame

$ cd pygame

$ sudo apt-get install libsdl-dev libsdl-image1.2-dev libsdl-
mixer1.2-dev libsdl-ttf2.0-dev

$ sudo apt-get install libsmpeg-dev libportmidi-dev libavformat-dev libswscale-dev

$ sudo apt-get install python3-dev python3-numpy

$ python3 setup.py build
$ sudo python3 setup.py install
</code>```

So now starts the fun..
I am getting the following error:

Traceback (most recent call last):   File
  "/home/pi/Python_Code/Revenge of the Morning Wood.py", line 19, in

      lumberJack = pygame.image.load('/home/pi/Python_Code/Revenge_of_the_Morning_wood/lumberJack.png')

pygame.error: Couldn't open
  /home/pi/Python_Code/Revenge_of_the_Morning_wood/lumberJack.png

Code up to the point of error:

```<code>import pygame
import time

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Revenge of the Morning Wood")
clock = pygame.time.Clock()

lumberJack = pygame.image.load('/home/pi/Python_Code/Revenge_of_the_Morning_wood/lumberJack.png'

def lumberJack(x,y):
    gameDisplay.blit(lumberJack,(x,y))

x = (display_width * 0.45)
y = (display_height * 0.8)
</code>```

It won't even show an uncompressed .bmp file. I've tried all file extensions and all combination of file locations in relation to source code/image/pygame_module.

pygame.image.get_extended() initially popped an error in python shell but after the installation detailed above now returns a value of "1".

答:
The long awaited resolve! I removed the image extension entirely. Ensuring the image was in the pygame directory:

```<code>lumber_Jack = pygame.image.load('/home/pi/pygame/lumberJack')
</code>```

This was actual mentioned in the documentation I included earlier but I overlooked it. https://www.pygame.org/docs/ref/image.html#pygame.image.load :

Pygame will automatically determine the image type (e.g., GIF or bitmap) and create a new Surface object from the data. In some cases it will need to know the file extension (e.g., GIF images should end in ”.gif”).

For those of you wondering why I changed the name of my variable. I also noticed an issue with my variable lumberjack sharing the same name as my lumberjack function but this did not contribute to the issue. For anyone else having this issue just leave off the .PNG, .BMP, JPG, etc.

Body:
To start, this seems to be a common issue for folks but the resolves which have helped them have been little help to myself. Preliminaries, I am running Raspbian w/Pixel on the RaspberryPi3B. I have read all relevant pygame documentation on the matter along with other resources. Here is the link to the doc; https://www.pygame.org/docs/ref/image.html#pygame.image.load .

I have re-installed everything using the shell:

$ sudo apt-get install mercurial

$ hg clone https://bitbucket.org/pygame/pygame

$ cd pygame

$ sudo apt-get install libsdl-dev libsdl-image1.2-dev libsdl-
mixer1.2-dev libsdl-ttf2.0-dev

$ sudo apt-get install libsmpeg-dev libportmidi-dev libavformat-dev libswscale-dev

$ sudo apt-get install python3-dev python3-numpy

$ python3 setup.py build
$ sudo python3 setup.py install

So now starts the fun..
I am getting the following error:

Traceback (most recent call last):   File
  "/home/pi/Python_Code/Revenge of the Morning Wood.py", line 19, in

      lumberJack = pygame.image.load('/home/pi/Python_Code/Revenge_of_the_Morning_wood/lumberJack.png')

pygame.error: Couldn't open
  /home/pi/Python_Code/Revenge_of_the_Morning_wood/lumberJack.png

Code up to the point of error:

import pygame
import time

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Revenge of the Morning Wood")
clock = pygame.time.Clock()

lumberJack = pygame.image.load('/home/pi/Python_Code/Revenge_of_the_Morning_wood/lumberJack.png'

def lumberJack(x,y):
    gameDisplay.blit(lumberJack,(x,y))

x = (display_width * 0.45)
y = (display_height * 0.8)

It won't even show an uncompressed .bmp file. I've tried all file extensions and all combination of file locations in relation to source code/image/pygame_module.

pygame.image.get_extended() initially popped an error in python shell but after the installation detailed above now returns a value of "1".

Body:
The long awaited resolve! I removed the image extension entirely. Ensuring the image was in the pygame directory:

lumber_Jack = pygame.image.load('/home/pi/pygame/lumberJack')

This was actual mentioned in the documentation I included earlier but I overlooked it. https://www.pygame.org/docs/ref/image.html#pygame.image.load :

Pygame will automatically determine the image type (e.g., GIF or bitmap) and create a new Surface object from the data. In some cases it will need to know the file extension (e.g., GIF images should end in ”.gif”).

For those of you wondering why I changed the name of my variable. I also noticed an issue with my variable lumberjack sharing the same name as my lumberjack function but this did not contribute to the issue. For anyone else having this issue just leave off the .PNG, .BMP, JPG, etc.


问:
Parsing Strange JSON Data in PHP
My example json data is below, I have tried to parse it however, I couldn't get the data with $response[0] or $response[1] etc... How can I parse it?

Thanks!

```<code>[
  {
    "Tags": [
      "diyarbakır",
      "bağlar",
      "patlama"
    ]
  },
  {
    "Tags": [
      "gazetehaberleri",
      "galatasaray lisesi",
      "kadri gürsel"
    ]
  }
]
</code>```

UPDATE

```<code>$response = json_decode($response);

foreach($response as $key => $value){
   echo $value;
}
</code>```

Warning: Invalid argument supplied for foreach()

答:
```<code>$response = json_decode($response, true);
</code>```

by default second argument is false. by using true it forces it to associative array.

http://php.net/json_decode

Title: Parsing Strange JSON Data in PHP

Body:
My example json data is below, I have tried to parse it however, I couldn't get the data with $response[0] or $response[1] etc... How can I parse it?

Thanks!

[
  {
    "Tags": [
      "diyarbakır",
      "bağlar",
      "patlama"
    ]
  },
  {
    "Tags": [
      "gazetehaberleri",
      "galatasaray lisesi",
      "kadri gürsel"
    ]
  }
]

UPDATE

$response = json_decode($response);

foreach($response as $key => $value){
   echo $value;
}

Warning: Invalid argument supplied for foreach()

Body:
$response = json_decode($response, true);

by default second argument is false. by using true it forces it to associative array.

http://php.net/json_decode


问:
Swift SKConstraint
Struggling with implementing SKConstraint in my iOS rugby game app.

Basically I create multiple nodes called 'defenders', the number depending on how many that particular level requires. Each node is named defender+number.

Thus if 3 defenders are spawned I have 3 defender nodes called: defender1, defender2, defender3

This is the code I used to spawn the defender node with initial positioning:

```<code>for defenderNumber in 1 ..< (numberDefenders+1) {
        let defender = Defender(imageNamed: "defender_\(teamShirt)")
        defender.position = CGPoint(x: defenderXposition, y: defenderYposition)
        defender.size = CGSize (width: 50, height: 35)
        defender.zPosition = 2
        defender.name = "defender\(defenderNumber)"
        defenderXposition = defenderXposition + defenderSpacing
        addChild(defender)

        }
</code>```

As part of the game the defenders then chase the attackers in various defensive patterns. However I've noticed that the defenders tend to group together and I want to include a constraint where the defenders keep a minimum distance away from each other.

I thought I would use a SKConstraint such as:

let range = SKRange(lowerLimit:150, upperLimit:1000)
            let constraint = SKConstraint.distance(range, to:defender)
            defender.constraints = [constraint]

I tried putting the above constraint code in my defender spawn code but it doesn't seem to have an effect.

Any advice greatly appreciated

答:
If anyone else is having this issue, I have created a work around - however its horribly clunky and not particularly easy on the coders eye!

The issue with the above I worked out was that as I was adding one defender childNode at a time in an iteration loop, I couldn't constrain that particular defender node to another defender as they did not exist within that loop.

Thus to work around this, after adding each defender node to the game scene I  nestled an node iteration loop inside another. Both iterated through the same set of defender nodes, but I called the second iteration 'next defender' within the first iteration loop. So for each defender brought up in the first loop, all the defenders are brought up in the second, assigned a different node name, and then I linked constraints to all second iteration nodes to the first.

```<code>    for defenderNumber in 1 ..< (self.numberDefenders+1) {
        enumerateChildNodes(withName: "defender\(defenderNumber)", using: {node, stop in

            let defender = node as! Defender

            for defenderNumber in 1 ..< (self.numberDefenders+1) {
                self.enumerateChildNodes(withName: "defender\(defenderNumber)", using: {node, stop in

                    let nextdefender = node as! Defender
                    let range = SKRange(lowerLimit:50)
                    let constraint = SKConstraint.distance(range, to:nextdefender)
                    defender.constraints = [constraint]
                })

            }
        })

    }
</code>```

This hurts my eyes so much that if anyone has a more elegant way of achieving this I would appreciate it greatly!

Title: Swift SKConstraint

Body:
Struggling with implementing SKConstraint in my iOS rugby game app.

Basically I create multiple nodes called 'defenders', the number depending on how many that particular level requires. Each node is named defender+number.

Thus if 3 defenders are spawned I have 3 defender nodes called: defender1, defender2, defender3

This is the code I used to spawn the defender node with initial positioning:

for defenderNumber in 1 ..< (numberDefenders+1) {
        let defender = Defender(imageNamed: "defender_\(teamShirt)")
        defender.position = CGPoint(x: defenderXposition, y: defenderYposition)
        defender.size = CGSize (width: 50, height: 35)
        defender.zPosition = 2
        defender.name = "defender\(defenderNumber)"
        defenderXposition = defenderXposition + defenderSpacing
        addChild(defender)

        }

As part of the game the defenders then chase the attackers in various defensive patterns. However I've noticed that the defenders tend to group together and I want to include a constraint where the defenders keep a minimum distance away from each other.

I thought I would use a SKConstraint such as:

let range = SKRange(lowerLimit:150, upperLimit:1000)
            let constraint = SKConstraint.distance(range, to:defender)
            defender.constraints = [constraint]

I tried putting the above constraint code in my defender spawn code but it doesn't seem to have an effect.

Any advice greatly appreciated

Body:
If anyone else is having this issue, I have created a work around - however its horribly clunky and not particularly easy on the coders eye!

The issue with the above I worked out was that as I was adding one defender childNode at a time in an iteration loop, I couldn't constrain that particular defender node to another defender as they did not exist within that loop.

Thus to work around this, after adding each defender node to the game scene I  nestled an node iteration loop inside another. Both iterated through the same set of defender nodes, but I called the second iteration 'next defender' within the first iteration loop. So for each defender brought up in the first loop, all the defenders are brought up in the second, assigned a different node name, and then I linked constraints to all second iteration nodes to the first.

    for defenderNumber in 1 ..< (self.numberDefenders+1) {
        enumerateChildNodes(withName: "defender\(defenderNumber)", using: {node, stop in

            let defender = node as! Defender

            for defenderNumber in 1 ..< (self.numberDefenders+1) {
                self.enumerateChildNodes(withName: "defender\(defenderNumber)", using: {node, stop in

                    let nextdefender = node as! Defender
                    let range = SKRange(lowerLimit:50)
                    let constraint = SKConstraint.distance(range, to:nextdefender)
                    defender.constraints = [constraint]
                })

            }
        })

    }

This hurts my eyes so much that if anyone has a more elegant way of achieving this I would appreciate it greatly!


问:
getScript function not working - jquery
I'm using bootstrap-select in my page.

at first time when the page loaded my bootstrap-select works fine. I loaded these libraries at the footer of my page:

```<code><script type="text/javascript" src="{{URL::to('/').'/assets/frontend/'}}_js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="{{URL::to('/').'/assets/frontend/'}}_js/bootstrap.min.js"></script>
<script type="text/javascript" src="{{URL::to('/').'/assets/frontend/'}}_js/bootstrap-select.min.js"></script>
</code>```

now user want to filter products and I use post ajax method:

```<code>function getPosts(page,brands,min_price,max_price) {
        $.ajax({
            async: true,
            url: '?page=' + page+'&brands=' + brands + '&min_price=' + min_price + '&max_price=' + max_price ,
        }).done(function(data) {

            if(data == 'empty')
            {

            }else{

                $('.product-list').html(data);
                location.hash = page;

                var url_1 = '{{URL::to('/').'/assets/frontend/'}}_js/jquery-3.1.1.min.js';
                var url_2 = '{{URL::to('/').'/assets/frontend/'}}_js/bootstrap.min.js';
                var url_3 = '{{URL::to('/').'/assets/frontend/'}}_js/bootstrap-select.min.js';

                $.getScript(url_1);
                $.getScript(url_2);
                $.getScript(url_3);
            }

        }).fail(function() {
            if(brands != null)
            {
                getPosts(1,null,0,0);

            }else{

            }

        });
    }
</code>```

my products will load in my page but bootstrap-select not work at all.

my html code:

```<code> <select name="product-quantity"  class="form-control selectpicker" data-size="5">
...
</code>```

getScript called but not work on my select-option:

答:
No need to re-insert the libraries. Once is enough.

You just need to run the script that initializes the select drop-down.

else {

  $('.product-list').html(data);
  location.hash = page;
  $('.selectpicker').selectpicker();

}
```

Title: getScript function not working - jquery

Body:
I'm using bootstrap-select in my page.

at first time when the page loaded my bootstrap-select works fine. I loaded these libraries at the footer of my page:

now user want to filter products and I use post ajax method:

function getPosts(page,brands,min_price,max_price) {
        $.ajax({
            async: true,
            url: '?page=' + page+'&brands=' + brands + '&min_price=' + min_price + '&max_price=' + max_price ,
        }).done(function(data) {

            if(data == 'empty')
            {

            }else{

                $('.product-list').html(data);
                location.hash = page;

                var url_1 = '{{URL::to('/').'/assets/frontend/'}}_js/jquery-3.1.1.min.js';
                var url_2 = '{{URL::to('/').'/assets/frontend/'}}_js/bootstrap.min.js';
                var url_3 = '{{URL::to('/').'/assets/frontend/'}}_js/bootstrap-select.min.js';

                $.getScript(url_1);
                $.getScript(url_2);
                $.getScript(url_3);
            }

        }).fail(function() {
            if(brands != null)
            {
                getPosts(1,null,0,0);

            }else{

            }

        });
    }

my products will load in my page but bootstrap-select not work at all.

my html code:

 <select name="product-quantity"  class="form-control selectpicker" data-size="5">
...

getScript called but not work on my select-option:


问:
jQuery How to hide all span containing td in a table
I have some rows in a table like the code below and I want after some seconds to hide the contents of td's (i have filled them with text in a loop).
My sample code is this

```<code>setTimeout(function() {
  $('span').each(function(index, el) {
      $(this).hide();//nothing happens
  });
}, 5000);

<tr>
  <span class="myspan"><td></td></span>
  <span class="myspan"><td></td></span>
  <span class="myspan"><td></td></span>
  <span class="myspan"><td></td></span>
</tr>
</code>```

I tried using other ways too, like saving all spans to an array, or selecting the class and hiding it.

```<code>var arr=$('span');
for (var i=0;i<arr.length;i++){
  arr[i].css('visibility','hidden');
}
</code>```

but same thing happened. I want to be able to show and hide the contents of td's when it's needed without hiding the border if it is possible

答:
you can just use any element in td tag from table.
otherwise browser convert your code to valid code.
output your HTML is like that in browser:

```<code><body>
    <span class="myspan"></span>
    <span class="myspan"></span>
    <span class="myspan"></span>
    <span class="myspan"></span>
    <table>
        <tbody>
           <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
      </tbody>
   </table>
</body>
</code>```

you select span but there is no more td in your target span. SO your delect is false.

you have to change yor HTML:

```<code><tr>
  <td><span class="myspan"></span></td>
  <td><span class="myspan"></span></td>
  <td><span class="myspan"></span></td>
  <td><span class="myspan"></span></td>
</tr>
</code>```

now you can select it and do your function:

```<code>var arr=$('span');
arr.css('visibility','hidden');
</code>```

or

```<code>var arr=$('span');
arr.hide();
</code>```

later show yor it:

```<code>att.show();
</code>```

you dont need for or any loop. just select your target and say ehat do you want to do. JQuery do it for each on in your selector (exactly like a loop)

Body:
I have some rows in a table like the code below and I want after some seconds to hide the contents of td's (i have filled them with text in a loop).
My sample code is this

setTimeout(function() {
  $('span').each(function(index, el) {
      $(this).hide();//nothing happens
  });
}, 5000);

I tried using other ways too, like saving all spans to an array, or selecting the class and hiding it.

var arr=$('span');
for (var i=0;i<arr.length;i++){
  arr[i].css('visibility','hidden');
}

but same thing happened. I want to be able to show and hide the contents of td's when it's needed without hiding the border if it is possible

Body:
you can just use any element in td tag from table.
otherwise browser convert your code to valid code.
output your HTML is like that in browser:

<body>
    <span class="myspan"></span>
    <span class="myspan"></span>
    <span class="myspan"></span>
    <span class="myspan"></span>
    <table>
        <tbody>
           <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
      </tbody>
   </table>
</body>

you select span but there is no more td in your target span. SO your delect is false.

you have to change yor HTML:

<tr>
  <td><span class="myspan"></span></td>
  <td><span class="myspan"></span></td>
  <td><span class="myspan"></span></td>
  <td><span class="myspan"></span></td>
</tr>

now you can select it and do your function:

var arr=$('span');
arr.css('visibility','hidden');

or

var arr=$('span');
arr.hide();

later show yor it:

att.show();

you dont need for or any loop. just select your target and say ehat do you want to do. JQuery do it for each on in your selector (exactly like a loop)


问:
Inplace versions of set_difference, set_intersection and set_union
I implemented versions of set_union, set_intersection and set_difference that take a sorted container and a sorted range (that must not be within the container), and write the result of the operation into the container.

```<code>template<class Container, class Iter>
void assign_difference(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_difference( // (1)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_intersection(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_intersection( // (2)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_union(Container& cont, Iter first, Iter last)
{
    auto insert_count = last - first;
    cont.resize(cont.size() + insert_count); // T must be default-constructible
    auto rfirst1 = cont.rbegin() + insert_count, rlast1 = cont.rend();
    auto rfirst2 = std::make_reverse_iterator(last);
    auto rlast2 = std::make_reverse_iterator(first);
    rlast1 = std::set_union( // (3)
        rfirst1, rlast1, rfirst2, rlast2, cont.rbegin(), std::greater<>());
    cont.erase(std::copy(rlast1.base(), cont.end(), cont.begin()), cont.end());
}
</code>```

The goal was:

No allocation is performed if the container has enaugh capacity to hold the result.

Otherwise exactly one allocation is performed to give the container the capacity to hold the result.

As you can see in the lines marked (1), (2) and (3), the same container is used as input and output for those STL algorithms. Assuming a usual implementation of those STL algorithms, this code works, since it only writes to parts of the container that have already been processed.

As pointed out in the comments, it's not guaranteed by the standard that this works. set_union, set_intersection and set_difference require that the resulting range doesn't overlap with one of the input ranges.
However, can there be a STL implementation that breaks the code?

If your answer is yes, please provide a conforming implementations of one of the three used STL algorithms that breaks the code.

答:
A conforming implementation could check if argument 1 and 5 of set_intersection are equal, and if they are format your harddrive.

If you violate the requirements, the behaviour of your program is not constrained by the standard; your program is ill formed.

There are situations where UB may be worth the risk and cost (auditing all compiler changes and assembly output).  I do not see the point here; write your own.  Any fancy optimizations that the std library comes up with could cause problems when you violate requirements as you are doing, and as you have noted the naive implementation is simple.

Body:
I implemented versions of set_union, set_intersection and set_difference that take a sorted container and a sorted range (that must not be within the container), and write the result of the operation into the container.

template<class Container, class Iter>
void assign_difference(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_difference( // (1)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_intersection(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_intersection( // (2)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_union(Container& cont, Iter first, Iter last)
{
    auto insert_count = last - first;
    cont.resize(cont.size() + insert_count); // T must be default-constructible
    auto rfirst1 = cont.rbegin() + insert_count, rlast1 = cont.rend();
    auto rfirst2 = std::make_reverse_iterator(last);
    auto rlast2 = std::make_reverse_iterator(first);
    rlast1 = std::set_union( // (3)
        rfirst1, rlast1, rfirst2, rlast2, cont.rbegin(), std::greater<>());
    cont.erase(std::copy(rlast1.base(), cont.end(), cont.begin()), cont.end());
}

The goal was:

No allocation is performed if the container has enaugh capacity to hold the result.

Otherwise exactly one allocation is performed to give the container the capacity to hold the result.

As you can see in the lines marked (1), (2) and (3), the same container is used as input and output for those STL algorithms. Assuming a usual implementation of those STL algorithms, this code works, since it only writes to parts of the container that have already been processed.

As pointed out in the comments, it's not guaranteed by the standard that this works. set_union, set_intersection and set_difference require that the resulting range doesn't overlap with one of the input ranges.
However, can there be a STL implementation that breaks the code?

If your answer is yes, please provide a conforming implementations of one of the three used STL algorithms that breaks the code.


问:
Database Modeling: Shipping Rules
I'm working on an e-commerce type web application and need to somehow handle calculation of shipping costs. Some rules I've found:

Free shipping

Free shipping with minimum purchase

Free shipping within a certain geographic area

Flat rate shipping

Flat rate + set amount per product

Various rates depending on speed of shipping (shipped immediately and/or how soon it gets to customer)

Based on height, width, depth, weight + shipping distance

Based on rates of various shippers

... and so on.

Any suggestions how to tackle such a problem?

答: I suggest you take a look at some available open source ecommerce solutions. There are a LOT of them and each one takes a stab at doing exactly what you are trying to do. If it is schema design you are after I wouldn't limit your searches to just MySQL - as long as it contains a relational database it should be easy to dig into the design. I'd take a look at nopcommerce to name just one...</p>

ContentLicense: CC BY-SA 4.0

Title: Database Modeling: Shipping Rules


问:
Listing elements without manually specifying them
I'm attempting to turn the old, "roll dice" program into something more different. I would like to add more numbers instead of 6, but typing all the numbers out seems painstaking. I'm sure you programmers have an easier way to do things like this.

Example:

```<code>hist = pygal.Bar()

    hist.title = "Results of rolling numbers 0-69 100 times."
    hist.x_labels = ['1', '2', '3']
    hist.x_title = "Numbers Rolled"
    hist.y_title = "Frequency of numbers rolled"
</code>```

On line 3, I want to be able to insert numbers 1-69, or even more if i wish to change it. How can I do this easily?

I thought the range() function would work, but it didn't, unless I'm doing something wrong. Thank you

答:
Use a list and a simple for loop, e.g.

```<code>numbers = []
for number in range(100):
    numbers.append(number)
</code>```

this will give you a list with all values from 0 -> 100.

as John Gordon pointed out it seems you may want to have those numbers as Strings, for that just change the third line to:

```<code>numbers.append(str(number))
</code>```

Body:
I'm attempting to turn the old, "roll dice" program into something more different. I would like to add more numbers instead of 6, but typing all the numbers out seems painstaking. I'm sure you programmers have an easier way to do things like this.

Example:

hist = pygal.Bar()

    hist.title = "Results of rolling numbers 0-69 100 times."
    hist.x_labels = ['1', '2', '3']
    hist.x_title = "Numbers Rolled"
    hist.y_title = "Frequency of numbers rolled"

On line 3, I want to be able to insert numbers 1-69, or even more if i wish to change it. How can I do this easily?

I thought the range() function would work, but it didn't, unless I'm doing something wrong. Thank you

Body:
Use a list and a simple for loop, e.g.

numbers = []
for number in range(100):
    numbers.append(number)

this will give you a list with all values from 0 -> 100.

as John Gordon pointed out it seems you may want to have those numbers as Strings, for that just change the third line to:

numbers.append(str(number))