问:
Flinging with RecyclerView + AppBarLayout
I am using the new CoordinatorLayout with AppBarLayout and CollapsingToolbarLayout. Below AppBarLayout, I have a RecyclerView with a list of content.

I have verified that fling scrolling works on the RecyclerView when I am scrolling up and down the list. However, I would also like the AppBarLayout to smoothly scroll during expansion.

When scrolling up to expand the CollaspingToolbarLayout, scrolling immediately stops once lifting your finger off the screen. If you scroll up in a quick motion, sometimes the CollapsingToolbarLayout re-collapses as well. This behavior with the RecyclerView seems to function much differently than when using a NestedScrollView.

I've tried to set different scroll properties on the recyclerview but I haven't been able to figure this out.

Here is a video showing some of the scrolling issues.
https://youtu.be/xMLKoJOsTAM

Here is an example showing the issue with the RecyclerView (CheeseDetailActivity).
https://github.com/tylerjroach/cheesesquare

Here is the original example that uses a NestedScrollView from Chris Banes.
https://github.com/chrisbanes/cheesesquare

答:
The accepted answer didn't work for me because I had RecyclerView inside a SwipeRefreshLayout and a ViewPager. This is the improved version that seeks a RecyclerView in the hierarchy and should work for any layout:

```<code>public final class FlingBehavior extends AppBarLayout.Behavior {
    private static final int TOP_CHILD_FLING_THRESHOLD = 3;
    private boolean isPositive;

    public FlingBehavior() {
    }

    public FlingBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
        if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
            velocityY = velocityY * -1;
        }
        if (!(target instanceof RecyclerView) && velocityY < 0) {
            RecyclerView recycler = findRecycler((ViewGroup) target);
            if (recycler != null){
                target = recycler;
            }
        }
        if (target instanceof RecyclerView && velocityY < 0) {
            final RecyclerView recyclerView = (RecyclerView) target;
            final View firstChild = recyclerView.getChildAt(0);
            final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
            consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
        }
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
        isPositive = dy > 0;
    }

    @Nullable
    private RecyclerView findRecycler(ViewGroup container){
        for (int i = 0; i < container.getChildCount(); i++) {
            View childAt = container.getChildAt(i);
            if (childAt instanceof RecyclerView){
                return (RecyclerView) childAt;
            }
            if (childAt instanceof ViewGroup){
                return findRecycler((ViewGroup) childAt);
            }
        }
        return null;
    }
}
</code>```

Body:
The accepted answer didn't work for me because I had RecyclerView inside a SwipeRefreshLayout and a ViewPager. This is the improved version that seeks a RecyclerView in the hierarchy and should work for any layout:

public final class FlingBehavior extends AppBarLayout.Behavior {
    private static final int TOP_CHILD_FLING_THRESHOLD = 3;
    private boolean isPositive;

    public FlingBehavior() {
    }

    public FlingBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
        if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
            velocityY = velocityY * -1;
        }
        if (!(target instanceof RecyclerView) && velocityY < 0) {
            RecyclerView recycler = findRecycler((ViewGroup) target);
            if (recycler != null){
                target = recycler;
            }
        }
        if (target instanceof RecyclerView && velocityY < 0) {
            final RecyclerView recyclerView = (RecyclerView) target;
            final View firstChild = recyclerView.getChildAt(0);
            final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
            consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
        }
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
        isPositive = dy > 0;
    }

    @Nullable
    private RecyclerView findRecycler(ViewGroup container){
        for (int i = 0; i < container.getChildCount(); i++) {
            View childAt = container.getChildAt(i);
            if (childAt instanceof RecyclerView){
                return (RecyclerView) childAt;
            }
            if (childAt instanceof ViewGroup){
                return findRecycler((ViewGroup) childAt);
            }
        }
        return null;
    }
}


来源: stackexchange

问:
Why must a:hover come after a:link and a:visited in the CSS?
Why does w3schools say that when we write anchor pseudo-classes in CSS we should write a:link first then a:visited followed by a:hover and finally a:active to be effective?

From: https://www.w3schools.com/css/tryit.asp?filename=trycss_link

How does the order of pseudo-classes effect the effectiveness?

答:
Because there is a priority order.

if hover was before visited, then hover wouldn't get ever applied, because it would be "forever" overwritten by visited style (if it has been really visited), that was applied after.

Same goes for :active (mouse down) - if it's defined before hover, then hover will always overwrite :active(mouse down)

Makes sense?

On the other hand, this is just "conventional rule" - it is not forced. If anyone wants to have :visited higher priority, overriding :hover/:active - you are free to do so - it simply would be just unconventional

And lastly, it is not only order that plays the role of style priority.

Elements that are more explicitly defined have higher priority.
Styles that are !important will have higher priority than explicitly defined styles.

Explicitly defined styles with !important and set last will have "ultimate" priority.

To question "Why would you want to use these to override styles? Wouldn't it be better just to make styles in your CSS file correctly ordered?" - Reason to use overrides by more explicit definition and !important priority overrides comes handy when you use large css/theme/bootstrap, that you haven't created and you have to quickly override/change some stuff... These dirty overrides come as a quick/cheap (not very pretty) solution.

.theBad:active {
  color: red;
}

.theBad:hover {
  color: green;
}

.theGood:hover {
  color: green;
}

.theGood:active {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>the Good - this will turn red on mouse down
<br />
the Bad - this poor little thing will not

<!--#ordermatters, The Ugly is lurking somewhere in the shadows--></code>```

ContentLicense: CC BY-SA 3.0

Body:
Because there is a priority order.

if hover was before visited, then hover wouldn't get ever applied, because it would be "forever" overwritten by visited style (if it has been really visited), that was applied after.

Same goes for :active (mouse down) - if it's defined before hover, then hover will always overwrite :active(mouse down)

Makes sense?

On the other hand, this is just "conventional rule" - it is not forced. If anyone wants to have :visited higher priority, overriding :hover/:active - you are free to do so - it simply would be just unconventional

And lastly, it is not only order that plays the role of style priority.

Elements that are more explicitly defined have higher priority.
Styles that are !important will have higher priority than explicitly defined styles.

Explicitly defined styles with !important and set last will have "ultimate" priority.

To question "Why would you want to use these to override styles? Wouldn't it be better just to make styles in your CSS file correctly ordered?" - Reason to use overrides by more explicit definition and !important priority overrides comes handy when you use large css/theme/bootstrap, that you haven't created and you have to quickly override/change some stuff... These dirty overrides come as a quick/cheap (not very pretty) solution.

.theBad:active {
  color: red;
}

.theBad:hover {
  color: green;
}

.theGood:hover {
  color: green;
}

.theGood:active {
  color: red;
}

<a href="#" class="theGood">the Good</a> - this will turn red on mouse down
<br />
<a href="#" class="theBad">the Bad</a> - this poor little thing will not

<!--#ordermatters, The Ugly is lurking somewhere in the shadows-->


答:
Is this what you want? I'm not sure.

```<code>ggplot(data = df,mapping = aes(x,acc))+geom_segment(data = df , mapping = aes(x=x,y=ystart,xend=x,yend=acc,color=col))
</code>```

```<code>df$x=year(as.Date(df$x))
df$ystart=0
df$col=ifelse(df$acc>=0,"blue","red")
</code>```

Title: R: How plot negative and positive anomaly (for this data) with ggplot?

Body:
I have this df

               x          acc
1  1902-01-01  0.782887804
2  1903-01-01 -0.003144199
3  1904-01-01  0.100006276
4  1905-01-01  0.326173392
5  1906-01-01  1.285114692
6  1907-01-01  2.844399973
7  1920-01-01 -0.300232190
8  1921-01-01  1.464389342
9  1922-01-01  0.142638653
10 1923-01-01 -0.020162385
11 1924-01-01  0.361928571
12 1925-01-01  0.616325588
13 1926-01-01 -0.108206003
14 1927-01-01 -0.318441954
15 1928-01-01 -0.267884586
16 1929-01-01 -0.022473777
17 1930-01-01 -0.294452983
18 1931-01-01 -0.654927109
19 1932-01-01 -0.263508341
20 1933-01-01  0.622530992
21 1934-01-01  1.009666043
22 1935-01-01  0.675484421
23 1936-01-01  1.209162008
24 1937-01-01  1.655280986
25 1948-01-01  2.080021785
26 1949-01-01  0.854572563
27 1950-01-01  0.997540963
28 1951-01-01  1.000244163
29 1952-01-01  0.958322941
30 1953-01-01  0.816259474
31 1954-01-01  0.814488644
32 1955-01-01  1.233694537
33 1958-01-01  0.460120970
34 1959-01-01  0.344201474
35 1960-01-01  1.601430139
36 1961-01-01  0.387850967
37 1962-01-01 -0.385954401
38 1963-01-01  0.699355708
39 1964-01-01  0.084519926
40 1965-01-01  0.708964572
41 1966-01-01  1.456280443
42 1967-01-01  1.479412638
43 1968-01-01  1.199000726
44 1969-01-01  0.282942042
45 1970-01-01 -0.181724504
46 1971-01-01  0.012170186
47 1972-01-01 -0.095891043
48 1973-01-01 -0.075384446
49 1974-01-01 -0.156668145
50 1975-01-01 -0.303023258
51 1976-01-01 -0.516027310
52 1977-01-01 -0.826791524
53 1980-01-01 -0.947112221
54 1981-01-01 -1.634878300
55 1982-01-01 -1.955298323
56 1987-01-01 -1.854447550
57 1988-01-01 -1.458955443
58 1989-01-01 -1.256102245
59 1990-01-01 -0.864108585
60 1991-01-01 -1.293373024
61 1992-01-01 -1.049530431
62 1993-01-01 -1.002526230
63 1994-01-01 -0.868783614
64 1995-01-01 -1.081858981
65 1996-01-01 -1.302103374
66 1997-01-01 -1.288048194
67 1998-01-01 -1.455750340
68 1999-01-01 -1.015467069
69 2000-01-01 -0.682789640
70 2001-01-01 -0.811058004
71 2002-01-01 -0.972374057
72 2003-01-01 -0.536505225
73 2004-01-01 -0.518686263
74 2005-01-01 -0.976298621
75 2006-01-01 -0.946429713

I would like plot the data in this kind:

where on x axes there is column x of df, and on y axes column acc.
Is possible plot it with ggplot?
I tried with this code:

ggplot(df,aes(x=x,y=acc))+
geom_linerange(data =df , aes(colour = ifelse(acc <0, "blue", "red")),ymin=min(df),ymax=max(cdf))

but the result is this:

Please, how I can do it?

Body:
Is this what you want? I'm not sure.

ggplot(data = df,mapping = aes(x,acc))+geom_segment(data = df , mapping = aes(x=x,y=ystart,xend=x,yend=acc,color=col))

df$x=year(as.Date(df$x))
df$ystart=0
df$col=ifelse(df$acc>=0,"blue","red")


问:
ASP.NET MVC 3 Razor: Include JavaScript file in the head tag
I'm trying to figure out the proper Razor syntax to get a JavaScript file for a particular *.cshtml to be in the head tag along with all the other include files that are defined in _Layout.cshtml.</p>

答:
You can use Named Sections.

_Layout.cshtml

```<code><head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>
</code>```

_SomeView.cshtml

```<code>@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
</code>```

Body:
You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}


问:
Is there a name for a pattern where you build a dependency tree that imitates a filesystem?
I find myself doing this when I write really big libraries in a dynamically-typed language and want to aggregate exported features near the root of the project. Doesn't have to be Node/JS, but here is an example filesystem for a Node project...

```<code>src/
    index.js -- imports A/index.js and B/index.js
    A/
        index.js -- imports X/index.js
        X/
            index.js -- imports foo.js and bar.js
            foo.js
            bar.js
        Y/
            index.js -- imports snafu.js and whatever.js
            snafu.js
            whatever.js
    B/
        index.js -- imports alpha.js and omega.js
        alpha.js
        omega.js
</code>```

..where the exported library would imitate the filesystem:

```<code>const {
    A: {
        X: {
            foo,
            bar
        },
        Y: {
            snafu,
            whatever
        }
    },
    B: {
        alpha,
        omega
    }
} = require('lib');
</code>```

Is there a name for this method of constructing a dependency tree?

EDIT: I understand the final result is a tree, but if I document how to contribute to source code, I can't just say "Include modules like a tree," since that doesn't qualify coupling to the filesystem or how to structure exports in each file. I'm looking for a more specific name that captures both the structure of the aggregate, and the way that you build it without having to explain it every time for each project.

答:
Consider Composite pattern.

Compose objects into tree structures to represent part-whole hierarchies. Group of objects is to be treated in the same way as a single instance of an object.

File system example using Composite.

Body:
I find myself doing this when I write really big libraries in a dynamically-typed language and want to aggregate exported features near the root of the project. Doesn't have to be Node/JS, but here is an example filesystem for a Node project...

src/
    index.js -- imports A/index.js and B/index.js
    A/
        index.js -- imports X/index.js
        X/
            index.js -- imports foo.js and bar.js
            foo.js
            bar.js
        Y/
            index.js -- imports snafu.js and whatever.js
            snafu.js
            whatever.js
    B/
        index.js -- imports alpha.js and omega.js
        alpha.js
        omega.js

..where the exported library would imitate the filesystem:

const {
    A: {
        X: {
            foo,
            bar
        },
        Y: {
            snafu,
            whatever
        }
    },
    B: {
        alpha,
        omega
    }
} = require('lib');

Is there a name for this method of constructing a dependency tree?

EDIT: I understand the final result is a tree, but if I document how to contribute to source code, I can't just say "Include modules like a tree," since that doesn't qualify coupling to the filesystem or how to structure exports in each file. I'm looking for a more specific name that captures both the structure of the aggregate, and the way that you build it without having to explain it every time for each project.


问:
What is the meaning of angle brackets in Python?
I found the following lines in the scikit-learn package:

```<code>if is_sparse:
    problem = csr_set_problem(
            (<np.ndarray[np.float64_t, ndim=1, mode='c']>X.data).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).data,
            Y.data, (<np.int32_t>X.shape[1]), bias,
            sample_weight.data)
else:
    ...
</code>```

All my searches for "angle brackets in Python" give answers about documentation or decorator syntax, which I am pretty sure this is neither because it looks like actual logic.

What do the angle brackets in the above Python code do and where can I learn more about them?

答:
That is Cython's syntax for type casting/coercion. It is not plain Python. Notice the file extension is .pyx

You can learn more about them in the documentation for Cython.

Here's an example taken from the doc page:

```<code>cdef char *p, float *q
p = <char*>q
</code>```

Using Cython is not uncommon with projects like scikit-learn, where one gains significant optimisations by mixing readable Python with blazing-speed C.

ContentLicense: CC BY-SA 4.0

Body:
I found the following lines in the scikit-learn package:

if is_sparse:
    problem = csr_set_problem(
            (<np.ndarray[np.float64_t, ndim=1, mode='c']>X.data).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).data,
            Y.data, (<np.int32_t>X.shape[1]), bias,
            sample_weight.data)
else:
    ...

All my searches for "angle brackets in Python" give answers about documentation or decorator syntax, which I am pretty sure this is neither because it looks like actual logic.

What do the angle brackets in the above Python code do and where can I learn more about them?

Body:
That is Cython's syntax for type casting/coercion. It is not plain Python. Notice the file extension is .pyx

You can learn more about them in the documentation for Cython.

Here's an example taken from the doc page:

cdef char *p, float *q
p = <char*>q

Using Cython is not uncommon with projects like scikit-learn, where one gains significant optimisations by mixing readable Python with blazing-speed C.


问:
RabbitMQ java client connection to several queues
I am using amqp-client-4.0.2
I have one topic exchange which routes messages to several queues
The queues are named in a x.x.x.x convention
My java client needs to be able to consume messages from several queues.
I would like to be able to do that in my spring config for example, to be able to specify a parameter, for example the routing key, or the name convention and the client to be able to consume messages from animal.orange.# queues for example. Is this possible?

答:
No, you cannot use wildcards for the queue names; you have to specify each queue fully.

EDIT

You could use the REST API to discover the queue names and dynamically configure the container.


问:
What to use instead of disable textarea?
Currently there is a bug in Firefox that doesn't let you to copy stuff from disabled textarea (in chrome it works fine) and I've been thinking how can I replace my code so that it works ok in firefox as well. i'm using GSP files but can use normal html tags within them as well.

Here is my code snippet:

```<code><g:textArea rows="5" cols="1" name="description" value="${forecast?.description}" class="description-t-area" disabled="${!canEdit}"/>
</code>```

And here is image how it looks on the web:

答:
The issue is that you can not set disabled to true or false, the existence of the attribute means true, eg:

```<code>disabled="false" == true
disabled="true"  == true
disabled         == true
</code>```

You have two options, use a plain text-area and conditionally print disabled or nothing html tag or set disabled via javascript.

More info here Correct value for disabled attribute

Edit: Just tried this is Grails 3.2.8 and it does actually work correctly now (been a while since I've looked, sorry!)

```<code><g:textArea name="foo" disabled="${false}"/>
</code>```

results in

```<code><textarea name="foo" id="foo" ></textarea>
</code>```

and

```<code><g:textArea name="foo" disabled="${true}"/>
</code>```

results in

```<code><textarea name="foo" id="foo" disabled="true" ></textarea>
</code>```

Body:
Currently there is a bug in Firefox that doesn't let you to copy stuff from disabled textarea (in chrome it works fine) and I've been thinking how can I replace my code so that it works ok in firefox as well. i'm using GSP files but can use normal html tags within them as well.

Here is my code snippet:

<g:textArea rows="5" cols="1" name="description" value="${forecast?.description}" class="description-t-area" disabled="${!canEdit}"/>

And here is image how it looks on the web:

Body:
The issue is that you can not set disabled to true or false, the existence of the attribute means true, eg:

disabled="false" == true
disabled="true"  == true
disabled         == true

You have two options, use a plain text-area and conditionally print disabled or nothing html tag or set disabled via javascript.

More info here Correct value for disabled attribute

Edit: Just tried this is Grails 3.2.8 and it does actually work correctly now (been a while since I've looked, sorry!)

<g:textArea name="foo" disabled="${false}"/>

results in

<textarea name="foo" id="foo" ></textarea>

and

<g:textArea name="foo" disabled="${true}"/>

results in

<textarea name="foo" id="foo" disabled="true" ></textarea>


问:
PHP $_POST self: defaults for checkboxes
OK I am sending data with $_POST to itself.

I have some checkboxes that I have checked by default. (1 & 2 in this example)

When the form is sumbitted I want to override these default's with the $_POST value.

```<code><?php
    $syndication_check_1 = 'checked="checked"';
    $syndication_check_2 = 'checked="checked"';
    $syndication_check_3 = '';
    if (isset($_POST['syndication'])) {
        //
    }
?>

<form name="form" method="post" action="">
    <!-- this is what I use for radiobuttons -->
    <legend>Sex:</legend>
    <input type="radio" name="sex" id="sex-1" value="M" <?php echo (!isset($_POST['sex']) || $_POST['sex'] == "M") ? 'checked="checked"': ''; ?> />
    <label for="sex-1"><?= _("Male"); ?></label>
    <input type="radio" name="sex" id="sex-2" value="F" <?php echo (isset($_POST['sex']) && $_POST['sex'] == "F") ? 'checked="checked"': ''; ?> />
    <label for="sex-2"><?= _("Female"); ?></label>

    <!-- now something similar for checkboxes -->
    <legend>Syndication:</legend>
    <input type="checkbox" name="syndication[]" id="syndication-1" value="yahoo" <?= $syndication_check_1; ?> /> <!-- checked -->
    <label for="syndication-1">Yahoo Real Estate</label>
    <input type="checkbox" name="syndication[]" id="syndication-2" value="trulia" <?= $syndication_check_2; ?> /> <!-- checked -->
    <label for="syndication-2">Trulia.com</label>
    <input type="checkbox" name="syndication[]" id="syndication-3" value="zillow" <?= $syndication_check_3; ?> />
    <label for="syndication-3">Zillow.com</label>
</form>
</code>```

答:
Id probably do something like this...</p>

```<code>$syndicationCheck = array(
  'yahoo' => null,
  'trulia' => null,
  'zillow' => null
);

if(isset($_POST['syndication'])){
  foreach($_POST['syndication'] as $value){
    $syndicationCheck[$value] = 'checked';
  }
}

<legend>Syndication:</legend>
    <input type="checkbox" name="syndication[]" id="syndication-1" value="yahoo" <?= $syndicationCheck['yahoo']; ?> /> <!-- checked -->
    <label for="syndication-1">Yahoo Real Estate</label>
    <input type="checkbox" name="syndication[]" id="syndication-2" value="trulia" <?= $syndicationCheck['trulia']; ?> /> <!-- checked -->
    <label for="syndication-2">Trulia.com</label>
    <input type="checkbox" name="syndication[]" id="syndication-3" value="zillow" <?= $syndicationCheck['zillow']; ?> />
    <label for="syndication-3">Zillow.com</label>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
OK I am sending data with $_POST to itself.

I have some checkboxes that I have checked by default. (1 & 2 in this example)

When the form is sumbitted I want to override these default's with the $_POST value.

<?php
    $syndication_check_1 = 'checked="checked"';
    $syndication_check_2 = 'checked="checked"';
    $syndication_check_3 = '';
    if (isset($_POST['syndication'])) {
        //
    }
?>

<form name="form" method="post" action="">

    <legend>Sex:</legend>
    <input type="radio" name="sex" id="sex-1" value="M" <?php echo (!isset($_POST['sex']) || $_POST['sex'] == "M") ? 'checked="checked"': ''; ?> />
    <?= _("Male"); ?>
    <input type="radio" name="sex" id="sex-2" value="F" <?php echo (isset($_POST['sex']) && $_POST['sex'] == "F") ? 'checked="checked"': ''; ?> />
    <?= _("Female"); ?>

    <legend>Syndication:</legend>
    <input type="checkbox" name="syndication[]" id="syndication-1" value="yahoo" <?= $syndication_check_1; ?> />
    Yahoo Real Estate
    <input type="checkbox" name="syndication[]" id="syndication-2" value="trulia" <?= $syndication_check_2; ?> />
    Trulia.com
    <input type="checkbox" name="syndication[]" id="syndication-3" value="zillow" <?= $syndication_check_3; ?> />
    Zillow.com
</form>

Body:
Id probably do something like this...

$syndicationCheck = array(
  'yahoo' => null,
  'trulia' => null,
  'zillow' => null
);

if(isset($_POST['syndication'])){
  foreach($_POST['syndication'] as $value){
    $syndicationCheck[$value] = 'checked';
  }
}

<legend>Syndication:</legend>
    <input type="checkbox" name="syndication[]" id="syndication-1" value="yahoo" <?= $syndicationCheck['yahoo']; ?> /> <!-- checked -->
    <label for="syndication-1">Yahoo Real Estate</label>
    <input type="checkbox" name="syndication[]" id="syndication-2" value="trulia" <?= $syndicationCheck['trulia']; ?> /> <!-- checked -->
    <label for="syndication-2">Trulia.com</label>
    <input type="checkbox" name="syndication[]" id="syndication-3" value="zillow" <?= $syndicationCheck['zillow']; ?> />
    <label for="syndication-3">Zillow.com</label>


问:
Add points to canvas in android without refreshing the whole canvas
Is there a way to update the path in a canvas without refreshing the whole canvas?
I want to update a path by adding a point every 100 milliseconds, and refreshing the whole canvas creates performance issues. </p>

答: There's no way to partially draw a view. On draw draws the whole thing. What you could do is double buffering- draw to a bitmap backed canvas, then your on draw is just drawing that bitmap to the view. The cost of this is as in memory bitmap of the view. But it's generally a huge perf win, drawing a bitmap is fast and can be done in a background thread, and copying a bitmap isn't bad. </p>


问:
What's wrong with mixing WinForm and WPF assemblies?
I am developing a WPF application and have a need for an icon in the System Tray. WinForms has the built in NotifyIcon class.

I see some developers going all out not to combine assemblies in an application. While others seems oblivious or blind to combining them.

Is it a bad idea to mix assemblies from both WinForms and WPF?
What are the issues aside from obvious things like WPF being DPI independent.

Thanks,
Michael

答:
The only real issue caused by mixing WinForms and WPF is maintainability.

When trying to add WPF functionality to none-WPF applications, you will need to import several WinForms assemblies, which will in many cases have very similar names to their WPF counterparts.

As a rule, it's a good idea to explicitly call any WinForms classes by their fully qualified name, rather than including a broad using statement.

The post here (C# trayicon using wpf) is a perfectly acceptable way to achieve what you're aiming to do, and will be the quickest option to get your project finished.

If you wish to work with just WPF, there is a nitify icon component which replicates the functionality of the WinForms notify icon - http://www.hardcodet.net/wpf-notifyicon

It's not best practice to mix approaches in this way, however in the real world when you need to get the job done, it's sometimes the most effective solution.


问:
Return an F# record type as JSON in Azure Functions
I'm creating a simple azure function in F#. At the end, I'm returning a record type as JSON. I'm doing something like this:

```<code>let y = {Gender = "Woman"; Frequency = 17; Percentage = 100.0}
req.CreateResponse(HttpStatusCode.OK, y);
</code>```

When I call the function from Postman I'm getting this JSON
{"Gender@":"Woman","Frequency@":17,"Percentage@":100}

It looks like that this is caused by the default serializer (Serializing F# Record type to JSON includes '@' character after each property).

Then I tried to use Newtonsoft.Json. Now, the code looks like this:

```<code>req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(y));
</code>```

But now I'm getting this using postman:

```<code>"{\"Gender\":\"Woman\",\"Frequency\":17,\"Percentage\":100}"
</code>```

I'd like to get this response:
{"Gender":"Woman","Frequency":17,"Percentage":100}

How can I get this JSON response? Is there any other way apart from specifying DataMemberAttribute?

Thanks

答:
I'm not 100 % to why you get that response, I think it is because you are actually taking the string of an object and not the actual string. If you do this it will work (I think):</p>

```<code>let response = sprintf "%s" JsonConvert.SerializeObject(y)
req.CreateResponse(HttpStatusCode.OK, response)
</code>```

Body:
I'm creating a simple azure function in F#. At the end, I'm returning a record type as JSON. I'm doing something like this:

let y = {Gender = "Woman"; Frequency = 17; Percentage = 100.0}
req.CreateResponse(HttpStatusCode.OK, y);

When I call the function from Postman I'm getting this JSON
{"Gender@":"Woman","Frequency@":17,"Percentage@":100}

It looks like that this is caused by the default serializer (Serializing F# Record type to JSON includes '@' character after each property).

Then I tried to use Newtonsoft.Json. Now, the code looks like this:

req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(y));

But now I'm getting this using postman:

"{\"Gender\":\"Woman\",\"Frequency\":17,\"Percentage\":100}"

I'd like to get this response:
{"Gender":"Woman","Frequency":17,"Percentage":100}

How can I get this JSON response? Is there any other way apart from specifying DataMemberAttribute?

Thanks

Body:
I'm not 100 % to why you get that response, I think it is because you are actually taking the string of an object and not the actual string. If you do this it will work (I think):

let response = sprintf "%s" JsonConvert.SerializeObject(y)
req.CreateResponse(HttpStatusCode.OK, response)


问:
Dataflow Error when running flowers-sample preprocessing
I am trying to use the preprocessing script contained in the flowers-sample (I saw that it has been modified today and it is no more deprecated).
However, after installing the required packages, the pipeline fails and outputs these error logs

```<code>(caeb3b0a930d0a6): Workflow failed. Causes: (caeb3b0a930d587): S01:Save to disk/Write/WriteImpl/InitializeWrite failed.
</code>```

and

```<code>(d50acb0dd46c44c6): Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 666, in run
    self._load_main_session(self.local_staging_directory)
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 411, in _load_main_session
    pickler.load_session(session_file)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/internal/pickler.py", line 230, in load_session
    return dill.load_session(file_path)
  File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 363, in load_session
    module = unpickler.load()
  File "/usr/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
  File "/usr/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 423, in find_class
    return StockUnpickler.find_class(self, module, name)
  File "/usr/lib/python2.7/pickle.py", line 1124, in find_class
    __import__(module)
ImportError: No module named util
</code>```

I get the same errors running the process from two different Google Compute Engines where I have installed the packages listed in requirements.txt.

Does it refer to the util.py file in the trainer directory or else, are there additional packages I should install to avoid this error?

答:
I have found a workaround: in preprocess.py I have replaced the import of the util package with the definition of get_cloud_project() that is contained in util.py.

I don't know if the issue was caused by the local package employed on a dataflow. I don't think this is the case because get_cloud_project() is not called inside the pipeline definition, but this is the first time I use dataflow.

If someone else knows if it is possibile to make the code work without modifying it, please tell me!

Body:
I am trying to use the preprocessing script contained in the flowers-sample (I saw that it has been modified today and it is no more deprecated).
However, after installing the required packages, the pipeline fails and outputs these error logs

(caeb3b0a930d0a6): Workflow failed. Causes: (caeb3b0a930d587): S01:Save to disk/Write/WriteImpl/InitializeWrite failed.

and

(d50acb0dd46c44c6): Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 666, in run
    self._load_main_session(self.local_staging_directory)
  File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 411, in _load_main_session
    pickler.load_session(session_file)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/internal/pickler.py", line 230, in load_session
    return dill.load_session(file_path)
  File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 363, in load_session
    module = unpickler.load()
  File "/usr/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
  File "/usr/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 423, in find_class
    return StockUnpickler.find_class(self, module, name)
  File "/usr/lib/python2.7/pickle.py", line 1124, in find_class
    __import__(module)
ImportError: No module named util

I get the same errors running the process from two different Google Compute Engines where I have installed the packages listed in requirements.txt.

Does it refer to the util.py file in the trainer directory or else, are there additional packages I should install to avoid this error?


问:
Loop thru values code
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

```<code><% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>
</code>```

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

```<code>  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end
</code>```

答:
@Theopap

The issue currently is the show method which returns the all the orders found in the Order database, refactor the show method to look for orders of a specific id, therefore your show method should look something like this:

Current show should become index action

```<code>def index
  @orders = Order.all
end
</code>```

This will get the order id from the route, so the

```<code>def show
  @order = Order.find(params[:id])
end
</code>```

Routes

Something like this should done with your routes so that your params[id].

get ‘\order\:id’, to:‘order#show’

Better still use the option below to generate the 7 default rails actions.e.g. index, show, create etc.
resources orders (http://guides.rubyonrails.org/v2.3/routing.html)

Title: Loop thru values code

Body:
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

<% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end

Body:
@Theopap

The issue currently is the show method which returns the all the orders found in the Order database, refactor the show method to look for orders of a specific id, therefore your show method should look something like this:

Current show should become index action

def index
  @orders = Order.all
end

This will get the order id from the route, so the

def show
  @order = Order.find(params[:id])
end

Routes

Something like this should done with your routes so that your params[id].

get ‘\order\:id’, to:‘order#show’

Better still use the option below to generate the 7 default rails actions.e.g. index, show, create etc.
resources orders (http://guides.rubyonrails.org/v2.3/routing.html)


问:
How to make TabLayout Custom Font , Custom color
I looking for TabLayout with following custom behaviour

Custom font

Text color change on select & un select of Tab

Bold & normal font on select & un select of Tab

By default 1st tab should be selected with Bold text

I am attaching following code snippet which all I tried for it.

1) I've created custom view Called FundayTabLayout

```<code><com.knackv.custom.view.FundayTabLayout
    android:id="@id/dashboard_tab_layout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabTextAppearance="@style/AppTabTextAppearance"></com.knackv.custom.view.FundayTabLayout>
</code>```

2) Styles which I've used

```<code><style name="AppTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabMaxWidth">@dimen/size_in_150_dp</item>
    <item name="tabIndicatorColor">@color/app_background</item>
    <item name="tabBackground">@drawable/tab_background_color_selector</item>
    <item name="tabTextAppearance">@style/AppTabTextAppearance</item>
    <item name="tabSelectedTextColor">@color/app_blue</item>
</style>

<style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">@dimen/size_in_15_dp</item>
    <item name="textAllCaps">false</item>
</style>
</code>```

3) setting up my custom font:

```<code> @Override
public void setupWithViewPager(@Nullable ViewPager viewPager) {
    super.setupWithViewPager(viewPager);

    this.removeAllTabs();

    ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0);
    for (int i = 0, count = viewPager.getAdapter().getCount(); i < count; i++) {
        Tab tab = this.newTab();
        this.addTab(tab.setText(viewPager.getAdapter().getPageTitle(i)));
        AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1);
        view.setAllCaps(false);
        view.setTypeface(Utility.getNormalTypeFace());
    }
}
</code>```

Please provide me optimum solution for this issue.

答:
```<code>Typeface fontTypeFace = Typeface.createFromAsset(getAssets(), "OpenSans-Semibold.ttf");

    for (int i = 0; i < tabLayout.getChildCount(); ++i) {
        View nextChild = tabLayout.getChildAt(i);
        if (nextChild instanceof TextView) {
            TextView textViewToConvert = (TextView) nextChild;
            textViewToConvert.setTypeface(fontTypeFace);
        }
    }
</code>```

try this

Body:
I looking for TabLayout with following custom behaviour

Custom font

Text color change on select & un select of Tab

Bold & normal font on select & un select of Tab

By default 1st tab should be selected with Bold text

I am attaching following code snippet which all I tried for it.

1) I've created custom view Called FundayTabLayout

<com.knackv.custom.view.FundayTabLayout
    android:id="@id/dashboard_tab_layout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabTextAppearance="@style/AppTabTextAppearance"></com.knackv.custom.view.FundayTabLayout>

2) Styles which I've used

3) setting up my custom font:

 @Override
public void setupWithViewPager(@Nullable ViewPager viewPager) {
    super.setupWithViewPager(viewPager);

    this.removeAllTabs();

    ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0);
    for (int i = 0, count = viewPager.getAdapter().getCount(); i < count; i++) {
        Tab tab = this.newTab();
        this.addTab(tab.setText(viewPager.getAdapter().getPageTitle(i)));
        AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1);
        view.setAllCaps(false);
        view.setTypeface(Utility.getNormalTypeFace());
    }
}

Please provide me optimum solution for this issue.

Body:
Typeface fontTypeFace = Typeface.createFromAsset(getAssets(), "OpenSans-Semibold.ttf");

    for (int i = 0; i < tabLayout.getChildCount(); ++i) {
        View nextChild = tabLayout.getChildAt(i);
        if (nextChild instanceof TextView) {
            TextView textViewToConvert = (TextView) nextChild;
            textViewToConvert.setTypeface(fontTypeFace);
        }
    }

try this


问:
How can I disable the responsive behaviour in Bootstrap 4?
How can I disable the responsive behaviour in Bootstrap 4, while maintaining the styles? I want users that access the website in the mobile phone to have the same website as the desktop version and zoom in and zoom out with finger gestures. How can I do it?</p>

答:
so i would suggest that you just put everything in the bootstrap grid and design it for mobile view only. so instead of using multiple classes for multiple screen sizes like "col-4 col-md-3" or flexible like "col" just use "col-n" classes only, so on mobile it'll look like you want it to look (also you would have to zoom in and out if you place enough content in the cols because with col-n you tell bootstrap to use n/12 of the available width on smallest screen size and up) and on desktop it'll show its full beauty without the need to zoom.
i hope this will help :)</p>


问:
How to set data in viewpager using ArrayList?
Here, in this viewpageradapter class is using to set data, how can I set data in viewpager. I can try to implement but I don't know how can be achieving this.I also add my PhotoviewAdater and PhotoActivity. plz solve this problem.

```<code>public class PhotoViewAdapter extends PagerAdapter {

Context context;
ArrayList<Model_image> all_folder = new ArrayList<>();
int int_position;
LayoutInflater inflater;

public PhotoViewAdapter(Context context, ArrayList<Model_image> all_folder, int int_position) {
    this.context=context;
    this.all_folder=all_folder;
    this.int_position=int_position;
}

@Override
public int getCount() {
    return all_folder.get(int_position).getAll_imagepath().size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.activity_photo_view_adapter, container,false);

    imageView = (ImageView) container.findViewById(R.id.im_page);

     try {
        imageView.setImageResource(Integer.parseInt((all_folder.get(position).getAll_imagepath().get(int_position))));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return viewLayout;
}
}
</code>```

PhotoActivity:

```<code>public class PhotoActivity extends AppCompatActivity {

ViewPager viewPager;
int int_position;
PhotoViewAdapter photoViewAdapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo_view);

    int_position = getIntent().getIntExtra("pos",0);
    viewPager = (ViewPager) findViewById(R.id.imagepage);
    photoViewAdapter = new PhotoViewAdapter(getApplicationContext(), ImageActivity.all_images, int_position);
    viewPager.setAdapter(photoViewAdapter);
}
}
</code>```

Model_image:

```<code>public class Model_image {

String str_folder;
ArrayList<String> all_imagepath;

public void setStr_folder(String str_folder)
{
    this.str_folder = str_folder;
}

public void setAll_imagepath(ArrayList<String> all_imagepath)
{
    this.all_imagepath = all_imagepath;
}

public String getStr_folder()
{
    return str_folder;
}

public ArrayList<String> getAll_imagepath()
{
    return all_imagepath;
}
}
</code>```

答:
Change this

```<code> imageView.setImageResource(all_folder[position]);
</code>```

to

```<code> imageView.setImageResource(all_folder.get(position));
</code>```

all_folder is defined as an Arraylist not as an array.

all_folder.get(position) returns an Model_image object.
To set the image in the imageView you need an image reference.

I dont know which image you are trying to set.

If you want to set the image from all_imagepath, try doing

```<code>imageView.setImageResource(all_folder.get(position).getAll_imagepath.get(<position of the required image>));
</code>```

Body:
Here, in this viewpageradapter class is using to set data, how can I set data in viewpager. I can try to implement but I don't know how can be achieving this.I also add my PhotoviewAdater and PhotoActivity. plz solve this problem.

public class PhotoViewAdapter extends PagerAdapter {

Context context;
ArrayList<Model_image> all_folder = new ArrayList<>();
int int_position;
LayoutInflater inflater;

public PhotoViewAdapter(Context context, ArrayList<Model_image> all_folder, int int_position) {
    this.context=context;
    this.all_folder=all_folder;
    this.int_position=int_position;
}

@Override
public int getCount() {
    return all_folder.get(int_position).getAll_imagepath().size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.activity_photo_view_adapter, container,false);

    imageView = (ImageView) container.findViewById(R.id.im_page);

     try {
        imageView.setImageResource(Integer.parseInt((all_folder.get(position).getAll_imagepath().get(int_position))));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return viewLayout;
}
}

PhotoActivity:

public class PhotoActivity extends AppCompatActivity {

ViewPager viewPager;
int int_position;
PhotoViewAdapter photoViewAdapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo_view);

    int_position = getIntent().getIntExtra("pos",0);
    viewPager = (ViewPager) findViewById(R.id.imagepage);
    photoViewAdapter = new PhotoViewAdapter(getApplicationContext(), ImageActivity.all_images, int_position);
    viewPager.setAdapter(photoViewAdapter);
}
}

Model_image:

public class Model_image {

String str_folder;
ArrayList<String> all_imagepath;

public void setStr_folder(String str_folder)
{
    this.str_folder = str_folder;
}

public void setAll_imagepath(ArrayList<String> all_imagepath)
{
    this.all_imagepath = all_imagepath;
}

public String getStr_folder()
{
    return str_folder;
}

public ArrayList<String> getAll_imagepath()
{
    return all_imagepath;
}
}

Body:
Change this

 imageView.setImageResource(all_folder[position]);

to

 imageView.setImageResource(all_folder.get(position));

all_folder is defined as an Arraylist not as an array.

all_folder.get(position) returns an Model_image object.
To set the image in the imageView you need an image reference.

I dont know which image you are trying to set.

If you want to set the image from all_imagepath, try doing

imageView.setImageResource(all_folder.get(position).getAll_imagepath.get(<position of the required image>));


问:
angular 2 - how to hide nav bar in some components
I am created nav bar separately in nav.component.html ,how to hide nav bar in some components like login.component.

nav.component.html

```<code><nav class="navbar navbar-default navbar-fixed-top navClass">
    <div class="container-fluid">
        <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed"
                        (click)="toggleState()">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>
         <div class="collapse navbar-collapse"
              [ngClass]="{ 'in': isIn }">
          enter code here   <ul class="nav navbar-nav">
               <li class="active"><a href="#">Home</a></li>
               <li><a href="#">about</a></li>

            </ul>

        </div>
    </div>
</nav>
</code>```

答:
You can use ngIF  directive on components where nav is located

```<code>   <nav *ngIf="this.currentRoute!=='login'" navigation>
   </nav>
</code>```

after you get the current route:

```<code>  this.router.events.subscribe(event => {
  if (event.constructor.name === "NavigationEnd") {
    this.name = (<any>event).url.split("/").slice(-1)[0];
    this.isLogin = this.currentRoute === 'login';
  }
})
</code>```

Body:
I am created nav bar separately in nav.component.html ,how to hide nav bar in some components like login.component.

nav.component.html

                <button type="button" class="navbar-toggle collapsed"
                        (click)="toggleState()">
                Toggle navigation

            </button>

          enter code here

Home

about

Body:
You can use ngIF  directive on components where nav is located

   <nav *ngIf="this.currentRoute!=='login'" navigation>
   </nav>

after you get the current route:

  this.router.events.subscribe(event => {
  if (event.constructor.name === "NavigationEnd") {
    this.name = (<any>event).url.split("/").slice(-1)[0];
    this.isLogin = this.currentRoute === 'login';
  }
})


问:
Add web part in master page in SharePoint 2007
How to add a web part in a master page in SPD in SharePoint 2007?</p>

答:
To add a web part in a master page you have to add the web part between some HTML Tags like  ,
 or place holder . Select the appropriate area in the master page where you want to add the web part, then click insert in top menu, select SharePoint controls under it, and select webparts. Drag and drop the required web part from the new webpart menu displayed in the right pane to the desired location in the master page.

Body: To add a web part in a master page you have to add the web part between some HTML Tags like <TD> ,<Div> or place holder . Select the appropriate area in the master page where you want to add the web part, then click insert in top menu, select SharePoint controls under it, and select webparts. Drag and drop the required web part from the new webpart menu displayed in the right pane to the desired location in the master page.


问:
Jackson parse string field as JSON
I have the following JSON:

```<code>{
    "some_key": "{\"a\": 1, \"b\": \"text\"}"
}
</code>```

As you can see some_key field is not a JSON object it is a string, that contains valid JSON.

I would like to parse it into following structure:

```<code>class Foo {
    Bar some_key;
}

class Bar {
    int a;
    String b;
}
</code>```

UPDATE:

class A and B, has getters and setters, constructors. I haven't show
them to keep sample short and simple.

I can't edit the weird structure of the JSON.

The question is how to ask Jackson parse the inner string field as
JSON object.

答:
There are a couple of problems:

json provided in example does not correspond to the schema. E.g. as per json, some_key is a String field (it's wrapped in double quotes) whereas as per schema, it's a Boo field. You need to change json to look like following (Or change some_value to String type):

{
    "some_key": {\"a\": 1, \"b\": \"text\"}
}

There are no getters or setters. Jackson can't deserialize can't access getters/setters via reflection.

Here's the working example:

```<code>class Foo {

    Bar some_key;

    public Bar getSome_key() {
        return some_key;
    }

    public void setSome_key(Bar some_key) {
        this.some_key = some_key;
    }

}

class Bar {
    int a;
    String b;
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public String getB() {
        return b;
    }
    public void setB(String b) {
        this.b = b;
    }
}
</code>```

Deserialization:

```<code>ObjectMapper mapper = new ObjectMapper();
Foo response = mapper.readValue("{\"some_key\": {\"a\": 1, \"b\": \"text\"}}", Foo.class);
</code>```

Title: Jackson parse string field as JSON

Body:
I have the following JSON:

{
    "some_key": "{\"a\": 1, \"b\": \"text\"}"
}

As you can see some_key field is not a JSON object it is a string, that contains valid JSON.

I would like to parse it into following structure:

class Foo {
    Bar some_key;
}

class Bar {
    int a;
    String b;
}

UPDATE:

class A and B, has getters and setters, constructors. I haven't show
them to keep sample short and simple.

I can't edit the weird structure of the JSON.

The question is how to ask Jackson parse the inner string field as
JSON object.

Body:
There are a couple of problems:

json provided in example does not correspond to the schema. E.g. as per json, some_key is a String field (it's wrapped in double quotes) whereas as per schema, it's a Boo field. You need to change json to look like following (Or change some_value to String type):

{
    "some_key": {\"a\": 1, \"b\": \"text\"}
}

There are no getters or setters. Jackson can't deserialize can't access getters/setters via reflection.

Here's the working example:

class Foo {

    Bar some_key;

    public Bar getSome_key() {
        return some_key;
    }

    public void setSome_key(Bar some_key) {
        this.some_key = some_key;
    }

}

class Bar {
    int a;
    String b;
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public String getB() {
        return b;
    }
    public void setB(String b) {
        this.b = b;
    }
}

Deserialization:

ObjectMapper mapper = new ObjectMapper();
Foo response = mapper.readValue("{\"some_key\": {\"a\": 1, \"b\": \"text\"}}", Foo.class);


问:
Accurately testing Pypy vs CPython performance
The Problem Description:

I have this custom "checksum" function:

```<code>NORMALIZER = 0x10000

def get_checksum(part1, part2, salt="trailing"):
    """Returns a checksum of two strings."""

    combined_string = part1 + part2 + " " + salt if part2 != "***" else part1
    ords = [ord(x) for x in combined_string]

    checksum = ords[0]  # initial value

    # TODO: document the logic behind the checksum calculations
    iterator = zip(ords[1:], ords)
    checksum += sum(x + 2 * y if counter % 2 else x * y
                    for counter, (x, y) in enumerate(iterator))
    checksum %= NORMALIZER

    return checksum
</code>```

Which I want to test on both Python3.6 and PyPy performance-wise. I'd like to see if the function would perform better on PyPy, but I'm not completely sure, what is the most reliable and clean way to do it.

What I've tried and the Question:

Currently, I'm using timeit for both:

```<code>$ python3.6 -mtimeit -s "from test import get_checksum" "get_checksum('test1' * 100000, 'test2' * 100000)"
10 loops, best of 3: 329 msec per loop

$ pypy -mtimeit -s "from test import get_checksum" "get_checksum('test1' * 100000, 'test2' * 100000)"
10 loops, best of 3: 104 msec per loop
</code>```

My concern is I'm not absolutely sure if timeit is the right tool for the job on PyPy because of the potential JIT warmup overhead.

Plus, the PyPy itself reports the following before reporting the test results:

```<code>WARNING: timeit is a very unreliable tool. use perf or something else for real measurements
pypy -m pip install perf
pypy -m perf timeit -s 'from test import get_checksum' "get_checksum('test1' * 1000000, 'test2' * 1000000)"
</code>```

What would be the best and most accurate approach to test the same exact function performance across these and potentially other Python implementations?

答:
You could increase the number of repetitions with the --repeat parameter in order to improve timing accuracy. see:

https://docs.python.org/2/library/timeit.html

Body:
The Problem Description:

I have this custom "checksum" function:

NORMALIZER = 0x10000

def get_checksum(part1, part2, salt="trailing"):
    """Returns a checksum of two strings."""

    combined_string = part1 + part2 + " " + salt if part2 != "***" else part1
    ords = [ord(x) for x in combined_string]

    checksum = ords[0]  # initial value

    # TODO: document the logic behind the checksum calculations
    iterator = zip(ords[1:], ords)
    checksum += sum(x + 2 * y if counter % 2 else x * y
                    for counter, (x, y) in enumerate(iterator))
    checksum %= NORMALIZER

    return checksum

Which I want to test on both Python3.6 and PyPy performance-wise. I'd like to see if the function would perform better on PyPy, but I'm not completely sure, what is the most reliable and clean way to do it.

What I've tried and the Question:

Currently, I'm using timeit for both:

$ python3.6 -mtimeit -s "from test import get_checksum" "get_checksum('test1' * 100000, 'test2' * 100000)"
10 loops, best of 3: 329 msec per loop

$ pypy -mtimeit -s "from test import get_checksum" "get_checksum('test1' * 100000, 'test2' * 100000)"
10 loops, best of 3: 104 msec per loop

My concern is I'm not absolutely sure if timeit is the right tool for the job on PyPy because of the potential JIT warmup overhead.

Plus, the PyPy itself reports the following before reporting the test results:

WARNING: timeit is a very unreliable tool. use perf or something else for real measurements
pypy -m pip install perf
pypy -m perf timeit -s 'from test import get_checksum' "get_checksum('test1' * 1000000, 'test2' * 1000000)"

What would be the best and most accurate approach to test the same exact function performance across these and potentially other Python implementations?


问:
How to get subscriptionId from Stripe Charge Object?
```<code>StripeCharge charge=Stripe.Mapper<StripeCharge>.MapFromJson(evtData.Object.ToString());
</code>```

I want to get subscriptionId from this Stripe charge object?How to get that?
Thanks in advance.

答: The charge has an invoice property that contains the identifier of the invoice corresponding to the charge if any. If it's set, you can then retrieve the invoice via the API. That invoice would have the subscription property that would be the identifier of the subscription associated with that invoice and that charge.

Body:
StripeCharge charge=Stripe.Mapper<StripeCharge>.MapFromJson(evtData.Object.ToString());

I want to get subscriptionId from this Stripe charge object?How to get that?
Thanks in advance.


问:
Strange behavior of list iteration using for loop in python
I've come across a situation where my python code behaves differently in similar cases. Here's the code:

```<code>import time
def greedy_cow_transport(cows,limit=10):
    weights = []
    for weight in cows.values():
        weights.append(weight)
    weights.sort(reverse=True)
    cows_copy = cows.copy()
    all_trips = []
    while (len(weights) > 0):
        avail_weight = limit
        curr_trip = []
        for weight in weights:
            if weight <= avail_weight:
                for n, w in cows_copy.items():
                    if weight == w:
                        curr_trip.append(n)
                        weights.remove(weight)
                        cows_copy.pop(n, None)
                        avail_weight -= w
                        break
        all_trips.append(curr_trip)
    return all_trips
cows = {'Lola': 2, 'Oreo': 2, 'Millie': 2, 'Betsy': 2, 'Moo Moo': 2, 'Milkshake': 2, 'Herman': 2, 'Florence': 2, 'Maggie': 2, 'Henrietta': 2}
limit=100
print(cows)
print(greedy_cow_transport(cows))
</code>```

Instead of greedy_cow_transport returning
the 2 list of lists of 5 members, it return 3 different lists of 5 3 2 members. Please explain why its happening? I know, I might be missing some subtle detail but I need help. Can't figure out the error.
Thanks.

答:
The problem is with the loop for weight in weights:

The loop is iterating over the items in the list, but the Python loop uses the position of the item in order to do that. When you remove an item with weights.remove(weight) the list shrinks while the position increases by 1 as it normally would. Basically, because you are removing items from weights while iterating over the list, it goes over every other item—hence the different list lengths as it shrinks (you can verify this by setting all the weights equal to 1; you'll get the same results as with 2)

An example of what's going on:

```<code>list = [1, 2, 3, 4, 5]
for item in list:
    print(item)
    list.remove(item)
    print(list)

# --> 1
# --> [2, 3, 4, 5]
# --> 3
# --> [2, 4, 5]
# --> 5
# --> [2, 4]
</code>```

^^ Notice how it only iterates every other item. Precisely what is happening with your weights.

An easy fix is to have your for loop iterate over a copy, while you remove from the original:

```<code>list = [1, 2, 3, 4, 5]
for item in list.copy():
    print(item)
    list.remove(item)
    print(list)

# --> 1
# --> [2, 3, 4, 5]
# --> 2
# --> [3, 4, 5]
# --> 3
# --> [4, 5]
# --> 4
# --> [5]
# --> 5
# --> []
</code>```

WOW! Look at that work so beautifully. For your cows that would look like this:

```<code>def greedy_cow_transport(cows,limit=10):
    weights = []
    for weight in cows.values():
        weights.append(weight)
    weights.sort(reverse=True)
    cows_copy = cows.copy()
    all_trips = []
    while (len(weights) > 0):
        avail_weight = limit
        curr_trip = []
        for weight in weights.copy():
            if weight <= avail_weight:
                for n, w in cows_copy.items(): # <--!!! THE CHANGE IS HERE
                    if weight == w:
                        curr_trip.append(n)
                        weights.remove(weight)
                        cows_copy.pop(n, None)
                        avail_weight -= w
                        break
        all_trips.append(curr_trip)
    return all_trips
cows = {'Lola': 2, 'Oreo': 2, 'Millie': 2, 'Betsy': 2, 'Moo Moo': 2, 'Milkshake': 2, 'Herman': 2, 'Florence': 2, 'Maggie': 2, 'Henrietta': 2}
print(greedy_cow_transport(cows))

# --> [['Oreo', 'Milkshake', 'Herman', 'Florence', 'Lola'], ['Maggie', 'Millie', 'Henrietta', 'Betsy', 'Moo Moo']]
</code>```

And voila! Hope you enjoyed.

@ShadowRanger added that in older versions of Python, list did not have a copy method, and so an alternative to list.copy() is using an empty slice like so list[:].

Body:
I've come across a situation where my python code behaves differently in similar cases. Here's the code:

import time
def greedy_cow_transport(cows,limit=10):
    weights = []
    for weight in cows.values():
        weights.append(weight)
    weights.sort(reverse=True)
    cows_copy = cows.copy()
    all_trips = []
    while (len(weights) > 0):
        avail_weight = limit
        curr_trip = []
        for weight in weights:
            if weight <= avail_weight:
                for n, w in cows_copy.items():
                    if weight == w:
                        curr_trip.append(n)
                        weights.remove(weight)
                        cows_copy.pop(n, None)
                        avail_weight -= w
                        break
        all_trips.append(curr_trip)
    return all_trips
cows = {'Lola': 2, 'Oreo': 2, 'Millie': 2, 'Betsy': 2, 'Moo Moo': 2, 'Milkshake': 2, 'Herman': 2, 'Florence': 2, 'Maggie': 2, 'Henrietta': 2}
limit=100
print(cows)
print(greedy_cow_transport(cows))

Instead of greedy_cow_transport returning
the 2 list of lists of 5 members, it return 3 different lists of 5 3 2 members. Please explain why its happening? I know, I might be missing some subtle detail but I need help. Can't figure out the error.
Thanks.

Body:
The problem is with the loop for weight in weights:

The loop is iterating over the items in the list, but the Python loop uses the position of the item in order to do that. When you remove an item with weights.remove(weight) the list shrinks while the position increases by 1 as it normally would. Basically, because you are removing items from weights while iterating over the list, it goes over every other item—hence the different list lengths as it shrinks (you can verify this by setting all the weights equal to 1; you'll get the same results as with 2)

An example of what's going on:

list = [1, 2, 3, 4, 5]
for item in list:
    print(item)
    list.remove(item)
    print(list)

# --> 1
# --> [2, 3, 4, 5]
# --> 3
# --> [2, 4, 5]
# --> 5
# --> [2, 4]

^^ Notice how it only iterates every other item. Precisely what is happening with your weights.

An easy fix is to have your for loop iterate over a copy, while you remove from the original:

list = [1, 2, 3, 4, 5]
for item in list.copy():
    print(item)
    list.remove(item)
    print(list)

# --> 1
# --> [2, 3, 4, 5]
# --> 2
# --> [3, 4, 5]
# --> 3
# --> [4, 5]
# --> 4
# --> [5]
# --> 5
# --> []

WOW! Look at that work so beautifully. For your cows that would look like this:

def greedy_cow_transport(cows,limit=10):
    weights = []
    for weight in cows.values():
        weights.append(weight)
    weights.sort(reverse=True)
    cows_copy = cows.copy()
    all_trips = []
    while (len(weights) > 0):
        avail_weight = limit
        curr_trip = []
        for weight in weights.copy():
            if weight <= avail_weight:
                for n, w in cows_copy.items(): # <--!!! THE CHANGE IS HERE
                    if weight == w:
                        curr_trip.append(n)
                        weights.remove(weight)
                        cows_copy.pop(n, None)
                        avail_weight -= w
                        break
        all_trips.append(curr_trip)
    return all_trips
cows = {'Lola': 2, 'Oreo': 2, 'Millie': 2, 'Betsy': 2, 'Moo Moo': 2, 'Milkshake': 2, 'Herman': 2, 'Florence': 2, 'Maggie': 2, 'Henrietta': 2}
print(greedy_cow_transport(cows))

# --> [['Oreo', 'Milkshake', 'Herman', 'Florence', 'Lola'], ['Maggie', 'Millie', 'Henrietta', 'Betsy', 'Moo Moo']]

And voila! Hope you enjoyed.

@ShadowRanger added that in older versions of Python, list did not have a copy method, and so an alternative to list.copy() is using an empty slice like so list[:].


问:
Determine TLS version from established SqlConnection
In a live system, we are making multiple connections to various MSSQL servers using the SqlConnection object in C#.

As a client is in the process of updating their SQL servers to TLS 1.2, I would like to know if there is a way to determine which implementation of TLS is in use on an active connection.

I would like to achieve this entirely in C# if possible, but can use alternative languages so long as the end result is a self contained application.

The purpose of this is to provide the client with a quick test tool which will help in ensuring that the software is working correctly with TLS 1.2 on an integration environment before the changes are made to the live system.

I have spent several hours looking into this, but am so far unable to find anything helpful. All the resources I have found are aimed at ASP developers, and do not go into detail on connecting directly to the SQL server in a desktop application.

The application is using .NET 4.5, so TLS 1.2 should be available.

Many thanks

答:
You can have your C# application pull the product version with query below:

```<code>SELECT SERVERPROPERTY('ProductVersion'), SERVERPROPERTY('ProductLevel')
</code>```

Then, compare this version with minimum versions from Microsoft for each product level/version (you'll have to customize the method to check if the build version is at least as high for each level).

SQL Server release - First build that supports TLS 1.2

```<code>SQL Server 2014 SP1 - 12.0.4439.1
SQL Server 2014 SP1 GDR - 12.0.4219.0
SQL Server 2014 RTM - 12.0.2564.0
SQL Server 2014 RTM GDR - 12.0.2271.0
SQL Server 2012 SP3 GDR - 11.0.6216.27
SQL Server 2012 SP3 - 11.0.6518.0
SQL Server 2012 SP2 GDR - 11.0.5352.0
SQL Server 2012 SP2 - 11.0.5644.2
SQL Server 2008 R2 SP3 - 10.50.6542.0
SQL Server 2008 R2 SP2 GDR (IA-64 only) - 10.50.4047.0
SQL Server 2008 R2 SP2 (IA-64 only) - 10.50.4344.0
SQL Server 2008 SP4 - 10.0.6547.0
SQL Server 2008 SP3 GDR (IA-64 only) - 10.0.5545.0
SQL Server 2008 SP3 (IA-64 only) - 10.0.5896.0
</code>```

Source: https://support.microsoft.com/en-us/help/3135244/tls-1.2-support-for-microsoft-sql-server

Body:
You can have your C# application pull the product version with query below:

SELECT SERVERPROPERTY('ProductVersion'), SERVERPROPERTY('ProductLevel')

Then, compare this version with minimum versions from Microsoft for each product level/version (you'll have to customize the method to check if the build version is at least as high for each level).

SQL Server release - First build that supports TLS 1.2

SQL Server 2014 SP1 - 12.0.4439.1
SQL Server 2014 SP1 GDR - 12.0.4219.0
SQL Server 2014 RTM - 12.0.2564.0
SQL Server 2014 RTM GDR - 12.0.2271.0
SQL Server 2012 SP3 GDR - 11.0.6216.27
SQL Server 2012 SP3 - 11.0.6518.0
SQL Server 2012 SP2 GDR - 11.0.5352.0
SQL Server 2012 SP2 - 11.0.5644.2
SQL Server 2008 R2 SP3 - 10.50.6542.0
SQL Server 2008 R2 SP2 GDR (IA-64 only) - 10.50.4047.0
SQL Server 2008 R2 SP2 (IA-64 only) - 10.50.4344.0
SQL Server 2008 SP4 - 10.0.6547.0
SQL Server 2008 SP3 GDR (IA-64 only) - 10.0.5545.0
SQL Server 2008 SP3 (IA-64 only) - 10.0.5896.0

Source: https://support.microsoft.com/en-us/help/3135244/tls-1.2-support-for-microsoft-sql-server


问:
Conditional Debug on Visual C++ 2008 Express
Is there a way to debug code on Visual C++ 2008 Express, such as I can watch a variable for certain value(s) and, when it assumes this value, to break?

For instance, I want to break when xbecomes 5. In gdb I would set a breakpoint then a condition that x == 5. How can I do it (if possible) on Visual C++ 2008 Express?

答:
Lucky! Visual Studio 2010 Express of C/C++ does support it. See How to: Specify a Breakpoint Condition.

I've tried it.


问:
Prolog code to split parts of a list into consecutive even and odd parts
I've been given the following question:

Any list of integers can (uniquely) be broken into "parity runs" where each run is a (maximal) sequence of consecutive even or odd numbers within the original list. For example, the list
List = [8,0,4,3,7,2,-1,9,9]
can be broken into [8, 0, 4], [3, 7], [2] and [-1, 9, 9]
Write a predicate paruns(List, RunList) that converts a list of numbers into the corresponding list of parity runs. For example:

```<code>?- paruns([8,0,4,3,7,2,-1,9,9], RunList).
RunList = [[8, 0, 4], [3, 7], [2], [-1, 9, 9]]
</code>```

Here was the code which I tried and it seems to work with the above sample case, thanks to one suggestion, but I've got an issue where when I run paruns([8,0,4], RunList). it prints RunList = [[8,0,4],[]]. Any suggestions would be appreciated :)

```<code>paruns([],[]).
paruns([Head | Tail], [E, O | S]) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
   paruns(Last1, S).

even([Head | Tail], [], [Head | Tail]) :-
   Head mod 2 =:= 1.
even([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 0,
   even(Tail, L, Last).
even([],[],[]).

odd([Head | Tail], [], [Head, Tail]) :-
   Head mod 2 =:= 0.
odd([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 1,
   odd(Tail, L, Last).
odd([],[],[]).
</code>```

答:
A major attraction of Prolog is its relational nature. This means that we can often use a Prolog predicate in several directions, if only we stick to sufficiently general primitives.

In this concrete case, since you are reasoning over integers, I highly recommend you use your Prolog system's CLP(FD) constraints to benefit from this generality. Please see clpfd for more information about this important declarative feature.

In addition, since you are describing a list, consider using DCG notation (dcg).

Here is a relational solution for your task:

```
parity_runs([], [])     --> [].
parity_runs([E|Es], Os) --> [E], { E mod 2 #= 0 }, parity_runs(Es, Os).
parity_runs(Es, [O|Os]) --> [O], { O mod 2 #= 1 }, parity_runs(Es, Os).
```

We can use it for the test case you posted, where the list is specified:

```
?- phrase(parity_runs(Es, Os), <b>[8,0,4,3,7,2,-1,9,9]</b>).
<b>Es = [8, 0, 4, 2],
Os = [3, 7, -1, 9, 9] ;</b>
false.
```

Moreover, we can also use it in other directions. For example, suppose that the runs are known, but the list isn't:

```
?- phrase(parity_runs(<b>[2,4]</b>, <b>[1,3]</b>), Ls).
<b>Ls = [2, 4, 1, 3] ;
Ls = [2, 1, 4, 3] ;
Ls = [2, 1, 3, 4] ;
Ls = [1, 2, 4, 3] ;
Ls = [1, 2, 3, 4] ;
Ls = [1, 3, 2, 4] ;</b>
false.
```

Moreover, we can also post the most general query, where nothing is known:

```
?- phrase(parity_runs(Es, Os), Ls).
Es = Os, Os = Ls, Ls = [] ;
Es = Ls, Ls = [_2012],
Os = [],
_2012 mod 2#=0 ;
Es = Ls, Ls = [_256, _258],
Os = [],
_256 mod 2#=0,
_258 mod 2#=0 ;
Es = Ls, Ls = [_826, _832, _838],
Os = [],
_826 mod 2#=0,
_832 mod 2#=0,
_838 mod 2#=0 ;
etc.
```

To fairly enumerate answers, we can use iterative deepening:

```
?- <b>length(Ls, _)</b>, phrase(parity_runs(Es, Os), Ls).
Ls = Es, Es = Os, Os = [] ;
Ls = Es, Es = [_168],
Os = [],
_168 mod 2#=0 ;
Ls = Os, Os = [_550],
Es = [],
_550 mod 2#=1 ;
Ls = Es, Es = [_770, _776],
Os = [],
_770 mod 2#=0,
_776 mod 2#=0 ;
Ls = [_770, _776],
Es = [_770],
Os = [_776],
_770 mod 2#=0,
_776 mod 2#=1 ;
etc.
```

Body:
I've been given the following question:

Any list of integers can (uniquely) be broken into "parity runs" where each run is a (maximal) sequence of consecutive even or odd numbers within the original list. For example, the list
List = [8,0,4,3,7,2,-1,9,9]
can be broken into [8, 0, 4], [3, 7], [2] and [-1, 9, 9]
Write a predicate paruns(List, RunList) that converts a list of numbers into the corresponding list of parity runs. For example:

?- paruns([8,0,4,3,7,2,-1,9,9], RunList).
RunList = [[8, 0, 4], [3, 7], [2], [-1, 9, 9]]

Here was the code which I tried and it seems to work with the above sample case, thanks to one suggestion, but I've got an issue where when I run paruns([8,0,4], RunList). it prints RunList = [[8,0,4],[]]. Any suggestions would be appreciated :)

paruns([],[]).
paruns([Head | Tail], [E, O | S]) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
   paruns(Last1, S).

even([Head | Tail], [], [Head | Tail]) :-
   Head mod 2 =:= 1.
even([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 0,
   even(Tail, L, Last).
even([],[],[]).

odd([Head | Tail], [], [Head, Tail]) :-
   Head mod 2 =:= 0.
odd([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 1,
   odd(Tail, L, Last).
odd([],[],[]).

Body:
A major attraction of Prolog is its relational nature. This means that we can often use a Prolog predicate in several directions, if only we stick to sufficiently general primitives.

In this concrete case, since you are reasoning over integers, I highly recommend you use your Prolog system's CLP(FD) constraints to benefit from this generality. Please see clpfd for more information about this important declarative feature.

In addition, since you are describing a list, consider using DCG notation (dcg).

Here is a relational solution for your task:

parity_runs([], [])     --> [].
parity_runs([E|Es], Os) --> [E], { E mod 2 #= 0 }, parity_runs(Es, Os).
parity_runs(Es, [O|Os]) --> [O], { O mod 2 #= 1 }, parity_runs(Es, Os).

We can use it for the test case you posted, where the list is specified:

?- phrase(parity_runs(Es, Os), [8,0,4,3,7,2,-1,9,9]).
Es = [8, 0, 4, 2],
Os = [3, 7, -1, 9, 9] ;
false.

Moreover, we can also use it in other directions. For example, suppose that the runs are known, but the list isn't:

?- phrase(parity_runs([2,4], [1,3]), Ls).
Ls = [2, 4, 1, 3] ;
Ls = [2, 1, 4, 3] ;
Ls = [2, 1, 3, 4] ;
Ls = [1, 2, 4, 3] ;
Ls = [1, 2, 3, 4] ;
Ls = [1, 3, 2, 4] ;
false.

Moreover, we can also post the most general query, where nothing is known:

?- phrase(parity_runs(Es, Os), Ls).
Es = Os, Os = Ls, Ls = [] ;
Es = Ls, Ls = [_2012],
Os = [],
_2012 mod 2#=0 ;
Es = Ls, Ls = [_256, _258],
Os = [],
_256 mod 2#=0,
_258 mod 2#=0 ;
Es = Ls, Ls = [_826, _832, _838],
Os = [],
_826 mod 2#=0,
_832 mod 2#=0,
_838 mod 2#=0 ;
etc.

To fairly enumerate answers, we can use iterative deepening:

?- length(Ls, _), phrase(parity_runs(Es, Os), Ls).
Ls = Es, Es = Os, Os = [] ;
Ls = Es, Es = [_168],
Os = [],
_168 mod 2#=0 ;
Ls = Os, Os = [_550],
Es = [],
_550 mod 2#=1 ;
Ls = Es, Es = [_770, _776],
Os = [],
_770 mod 2#=0,
_776 mod 2#=0 ;
Ls = [_770, _776],
Es = [_770],
Os = [_776],
_770 mod 2#=0,
_776 mod 2#=1 ;
etc.


问:
Update model according to database changes
I have an array filled with objects , queried from a database and this array is displayed as a table to the user.

The user wants to delete 1 item so the server receives the request from the client and updates the database accordingly.

Question : How should I update the user's view ?
should I requery the Database again and select everything from it and reasign it to my model or should I do a fast array.remove(element) ?

Which one is the preferred method ?

答:
You should wait to see if the db query (the delete) ran correctly and then remove the item from the array.

The only reason to do another select, is if you want to check for any modifications in the db.


问:
drag and drop picturebox
I am coding a simple solitaire game just for fun and a bit of practice but do not know how to drag and drop a card in a specified position.
The card itself was set as an image in a picturebox and I guess what I want to do is to drag this picturebox and drop it in a specified position at another picturebox location.

Any advice perhaps.

Kind regards

答:
Just add:

```<code>myPixtureBox.AllowDrop = true;
</code>```

Note: This is not available at design time.

https://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.allowdrop(v=vs.110).aspx

Title: drag and drop picturebox

Body:
Just add:

myPixtureBox.AllowDrop = true;

Note: This is not available at design time.

https://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.allowdrop(v=vs.110).aspx


问:
Standard or Legacy SQL for Google Analytics Data in BigQuery?
we are just starting to use Google Analytics data in BigQuery and previously used just the MSSQL Server in the work environment. We would like to move some of the analysis to the GCP and BigQuery, but could not decide on what is the better option to use - standard or legacy SQL?<br>
In both cases we would have to adjust to the new language version, but the real question is what is the best choice when it comes to Google Analytics data analysis? Is there something that from the technical point of view should make us choose legacy over standard, or the other way around?
It is very misleading for us that there are two versions, because legacy seems to be more developed now, but perphaps standard will be the main version for SQL in the future in BQ? </p>

答:
BigQuery Standard SQL is the way to go. It has much more features than Legacy SQL.

Note: it is not binary choice. You always can use Legacy SQL - if there is something that you will find easier to express with it. From my experience it is mostly opposite - with very few exceptions. Most prominent (for me for example being) - Table Decorators - Support for table decorators in standard SQL is planned but not yet implemented.

I would recommend looking into Migrating from legacy SQL - not from migration point of view as you are the new to BigQuery  - but because it is a good place to see and compare features of both dialects in one place.

Also I recommend to check BigQuery Issue Tracker so you can get some extra insight

Body:
we are just starting to use Google Analytics data in BigQuery and previously used just the MSSQL Server in the work environment. We would like to move some of the analysis to the GCP and BigQuery, but could not decide on what is the better option to use - standard or legacy SQL?

In both cases we would have to adjust to the new language version, but the real question is what is the best choice when it comes to Google Analytics data analysis? Is there something that from the technical point of view should make us choose legacy over standard, or the other way around?
It is very misleading for us that there are two versions, because legacy seems to be more developed now, but perphaps standard will be the main version for SQL in the future in BQ?


问:
How to update variable in the JS file from a child aspx page
I have a JS file with below code. I need to update the value of variable currentIndex from my child aspx page. Right now this js refrence is over a parent page. I would like to know how to do it. What syntax should be passed from child.aspx page to have the updated value of currentIndex everywhere.

```<code>(function($, global, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...
</code>```

答:
You could expose a function that will modify the currentIndex variable to global scope. But this approach does not scale well and should be considered as bad practice, because it could cause name clashes and other downsides. How to avoid global variables in JavaScript?. So if you need to access parent page from child iframes you should think of better approach like communication through messages https://stackoverflow.com/a/41566923/2138959 or similar custom implementation.

For the time being the easiest way to solve your problem to define a setter function that will update currentIndex variable:

```<code>(function($, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  window.setCurrentIndex = function(indexValue) {
    currentIndex = indexValue;
  };

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...
</code>```

And if you want to set index to value 3 for instance you could do:

```<code>window.setCurrentIndex(3);
</code>```

Body:
I have a JS file with below code. I need to update the value of variable currentIndex from my child aspx page. Right now this js refrence is over a parent page. I would like to know how to do it. What syntax should be passed from child.aspx page to have the updated value of currentIndex everywhere.

(function($, global, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...

Body:
You could expose a function that will modify the currentIndex variable to global scope. But this approach does not scale well and should be considered as bad practice, because it could cause name clashes and other downsides. How to avoid global variables in JavaScript?. So if you need to access parent page from child iframes you should think of better approach like communication through messages https://stackoverflow.com/a/41566923/2138959 or similar custom implementation.

For the time being the easiest way to solve your problem to define a setter function that will update currentIndex variable:

(function($, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  window.setCurrentIndex = function(indexValue) {
    currentIndex = indexValue;
  };

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...

And if you want to set index to value 3 for instance you could do:

window.setCurrentIndex(3);


问:
What is the meaning of angle brackets in Python?
I found the following lines in the scikit-learn package:

```<code>if is_sparse:
    problem = csr_set_problem(
            (<np.ndarray[np.float64_t, ndim=1, mode='c']>X.data).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).data,
            Y.data, (<np.int32_t>X.shape[1]), bias,
            sample_weight.data)
else:
    ...
</code>```

All my searches for "angle brackets in Python" give answers about documentation or decorator syntax, which I am pretty sure this is neither because it looks like actual logic.

What do the angle brackets in the above Python code do and where can I learn more about them?

答:
Take a look at Cython documentation, about types.

Additionally you could note that the file extension is .pyx and on the top of the file there are cimport statements.

Body:
I found the following lines in the scikit-learn package:

if is_sparse:
    problem = csr_set_problem(
            (<np.ndarray[np.float64_t, ndim=1, mode='c']>X.data).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indices).data,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).shape,
            (<np.ndarray[np.int32_t,   ndim=1, mode='c']>X.indptr).data,
            Y.data, (<np.int32_t>X.shape[1]), bias,
            sample_weight.data)
else:
    ...

All my searches for "angle brackets in Python" give answers about documentation or decorator syntax, which I am pretty sure this is neither because it looks like actual logic.

What do the angle brackets in the above Python code do and where can I learn more about them?


问:
How to setup a unique click listener for every  tag in a table data
My table has many columns with images as data. I was able to setup a 'common listener' for all of the images in a table row so that when i click any image , the same listener is called.

```<code> $('#mytable tbody td img').click(function () {
 // handle event here...
 }
</code>```

How do i have unique listeners for each img in the table row ? Do i use the id tag ?

答:
Hello,

The best option is to even put an id in each image
and in your onclick use the id to differentiate the images.

Here is an example

```<code><img src="src_image" id="id_image">
</code>```

```<code>$('#mytable tbody td img').click(function () {
    console.log(this.id);
});
</code>```

I hope I have helped!

Title: How to setup a unique click listener for every <img> tag in a table data

Body:
My table has many columns with images as data. I was able to setup a 'common listener' for all of the images in a table row so that when i click any image , the same listener is called.

 $('#mytable tbody td img').click(function () {
 // handle event here...
 }

How do i have unique listeners for each img in the table row ? Do i use the id tag ?

Body:
Hello,

The best option is to even put an id in each image
and in your onclick use the id to differentiate the images.

Here is an example

<img src="src_image" id="id_image">

$('#mytable tbody td img').click(function () {
    console.log(this.id);
});

I hope I have helped!


问:
delete nth row from table (postgresql)
I know its possible to select nth row.

For example

```<code>select from table limit 1 offset 3;
</code>```

Is it possible to delete nth row?

答:
If you have an id and something to order by and/or partition by you can delete using row_number() like so:

```<code>drop table if exists t;
create table t (id int, val int);
insert into t values (1,9),(2,8),(3,7),(4,6),(5,5);

delete
from t
where id in (
  select id
  from (
    select id, row_number() over (order by val asc) as rn
    from t
    ) s
  where s.rn = 3);

select * from t;
</code>```

rextester demo: http://rextester.com/XJHB50704

returns:

```<code>+----+-----+
| id | val |
+----+-----+
|  1 |   9 |
|  2 |   8 |
|  4 |   6 |
|  5 |   5 |
+----+-----+
</code>```

Title: delete nth row from table (postgresql)

Body:
I know its possible to select nth row.

For example

select from table limit 1 offset 3;

Is it possible to delete nth row?

Body:
If you have an id and something to order by and/or partition by you can delete using row_number() like so:

drop table if exists t;
create table t (id int, val int);
insert into t values (1,9),(2,8),(3,7),(4,6),(5,5);

delete
from t
where id in (
  select id
  from (
    select id, row_number() over (order by val asc) as rn
    from t
    ) s
  where s.rn = 3);

select * from t;

rextester demo: http://rextester.com/XJHB50704

returns:

+----+-----+
| id | val |
+----+-----+
|  1 |   9 |
|  2 |   8 |
|  4 |   6 |
|  5 |   5 |
+----+-----+


问:
Why does the line number of the source code not match when debugging on the device
Why the line number of the source code does not match when debugging on the device. The version API23 of the source code corresponds to the version of the android 6.0.1 installed on the phone.
My application writes to own error-log information about exceptions and the call stack. I see an entry in the log that the function in line 466 has raised an exception. I run the debugger and I see that this function is in another line. What it means and whether it is possible to correct the situation? </p>

```<code>Stack call[ver:1.2.116]:android.database.AbstractCursor.checkPosition(AbstractCursor.java:466)  Wrong line number!!!! In source code is line 460
Stack call[ver:1.2.116]:android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
Stack call[ver:1.2.116]:android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:44)
Stack call[ver:1.2.116]:**.***********.************.DataEngine$Photo.getPhotoBody(DataEngine.java:982)
Stack call[ver:1.2.116]:**.***********.************.services.IntentServicePhotoByReportUpload.Job(IntentServicePhotoByReportUpload.java:149)
Stack call[ver:1.2.116]:**.***********.************.services.IntentServicePhotoByReportUpload.onHandleIntent(IntentServicePhotoByReportUpload.java:84)
Stack call[ver:1.2.116]:android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
Stack call[ver:1.2.116]:android.os.Handler.dispatchMessage(Handler.java:102)
Stack call[ver:1.2.116]:android.os.Looper.loop(Looper.java:148)
Stack call[ver:1.2.116]:android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

答:
It just means that the source code you have does not match with the code running on the device. This can be because of manufacturer changes, hot-fixes and so on.

I don't think there's any good way around it unless you can get your hands on the exact version of the source that the device is running.

Body:
Why the line number of the source code does not match when debugging on the device. The version API23 of the source code corresponds to the version of the android 6.0.1 installed on the phone.
My application writes to own error-log information about exceptions and the call stack. I see an entry in the log that the function in line 466 has raised an exception. I run the debugger and I see that this function is in another line. What it means and whether it is possible to correct the situation?

Stack call[ver:1.2.116]:android.database.AbstractCursor.checkPosition(AbstractCursor.java:466)  Wrong line number!!!! In source code is line 460
Stack call[ver:1.2.116]:android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
Stack call[ver:1.2.116]:android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:44)
Stack call[ver:1.2.116]:**.***********.************.DataEngine$Photo.getPhotoBody(DataEngine.java:982)
Stack call[ver:1.2.116]:**.***********.************.services.IntentServicePhotoByReportUpload.Job(IntentServicePhotoByReportUpload.java:149)
Stack call[ver:1.2.116]:**.***********.************.services.IntentServicePhotoByReportUpload.onHandleIntent(IntentServicePhotoByReportUpload.java:84)
Stack call[ver:1.2.116]:android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
Stack call[ver:1.2.116]:android.os.Handler.dispatchMessage(Handler.java:102)
Stack call[ver:1.2.116]:android.os.Looper.loop(Looper.java:148)
Stack call[ver:1.2.116]:android.os.HandlerThread.run(HandlerThread.java:61)


问:
SQL DB schema best practice for List item table
I have a table say Table1 which has following columns

```<code>1. Id
2. Name
3. TransportModeId
4. ParkingId
5. ActivityId
</code>```

Column 3,4,5 are the foreign keys and all three are simple list tables which has following columns

```<code>1. Id
2. Item
</code>```

For simplicity I have shown 3 tables otherwise my actual schema contains almost 25 List table.

What should be the best Practice

Option 1.
Keep all list table separate which will create 25 tables but on the other hand i will have a clean modular schema

Option 2.
Make a table with self join and add all the items in that table in which ParentId null will represent the name of the table and it can have more than one references in other tables as described above and it has to be kept in some kind of common module

thanks

答:
Option 1 is the way how it is normally done when designing a system that is not supposed to be very configurable by end user/implementator. It has several important advantages, two of them:

when you need to add an extra attribute to any of the enumerations (e.g. parking location to the Parking enumeration), it is quite simple and does not produce extra problems.

It is optimized for speed using relation database engine's native algorithms for linking records.

As for Option 2:
It is something called Generalization. You take more types with similar attributes (methods) and create a class/table with a structure that fits different purposes.

The self reference, as you speak about it, is not a good idea for Option 2, rather make a reference to another EnumerationType table containing type names like Parking, Activity etc. with id.

Using this approach could make sense in case you need to enable end user to configure the attributes himself within your app. But otherwise it could cause you problems when you find out, that different enumeration tables need to have different structures.

Body:
I have a table say Table1 which has following columns

1. Id
2. Name
3. TransportModeId
4. ParkingId
5. ActivityId

Column 3,4,5 are the foreign keys and all three are simple list tables which has following columns

1. Id
2. Item

For simplicity I have shown 3 tables otherwise my actual schema contains almost 25 List table.

What should be the best Practice

Option 1.
Keep all list table separate which will create 25 tables but on the other hand i will have a clean modular schema

Option 2.
Make a table with self join and add all the items in that table in which ParentId null will represent the name of the table and it can have more than one references in other tables as described above and it has to be kept in some kind of common module

thanks