问:
php function not executing
Here is my php code where i am calling a function dataLC() to update some values, but as soon as the page executes, the function calling part didn't execute, I am unable to figure out the problem--

```<code><?php
include 'db.php';
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;

echo $GLOBALS['lks'];
echo $GLOBALS['cmnts'];
?>
<div class="btnclasess">
          <div id="likescommentID" class="likescomment"><?php dataLC(2); ?><a style="padding-right: 7px" href="#"><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?></a><a href="#"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></a></div>
         <div class="pull-left likebtn"><a href="#" onClick="connect(2)"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</a></div>
         <button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo2"><li class="fa fa-comments show_hide" style="margin-right: 6px;"></li>Comment</button>
         <button class="pull-left btnhideshow show_hide"><li class="fa fa-share-alt show_hide" style="margin-right: 6px;"></li>Share</button>
         <div class="clear"></div>
      <div class="clear"></div>
    </div>
<script>
        function connect(num) {

    $.ajax({
    type: "POST",
    url: "user-likes.php?id="+num,
    success: function(data) {
        $("#likescommentID").load(" #likescommentID");
    }
    });
    }
</script>
<?php
function dataLC($val)
{
    $stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
    $stmt->bind_param("s", $val);
    $stmt->execute();
    $stmt->bind_result($lksD,$cmntsD);
    $stmt->fetch();
    $stmt->close();

    $GLOBALS['lks']=$lksD;
    $GLOBALS['cmnts']=$cmntsD;
}
?>
</code>```

Can anyone pls check why the function dataLC() call is not working.

答:
You need to pass the database variable as a parameter instead. The variable $linkID1 does not exist in the function.

Pass it as a parameter :

```<code>function dataLC($linkID1 , $val) {

}
</code>```

Title: php function not executing

Body:
Here is my php code where i am calling a function dataLC() to update some values, but as soon as the page executes, the function calling part didn't execute, I am unable to figure out the problem--

<?php
include 'db.php';
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;

echo $GLOBALS['lks'];
echo $GLOBALS['cmnts'];
?>

<?php dataLC(2); ?><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?>

Like

         <button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo2">

Comment</button>
         <button class="pull-left btnhideshow show_hide">

Share</button>

<?php
function dataLC($val)
{
    $stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
    $stmt->bind_param("s", $val);
    $stmt->execute();
    $stmt->bind_result($lksD,$cmntsD);
    $stmt->fetch();
    $stmt->close();

    $GLOBALS['lks']=$lksD;
    $GLOBALS['cmnts']=$cmntsD;
}
?>

Can anyone pls check why the function dataLC() call is not working.

Body:
You need to pass the database variable as a parameter instead. The variable $linkID1 does not exist in the function.

Pass it as a parameter :

function dataLC($linkID1 , $val) {

}


来源: stackexchange

问:
What Does GetLineFromCharIndex() Really Do?
I'm working through Ron Jeffries's Extreme Programming Adventures in C#. His main example is a simple XML text editor. Given the age of the book (published in 2004), I suspected that a lot of his initial coding, finding what line the cursor is on and where the insertion point is, can be replaced with new TextBox methods or properties. I'm Visual Studio 2005. Trying to keep with the spirit of Agile development and XP, I wrote some tests first:

```<code>[Test]
public void TestGetFirstCharIndexOfCurrentLine() {
  String[] newlines = new string[] { "<P>one</P>", "<P>two</P>" }; //TextLength == 20
  notepad.txtbox.Lines = newlines;
  Expect(notepad.txtbox.SelectionStart, EqualTo(20));
  Expect(notepad.txtbox.GetFirstCharIndexOfCurrentLine(), EqualTo(11));
  Expect(notepad.txtbox.GetLineFromCharIndex(11), EqualTo(1));
}
</code>```

(I'm being lazy (erm... I mean I'm trying to save space). This code actually combines three tests that I actually run in separate methods.)

In any event, each of the tests fails. First, the txtbox.SelectionStart returns 0. This may be consistent with what the documentation suggests, but when I step through in debug, the value is 20. The other two tests yield similar results; a zero where I would expect a positive integer value. These latter two cases, in particular, do not comport with my reading of the documentation.

I would really appreciate a clue where I'm going wrong.

答:
Not sure if this will solve it, but try inserting the following line after you've done all the TextBox manipulation (i.e. just before the first Expect call):

```<code>Application.DoEvents();
</code>```

This should allow the Windows message pump to operate briefly and insure that the TextBox is in the correct state regardless of everything else. Also, the second test of your previous post might be failing because you use \n rather than \r\n (the standard line break sequence) in your call to AppendText.

ContentLicense: CC BY-SA 3.0

Body:
I'm working through Ron Jeffries's Extreme Programming Adventures in C#. His main example is a simple XML text editor. Given the age of the book (published in 2004), I suspected that a lot of his initial coding, finding what line the cursor is on and where the insertion point is, can be replaced with new TextBox methods or properties. I'm Visual Studio 2005. Trying to keep with the spirit of Agile development and XP, I wrote some tests first:

[Test]
public void TestGetFirstCharIndexOfCurrentLine() {
  String[] newlines = new string[] { "
one
", "
two
" }; //TextLength == 20
  notepad.txtbox.Lines = newlines;
  Expect(notepad.txtbox.SelectionStart, EqualTo(20));
  Expect(notepad.txtbox.GetFirstCharIndexOfCurrentLine(), EqualTo(11));
  Expect(notepad.txtbox.GetLineFromCharIndex(11), EqualTo(1));
}

(I'm being lazy (erm... I mean I'm trying to save space). This code actually combines three tests that I actually run in separate methods.)

In any event, each of the tests fails. First, the txtbox.SelectionStart returns 0. This may be consistent with what the documentation suggests, but when I step through in debug, the value is 20. The other two tests yield similar results; a zero where I would expect a positive integer value. These latter two cases, in particular, do not comport with my reading of the documentation.

I would really appreciate a clue where I'm going wrong.

Body:
Not sure if this will solve it, but try inserting the following line after you've done all the TextBox manipulation (i.e. just before the first Expect call):

Application.DoEvents();

This should allow the Windows message pump to operate briefly and insure that the TextBox is in the correct state regardless of everything else. Also, the second test of your previous post might be failing because you use \n rather than \r\n (the standard line break sequence) in your call to AppendText.

OwnerDisplayName: Noldorin


问:
RC variables in matplotlib doesn't apply to graphs, axes in web app
I'm trying to set line widths for matplotlib in a web application that generates graphs using

```<code>matplotlib.rc('lines', linewidth=0.5)
</code>```

This works fine when working with matplotlib in interactive mode, but in my web application it has no effect, and the only way I can get the correct line widths is by supplying the argument on the individual calls, i.e.:

```<code>vals = map(itemgetter(1), sorted(series1.items(), reverse=True))
group1_rects = ax.barh(ind, vals, width, color='r', snap=True, linewidth=0.5)
vals = map(itemgetter(1), sorted(series2.items(), reverse=True))
group2_rects = ax.barh(ind+width, vals, width, color='b', linewidth=0.5)
</code>```

Is there some trick involved to make the matplotlib.rc call work in web apps?

The code I'm using for getting a figure to draw on looks like this:

```<code>@contextmanager
def render_plot(w=8,h=8):
    fig = Figure(figsize=(w,h))
    canvas = FigureCanvas(fig)
    response.content_type = 'image/png'
    #Here is where I hope to put RC settings
    matplotlib.rc('lines', linewidth=0.5)
    yield fig
    s = StringIO()
    canvas.print_figure(s)
    response.content = s.getvalue()
</code>```

答:
What you've posted should work.  Just as a reference, the following works perfectly for me using python 2.6 and matplotlib 1.0.

```<code>from contextlib import contextmanager

import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

@contextmanager
def render_plot(w=8,h=8):
    fig = Figure(figsize=(w,h))
    canvas = FigureCanvas(fig)
    mpl.rc('lines', linewidth=5)
    yield fig
    s = file('temp.png', 'w')
    canvas.print_figure(s)

with render_plot() as fig:
    ax = fig.add_subplot(111)
    ax.plot(range(10))
</code>```

Does this example work on your system?

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to set line widths for matplotlib in a web application that generates graphs using

matplotlib.rc('lines', linewidth=0.5)

This works fine when working with matplotlib in interactive mode, but in my web application it has no effect, and the only way I can get the correct line widths is by supplying the argument on the individual calls, i.e.:

vals = map(itemgetter(1), sorted(series1.items(), reverse=True))
group1_rects = ax.barh(ind, vals, width, color='r', snap=True, linewidth=0.5)
vals = map(itemgetter(1), sorted(series2.items(), reverse=True))
group2_rects = ax.barh(ind+width, vals, width, color='b', linewidth=0.5)

Is there some trick involved to make the matplotlib.rc call work in web apps?

The code I'm using for getting a figure to draw on looks like this:

@contextmanager
def render_plot(w=8,h=8):
    fig = Figure(figsize=(w,h))
    canvas = FigureCanvas(fig)
    response.content_type = 'image/png'
    #Here is where I hope to put RC settings
    matplotlib.rc('lines', linewidth=0.5)
    yield fig
    s = StringIO()
    canvas.print_figure(s)
    response.content = s.getvalue()

Body:
What you've posted should work.  Just as a reference, the following works perfectly for me using python 2.6 and matplotlib 1.0.

from contextlib import contextmanager

import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

@contextmanager
def render_plot(w=8,h=8):
    fig = Figure(figsize=(w,h))
    canvas = FigureCanvas(fig)
    mpl.rc('lines', linewidth=5)
    yield fig
    s = file('temp.png', 'w')
    canvas.print_figure(s)

with render_plot() as fig:
    ax = fig.add_subplot(111)
    ax.plot(range(10))

Does this example work on your system?


问:
How to Search only SUBURB list in Google Place API
Is it possible to search within a SUBURB in Google places api? For example, can I force Places API to return only results from a particular 'locality' or country?
Thanks.</p>

答:
can I force Places API to return only results from a particular 'locality' or country?

Yes you can  just use AutocompleteFilter.Builder

Public Method Summary

setCountry(String country)
  The country to restrict results to.

setTypeFilter(int typeFilter)
  Allows you to restrict the result set of a Place Autocomplete request.

Allows you to restrict the result set of a Place Autocomplete request.

Valid values are:

TYPE_FILTER_NONE

TYPE_FILTER_GEOCODE

TYPE_FILTER_ADDRESS

TYPE_FILTER_ESTABLISHMENT

TYPE_FILTER_REGIONS

TYPE_FILTER_CITIES

sample code

```<code>AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
        .setCountry("AU")// set her your Country
        .build();

autocompleteFragment.setFilter(typeFilter);
// or
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                            .setFilter(typeFilter)
                            .build(this);
</code>```

for more information rtead from the Place Autocomplete

Body:
can I force Places API to return only results from a particular 'locality' or country?

Yes you can  just use AutocompleteFilter.Builder

Public Method Summary

setCountry(String country)
  The country to restrict results to.

setTypeFilter(int typeFilter)
  Allows you to restrict the result set of a Place Autocomplete request.

Allows you to restrict the result set of a Place Autocomplete request.

Valid values are:

TYPE_FILTER_NONE

TYPE_FILTER_GEOCODE

TYPE_FILTER_ADDRESS

TYPE_FILTER_ESTABLISHMENT

TYPE_FILTER_REGIONS

TYPE_FILTER_CITIES

sample code

AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
        .setCountry("AU")// set her your Country
        .build();

autocompleteFragment.setFilter(typeFilter);
// or
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                            .setFilter(typeFilter)
                            .build(this);

for more information rtead from the Place Autocomplete


问:
spring framework : expected single matching bean but found 2
This super class DAO:

```<code>public class CrudDAO{

}
</code>```

This child class:

```<code>@Repository
public class JnsTimeDao extends CrudDAO {

}

@Repository
public class BatchDAO extends CrudDAO {
}
</code>```

this super service class

```<code>@Transactional(readOnly = true)
public abstract class CrudService<D extends CrudDAO> {

    @Autowired
    protected D dao;
}
</code>```

startup error:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type [com.gp.dao.CrudDAO] is defined: expected
  single matching bean but found 2: batchDAO,jnsTimeDao

答:
There are 2 beans of type CrudDAO. So, Spring won't be able to understand which bean to inject. Can be solved as follows

```<code>@Repository("jnsTimeDao")
public class JnsTimeDao extends CrudDAO {

}

@Repository("batchDao")
public class BatchDAO extends CrudDAO {
}
</code>```

While injecting use @Qualifier

```<code> @Transactional(readOnly = true)
    public abstract class CrudService<D extends CrudDAO> {

        @Autowired
        @Qualifier("batchDao")
        protected D dao;
    }
</code>```

Body:
This super class DAO:

public class CrudDAO{

}

This child class:

@Repository
public class JnsTimeDao extends CrudDAO {

}

@Repository
public class BatchDAO extends CrudDAO {
}

this super service class

@Transactional(readOnly = true)
public abstract class CrudService<D extends CrudDAO> {

    @Autowired
    protected D dao;
}

startup error:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type [com.gp.dao.CrudDAO] is defined: expected
  single matching bean but found 2: batchDAO,jnsTimeDao

Body:
There are 2 beans of type CrudDAO. So, Spring won't be able to understand which bean to inject. Can be solved as follows

@Repository("jnsTimeDao")
public class JnsTimeDao extends CrudDAO {

}

@Repository("batchDao")
public class BatchDAO extends CrudDAO {
}

While injecting use @Qualifier

 @Transactional(readOnly = true)
    public abstract class CrudService<D extends CrudDAO> {

        @Autowired
        @Qualifier("batchDao")
        protected D dao;
    }


问:
Merge multiple row then left join-php mysql
I have two tables: invoices and sales. These are simplified version of them:

Invoices:

```<code>InvoiceNo  |  ProductNo  |  QtyIn
-----------------------------------
F01        |  00001      |  20
F01        |  00002      |  50
F01        |  00003      |  15
F02        |  00002      |  10
</code>```

Sales:

```<code>Date    |  ProductNo  |  QtyOut
---------------------------------
3/2/17  |  00002      |  12
3/3/17  |  00002      |  8
3/4/17  |  00003      |  10
</code>```

What I'm trying to do is to make a stock summary table, which looks like this:

```<code>ProductNo  |  QtyIn  |  QtyOut  |  Stock
-------------------------------------------
00001      |  20     |  0       |  20
00002      |  60     |  20      |  40
00003      |  15     |  10      |  5
</code>```

To make that stock table, as far as I can think is:

Make another database for invoice where same product will be merge
and it's quantity will be sum up.

Make something like the first one for sales.

Then make a join table for both of them.

By this way, I will end up having 5 tables. Is there any simpler way to do this? Thanks.

答:
If you apply a filer on Invoices and Sales (e.g. for a date range) either filtered result could have products not referenced in the other. Hence a single outer join does not cover all possible conditions. As there is no "full outer join" in MySQL a simple method to overcome this is to union all source rows then group that:</p>

```<code>select ProductNo, sum(QtyIn) QtyIn, sum(QtyOut) QtyOut, sum(QtyIn) - sum(QtyOut) Stock
from (
      select ProductNo, QtyIn, 0 as QtyOut
      from invoices
        # where datecol >= `2017-01-01`
      union all
      select ProductNo, 0 as QtyIn, QtyOut
      from Sales
        # where datecol >= `2017-01-01`
     ) u
group by ProductNo
</code>```

Body:
I have two tables: invoices and sales. These are simplified version of them:

Invoices:

InvoiceNo  |  ProductNo  |  QtyIn
-----------------------------------
F01        |  00001      |  20
F01        |  00002      |  50
F01        |  00003      |  15
F02        |  00002      |  10

Sales:

Date    |  ProductNo  |  QtyOut
---------------------------------
3/2/17  |  00002      |  12
3/3/17  |  00002      |  8
3/4/17  |  00003      |  10

What I'm trying to do is to make a stock summary table, which looks like this:

ProductNo  |  QtyIn  |  QtyOut  |  Stock
-------------------------------------------
00001      |  20     |  0       |  20
00002      |  60     |  20      |  40
00003      |  15     |  10      |  5

To make that stock table, as far as I can think is:

Make another database for invoice where same product will be merge
and it's quantity will be sum up.

Make something like the first one for sales.

Then make a join table for both of them.

By this way, I will end up having 5 tables. Is there any simpler way to do this? Thanks.

Body:
If you apply a filer on Invoices and Sales (e.g. for a date range) either filtered result could have products not referenced in the other. Hence a single outer join does not cover all possible conditions. As there is no "full outer join" in MySQL a simple method to overcome this is to union all source rows then group that:

select ProductNo, sum(QtyIn) QtyIn, sum(QtyOut) QtyOut, sum(QtyIn) - sum(QtyOut) Stock
from (
      select ProductNo, QtyIn, 0 as QtyOut
      from invoices
        # where datecol >= `2017-01-01`
      union all
      select ProductNo, 0 as QtyIn, QtyOut
      from Sales
        # where datecol >= `2017-01-01`
     ) u
group by ProductNo


问:
Differentiation between rectangle and square in image using opencv2 python
I'm learning how to recognize shapes that're within image provided. I'm able to recognize shape by number of edges present to the geometrical body. But now I'm wondering is there any way to differentiate between square and rectangle within image?
Here's my code. Currently I'm just drawing contours to the geometrical figures.

```<code>import cv2

raw_image = cv2.imread('test1.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)

bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)

edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) >= 3)):
        contour_list.append(contour)

cv2.drawContours(raw_image, contour_list,  -1, (0,0,0), 2)
cv2.imshow('Objects Detected',raw_image)
cv2.waitKey(0)
</code>```

答:
I have an alternate way:

Find all the connected components.

Find the feature points in the original image, since in this case we have simple geometrical bodies not complex objects, you can use corner points as feature points using Harris corner algorithm.

Group these feature points lying on the same connected components.

Use the relation(distance/angle) between these features points on all the connected components and accordingly you can classify these geometrical shapes.

Body:
I'm learning how to recognize shapes that're within image provided. I'm able to recognize shape by number of edges present to the geometrical body. But now I'm wondering is there any way to differentiate between square and rectangle within image?
Here's my code. Currently I'm just drawing contours to the geometrical figures.

import cv2

raw_image = cv2.imread('test1.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)

bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)

edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) >= 3)):
        contour_list.append(contour)

cv2.drawContours(raw_image, contour_list,  -1, (0,0,0), 2)
cv2.imshow('Objects Detected',raw_image)
cv2.waitKey(0)


问:
How to make a button redirect to another XML layout
I'm making a button in xml(res / layout / activity_home.xml), like this:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity" >
    <ImageView
        android:id="@+id/imageView1"
        android:src="@drawable/schkopwide"
        android:contentDescription="@string/HTI"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="78dp"
        android:onclick="Intent i = new Intent(activity_store.xml);
        startActivity(i);"
        android:text="@string/HTI" />
</RelativeLayout>
</code>```

so what should I add into this xml to let it redirect to another xml page (res / layout / activity_store.xml)?

Thank you

答:
If you Want to show two different layouts in Same Activity, then ViewSwitcher is best layout.

You can add multiple layouts in ViewSwithcher. And Replace them by using viewswitcher.next();  function.

```<code><ViewSwitcher

android:id="@+id/viewswitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<!--   Add Two View’s Here -- >

</ViewSwitcher>
</code>```

You can take reference from this link: http://abhiandroid.com/ui/viewswitcher

Body:
I'm making a button in xml(res / layout / activity_home.xml), like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity" >
    <ImageView
        android:id="@+id/imageView1"
        android:src="@drawable/schkopwide"
        android:contentDescription="@string/HTI"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="78dp"
        android:onclick="Intent i = new Intent(activity_store.xml);
        startActivity(i);"
        android:text="@string/HTI" />
</RelativeLayout>

so what should I add into this xml to let it redirect to another xml page (res / layout / activity_store.xml)?

Thank you

Body:
If you Want to show two different layouts in Same Activity, then ViewSwitcher is best layout.

You can add multiple layouts in ViewSwithcher. And Replace them by using viewswitcher.next();  function.

<ViewSwitcher

android:id="@+id/viewswitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<!--   Add Two View’s Here -- >

</ViewSwitcher>

You can take reference from this link: http://abhiandroid.com/ui/viewswitcher


问:
Extracting the Revision number of a file from the SVN Command line
Hello
Basically i need to extract the version info from the XML
I thought of puttin the entire result to a XML file and then
parse it to get the revision information.

i tried to output the svn info to a xml file by specifying

```<code>$ svn info C:\Projects\Foo.xml --xml C:\Projects\FileInfo.xml
</code>```

Im getting errors if i try to save

```<code>$ svn info --xml C:\Projects\Foo.xml
<?xml version="1.0"?>
<info>
<entry
   kind="dir"
   path="."
   revision="1">
<url>https://rbins.com/trunk/Projects/Foo.xml</url>
<repository>
<root>https://rbins.com/trunk/Projects/</root>
<uuid>5e7d134a-54fb-0310-bd04-b611643e5c25</uuid>
</repository>
<wc-info>
<schedule>normal</schedule>
<depth>infinity</depth>
</wc-info>
<commit
   revision="240">
<author>sally</author>
<date>2003-01-15T23:35:12.847647Z</date>
</commit>
</entry>
</info>
</code>```

i do not receive error if i run

$ svn info C:\Projects\Foo.xml --xml

Help me where am i going wrong also suggest me if theres any alternative available to extract the revision number of the working copy

Thanks in advance

答:
You need to redirect svn info's output to the file, the --xml option takes no parameter:

svn info C:\Projects\Foo.xml --xml
  > C:\Projects\FileInfo.xml

Body:
Hello
Basically i need to extract the version info from the XML
I thought of puttin the entire result to a XML file and then
parse it to get the revision information.

i tried to output the svn info to a xml file by specifying

$ svn info C:\Projects\Foo.xml --xml C:\Projects\FileInfo.xml

Im getting errors if i try to save

$ svn info --xml C:\Projects\Foo.xml
<?xml version="1.0"?>
<info>
<entry
   kind="dir"
   path="."
   revision="1">
<url>https://rbins.com/trunk/Projects/Foo.xml</url>
<repository>
<root>https://rbins.com/trunk/Projects/</root>
<uuid>5e7d134a-54fb-0310-bd04-b611643e5c25</uuid>
</repository>
<wc-info>
<schedule>normal</schedule>
<depth>infinity</depth>
</wc-info>
<commit
   revision="240">
<author>sally</author>
<date>2003-01-15T23:35:12.847647Z</date>
</commit>
</entry>
</info>

i do not receive error if i run

$ svn info C:\Projects\Foo.xml --xml

Help me where am i going wrong also suggest me if theres any alternative available to extract the revision number of the working copy

Thanks in advance


问:
What am I doing wrong here with these quotes?
It's saying that the quote ' after test.bat and before ) is invalid syntax in the first system_call(). . How can I fix this? I don't seem to be doing anything wrong. (I am new to Python.)

```<code>import os

import subprocess

def system_call(command):

r = subprocess.call("cmd.exe /K " + "%s" % command,shell=False)
print (r)

system_call(r 'echo “@ECHO OFF\nECHO.\nECHO\n This is a batch file\nECHO.\nPAUSE\nCLS\nEXIT” > C:\Users\User\Desktop\test.bat ')

system_call('cd C:\Users\User\Desktop\ ')

system_call('test')
</code>```

答:
Try changing the quotation marks surrounding this section of code,

```<code>“@ECHO OFF\nECHO.\nECHO\n This is a batch file\nECHO.\nPAUSE\nCLS\nEXIT”
</code>```

Change to

```<code>"@ECHO OFF\nECHO.\nECHO\n This is a batch file\nECHO.\nPAUSE\nCLS\nEXIT"
</code>```

Notice how the original quotes(your code) has a curve to them where as I replaced those with straight, non fancy quotations. In my experience the fancy ones can, at times, cause issues.

P.S. This is my first answer here on Stack over flow, so I'm taking a stab at it :) hope it helps

Body:
It's saying that the quote ' after test.bat and before ) is invalid syntax in the first system_call(). . How can I fix this? I don't seem to be doing anything wrong. (I am new to Python.)

import os

import subprocess

def system_call(command):

r = subprocess.call("cmd.exe /K " + "%s" % command,shell=False)
print (r)

system_call(r 'echo “@ECHO OFF\nECHO.\nECHO\n This is a batch file\nECHO.\nPAUSE\nCLS\nEXIT” > C:\Users\User\Desktop\test.bat ')

system_call('cd C:\Users\User\Desktop\ ')

system_call('test')

Body:
Try changing the quotation marks surrounding this section of code,

“@ECHO OFF\nECHO.\nECHO\n This is a batch file\nECHO.\nPAUSE\nCLS\nEXIT”

Change to

"@ECHO OFF\nECHO.\nECHO\n This is a batch file\nECHO.\nPAUSE\nCLS\nEXIT"

Notice how the original quotes(your code) has a curve to them where as I replaced those with straight, non fancy quotations. In my experience the fancy ones can, at times, cause issues.

P.S. This is my first answer here on Stack over flow, so I'm taking a stab at it :) hope it helps


问:
The length of the string exceeds the value set on the maxJsonLength property.c#
I am trying to get the result from my wcf service in json as you can see :

```<code>public List<InquiryStatus> SearchInquiryStatus(string userid, string datestart, string dateend)
{
    string result = "";
    using (WebClient ClientRequest = new WebClient())
    {
        ClientRequest.Headers["Content-type"] = "application/json";
        ClientRequest.Encoding = System.Text.Encoding.UTF8;
        result = ClientRequest.DownloadString(ServiceHostName + "/MonitoringInquiryService.svc/SearchInquiryStatus/" +
                                                userid + "/"
                                                + datestart + "/" + dateend
                                                );
    }
    var javascriptserializer = new JavaScriptSerializer();
    return javascriptserializer.Deserialize<List<InquiryStatus>>(result);
}
</code>```

But i get this error :

```<code>Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input
</code>```

As a note when i call my service url http://reporting.demo.ir/MonitoringInquiryService.svc/SearchInquiryStatus/null/'20171106'/'20171113'
in browser i get the result .
I googled my error and i found this :

```<code><configuration>
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration>
</code>```

I added this to my UI web config .but i get same error.

答:
Add this line in your function.</p>

```<code> var javascriptserializer = new JavaScriptSerializer();
javascriptserializer.MaxJsonLength = Int32.MaxValue;
</code>```

Body:
I am trying to get the result from my wcf service in json as you can see :

public List<InquiryStatus> SearchInquiryStatus(string userid, string datestart, string dateend)
{
    string result = "";
    using (WebClient ClientRequest = new WebClient())
    {
        ClientRequest.Headers["Content-type"] = "application/json";
        ClientRequest.Encoding = System.Text.Encoding.UTF8;
        result = ClientRequest.DownloadString(ServiceHostName + "/MonitoringInquiryService.svc/SearchInquiryStatus/" +
                                                userid + "/"
                                                + datestart + "/" + dateend
                                                );
    }
    var javascriptserializer = new JavaScriptSerializer();
    return javascriptserializer.Deserialize<List<InquiryStatus>>(result);
}

But i get this error :

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input

As a note when i call my service url http://reporting.demo.ir/MonitoringInquiryService.svc/SearchInquiryStatus/null/'20171106'/'20171113'
in browser i get the result .
I googled my error and i found this :

<configuration>
   <system.web.extensions>

   </system.web.extensions>
</configuration>

I added this to my UI web config .but i get same error.

Body:
Add this line in your function.

 var javascriptserializer = new JavaScriptSerializer();
javascriptserializer.MaxJsonLength = Int32.MaxValue;


问:
iterate through multiple lists with python
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

```<code>pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i
</code>```

My source data is as follows:

```<code>CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
</code>```

UserID and Page Number
eeIDlist:

```<code>[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]
</code>```

Desired Output List:

```<code>[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]
</code>```

答:
You could also turn the eeIDlist into a dictionary which would make searching it a lot faster. This would also let you perform the entire operation in one line:

```<code>eeIDdict = dict(eeIDlist)
[j.append([eeIDdict[int(k)] for k in j[0:2]]) for j in CompanyNameList]
</code>```

Now we have:

```<code>CompanyNameList =
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]
</code>```

As required.

Body:
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i

My source data is as follows:

CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

UserID and Page Number
eeIDlist:

[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]

Desired Output List:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]

Body:
You could also turn the eeIDlist into a dictionary which would make searching it a lot faster. This would also let you perform the entire operation in one line:

eeIDdict = dict(eeIDlist)
[j.append([eeIDdict[int(k)] for k in j[0:2]]) for j in CompanyNameList]

Now we have:

CompanyNameList =
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]

As required.


问:
can't inject repository when use @Autowired in a non-web-application
I want to use spring-boot-jpa in my spider application, and I already have the maven dependency, models, modelRepository and the application.properties. After I use the annotation @autowired to use these repository, it will have a NullPointerException. How can I use them in my spider?
Here is my spider.

```<code>@Component
public class Crawler implements PageProcessor {
    SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    CategoryRepository categoryRepository;
    @Autowired
    NewsRepository newsRepository;
    @Autowired
    SourceRepository sourceRepository;
    public static String content;
    private Site site = Site.me().setRetryTimes(0).setSleepTime(100000000);
    public void process(Page page) {
        Pattern pattern = Pattern.compile("artiList\\((.*)\\)");
        Matcher matcher = pattern.matcher(page.getRawText());
        String json = null;
        if (matcher.find()) {
            json = matcher.group(1);
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode;
        try {
            rootNode = mapper.readTree(json);
            JsonNode mainJson = rootNode.path("BAI6RHDKwangning");
            Iterator<JsonNode> iterator = mainJson.elements();
            String cur = null;
            JsonNode mark = null;
            List<Map<String, Object>> list = new ArrayList<>();
            while (iterator.hasNext()) {
                mark = iterator.next();
                cur = mark.toString();
                Map<String, Object> map = mapper.readValue(cur, Map.class);
                list.add(map);
            }

            dbService(list);

        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    public void dbService(List<Map<String, Object>> list) {
        try {
                for (Map<String, Object> map : list) {

                    for (String s : map.keySet()) {
                        System.out.println(s + "=" + map.get(s));
                        System.out.println();
                    }
                    Article article = new Article();
                    article.setUrl(map.get("url").toString());
                    if (categoryRepository == null) {
                        System.out.println("================================================asdasasdsad");
                    }
                    Category category = categoryRepository.findByCategoryName("game");
                    News news = new News();
                    Source source = sourceRepository.findBySourceName(map.get("source").toString());
                    if (source == null) {
                        source = new Source();
                        source.setSourceName(map.get("source").toString());
                    } else {
                        source.setPublishCount(source.getPublishCount() + 1);
                    }
                    news.setDocid(map.get("docid").toString());
                    news.setCommentCount(Integer.valueOf(map.get("commentCount").toString()));
                    news.setDigest(map.get("digest").toString());
                    news.setHasImg(Integer.valueOf(map.get("hasImg").toString()));
                    news.setImgsrc(map.get("imgsrc").toString());
                    news.setPriority(Integer.valueOf(map.get("priority").toString()));
                    news.setPtime(sdf.parse(map.get("ptime").toString()));
                    news.setTitle(map.get("title").toString());
                    news.setArticleId(article);
                    news.setCategoryCode(category);
                    news.setArticleId(article);
                    news.setSourceId(source);

                    articleRepository.save(article);
                    sourceRepository.save(source);
                    newsRepository.save(news);

                }
        } catch (ParseException e) {
            System.out.println(e.getMessage() );
            e.printStackTrace();
        }
    }

    public Site getSite() {
        return site;
    }
    public void runSpider() {
        Spider.create(new Crawler())
        .addUrl("http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html")

        .thread(5)

        .run();
    }
}
</code>```

This is my MainApplication.

```<code>@SpringBootApplication
public class NethardApplication implements CommandLineRunner{

    @Autowired
    Crawler crawler;
    public static void main(String[] args) {
        SpringApplication.run(NethardApplication.class, args);
    }
    @Override
    public void run(String... args) {
        crawler.runSpider();
    }
}
</code>```

And this is my project directory.

This is the console

```<code>10:05:34.602 [pool-1-thread-1] ERROR us.codecraft.webmagic.Spider - process request Request{url='http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html', method='null', extras=null, priority=0, headers={}, cookies={}} error
java.lang.NullPointerException: null
    at com.cmh.Crawler.dbService(Crawler.java:90)
    at com.cmh.Crawler.process(Crawler.java:70)
    at us.codecraft.webmagic.Spider.onDownloadSuccess(Spider.java:414)
    at us.codecraft.webmagic.Spider.processRequest(Spider.java:406)
    at us.codecraft.webmagic.Spider.access$000(Spider.java:61)
    at us.codecraft.webmagic.Spider$1.run(Spider.java:320)
    at us.codecraft.webmagic.thread.CountableThreadPool$1.run(CountableThreadPool.java:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
10:05:34.603 [main] INFO us.codecraft.webmagic.Spider - Spider 3g.163.com closed! 1 pages downloaded.
</code>```

答:
How to injecting beans into a class outside the Spring managed context

Create the class for getApplicationContext

```<code>public class ApplicationContextProvider implements ApplicationContextAware {

private static ApplicationContext context;

public static ApplicationContext getApplicationContext(){
    return context;
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    context = applicationContext;
}
}
</code>```

at your spider application

```<code>ArticleRepository articleRepository= ApplicationContextProvider.getApplicationContext().getBean(ArticleRepository.class);
CategoryRepository categoryRepository= ApplicationContextProvider.getApplicationContext().getBean(CategoryRepository.class);
NewsRepository newsRepository= ApplicationContextProvider.getApplicationContext().getBean(NewsRepository.class);
SourceRepository sourceRepository= ApplicationContextProvider.getApplicationContext().getBean(SourceRepository.class);
</code>```

Body:
I want to use spring-boot-jpa in my spider application, and I already have the maven dependency, models, modelRepository and the application.properties. After I use the annotation @autowired to use these repository, it will have a NullPointerException. How can I use them in my spider?
Here is my spider.

@Component
public class Crawler implements PageProcessor {
    SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    CategoryRepository categoryRepository;
    @Autowired
    NewsRepository newsRepository;
    @Autowired
    SourceRepository sourceRepository;
    public static String content;
    private Site site = Site.me().setRetryTimes(0).setSleepTime(100000000);
    public void process(Page page) {
        Pattern pattern = Pattern.compile("artiList\\((.*)\\)");
        Matcher matcher = pattern.matcher(page.getRawText());
        String json = null;
        if (matcher.find()) {
            json = matcher.group(1);
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode;
        try {
            rootNode = mapper.readTree(json);
            JsonNode mainJson = rootNode.path("BAI6RHDKwangning");
            Iterator<JsonNode> iterator = mainJson.elements();
            String cur = null;
            JsonNode mark = null;
            List<Map<String, Object>> list = new ArrayList<>();
            while (iterator.hasNext()) {
                mark = iterator.next();
                cur = mark.toString();
                Map<String, Object> map = mapper.readValue(cur, Map.class);
                list.add(map);
            }

            dbService(list);

        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    public void dbService(List<Map<String, Object>> list) {
        try {
                for (Map<String, Object> map : list) {

                    for (String s : map.keySet()) {
                        System.out.println(s + "=" + map.get(s));
                        System.out.println();
                    }
                    Article article = new Article();
                    article.setUrl(map.get("url").toString());
                    if (categoryRepository == null) {
                        System.out.println("================================================asdasasdsad");
                    }
                    Category category = categoryRepository.findByCategoryName("game");
                    News news = new News();
                    Source source = sourceRepository.findBySourceName(map.get("source").toString());
                    if (source == null) {
                        source = new Source();
                        source.setSourceName(map.get("source").toString());
                    } else {
                        source.setPublishCount(source.getPublishCount() + 1);
                    }
                    news.setDocid(map.get("docid").toString());
                    news.setCommentCount(Integer.valueOf(map.get("commentCount").toString()));
                    news.setDigest(map.get("digest").toString());
                    news.setHasImg(Integer.valueOf(map.get("hasImg").toString()));
                    news.setImgsrc(map.get("imgsrc").toString());
                    news.setPriority(Integer.valueOf(map.get("priority").toString()));
                    news.setPtime(sdf.parse(map.get("ptime").toString()));
                    news.setTitle(map.get("title").toString());
                    news.setArticleId(article);
                    news.setCategoryCode(category);
                    news.setArticleId(article);
                    news.setSourceId(source);

                    articleRepository.save(article);
                    sourceRepository.save(source);
                    newsRepository.save(news);

                }
        } catch (ParseException e) {
            System.out.println(e.getMessage() );
            e.printStackTrace();
        }
    }

    public Site getSite() {
        return site;
    }
    public void runSpider() {
        Spider.create(new Crawler())
        .addUrl("http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html")

        .thread(5)

        .run();
    }
}

This is my MainApplication.

@SpringBootApplication
public class NethardApplication implements CommandLineRunner{

    @Autowired
    Crawler crawler;
    public static void main(String[] args) {
        SpringApplication.run(NethardApplication.class, args);
    }
    @Override
    public void run(String... args) {
        crawler.runSpider();
    }
}

And this is my project directory.

This is the console

10:05:34.602 [pool-1-thread-1] ERROR us.codecraft.webmagic.Spider - process request Request{url='http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html', method='null', extras=null, priority=0, headers={}, cookies={}} error
java.lang.NullPointerException: null
    at com.cmh.Crawler.dbService(Crawler.java:90)
    at com.cmh.Crawler.process(Crawler.java:70)
    at us.codecraft.webmagic.Spider.onDownloadSuccess(Spider.java:414)
    at us.codecraft.webmagic.Spider.processRequest(Spider.java:406)
    at us.codecraft.webmagic.Spider.access$000(Spider.java:61)
    at us.codecraft.webmagic.Spider$1.run(Spider.java:320)
    at us.codecraft.webmagic.thread.CountableThreadPool$1.run(CountableThreadPool.java:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
10:05:34.603 [main] INFO us.codecraft.webmagic.Spider - Spider 3g.163.com closed! 1 pages downloaded.

Body:
How to injecting beans into a class outside the Spring managed context

Create the class for getApplicationContext

public class ApplicationContextProvider implements ApplicationContextAware {

private static ApplicationContext context;

public static ApplicationContext getApplicationContext(){
    return context;
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    context = applicationContext;
}
}

at your spider application

ArticleRepository articleRepository= ApplicationContextProvider.getApplicationContext().getBean(ArticleRepository.class);
CategoryRepository categoryRepository= ApplicationContextProvider.getApplicationContext().getBean(CategoryRepository.class);
NewsRepository newsRepository= ApplicationContextProvider.getApplicationContext().getBean(NewsRepository.class);
SourceRepository sourceRepository= ApplicationContextProvider.getApplicationContext().getBean(SourceRepository.class);


问:
Setting font for collection of labels
I have a nameLabel and I can set the font as

```<code> @IBOutlet weak var nameLabel: UILabel!
 nameLabel.font = UIFont(name: "Georgia-bold", size: 18)
</code>```

Is there a way, I can do same for collection of labels at once,

```<code>@IBOutlet weak var collectionNameLabels: [UILabel]!
</code>```

答:
property observer.

@IBOutlet weak var collectionNameLabels: [UILabel]! {

```<code>didSet{
  for nameLabel  in collectionNameLabels{
    nameLabel.font = UIFont(name: "Georgia-bold", size: 18)
  }
}
</code>```

}

Title: Setting font for collection of labels

Body:
I have a nameLabel and I can set the font as

 @IBOutlet weak var nameLabel: UILabel!
 nameLabel.font = UIFont(name: "Georgia-bold", size: 18)

Is there a way, I can do same for collection of labels at once,

@IBOutlet weak var collectionNameLabels: [UILabel]!

Body:
property observer.

@IBOutlet weak var collectionNameLabels: [UILabel]! {

didSet{
  for nameLabel  in collectionNameLabels{
    nameLabel.font = UIFont(name: "Georgia-bold", size: 18)
  }
}

}


问:
Disabling/Removing caret from chat window
I have setup richedit control as a chat window and I've no idea how to remove the blinking caret from the control, does anyone know how to do that in edit/richedit control?</p>

答: Based on this page, you need to handle the EN_SETFOCUS Windows message and call HideCaret().  The docs there say that calls to HideCaret() are cumulative, so you probably should only call it once (use a static variable to remember whether it has been set), or alternatively call ShowCaret() in response to EN_KILLFOCUS.


问:
How I can make chess-timer clock in android
I am a beginner in android, and I want to make a simple chess-timer clock. Here, I have taken two buttons. If I click on the first one the second button should start a countdown or vice-versa. But pause button is not working properly it pauses only one time second time it will not pause. Here I attached my code.</p>

```<code>package com.example.jaydeep.practicework.chessClock;

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.jaydeep.practicework.R;

public class Main8Activity extends AppCompatActivity {
Button button11,button22;
    CountDownTimer count,count1;
    int s1=60,s2=60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main8);
        button11 = (Button) findViewById(R.id.Button11);
        button22 = (Button) findViewById(R.id.Button22);

        button11.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                button11.setEnabled(false);
                    reverseTimer1(s2, button22);
            }
        });
        button22.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               button22.setEnabled(false);
                    reverseTimer(s1, button11);
            }
        });
    }

    public void reverseTimer(int Seconds,final Button button){
        button11.setEnabled(true);
     count= new CountDownTimer(Seconds* 1000+1000, 1000) {

            public void onTick(long millisUntilFinished) {
                int seconds = (int) (millisUntilFinished / 1000);
                s1=seconds;
                int minutes = seconds / 60;
                seconds = seconds % 60;
                button.setText( String.format("%02d", minutes)
                        + ":" + String.format("%02d", seconds));
            }

            public void onFinish() {
                button.setText("Time Up!!!");
            }
        };
        count.start();
    }
    public void reverseTimer1(int Seconds,final Button button){
        button22.setEnabled(true);
        count1= new CountDownTimer(Seconds* 1000+1000, 1000) {

                    public void onTick(long millisUntilFinished) {
                        int seconds = (int) (millisUntilFinished / 1000);
                        s2=seconds;
                        int minutes = seconds / 60;
                        seconds = seconds % 60;
                        button.setText( String.format("%02d", minutes)
                                + ":" + String.format("%02d", seconds));
                    }

                    public void onFinish() {
                        button.setText("Time Up!!!");
                    }
                };
        count1.start();
    }
}
</code>```

答:
```<code>   cancel();
</code>```

You need this code

```<code> if(isPaused || isCanceled)
                        {
                            //If the user request to cancel or paused the
                            //CountDownTimer we will cancel the current instance
                            cancel();
                        }
</code>```

This link should help you understand:
https://android--examples.blogspot.com.au/2015/04/android-countdowntimer-start-pause.html

Body:
I am a beginner in android, and I want to make a simple chess-timer clock. Here, I have taken two buttons. If I click on the first one the second button should start a countdown or vice-versa. But pause button is not working properly it pauses only one time second time it will not pause. Here I attached my code.

package com.example.jaydeep.practicework.chessClock;

import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.jaydeep.practicework.R;

public class Main8Activity extends AppCompatActivity {
Button button11,button22;
    CountDownTimer count,count1;
    int s1=60,s2=60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main8);
        button11 = (Button) findViewById(R.id.Button11);
        button22 = (Button) findViewById(R.id.Button22);

        button11.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                button11.setEnabled(false);
                    reverseTimer1(s2, button22);
            }
        });
        button22.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               button22.setEnabled(false);
                    reverseTimer(s1, button11);
            }
        });
    }

    public void reverseTimer(int Seconds,final Button button){
        button11.setEnabled(true);
     count= new CountDownTimer(Seconds* 1000+1000, 1000) {

            public void onTick(long millisUntilFinished) {
                int seconds = (int) (millisUntilFinished / 1000);
                s1=seconds;
                int minutes = seconds / 60;
                seconds = seconds % 60;
                button.setText( String.format("%02d", minutes)
                        + ":" + String.format("%02d", seconds));
            }

            public void onFinish() {
                button.setText("Time Up!!!");
            }
        };
        count.start();
    }
    public void reverseTimer1(int Seconds,final Button button){
        button22.setEnabled(true);
        count1= new CountDownTimer(Seconds* 1000+1000, 1000) {

                    public void onTick(long millisUntilFinished) {
                        int seconds = (int) (millisUntilFinished / 1000);
                        s2=seconds;
                        int minutes = seconds / 60;
                        seconds = seconds % 60;
                        button.setText( String.format("%02d", minutes)
                                + ":" + String.format("%02d", seconds));
                    }

                    public void onFinish() {
                        button.setText("Time Up!!!");
                    }
                };
        count1.start();
    }
}

Body:
   cancel();

You need this code

 if(isPaused || isCanceled)
                        {
                            //If the user request to cancel or paused the
                            //CountDownTimer we will cancel the current instance
                            cancel();
                        }

This link should help you understand:
https://android--examples.blogspot.com.au/2015/04/android-countdowntimer-start-pause.html


问:
Jquery onclick function called two time on dynamically added button element
I have created a code on my HTML page that their multiple checkboxes and created one button dynamically in js snippet for performing some event, but when I clicked on the button to perform that even that, then it's making calls to that event snippet two times. I wanted to know how to add the event to that button.

Here is the js code:-

```<code>$(".panel-body").on("click", '#select_none', function(event) {
     $("input[name='nodelevel']:checkbox").each(function() {
         this.checked = false;
     });
});
</code>```

答:
Make sure there is only one parent with .panel-body class name. maybe there is two of .panel-body and it makes this happen. like this:

```<code><div class="panel-body">
  ...
  <div class="panel-body">
    ...
      <!-- your selectors -->
  </div>
</div>
</code>```

try stoppropagation to avoid second parent event listener call:

```<code>$(".panel-body").on("click", '#select_none', function(event) {
     event.stopPropagation();
     $("input[name='nodelevel']:checkbox").each(function() {
         this.checked = false;
     });
});
</code>```

EDIT : and of course you can add listener to document instead of .panel-body :)

Body:
I have created a code on my HTML page that their multiple checkboxes and created one button dynamically in js snippet for performing some event, but when I clicked on the button to perform that even that, then it's making calls to that event snippet two times. I wanted to know how to add the event to that button.

Here is the js code:-

$(".panel-body").on("click", '#select_none', function(event) {
     $("input[name='nodelevel']:checkbox").each(function() {
         this.checked = false;
     });
});

Body:
Make sure there is only one parent with .panel-body class name. maybe there is two of .panel-body and it makes this happen. like this:

<div class="panel-body">
  ...
  <div class="panel-body">
    ...
      <!-- your selectors -->
  </div>
</div>

try stoppropagation to avoid second parent event listener call:

$(".panel-body").on("click", '#select_none', function(event) {
     event.stopPropagation();
     $("input[name='nodelevel']:checkbox").each(function() {
         this.checked = false;
     });
});

EDIT : and of course you can add listener to document instead of .panel-body :)


问:
Prestashop 1.7.2 + Nginx 1.10 + SSL - Rewrite Rules
I keep getting 404 error when trying to navigate to the frontend shop of a Prestashop 1.7.2 site products page.I am having some problems with images not shown. However it is fine when going to the admin backend.

Any suggestions would be helpful.

This is my /etc/nginx/site-available/default conf file:

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;
        access_log  /var/log/nginx/h2o.prod.access.log;
        error_log   /var/log/nginx/h2o.prod.error.log;

        root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name 165.227.162.248;
        #Specify a charset
        charset utf-8;
        # Gzip Settings, convert all types.
            gzip on;
            gzip_vary on;
            gzip_proxied any;

            # Can be enhance to 5, but it can slow you server
            # gzip_comp_level    5;
            # gzip_min_length    256;

            gzip_types
                application/atom+xml
                application/javascript
                application/json
                application/ld+json
                application/manifest+json
                application/rss+xml
                application/vnd.geo+json
                application/vnd.ms-fontobject
                application/x-font-ttf
                application/x-web-app-manifest+json
                application/xhtml+xml
                application/xml
                font/opentype
                image/bmp
                image/svg+xml
                image/x-icon
                text/cache-manifest
                text/css
                text/plain
                text/vcard
                text/vnd.rim.location.xloc
                text/vtt
                text/x-component
                text/x-cross-domain-policy;
                # Supposed to be the case but we never know
                # text/html;

        gzip_disable "MSIE [1-6]\.(?!.*SV1)";

        location ~* \.(eot|gif|ico|jpg|jpeg|otf|pdf|png|svg|swf|ttf|woff)$ {
    rewrite ^/([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$1$2$3.jpg break;
    rewrite ^/([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$1$2$3$4.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$1$2$3$4$5.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg break;
    rewrite ^/c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2$3.jpg break;
    rewrite ^/c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg break;
    rewrite ^/images_ie/?([^/]+)\.(jpe?g|png|gif)$ /js/jquery/plugins/fancybox/images/$1.$2 break;
    # next line is PSCSX-2790 bug workaround, fixed in 1.6.0.10
    rewrite ^/[a-zA-Z]+/img/cms/(.*)$ /img/cms/$1 break;
    expires 1M;
    add_header Cache-Control public;
    allow all;
        }

        # Block everything else in these directories
        location ~ ^/img/cms/ {
                deny all;
        }

        # 1 week expiry on CSS and JavaScript
        location ~ \.(css|js)$ {
                expires 1w;
                add_header Cache-Control public;
                allow all;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location ~ ^/medicalstrechers17/admin1900/index.php/(.*) {
        try_files $uri $uri/ /medicalstrechers17/admin1900/index.php$is_args$args;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        #include snippets/fastcgi-php.conf;
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
                #include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                include fastcgi.conf;
                fastcgi_intercept_errors on;

    }
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                    expires max;
                    log_not_found off;
        }
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}
</code>```

Thanks in advance.

答:
i think you haven't the correct file permissions, try this by ssh with root:</p>

```<code>sudo chown -R www-data:www-data /var/www/html/medicalstrechers17/
sudo chmod -R 755 /var/www/html/medicalstrechers17/
</code>```

Body:
I keep getting 404 error when trying to navigate to the frontend shop of a Prestashop 1.7.2 site products page.I am having some problems with images not shown. However it is fine when going to the admin backend.

Any suggestions would be helpful.

This is my /etc/nginx/site-available/default conf file:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;
        access_log  /var/log/nginx/h2o.prod.access.log;
        error_log   /var/log/nginx/h2o.prod.error.log;

        root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name 165.227.162.248;
        #Specify a charset
        charset utf-8;
        # Gzip Settings, convert all types.
            gzip on;
            gzip_vary on;
            gzip_proxied any;

            # Can be enhance to 5, but it can slow you server
            # gzip_comp_level    5;
            # gzip_min_length    256;

            gzip_types
                application/atom+xml
                application/javascript
                application/json
                application/ld+json
                application/manifest+json
                application/rss+xml
                application/vnd.geo+json
                application/vnd.ms-fontobject
                application/x-font-ttf
                application/x-web-app-manifest+json
                application/xhtml+xml
                application/xml
                font/opentype
                image/bmp
                image/svg+xml
                image/x-icon
                text/cache-manifest
                text/css
                text/plain
                text/vcard
                text/vnd.rim.location.xloc
                text/vtt
                text/x-component
                text/x-cross-domain-policy;
                # Supposed to be the case but we never know
                # text/html;

        gzip_disable "MSIE [1-6]\.(?!.*SV1)";

        location ~* \.(eot|gif|ico|jpg|jpeg|otf|pdf|png|svg|swf|ttf|woff)$ {
    rewrite ^/([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$1$2$3.jpg break;
    rewrite ^/([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$1$2$3$4.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$1$2$3$4$5.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg break;
    rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg break;
    rewrite ^/c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2$3.jpg break;
    rewrite ^/c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ /img/c/$1$2.jpg break;
    rewrite ^/images_ie/?([^/]+)\.(jpe?g|png|gif)$ /js/jquery/plugins/fancybox/images/$1.$2 break;
    # next line is PSCSX-2790 bug workaround, fixed in 1.6.0.10
    rewrite ^/[a-zA-Z]+/img/cms/(.*)$ /img/cms/$1 break;
    expires 1M;
    add_header Cache-Control public;
    allow all;
        }

        # Block everything else in these directories
        location ~ ^/img/cms/ {
                deny all;
        }

        # 1 week expiry on CSS and JavaScript
        location ~ \.(css|js)$ {
                expires 1w;
                add_header Cache-Control public;
                allow all;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location ~ ^/medicalstrechers17/admin1900/index.php/(.*) {
        try_files $uri $uri/ /medicalstrechers17/admin1900/index.php$is_args$args;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        #include snippets/fastcgi-php.conf;
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
                #include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                include fastcgi.conf;
                fastcgi_intercept_errors on;

    }
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                    expires max;
                    log_not_found off;
        }
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}

Thanks in advance.

Body:
i think you haven't the correct file permissions, try this by ssh with root:

sudo chown -R www-data:www-data /var/www/html/medicalstrechers17/
sudo chmod -R 755 /var/www/html/medicalstrechers17/


问:
How can I trigger an segue action on button in a UITableViewCell created from a nib?
Right now I am creating a table view cell from a nib file. I have a button in this nib file. I want this button to trigger a segue to a specific view controller on the storyboard.

Seems pretty straight forward, except this nib file is being used in many different tables on different view controllers throughout my app, and I want the button to link to the same destination view controller in every single instance. Furthermore, the destination view controller also contains a table with this nib file as a cell, meaning it will also need to link to itself.

For these reasons, I would love if there was a solution that contained this code to the UITableViewCell subclass for said nib file. (however I doubt this is possible.)

A good example of the functionality I want is Instagram. Think about how several different tabs on Instagram have tables with cells that look like this:

and no matter what tab you are in, clicking the username on the top left of this cell transitions you to the user view controller, even if you are already in the user view controller:

答:
You can use a create a protocol that will return the required ViewController that you want to navigate to. You just need to make your custom cell conform to the protocol and return the required view controller or storyboard identifier. Once that is done in the didSelect method you can try casting it as that protocol. If it succeeds push the required view controller. Check this code below where I'm using a storyboard identifier to get the required view controller

```<code>protocol CustomCellNavigator {
    var identifier: String { get }
}

class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var myTableView: UITableView!

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "YourIdentifier", for: indexPath) as! CustomCell
        cell.destinationStoryBoardIdentifier = "YourIdentifier"
        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = myTableView.cellForRow(at: indexPath) as? CustomCellNavigator {
            if let viewcontroller = storyboard?.instantiateViewController(withIdentifier: cell.identifier) {
                navigationController?.pushViewController(viewcontroller, animated: true)
            }
        }
    }
}

class CustomCell: UITableViewCell, CustomCellNavigator {

    var identifier: String {
        get { return destinationStoryBoardIdentifier }
    }

    // You can replace with whatever logic you want to use for
    // finding the required viewcontroller
    // I have just used a storyboard identifier here
    var destinationStoryBoardIdentifier = "YourViewController"
}
</code>```

Body:
You can use a create a protocol that will return the required ViewController that you want to navigate to. You just need to make your custom cell conform to the protocol and return the required view controller or storyboard identifier. Once that is done in the didSelect method you can try casting it as that protocol. If it succeeds push the required view controller. Check this code below where I'm using a storyboard identifier to get the required view controller

protocol CustomCellNavigator {
    var identifier: String { get }
}

class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var myTableView: UITableView!

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "YourIdentifier", for: indexPath) as! CustomCell
        cell.destinationStoryBoardIdentifier = "YourIdentifier"
        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = myTableView.cellForRow(at: indexPath) as? CustomCellNavigator {
            if let viewcontroller = storyboard?.instantiateViewController(withIdentifier: cell.identifier) {
                navigationController?.pushViewController(viewcontroller, animated: true)
            }
        }
    }
}

class CustomCell: UITableViewCell, CustomCellNavigator {

    var identifier: String {
        get { return destinationStoryBoardIdentifier }
    }

    // You can replace with whatever logic you want to use for
    // finding the required viewcontroller
    // I have just used a storyboard identifier here
    var destinationStoryBoardIdentifier = "YourViewController"
}


问:
Plot Sum of column by values in other columns
I have a dataframe like the sample data below.  I would like to create a plot showing the sum of the "Correct" column by each of the other 4 columns, when those columns have value 1.  The columns are dummy variables, so a 1 in the "Chinese" column indicates that record was flagged as Chinese.  So I'd like to create a bar plot showing sum of "Correct" for each dummy variable.

Sample Data:

```<code>           Food  Chinese  Italian  Food Stands    \
176          1     0        0        0
148          0     0        0        0
143          0     1        0        0
45           0     1        0        0

     Correct
176        0
148        1
143        0
45         1
</code>```

答:
Use pd.DataFrame.dot

```<code>df.drop('Correct', 1).T.dot(df.Correct).plot.bar()
</code>```

Body:
I have a dataframe like the sample data below.  I would like to create a plot showing the sum of the "Correct" column by each of the other 4 columns, when those columns have value 1.  The columns are dummy variables, so a 1 in the "Chinese" column indicates that record was flagged as Chinese.  So I'd like to create a bar plot showing sum of "Correct" for each dummy variable.

Sample Data:

           Food  Chinese  Italian  Food Stands    \
176          1     0        0        0
148          0     0        0        0
143          0     1        0        0
45           0     1        0        0

     Correct
176        0
148        1
143        0
45         1

Body:
Use pd.DataFrame.dot

df.drop('Correct', 1).T.dot(df.Correct).plot.bar()


问:
How to restrict to call shouldOverrideUrlLoading when first time webview loading in fragment
In my app, there are four tabs and in the second tab, I am trying to load webview...
after disable shouldOverrideUrlLoading it perfectly load webview in fragment...
but with shouldOverrideUrlLoading method, it redirects on new activity...
But what I want is to load webview first on fragment and after clicking on any content link it should be redirected on new activity

```<code> private void setUpWebView() {

    WebSettings ws = webView.getSettings();
    ws.setJavaScriptEnabled(true);
    ws.setAllowFileAccess(true);
    webView.setScrollContainer(false);
    webView.setWebViewClient(new WebViewClient());
}

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

private class WebViewClient extends android.webkit.WebViewClient{

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
    {
        Intent intent = new Intent(getContext(),WebViewShowActivity.class);
        startActivity(intent);
        return true;
    }

}
</code>```

答:
```<code>public class WebViewJavaScriptInterface {
        public Context context;

        public WebViewJavaScriptInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void openPost(String url,String posttitle) {
            String postUrl = "https://google.in"+url;
            String postTitle = posttitle;
            Log.d("POSTURL",postUrl);
            Intent intent = new Intent(getContext(), WebViewShowActivity.class);
            intent.putExtra("linkUrl",postUrl);
            intent.putExtra("postTitle",postTitle);
            startActivity(intent);
        }

        @JavascriptInterface
        public void openVideo(String url) {
            String youtubeUrl = url;
            Log.d("YoutubeURL",youtubeUrl);
            ForTrainertUtil.playPostVideoForYoutubeID(context,youtubeUrl);
        }

    }
</code>```

this is how we can handle click event from web page through JavaScript..
when I click on a specific content of web page it handle associate method in android.

Body:
In my app, there are four tabs and in the second tab, I am trying to load webview...
after disable shouldOverrideUrlLoading it perfectly load webview in fragment...
but with shouldOverrideUrlLoading method, it redirects on new activity...
But what I want is to load webview first on fragment and after clicking on any content link it should be redirected on new activity

 private void setUpWebView() {

    WebSettings ws = webView.getSettings();
    ws.setJavaScriptEnabled(true);
    ws.setAllowFileAccess(true);
    webView.setScrollContainer(false);
    webView.setWebViewClient(new WebViewClient());
}

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

private class WebViewClient extends android.webkit.WebViewClient{

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
    {
        Intent intent = new Intent(getContext(),WebViewShowActivity.class);
        startActivity(intent);
        return true;
    }

}

Body:
public class WebViewJavaScriptInterface {
        public Context context;

        public WebViewJavaScriptInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void openPost(String url,String posttitle) {
            String postUrl = "https://google.in"+url;
            String postTitle = posttitle;
            Log.d("POSTURL",postUrl);
            Intent intent = new Intent(getContext(), WebViewShowActivity.class);
            intent.putExtra("linkUrl",postUrl);
            intent.putExtra("postTitle",postTitle);
            startActivity(intent);
        }

        @JavascriptInterface
        public void openVideo(String url) {
            String youtubeUrl = url;
            Log.d("YoutubeURL",youtubeUrl);
            ForTrainertUtil.playPostVideoForYoutubeID(context,youtubeUrl);
        }

    }

this is how we can handle click event from web page through JavaScript..
when I click on a specific content of web page it handle associate method in android.


问:
Get OS system and relative path to a folder in java
I write my test on my local Windows, and I create webdriver like this:

```<code>@BeforeMethod
@Parameters("browser")
public void setUp(String browser) throws Exception {
    if (browser.equalsIgnoreCase("chrome")) {
        System.out.println("Chrome test starting ...");
        System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver_win.exe");
        webDriver = new ChromeDriver();
    }
    else {
        throw new Exception("Browser is not supported");
    }
</code>```

For the setProperty, I use a hard path to Chrome Driver, but I would like change the path to relative by checking the OS to use appropriate driver for Windows and Mac. Can someone give me a hint. Thanks

答:
By using config property file you can get both browser type and chrome driver location.

you can create one folder in your work space with the name Drivers and paste your chrome driver

Below is config.properties file

```<code>browserType=Chrome
ChromeDriver = Drivers/chromedriver.exe
</code>```

Below is the code to run chrome driver on different operating systems

```<code>String os = System.getProperty("os.name");
public String currentBrowser;
if(CONFIG.getProperty("browserType").contains(","))
{
  data=currentBrowser;
}
if (os.contains("Windows"))
{
    else if (data.equals("Chrome")) {
    APP_LOGS.debug("Chrome Browser Opening Method Start");
    DesiredCapabilities capability = DesiredCapabilities.chrome();
    // To Accept SSL certificate
    capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    System.setProperty("webdriver.chrome.driver",
            CONFIG.getProperty("ChromeDriver"));
    Thread.sleep(10000);
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

    long
    implicitWaitTime=Long.parseLong(CONFIG.getProperty("implicitwait"));
    driver.manage().timeouts().implicitlyWait(implicitWaitTime,
    TimeUnit.SECONDS);
    driver.manage().window().maximize();
}
    return os;
}
</code>```

Body:
I write my test on my local Windows, and I create webdriver like this:

@BeforeMethod
@Parameters("browser")
public void setUp(String browser) throws Exception {
    if (browser.equalsIgnoreCase("chrome")) {
        System.out.println("Chrome test starting ...");
        System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver_win.exe");
        webDriver = new ChromeDriver();
    }
    else {
        throw new Exception("Browser is not supported");
    }

For the setProperty, I use a hard path to Chrome Driver, but I would like change the path to relative by checking the OS to use appropriate driver for Windows and Mac. Can someone give me a hint. Thanks

Body:
By using config property file you can get both browser type and chrome driver location.

you can create one folder in your work space with the name Drivers and paste your chrome driver

Below is config.properties file

browserType=Chrome
ChromeDriver = Drivers/chromedriver.exe

Below is the code to run chrome driver on different operating systems

String os = System.getProperty("os.name");
public String currentBrowser;
if(CONFIG.getProperty("browserType").contains(","))
{
  data=currentBrowser;
}
if (os.contains("Windows"))
{
    else if (data.equals("Chrome")) {
    APP_LOGS.debug("Chrome Browser Opening Method Start");
    DesiredCapabilities capability = DesiredCapabilities.chrome();
    // To Accept SSL certificate
    capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    System.setProperty("webdriver.chrome.driver",
            CONFIG.getProperty("ChromeDriver"));
    Thread.sleep(10000);
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

    long
    implicitWaitTime=Long.parseLong(CONFIG.getProperty("implicitwait"));
    driver.manage().timeouts().implicitlyWait(implicitWaitTime,
    TimeUnit.SECONDS);
    driver.manage().window().maximize();
}
    return os;
}


问:
Spring batch how to fail a step and therefor the job from inside a Partitioner
I currently have a partitioner extending partitiner and Overriding the method partition.

In the partition method I try to read configuration records from the database in order to partition downloads

If I'm unable to read from the database for some reason I want to fail the Job.

How do I do exactly that?

答:
You can use SimpleJobOperator bean for this purpose.

SimpleJobOperator bean has method jobOperator.stop(executionId) method which takes executionId of job as parameter.

You can get executionId from JobExecution.
    something like this executionId =JobExecution.getId();

I am using similar setup and it's working fine. Hope this helps


问:
How do I write a conditional (IF DATA EXISTS) LINQ statement without repetition?
I need to write a Linq query where the condition like this:

when data exists then the join will be  INNER JOIN

when data is not exists then the join will be  LEFT JOIN.

```<code>bool ifexists =  db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
    query=my inner join linq;
    query = from s in query select s;
    return query.ToList();
}
else
{
    query=my left join linq;
    query = from s in query select s;
    return query.ToList();
}
</code>```

Now how I can write this Linq? Is there any way to write this linq in a single Linq statement - I don't want to write the linq twice?

答:
You can conditionally compose on an IQueryable before evaluating it against the database - this will allow you to at least partially DRY up the common actions on the different legs of your branching:

```<code>var query = db.SomeTable
    .AsQueryable() // Not needed if `db.SomeTable` is already a Queryable
    .Where(x => ** common predicates on x ** ));
    // NB : Do not materialize here!

if(exists) // Don't need == true
{
     query = query
      .Where(x => ** branch 1 predicates **));
}
else
{
     query = query
      .Where(x => ** branch 2 predicates **);
}
return query
  .Select(q => ** common fields to project **)
  .OrderBy(q => ** common ordering **)
  .ToList(); // Materialize right at the end
</code>```

Body:
I need to write a Linq query where the condition like this:

when data exists then the join will be  INNER JOIN

when data is not exists then the join will be  LEFT JOIN.

bool ifexists =  db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
    query=my inner join linq;
    query = from s in query select s;
    return query.ToList();
}
else
{
    query=my left join linq;
    query = from s in query select s;
    return query.ToList();
}

Now how I can write this Linq? Is there any way to write this linq in a single Linq statement - I don't want to write the linq twice?

Body:
You can conditionally compose on an IQueryable before evaluating it against the database - this will allow you to at least partially DRY up the common actions on the different legs of your branching:

var query = db.SomeTable
    .AsQueryable() // Not needed if `db.SomeTable` is already a Queryable
    .Where(x => ** common predicates on x ** ));
    // NB : Do not materialize here!

if(exists) // Don't need == true
{
     query = query
      .Where(x => ** branch 1 predicates **));
}
else
{
     query = query
      .Where(x => ** branch 2 predicates **);
}
return query
  .Select(q => ** common fields to project **)
  .OrderBy(q => ** common ordering **)
  .ToList(); // Materialize right at the end


问:
How is memory allocation treated with respect to time complexity?
This question: Time complexity of memory allocation says that memory allocation takes non-deterministic time. Based on this, how is it valid to say, for example, that "adding an item to a dynamic array takes amortized O(1) time"? In this scenario, if adding the item causes the dynamic array to resize, then a new backing buffer must be allocated. For all we know, allocating that buffer could take O(1) time, or O(n^2) time, or some crazily large expression that dwarfs n, depending on the algorithm the memory allocator uses and its current state.

Do academic papers simply ignore the time complexity of memory allocation / assume that it is O(1) in calculating time complexity?

答:
For asymptotic (big O) analysis of algorithms that use dynamic memory, it's generally safe to assume that the amortized cost of an allocation is proportional to the size of the allocation.

That is conservative, in that there are real memory allocation schemes, like simple copying garbage collection, that can guarantee that time.  At the same time, it would usually do no good to assume a faster allocation scheme, since the cost of actually using the memory you allocate is at least proportional to the size of the allocation as well.

Real allocators often also impose a linear cost to zero out memory or map pages or whatever, so even when it might be convenient to assume a faster allocator, it should be avoided as unrealistic.