问:
Extra white space on SlidingTabLayout bar in Android 7.0 N?
Just upgraded to Android 7.0 and all my SlidingTabLayout bars now have extra white space on the bottom. Not sure if this is intended by the Android team or not, but is there anyway of getting rid of the new white space?

I am using code provided by Android which can be found here:

Sliding Tab Layout: https://developer.android.com/samples/BasicTransition/src/com.example.android.common/view/SlidingTabLayout.html

Sliding Tab Strip:
https://developer.android.com/samples/BasicTransition/src/com.example.android.common/view/SlidingTabStrip.html

Here is a snippet of my layout code:

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/tool_bar"
        android:layout_height="56dp"
        android:layout_width="match_parent"
        android:background="@drawable/toolbar_gradient"
        app:layout_scrollFlags="scroll|enterAlways"
        android:theme="@style/Base.ThemeOverlay.AppCompat.Dark" />

    <com.airsenze.wineinsider.controllers.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"/>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent">
</android.support.v4.view.ViewPager>
</code>```

Thanks! Let me know if you need anymore information.

答:
You should set max lines to 1 to tab's TextView.

There are two ways:

1. Change SlidingTabLayout:

```<code>protected TextView createDefaultTabView(Context context) {
    TextView textView = new TextView(context);
    textView.setMaxLines(1);
    ...
}
</code>```

2. Use custom tab layout

For example:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="?selectableItemBackground"
              android:gravity="center_horizontal"
              android:orientation="vertical"
              android:paddingBottom="8dp"
              android:paddingTop="8dp">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="true"
        android:textColor="@color/text_tab"
        android:maxLines="1" <=============attention==============
        android:textSize="12dp"
        android:textStyle="bold"/>

</LinearLayout>
</code>```

Body:
Just upgraded to Android 7.0 and all my SlidingTabLayout bars now have extra white space on the bottom. Not sure if this is intended by the Android team or not, but is there anyway of getting rid of the new white space?

I am using code provided by Android which can be found here:

Sliding Tab Layout: https://developer.android.com/samples/BasicTransition/src/com.example.android.common/view/SlidingTabLayout.html

Sliding Tab Strip:
https://developer.android.com/samples/BasicTransition/src/com.example.android.common/view/SlidingTabStrip.html

Here is a snippet of my layout code:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/tool_bar"
        android:layout_height="56dp"
        android:layout_width="match_parent"
        android:background="@drawable/toolbar_gradient"
        app:layout_scrollFlags="scroll|enterAlways"
        android:theme="@style/Base.ThemeOverlay.AppCompat.Dark" />

    <com.airsenze.wineinsider.controllers.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"/>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent">
</android.support.v4.view.ViewPager>

Thanks! Let me know if you need anymore information.

Body:
You should set max lines to 1 to tab's TextView.

There are two ways:

1. Change SlidingTabLayout:

protected TextView createDefaultTabView(Context context) {
    TextView textView = new TextView(context);
    textView.setMaxLines(1);
    ...
}

2. Use custom tab layout

For example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="?selectableItemBackground"
              android:gravity="center_horizontal"
              android:orientation="vertical"
              android:paddingBottom="8dp"
              android:paddingTop="8dp">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="true"
        android:textColor="@color/text_tab"
        android:maxLines="1" <=============attention==============
        android:textSize="12dp"
        android:textStyle="bold"/>

</LinearLayout>


来源: stackexchange

问:
How to not restart IIS every time I make changes to code?
I have my web application running. And every time I change some little peace of logic code I need to stop the app and wait for IIS to restart entirely.

Somewhere in the web I saw some guy saying that one of cool features of MVC5 (or maybe MVC6 on ASP.NET Core) that you can make changes "on the fly".

So can I not stop and restart IIS every time, or I just misunderstood something?

答: It depends on how the ASP.NET Core app is deployed. Essentially, its ability to make changes on the fly is owed to it being able to be deployed as just plain code, rather than as a compiled application. The web server essentially compiles it on the fly. However, for that to happen, you need to be using a web server than actually can compile it on the fly. IIS cannot. However, IIS can act as a reverse proxy for Kestrel, and Kestrel can compile on the fly. If you deploy the app in the traditional "compile and publish directly to IIS application directory" approach, then you will not benefit from this.</p>

ContentLicense: CC BY-SA 3.0


问:
Python indexing for central differencing
I have a question about python indexing: I am trying to use central differencing to estimate 'dU' from an array 'U' and I'm doing this by initialising 'dU' with an array of 'nan' of length(U) and then applying central differencing such that dU(i) = (U(i+1) - U(i-1))/2 to the central elements. The output 'dU' array is currently giving me two 'nan' entries at the end of the vector. Can anyone explain why the second to last element isn't being updated?</p>

```<code>import numpy as np
U= np.array([1,2,3,4,5,6])
dU = np.zeros(len(U))
dU[:] = np.NAN
dU[1:-2] = (U[2:-1]-U[0:-3])/2

>>> dU
array([ nan,   1.,   1.,   1.,  nan,  nan])
</code>```

答:
Doesn't answer your question, but as a helpful tip, you can just use numpy.gradient

```<code>>>> np.gradient(np.array([1,2,3,4,5,6]))
>>> array([ 1.,  1.,  1.,  1.,  1.,  1.])
</code>```

Body:
I have a question about python indexing: I am trying to use central differencing to estimate 'dU' from an array 'U' and I'm doing this by initialising 'dU' with an array of 'nan' of length(U) and then applying central differencing such that dU(i) = (U(i+1) - U(i-1))/2 to the central elements. The output 'dU' array is currently giving me two 'nan' entries at the end of the vector. Can anyone explain why the second to last element isn't being updated?

import numpy as np
U= np.array([1,2,3,4,5,6])
dU = np.zeros(len(U))
dU[:] = np.NAN
dU[1:-2] = (U[2:-1]-U[0:-3])/2

>>> dU
array([ nan,   1.,   1.,   1.,  nan,  nan])

Body:
Doesn't answer your question, but as a helpful tip, you can just use numpy.gradient

>>> np.gradient(np.array([1,2,3,4,5,6]))
>>> array([ 1.,  1.,  1.,  1.,  1.,  1.])


问:
regex select not commented statements
```<code>echo '```'; print_r(1); echo '```';  <- select this

 echo '```'; print_r($temp); echo '```';  <- select this without space

// echo '```'; print_r($temp); echo '```';  <- skip this

echo '```'; print_r($temp3); echo '```';  <- select this

print_r($temp1);  <- select this

// print_r($temp11);  <- skip this

    print_r($temp2);  <- select this without spaces

    if (true) {
        print_r($temp4);  <- select this without spaces

    }
</code>```

I have a code with print statements I need to select only non commented statements

here is a regex

```<code>^((?!\/\/\s?))(echo '```';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?
```

DEMO

how to skip spaces ?'      print_r($temp4);'
or how can I change regex to make it work ?

Title: regex select not commented statements

Body:
echo '
'; print_r(1); echo '
';  <- select this

 echo '
'; print_r($temp); echo '
';  <- select this without space

// echo '
'; print_r($temp); echo '
';  <- skip this

echo '
'; print_r($temp3); echo '
';  <- select this

print_r($temp1);  <- select this

// print_r($temp11);  <- skip this

    print_r($temp2);  <- select this without spaces

    if (true) {
        print_r($temp4);  <- select this without spaces

    }

I have a code with print statements I need to select only non commented statements

here is a regex

^((?!\/\/\s?))(echo '
';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?

DEMO

how to skip spaces ?'      print_r($temp4);'
or how can I change regex to make it work ?

Body:
Perhaps like this:

^(?!\/\/) *(echo '<pre>';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?


问:
Common libraries in a large team
Assume you have five products, and all of them use one or more of the company's internal libraries, written by individual developers.

It sounds simple but in practice, I found it to be very difficult to maintain.

How do you deal with the following scenarios:

A developer unintentionally introduces a bug and breaks everything in production.

Every library has to mature, That means the API needs to evolve, so how do you deploy the updated version to production if every developer needs to update/test their code while they are extremely busy on other projects? Is this a resource and time issue?

Version control, deployment,and usage. Would you store this in one global location or force each project to use, say, svn:externals to "tie" a library?

I've found that it is extremely hard to come up with a good strategy. My own pet theory is this:

Each common library has to have a super-thorough set of tests or else it should never be common, even if it means someone else duplicates the effort. Duplicate untested code is better than common untested code (you break only one project).

Each common library has to have a dedicated maintainer (can be offset by a really good test suite in a smaller team).

Each project should check out the version of the library that is known to work with it. This means a developer does not have to get pulled away to update API usage, as the common code gets updated. Which it will be. Every non-trivial piece of code evolves over months and years.

Thank you for your thoughts on this!

答:
Duplication is the root of all evil

I would argue that unchecked government is the root of all evil :)

I do get a lot of flack for even suggesting that duplication should be an option. I understand why, but let me complicate this a bit.

Say you have a fairly large library that doesn't actually do anything in particular - it's just a collection of utilities. There are NO tests for this library - at all. You need only one function from it. Say, something that parses out a file's extension.

Pop quiz: do you just write something as small as this in your own project, or you bite the bullet and use the free-for-all untested set of utilities, which WILL break your application if someone breaks the function?

Also, imagine you are in environment where writing tests is not part of the culture, since most projects are very intense and have a very short development span.

Duplicating large systems - such as client registration - would be dumb beyond belief, of course. However, aren't there any cases where it is safer to duplicate something fairly small in your project if the alternative is not safe enough (no system for maintaining common code).

Think of it this way - and this happens all the time - multiple contractors working on different projects, for the same company. They don't even know about each other.

My argument is this:

If a team cannot dedicate to maintaining a solid common codebase, or if the environment does not give them enough time to, it's best to let them work as separate "contractors".

You will STILL need to use large existing systems that simply cannot be duplicated.

OwnerDisplayName: Andrei

ContentLicense: CC BY-SA 2.5

Title: Common libraries in a large team

LastEditorDisplayName: Roger Lipscombe

LastEditorDisplayName: Andrei Taranchenko


问:
How to disable Liferay portlet cache?
I am developing a portlet for Liferay Portal.

I have disabled CSS and JavaScript caching by using these codes in portal-developer.properties file:

```
theme.css.fast.load=false
theme.images.fast.load=false
javascript.fast.load=false
javascript.log.enabled=true
layout.template.cache.enabled=false
last.modified.check=false
velocity.engine.resource.manager.cache.enabled=false
com.liferay.portal.servlet.filters.cache.CacheFilter=false
com.liferay.portal.servlet.filters.layoutcache.LayoutCacheFilter=false
```

But I don't know how to disable portlet caching.

When I update view.jsp file in my portlet directory I have to restart Tomcat to see changes.

答:
Why do you restart tomcat. Simply deploy your portlet into deploy directory. It's fastest.
And if you run the Liferay from Eclipse IDE I think the changes are picked up automatically.</p>

Title: How to disable Liferay portlet cache?

Body:
I am developing a portlet for Liferay Portal.

I have disabled CSS and JavaScript caching by using these codes in portal-developer.properties file:

theme.css.fast.load=false
theme.images.fast.load=false
javascript.fast.load=false
javascript.log.enabled=true
layout.template.cache.enabled=false
last.modified.check=false
velocity.engine.resource.manager.cache.enabled=false
com.liferay.portal.servlet.filters.cache.CacheFilter=false
com.liferay.portal.servlet.filters.layoutcache.LayoutCacheFilter=false

But I don't know how to disable portlet caching.

When I update view.jsp file in my portlet directory I have to restart Tomcat to see changes.


问:
C# reflection and instantiation - is there a way to do Activator.CreateInstance(myType){ X = x }?
I'm not sure of the terminology for this kind of code, but I want to know if it's possible to instantiate variables after the parentheses, but whilst using reflection.

I have a map which gets loaded from an XML file. This is a collection of (int X, int Y, string S) where the X,Y is the position of some terrain, and S is a string representing the type of the terrain. I have a dictionary to pass between the strings and the relevant types; for example one key-value pair might be "Tree", typeof(Tree).

When using reflection, although I know it's possible to instantiate with parameters, the only way I'm comfortable is just by using Activator.CreateInstance(Type t), i.e. with an empty constructor.

When I had the maps hard coded, I would originally instantiate like this (within some i,j for loop):

```<code>case: "Tree"
 world.Add( new Tree(i,j) );
</code>```

Whilst starting to think about reflection and my save file, I changed this to:

```<code>world.Add( new Tree() { X = i, Y = j }
</code>```

However, I realised that this won't work with reflection, so I am having to do the following (Tree inherits from Terrain, and the dictionary just converts the XML save data string to a type):

```<code>Type type = dictionary[dataItem.typeAsString];
Terrain t = (Terrain)Activator.CreateInstance(type);
t.X = i;
t.Y = j;
world.Add(t);
</code>```

I would prefer to do this using something like

```<code>Type type = dictionary[dataItem.typeAsString];
world.Add((Terrain)Activator.CreateInstance(type) { X = i, Y = j }
</code>```

Is there any shortcut like this? I guess if not I could edit world.Add to take an X and Y and cast to Terrain in there to access those variables, but I am still curious as to a) what this {var1 = X, var2 = Y} programming is called, and b) whether something similar exists when using reflection.

答:
```<code>public sealed class ReflectionUtils
    {

        public static T ObjectInitializer<T>(Action<T> initialize)
        {
            var result = Activator.CreateInstance<T>();
            initialize(result);
            return result;
        }
    }

public class MyModel
{
    public string Name{get;set;}
}
</code>```

And after that just make the call :

```<code>var myModel = ReflectionUtils.ObjectInitializer<MyModel>(m =>
   {
     m.Name = "Asdf"
   });
</code>```

The advantage is that in this way you will have type safety and use reflection as minimum required, because we all know that reflection is an expensive operation that should be avoided as much as possible.

Body:
I'm not sure of the terminology for this kind of code, but I want to know if it's possible to instantiate variables after the parentheses, but whilst using reflection.

I have a map which gets loaded from an XML file. This is a collection of (int X, int Y, string S) where the X,Y is the position of some terrain, and S is a string representing the type of the terrain. I have a dictionary to pass between the strings and the relevant types; for example one key-value pair might be "Tree", typeof(Tree).

When using reflection, although I know it's possible to instantiate with parameters, the only way I'm comfortable is just by using Activator.CreateInstance(Type t), i.e. with an empty constructor.

When I had the maps hard coded, I would originally instantiate like this (within some i,j for loop):

case: "Tree"
 world.Add( new Tree(i,j) );

Whilst starting to think about reflection and my save file, I changed this to:

world.Add( new Tree() { X = i, Y = j }

However, I realised that this won't work with reflection, so I am having to do the following (Tree inherits from Terrain, and the dictionary just converts the XML save data string to a type):

Type type = dictionary[dataItem.typeAsString];
Terrain t = (Terrain)Activator.CreateInstance(type);
t.X = i;
t.Y = j;
world.Add(t);

I would prefer to do this using something like

Type type = dictionary[dataItem.typeAsString];
world.Add((Terrain)Activator.CreateInstance(type) { X = i, Y = j }

Is there any shortcut like this? I guess if not I could edit world.Add to take an X and Y and cast to Terrain in there to access those variables, but I am still curious as to a) what this {var1 = X, var2 = Y} programming is called, and b) whether something similar exists when using reflection.

Body:
public sealed class ReflectionUtils
    {

        public static T ObjectInitializer<T>(Action<T> initialize)
        {
            var result = Activator.CreateInstance<T>();
            initialize(result);
            return result;
        }
    }

public class MyModel
{
    public string Name{get;set;}
}

And after that just make the call :

var myModel = ReflectionUtils.ObjectInitializer<MyModel>(m =>
   {
     m.Name = "Asdf"
   });

The advantage is that in this way you will have type safety and use reflection as minimum required, because we all know that reflection is an expensive operation that should be avoided as much as possible.


问:
how to make dots inherit the width of the image? (slick)
There is a block 225px. Inside you insert a picture large size (850px). And she goes outside.

It looks like this:

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
}

.single-slide img {
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
    <div class="column">
      <div class="slider single-slide">
        <div><img src='https://s-media-cache-ak0.pinimg.com/736x/2c/d0/19/2cd0197c5eb8c1f84e81734f97e80cd3.jpg' /></div>
        <div>to place the center of the image</div>
      </div>
    </div>
  </div></code>```

Using slick slider. I want to add dots to control the slider.

When I add the dots they are placed in the middle of the block. It's okay, I understand. But I want to place them in the center of the picture. How to do it?

UPD: The image goes beyond the block, that's right! And I need to do to the dots were at the center of the image, not the block

答:
I see that your dots are in the center of the window.
To do this, your dots list must be inside a container with the image's width.

I think you should enlarge your slider or limit image's width with a max-width: 100%;

Body:
There is a block 225px. Inside you insert a picture large size (850px). And she goes outside.

It looks like this:

.content {display: inline-block;}

.column {float:right; width:225px;}

.slider {
  border: 1px solid;
  width: 220px;
  padding: 5px;
}

.single-slide img {
  width: auto;
}

to place the center of the image

Using slick slider. I want to add dots to control the slider.

When I add the dots they are placed in the middle of the block. It's okay, I understand. But I want to place them in the center of the picture. How to do it?

UPD: The image goes beyond the block, that's right! And I need to do to the dots were at the center of the image, not the block


问:
Ionic framework : position absolute with bottom in % doesn't work
I am trying to position a
 absolutely using bottom=50% in an AngularJS/Ionic page as follows:

HTML:

```<code><ion-view title="BoardLine">
  <ion-nav-buttons side="left">
    <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
  </ion-nav-buttons>
  <ion-content class="has-header">

        <div id="imagecontainer">
            <img id="boardimage" ng-src="{{mainResultImagePath}}" />
            <div id="photocredits" class="rotateimagecredits">
                Image courtesy: {{computed.prophotocredits}}</div>
            </div>
....
</code>```

CSS:

```<code>#imagecontainer {
    position:absolute;
    top:3%;
    left:0;
    right:62%;
    bottom:50%;
}
#boardimage {
    position:absolute;
    left:10%;
    max-width:85%;
    bottom:0;
    height:100%;
}
</code>```

But just before div id="imagecontainer", Ionic generates a div class="scroll",like below, which has a height of 20px. And the top and bottom css for my imagecontainer refers to this height, but the div class="scroll"  has a position:static. Therefore my imagecontainer absolute positioning should refer to the first parent that has a non-static position
which should be the <ion-content>

```<code><ion-content class="scroll-content ionic-scroll  has-header">
    <div class="scroll" style="-webkit-transform: translate3d(0px, 0px, 0px) scale(1);">
        <div id="imagecontainer">
            <img id="boardimage" ng-src="./img/boards/SD360.jpg" src="./img/boards/SD360.jpg">
            <div id="photocredits" class="rotateimagecredits ng-binding">Image courtesy: john carper</div>
        </div>
</code>```

答:
The footer component of ionic is fixed regarding the screen, I think you can try to implement an equivalent one. More info about the footer:  http://ionicframework.com/docs/v1/components/#footer

The main css-properties of the element are:

```<code>    .bar-footer {
        bottom: 0;
        height: 44px;
    }
    .bar {
        display: flex;
        user-select: none;
        position: absolute;
        right: 0;
        left: 0;
        z-index: 9;
        width: 100%;
        height: 44px;
     }
</code>```

Modify the above properties with your specific ones (eg. bottom: 50%;) and ensure display is set as absolute.

Considering your parent's positionning issues, you should try to put your piece of code outside <ion-content></ion-content>, inside <ion-view></ion-view>.

It's the only way I succesfully set a button positioned as absolute within ionic mobile framework.

EDIT: /!\ Be careful not to write anything out of <ion-view></ion-view>. My previous answer was creating trouble in the way ionic manages the different pages.

Body:
I am trying to position a
 absolutely using bottom=50% in an AngularJS/Ionic page as follows:

HTML:

<ion-view title="BoardLine">
  <ion-nav-buttons side="left">
    <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
  </ion-nav-buttons>
  <ion-content class="has-header">

                Image courtesy: {{computed.prophotocredits}}

....

CSS:

#imagecontainer {
    position:absolute;
    top:3%;
    left:0;
    right:62%;
    bottom:50%;
}
#boardimage {
    position:absolute;
    left:10%;
    max-width:85%;
    bottom:0;
    height:100%;
}

But just before div id="imagecontainer", Ionic generates a div class="scroll",like below, which has a height of 20px. And the top and bottom css for my imagecontainer refers to this height, but the div class="scroll"  has a position:static. Therefore my imagecontainer absolute positioning should refer to the first parent that has a non-static position
which should be the <ion-content>

<ion-content class="scroll-content ionic-scroll  has-header">

Image courtesy: john carper

Body:
The footer component of ionic is fixed regarding the screen, I think you can try to implement an equivalent one. More info about the footer:  http://ionicframework.com/docs/v1/components/#footer

The main css-properties of the element are:

    .bar-footer {
        bottom: 0;
        height: 44px;
    }
    .bar {
        display: flex;
        user-select: none;
        position: absolute;
        right: 0;
        left: 0;
        z-index: 9;
        width: 100%;
        height: 44px;
     }

Modify the above properties with your specific ones (eg. bottom: 50%;) and ensure display is set as absolute.

Considering your parent's positionning issues, you should try to put your piece of code outside <ion-content></ion-content>, inside <ion-view></ion-view>.

It's the only way I succesfully set a button positioned as absolute within ionic mobile framework.

EDIT: /!\ Be careful not to write anything out of <ion-view></ion-view>. My previous answer was creating trouble in the way ionic manages the different pages.


问:
Running node.js app and getting angular is not defined message
I am trying to run an app in node.js and I've never used node before, when I enter node app.js into terminal, I get this error message:

```<code>ReferenceError: angular is not defined
at Object.<anonymous> (/Users/michael/Desktop/myapp/app/app.js:20:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3
</code>```

I installed angular. Here is the section of code for the app.js file that is mentioned in the error:

```<code>var app = angular
.module('gbook', ['ui.router', 'uiSwitch', 'LocalStorageModule', 'vsGoogleAutocomplete', 'ngCookies', 'gbook.config', 'gbook.intlTelInput', 'ui.timepicker', 'ngAnimate', 'ngSanitize', 'mgcrea.ngStrap', 'froala', 'ui.bootstrap'])
.config(config)
.run(run);
</code>```

I also have this code in index.js under the angular folder:

```<code>require('./angular');
module.exports = angular;
</code>```

Did I do something wrong installing angular, or is it something else?

答: I don't think you can use angular on server side. Angular is used for client side scripting.</p>

Body:
I am trying to run an app in node.js and I've never used node before, when I enter node app.js into terminal, I get this error message:

ReferenceError: angular is not defined
at Object.<anonymous> (/Users/michael/Desktop/myapp/app/app.js:20:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3

I installed angular. Here is the section of code for the app.js file that is mentioned in the error:

var app = angular
.module('gbook', ['ui.router', 'uiSwitch', 'LocalStorageModule', 'vsGoogleAutocomplete', 'ngCookies', 'gbook.config', 'gbook.intlTelInput', 'ui.timepicker', 'ngAnimate', 'ngSanitize', 'mgcrea.ngStrap', 'froala', 'ui.bootstrap'])
.config(config)
.run(run);

I also have this code in index.js under the angular folder:

require('./angular');
module.exports = angular;

Did I do something wrong installing angular, or is it something else?


问:
Converting pandas strings column to datetime with ocassionally missing hour part
I have duration string noted as '48m 37s' and sometimes as '1h 38m 29s' and a collection of string that holds this data in pandas dataframe's column

I'm trying to convert datatype of duration column to datetime as follows

```<code>pd.to_datetime(usg['duration'], format='%Hh %Mm %Ss')
</code>```

but failing with the following error

```<code>ValueError: time data '1h 38m 29s' does not match format '%Mm %Ss' (match)
</code>```

I understand that sometimes the hour part is missing in the list entries of duration column and wondering if there is a way to specify multiple formats if in case one fails to match other succeeds.

Doing so shall yield the output as below preserving the order of entries in the column

```<code>     00:39:40
     01:38:29
     07:39:40
</code>```

答:
Better use: pd.to_timedelta(usg['duration'])

```<code>usg = pd.DataFrame({'duration': ['48m 37s', '1h 38m 29s']})

pd.to_timedelta(usg['duration'])
</code>```

gives the output:

```<code>0   00:48:37
1   01:38:29
Name: duration, dtype: timedelta64[ns]
</code>```

Body:
I have duration string noted as '48m 37s' and sometimes as '1h 38m 29s' and a collection of string that holds this data in pandas dataframe's column

I'm trying to convert datatype of duration column to datetime as follows

pd.to_datetime(usg['duration'], format='%Hh %Mm %Ss')

but failing with the following error

ValueError: time data '1h 38m 29s' does not match format '%Mm %Ss' (match)

I understand that sometimes the hour part is missing in the list entries of duration column and wondering if there is a way to specify multiple formats if in case one fails to match other succeeds.

Doing so shall yield the output as below preserving the order of entries in the column

     00:39:40
     01:38:29
     07:39:40

Body:
Better use: pd.to_timedelta(usg['duration'])

usg = pd.DataFrame({'duration': ['48m 37s', '1h 38m 29s']})

pd.to_timedelta(usg['duration'])

gives the output:

0   00:48:37
1   01:38:29
Name: duration, dtype: timedelta64[ns]


问:
angular repeat order by not work on nested scope
I have a html table where rows are a object and data is a property:

```<code>$scope.rows = [
    { row_id: 1,row_selected:false, data: { col_1: "a", col_2: "b", col_3: "c" } },
    { row_id: 2,row_selected:false, data: { col_1: "d", col_2: "e", col_3: "f" } },
    { row_id: 3,row_selected:false, data: { col_1: "g", col_2: "h", col_3: "i" } }
]
</code>```

and in table:

```<code>   <table border="1">
     <tr>
       <th ng-repeat="col in cols | orderBy:'order':false">
         <a href ng-click='changeOrderBy(col)'>{{col.name}} [{{col.order}}]</a>
       </th>
     </tr>
     <tr ng-repeat="row in rows | orderBy:data[orderBy]:reverse | filter:filter">
       <td ng-repeat="col in cols | orderBy:'order':false">
         {{row.data[col.field]}}
       </td>
     </tr>
   </table>
</code>```

I tried with orderBy:data[orderBy] and orderBy:'data[orderBy]'

changeOrderBy function:

```<code>    $scope.changeOrderBy = function(col){
      if($scope.orderBy == col.field){
        $scope.reverse = !$scope.reverse;
      }
      $scope.orderBy = col.field;
    }
</code>```

But it does not seem to me to order the rows, and I suppose it will be a similar solution to make the filter

jsFiddle

答:
I found this solution, add the prefix 'data.' before the field, To be as follows

```<code>orderBy = 'data.col_1'
</code>```

js:

```<code>$scope.orderBy = null;
$scope.reverse = false;
$scope.changeOrderBy = function(col){
  var prefix = 'data.';
  if($scope.orderBy == prefix + col.field){
    $scope.reverse = !$scope.reverse;
  }
  $scope.orderBy = prefix + col.field;
}
</code>```

html:

```<code><tr ng-repeat="row in rows | orderBy:orderBy:reverse">
</code>```

updated jsFiddle

Body:
I have a html table where rows are a object and data is a property:

$scope.rows = [
    { row_id: 1,row_selected:false, data: { col_1: "a", col_2: "b", col_3: "c" } },
    { row_id: 2,row_selected:false, data: { col_1: "d", col_2: "e", col_3: "f" } },
    { row_id: 3,row_selected:false, data: { col_1: "g", col_2: "h", col_3: "i" } }
]

and in table:

         {{col.name}} [{{col.order}}]

         {{row.data[col.field]}}

I tried with orderBy:data[orderBy] and orderBy:'data[orderBy]'

changeOrderBy function:

    $scope.changeOrderBy = function(col){
      if($scope.orderBy == col.field){
        $scope.reverse = !$scope.reverse;
      }
      $scope.orderBy = col.field;
    }

But it does not seem to me to order the rows, and I suppose it will be a similar solution to make the filter

jsFiddle

Body:
I found this solution, add the prefix 'data.' before the field, To be as follows

orderBy = 'data.col_1'

js:

$scope.orderBy = null;
$scope.reverse = false;
$scope.changeOrderBy = function(col){
  var prefix = 'data.';
  if($scope.orderBy == prefix + col.field){
    $scope.reverse = !$scope.reverse;
  }
  $scope.orderBy = prefix + col.field;
}

html:

<tr ng-repeat="row in rows | orderBy:orderBy:reverse">

updated jsFiddle


问:
Tornado security issue
I am new to Tornado, the python framework. I came across that, It does not support session and authentication is done using secure cookies.

But how secure really it is?

I did this simple thing to test it. I logged in to the application, Exported the cookies using EditThisCookie and then I logged out. After that, I simply imported the cookie and now I am logged into the application.

I tried this with 2 applications that claim to have done using tornado and got same result on both the occasions.

Is this something expected? Or is there a better way to secure the tornado applications?

I tried with an example from the tornado website and found the same issue

答: That's expected behavior. The secure cookie is a token the browser keeps to prove it's logged in. If you move the cookie from the browser to your hard drive, then reimport it to the browser, the browser can once again prove to the Tornado application that it's logged in.</p>

Title: Tornado security issue


问:
AngularJS ng-model binding with numerical value
In angularJs ng-model i m binding with some name with ++ operator like

```<code><div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="firstname++hkjnh">
    {{firstname+" "+lastname}}
</div>
</code>```

output -> FirstName0
from where 0 comes in text

or

```<code>  <div ng-app="myApp" ng-controller="myCtrl">
        <input type="text" ng-model="+124343">
        {{firstname+" "+lastname}}
    </div>
</code>```

output ->124343

so plese tell me how angular work with these type of things

答:
ng-model directive we are using for two way binding. That's just a variable, we can get corresponding value in controller. Refer

https://plnkr.co/edit/AEblZEuiEL8mzvsFoz8M?p=preview

```<code>angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
   $scope.val++a = '1';
}]);

<input ng-model="val++a" ng-pattern="/^\d+$/" name="anim" class="my-input"
     aria-describedby="inputDescription" />
</code>```

Body:
In angularJs ng-model i m binding with some name with ++ operator like

    <input type="text" ng-model="firstname++hkjnh">
    {{firstname+" "+lastname}}

output -> FirstName0
from where 0 comes in text

or

        <input type="text" ng-model="+124343">
        {{firstname+" "+lastname}}

output ->124343

so plese tell me how angular work with these type of things

Body:
ng-model directive we are using for two way binding. That's just a variable, we can get corresponding value in controller. Refer

https://plnkr.co/edit/AEblZEuiEL8mzvsFoz8M?p=preview

angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
   $scope.val++a = '1';
}]);

<input ng-model="val++a" ng-pattern="/^\d+$/" name="anim" class="my-input"
     aria-describedby="inputDescription" />


问:
Execute code in Django after response has been sent to the client
In my Django application I want to keep track of whether a response has been sent to the client successfully. I am well aware that there is no "watertight" way in a connectionless protocol like HTTP to ensure the client has received (and displayed) a response, so this will not be mission-critical functionality, but still I want to do this at the latest possible time. The response will not be HTML so any callbacks from the client (using Javascript or IMG tags etc.) are not possible.

The "latest" hook I can find would be adding a custom middleware implementing process_response at the first position of the middleware list, but to my understanding this is executed before the actual response is constructed and sent to the client. Are there any hooks/events in Django to execute code after the response has been sent successfully?

答:
The method I am going for at the moment uses a subclass of HttpResponse:

```<code>from django.template import loader
from django.http import HttpResponse

# use custom response class to override HttpResponse.close()
class LogSuccessResponse(HttpResponse):

    def close(self):
        super(LogSuccessResponse, self).close()
        # do whatever you want, this is the last codepoint in request handling
        if self.status_code == 200:
            print('HttpResponse successful: %s' % self.status_code)

# this would be the view definition
def logging_view(request):
    response = LogSuccessResponse('Hello World', mimetype='text/plain')
    return response
</code>```

By reading the Django code I am very much convinced that HttpResponse.close() is the latest point to inject code into the request handling. I am not sure if there really are error cases that are handled better by this method compared to the ones mentioned above, so I am leaving the question open for now.

The reasons I prefer this approach to the others mentioned in lazerscience's answer are that it can be set up in the view alone and does not require middleware to be installed. Using the request_finished signal, on the other hand, wouldn't allow me to access the response object.

Body:
The method I am going for at the moment uses a subclass of HttpResponse:

from django.template import loader
from django.http import HttpResponse

# use custom response class to override HttpResponse.close()
class LogSuccessResponse(HttpResponse):

    def close(self):
        super(LogSuccessResponse, self).close()
        # do whatever you want, this is the last codepoint in request handling
        if self.status_code == 200:
            print('HttpResponse successful: %s' % self.status_code)

# this would be the view definition
def logging_view(request):
    response = LogSuccessResponse('Hello World', mimetype='text/plain')
    return response

By reading the Django code I am very much convinced that HttpResponse.close() is the latest point to inject code into the request handling. I am not sure if there really are error cases that are handled better by this method compared to the ones mentioned above, so I am leaving the question open for now.

The reasons I prefer this approach to the others mentioned in lazerscience's answer are that it can be set up in the view alone and does not require middleware to be installed. Using the request_finished signal, on the other hand, wouldn't allow me to access the response object.


问:
How to put gap for toggle image and hint text in Edittext android?
I am new for android. i want space gap between toggle image and hint text same field of edit text

.

This is my edit text xml code

```<code>     <EditText
            android:id="@+id/nation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/email"
            android:layout_centerHorizontal="true"
            android:drawableLeft="@drawable/ic_flag"
            android:layout_marginTop="11dp"
            android:inputType="textCapWords"
            android:hint="Nationality"/>
</code>```

答:
Here is solution

I want space gap between toggle image and hint text same field of edit
  text

set drawablePadding android:drawablePadding="15dp"

```<code><EditText
android:id="@+id/nation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/email"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:drawableLeft="@drawable/ic_flag"
android:drawablePadding="15dp"
android:hint="Nationality"
android:inputType="textCapWords" />
</code>```

in this edittext possible to decrease the hint text darkness

You can set hint color programmatically

```<code>editText.setHintTextColor(getResources().getColor(R.color.dark_gray));
</code>```

Body:
I am new for android. i want space gap between toggle image and hint text same field of edit text

.

This is my edit text xml code

     <EditText
            android:id="@+id/nation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/email"
            android:layout_centerHorizontal="true"
            android:drawableLeft="@drawable/ic_flag"
            android:layout_marginTop="11dp"
            android:inputType="textCapWords"
            android:hint="Nationality"/>

Body:
Here is solution

I want space gap between toggle image and hint text same field of edit
  text

set drawablePadding android:drawablePadding="15dp"

<EditText
android:id="@+id/nation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/email"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:drawableLeft="@drawable/ic_flag"
android:drawablePadding="15dp"
android:hint="Nationality"
android:inputType="textCapWords" />

in this edittext possible to decrease the hint text darkness

You can set hint color programmatically

editText.setHintTextColor(getResources().getColor(R.color.dark_gray));


问:
Exiting from a powershell menu
I've created a powershell menu script but occasionally I don't want to use the menu function I have created I want to come out and run a custom command, or even better add a menu feature which allows me to write a custom command.

Can anyone help me achieve this please?

```<code>write-host  "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
write-host          "Exchange Online Management"
write-host
write-host          "Press 1: To assign Full Access To A Mailbox"
write-host          "Press 2: Get Mailbox Size"
write-host          "Press 3: Custom Exchange Command"
write-host          "Press Q: To Leave Exchange Management"
write-host
write-host
write-host "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
$SM2 = Read-Host "Please Make A Selection"
Switch ($SM2) {
'1'{
DO something
}
'2' {
$Mailboxuser = read-host "Who's Mailbox are you trying to query?"
Get-MailboxStatistics $Mailboxuser | ft DisplayName, TotalItemSize, ItemCount
}
'3' {
return
}
'Q' {
Remove-PSSession $Session
return
}
}
}
until ($SM -eq 'Q')
</code>```

答:
The PowerShell console window is closing after it has finished executing your script.

You can get around this by running another powershell process with your script:

```<code>'Q' {
Remove-PSSession $Session
& powershell
}
</code>```

The other option is to create a shortcut to your script and add the -NoExit switch, which stops the window from closing when the script is finished.

PowerShell -NoExit "C:\folder\script.ps1"

Title: Exiting from a powershell menu

Body:
I've created a powershell menu script but occasionally I don't want to use the menu function I have created I want to come out and run a custom command, or even better add a menu feature which allows me to write a custom command.

Can anyone help me achieve this please?

write-host  "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
write-host          "Exchange Online Management"
write-host
write-host          "Press 1: To assign Full Access To A Mailbox"
write-host          "Press 2: Get Mailbox Size"
write-host          "Press 3: Custom Exchange Command"
write-host          "Press Q: To Leave Exchange Management"
write-host
write-host
write-host "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
$SM2 = Read-Host "Please Make A Selection"
Switch ($SM2) {
'1'{
DO something
}
'2' {
$Mailboxuser = read-host "Who's Mailbox are you trying to query?"
Get-MailboxStatistics $Mailboxuser | ft DisplayName, TotalItemSize, ItemCount
}
'3' {
return
}
'Q' {
Remove-PSSession $Session
return
}
}
}
until ($SM -eq 'Q')

Body:
The PowerShell console window is closing after it has finished executing your script.

You can get around this by running another powershell process with your script:

'Q' {
Remove-PSSession $Session
& powershell
}

The other option is to create a shortcut to your script and add the -NoExit switch, which stops the window from closing when the script is finished.

PowerShell -NoExit "C:\folder\script.ps1"


问:
Android ndk build can't build 32bit executable file
Depending on my first question, I tried to include the fanotify.h header in my application. The application is based on fsmon (a small application to use the fanotify syscall), I changed some code lines for my purpose and created an Android.mk makefile:

```<code>APP_PLATFORM := android-23
TARGET_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie

# give module name
LOCAL_MODULE := fsmon

# include fanotify by api 23:
LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/platforms/android-23/arch-arm/usr/include

# include fanotify by sysroot ->
# LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/

# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c

# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)
</code>```

I need to include the linux/inotify.h and the linux/fanotify.h headers.

On executing ndk-build, only the arm64-v8a, mips64 and x86_64 executable files (in libs/xxx) get created cause of following error messages:

```<code>fabian@fabian-ubuntu:~/kernel_android_goldfish/fsmon/fsmon/jni$ ndk-build
[arm64-v8a] Compile        : fsmon <= inotify.c
[arm64-v8a] Compile        : fsmon <= fanotify.c
[arm64-v8a] Compile        : fsmon <= util.c
[arm64-v8a] Compile        : fsmon <= main.c
[arm64-v8a] Executable     : fsmon
[arm64-v8a] Install        : fsmon => libs/arm64-v8a/fsmon
[x86_64] Compile        : fsmon <= inotify.c
[x86_64] Compile        : fsmon <= fanotify.c
[x86_64] Compile        : fsmon <= util.c
[x86_64] Compile        : fsmon <= main.c
[x86_64] Executable     : fsmon
[x86_64] Install        : fsmon => libs/x86_64/fsmon
[mips64] Compile        : fsmon <= inotify.c
[mips64] Compile        : fsmon <= fanotify.c
[mips64] Compile        : fsmon <= util.c
[mips64] Compile        : fsmon <= main.c
[mips64] Executable     : fsmon
[mips64] Install        : fsmon => libs/mips64/fsmon
[armeabi-v7a] Compile thumb  : fsmon <= inotify.c
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
In file included from /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:82:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:92:21: error: use of undeclared identifier
      '__BITS_PER_LONG'
  unsigned long sig[_NSIG_WORDS];
                    ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:25:38: note: expanded from macro '_NSIG_WORDS'
#define _NSIG_WORDS (_KERNEL__NSIG / _NSIG_BPW)
                                     ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:24:19: note: expanded from macro '_NSIG_BPW'
#define _NSIG_BPW __BITS_PER_LONG
                  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:94:3: error: typedef redefinition with different
      types ('struct (anonymous struct at /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:91:9)' vs
      'unsigned long')
} sigset_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:20:23: note: previous definition is here
typedef unsigned long sigset_t;
                      ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:84:8: error: redefinition of 'sigaction'
struct sigaction {
       ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:101:8: note: previous definition is here
struct sigaction {
       ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16: error: redefinition of
      'sigaltstack'
typedef struct sigaltstack {
               ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:111:16: note: previous definition is here
typedef struct sigaltstack {
               ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:101:3: error: typedef redefinition with
      different types ('struct (anonymous struct at
      /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16)' vs 'struct sigaltstack')
} stack_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:116:3: note: previous definition is here
} stack_t;
  ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:71:9: warning: 'NSIG' macro redefined [-Wmacro-redefined]
#define NSIG _NSIG
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:19:9: note: previous definition is here
#define NSIG 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:79:9: warning: 'SIGRTMIN' macro redefined [-Wmacro-redefined]
#define SIGRTMIN (__libc_current_sigrtmin())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:58:9: note: previous definition is here
#define SIGRTMIN 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:80:9: warning: 'SIGRTMAX' macro redefined [-Wmacro-redefined]
#define SIGRTMAX (__libc_current_sigrtmax())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:59:9: note: previous definition is here
#define SIGRTMAX _NSIG
        ^
5 errors generated.
    make: *** [/home/fabian/kernel_android_goldfish/fsmon/fsmon/obj/local/armeabi-v7a/objs/fsmon/inotify.o] Error 1
</code>```

Cause of inotify.c including the signal.h header which re-includes the linux/signal.h and this in turn the platforms/android-9/arch-arm/usr/include/asm/signal.h , where the error appears. (suddenly from android-9).

I can't figure out where the problem is.. I tried to include the include folder from sysroot - but similar errors appear.

Source file:
inotify.c
fanotify.c

答:
You shouldn't manually point to the NDK headers in LOCAL_C_INCLUDES. This should be added automatically, pointing to the right version. However, nothing actually uses the variables APP_PLATFORM or TARGET_PLATFORM here.

Instead, add APP_PLATFORM := android-23 in the file jni/Application.mk. That should make it build using the right platform headers, for all architectures.

Body:
Depending on my first question, I tried to include the fanotify.h header in my application. The application is based on fsmon (a small application to use the fanotify syscall), I changed some code lines for my purpose and created an Android.mk makefile:

APP_PLATFORM := android-23
TARGET_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie

# give module name
LOCAL_MODULE := fsmon

# include fanotify by api 23:
LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/platforms/android-23/arch-arm/usr/include

# include fanotify by sysroot ->
# LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/

# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c

# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)

I need to include the linux/inotify.h and the linux/fanotify.h headers.

On executing ndk-build, only the arm64-v8a, mips64 and x86_64 executable files (in libs/xxx) get created cause of following error messages:

fabian@fabian-ubuntu:~/kernel_android_goldfish/fsmon/fsmon/jni$ ndk-build
[arm64-v8a] Compile        : fsmon <= inotify.c
[arm64-v8a] Compile        : fsmon <= fanotify.c
[arm64-v8a] Compile        : fsmon <= util.c
[arm64-v8a] Compile        : fsmon <= main.c
[arm64-v8a] Executable     : fsmon
[arm64-v8a] Install        : fsmon => libs/arm64-v8a/fsmon
[x86_64] Compile        : fsmon <= inotify.c
[x86_64] Compile        : fsmon <= fanotify.c
[x86_64] Compile        : fsmon <= util.c
[x86_64] Compile        : fsmon <= main.c
[x86_64] Executable     : fsmon
[x86_64] Install        : fsmon => libs/x86_64/fsmon
[mips64] Compile        : fsmon <= inotify.c
[mips64] Compile        : fsmon <= fanotify.c
[mips64] Compile        : fsmon <= util.c
[mips64] Compile        : fsmon <= main.c
[mips64] Executable     : fsmon
[mips64] Install        : fsmon => libs/mips64/fsmon
[armeabi-v7a] Compile thumb  : fsmon <= inotify.c
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
In file included from /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:82:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:92:21: error: use of undeclared identifier
      '__BITS_PER_LONG'
  unsigned long sig[_NSIG_WORDS];
                    ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:25:38: note: expanded from macro '_NSIG_WORDS'
#define _NSIG_WORDS (_KERNEL__NSIG / _NSIG_BPW)
                                     ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:24:19: note: expanded from macro '_NSIG_BPW'
#define _NSIG_BPW __BITS_PER_LONG
                  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:94:3: error: typedef redefinition with different
      types ('struct (anonymous struct at /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:91:9)' vs
      'unsigned long')
} sigset_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:20:23: note: previous definition is here
typedef unsigned long sigset_t;
                      ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:84:8: error: redefinition of 'sigaction'
struct sigaction {
       ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:101:8: note: previous definition is here
struct sigaction {
       ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16: error: redefinition of
      'sigaltstack'
typedef struct sigaltstack {
               ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:111:16: note: previous definition is here
typedef struct sigaltstack {
               ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:101:3: error: typedef redefinition with
      different types ('struct (anonymous struct at
      /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16)' vs 'struct sigaltstack')
} stack_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:116:3: note: previous definition is here
} stack_t;
  ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:71:9: warning: 'NSIG' macro redefined [-Wmacro-redefined]
#define NSIG _NSIG
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:19:9: note: previous definition is here
#define NSIG 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:79:9: warning: 'SIGRTMIN' macro redefined [-Wmacro-redefined]
#define SIGRTMIN (__libc_current_sigrtmin())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:58:9: note: previous definition is here
#define SIGRTMIN 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:80:9: warning: 'SIGRTMAX' macro redefined [-Wmacro-redefined]
#define SIGRTMAX (__libc_current_sigrtmax())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:59:9: note: previous definition is here
#define SIGRTMAX _NSIG
        ^
5 errors generated.
    make: *** [/home/fabian/kernel_android_goldfish/fsmon/fsmon/obj/local/armeabi-v7a/objs/fsmon/inotify.o] Error 1

Cause of inotify.c including the signal.h header which re-includes the linux/signal.h and this in turn the platforms/android-9/arch-arm/usr/include/asm/signal.h , where the error appears. (suddenly from android-9).

I can't figure out where the problem is.. I tried to include the include folder from sysroot - but similar errors appear.

Source file:
inotify.c
fanotify.c


问:
How one can make github linguist take *.Rnw files into account of repository language statistics?
I've got many repos containing files written with LaTeX and R with knitr so the filenames' extensions are "Rnw". Files with these extensions are not taken into account by github linguist. How can we fix that?

Tangling all the files to extract R code chunks into separate files and commit and push them is not the case, isn't it?

I've researched through linguist guidelines but haven't found the case.

I want them to be accounted as a mixture of TeX and R, if it is possible for linguist to parse the files, count bytes of R code in knitr chunks and bytes of TeX.

答:
What you want to do is not currently possible with Linguist (v5.0.8). Linguist can only count a file towards the statistics of a single language.

As a side note:

If you want to change the language detected, you can use Linguist overrides.

If your issue was with the highlighting of the source file, you could define a special grammar for .Rnw files, with support for both R and TeX.


问:
awk - How to print two parts of one record
I got fields like this one:

```<code>Dagmar Schlecht(ID: 1233), Taubenstr- 246, 71108 Germany, dr_schlecht@t-online-de 1233 Shopping cart #3664 - Grüne Pillen;
</code>```

How Can I print the characters until the first ")" appears in, e.g., $1 and the characters from ~/"Shopping" and 19 chars onward ( so the part "- Grüne Pillen" is being skipped) ?

The outcome shall be written to and new field, e.g. $2:

```<code>Dagmar Schlecht(ID: 1233) Shopping cart #3664
</code>```

答:
If you are ok with sed :

```<code>sed -r 's/(^[^,]+).*(Shopping cart[^-]+)(.*)/\1   \2/' inputfile
Dagmar Schlecht(ID: 1233)   Shopping cart #3664
</code>```

Here, backrefrencing is used to divide the record into multiple chunks and later referred using \N . Each group is defined by ()

Same regex can be used with gawk using match function which support thired argument.

```<code>awk '{match($0,/(^[^,]+).*(Shopping cart[^-]+)(.*)/,a);print a[1],a[2]}'
Dagmar Schlecht(ID: 1233) Shopping cart #3664
</code>```

Body:
I got fields like this one:

Dagmar Schlecht(ID: 1233), Taubenstr- 246, 71108 Germany, dr_schlecht@t-online-de 1233 Shopping cart #3664 - Grüne Pillen;

How Can I print the characters until the first ")" appears in, e.g., $1 and the characters from ~/"Shopping" and 19 chars onward ( so the part "- Grüne Pillen" is being skipped) ?

The outcome shall be written to and new field, e.g. $2:

Dagmar Schlecht(ID: 1233) Shopping cart #3664

Body:
If you are ok with sed :

sed -r 's/(^[^,]+).*(Shopping cart[^-]+)(.*)/\1   \2/' inputfile
Dagmar Schlecht(ID: 1233)   Shopping cart #3664

Here, backrefrencing is used to divide the record into multiple chunks and later referred using \N . Each group is defined by ()

Same regex can be used with gawk using match function which support thired argument.

awk '{match($0,/(^[^,]+).*(Shopping cart[^-]+)(.*)/,a);print a[1],a[2]}'
Dagmar Schlecht(ID: 1233) Shopping cart #3664


问:
c# adding controls in winform via plugin dll
I have a Winform Gui that serves various purposes.  I am creating an additional plugin, that if present, adds another tabpage to my tabcontrol and then adds the required controls, etc.

My question is, am I best coding this into the main app, ie 'if dll present create this view' or should I code it into the dll and use reflection?  Is it possible using reflection?

Thanks/

答:
You should maybe look into existing framework that does exactly what you are looking for. For exemple, Managed Extensibility Framework MEF

MEF presents a simple solution for the
  runtime extensibility problem. Until
  now, any application that wanted to
  support a plugin model needed to
  create its own infrastructure from
  scratch. Those plugins would often be
  application-specific and could not be
  reused across multiple
  implementations. MEF provides a
  standard way for the host application
  to expose itself and consume external
  extensions. Extensions, by their
  nature, can be reused amongst
  different applications. However, an
  extension could still be implemented
  in a way that is application-specific.
  Extensions themselves can depend on
  one another and MEF will make sure
  they are wired together in the correct
  order (another thing you won't have to
  worry about). MEF offers a set of
  discovery approaches for your
  application to locate and load
  available extensions.

Or if you need to be in seperate app domain, you can use Managed Addin Framework MAF

But in your case I think MEF should do the trick.
Might be overkill though if you just have this one scenario ... but it's an option.


问:
C# List<T> adding inherited items
Let's say that we have 2 classes. The first one is Person

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
</code>```

The second one is Teacher

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}
</code>```

And I want to add in a List the teacher

```<code>Teacher teacher = new Teacher() {FirstName="Peter", LastName="Janson",Position="boss" };
            List <Person> people= new List<Person> { };
            people.Add(teacher);
</code>```

How is it possible that I add the teacher in the list when this list is of type  and person only has FirstName and LastName properties and the "teacher" has also a Position property?

答:
Based on your previous question, I think you're having some issues understanding polymorphism.

Try to think of inheritance as the relationship between cars and vehicles. A vehicle is a base type, and a car, a motorbike, a plane, a truck, etc. is a derived type.

```<code>public class Vehicle
{
    public string Model {get;set;}
}
</code>```

Imagine you have an aeroplane hangar:

```<code>List<Vehicle> hangar = new List<Vehicle>();
</code>```

You can park multiple different vehicles in an aeroplane hangar because it's very big:

```<code>hangar.Add(new Plane());
hangar.Add(new Car());
</code>```

Although they're different types, they still inherit from vehicle, so they can be stored as vehicles.

The thing is, planes have wings and cars don't. If you just take the first vehicle hangar[0], you know it's a vehicle and you can get the basic information about it (information that's common to all vehicles): hangar[0].Model, but you have to be more specific about the type of vehicle you're accessing if you want more detailed information.

Now, since you might not know what type of vehicle it is, you need to check:

```<code>if (hangar[0] is Car)
{
    string registrationNumber = ((Car)hangar[0]).RegistrationNumber;
}
else if (hangar[0] is Plane)
{
    int numberOfWings = ((Plane)hangar[0]).NumberOfWings;
}
</code>```

Using the C#7 syntax you can also use this simplified form:

```<code>if (hangar[0] is Car car)
{
    string registrationNumber = car.RegistrationNumber;
}
else if (hangar[0] is Plane plane)
{
    int numberOfWings = plane.NumberOfWings;
}
</code>```

The analogy with real life is that if you enter the hangar, you have to look to see where the car is, and where the plane is. It's the same here.

Polymorphism lets you treat many derived classes as their common base. In your person example, this would be useful if you wanted to be able to search for someone by name. A teacher is a person, a doctor is a person, they are all people and they all have names, so in that situation you can treat them the same.

Think of it like speed dating - you go and you meet people. What do you do first? You ask the other person's name. Then you ask "What do you do for a living?" and they say "I'm a teacher" or "I'm a doctor". Now you know what type they are, and you can ask them "What do you teach?" or "What branch of medicine do you specialise in?"

I hope this makes it clearer for you :-)

Title: C# List<T> adding inherited items

Body:
Let's say that we have 2 classes. The first one is Person

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

The second one is Teacher

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}

And I want to add in a List the teacher

Teacher teacher = new Teacher() {FirstName="Peter", LastName="Janson",Position="boss" };
            List <Person> people= new List<Person> { };
            people.Add(teacher);

How is it possible that I add the teacher in the list when this list is of type  and person only has FirstName and LastName properties and the "teacher" has also a Position property?

Body:
Based on your previous question, I think you're having some issues understanding polymorphism.

Try to think of inheritance as the relationship between cars and vehicles. A vehicle is a base type, and a car, a motorbike, a plane, a truck, etc. is a derived type.

public class Vehicle
{
    public string Model {get;set;}
}

Imagine you have an aeroplane hangar:

List<Vehicle> hangar = new List<Vehicle>();

You can park multiple different vehicles in an aeroplane hangar because it's very big:

hangar.Add(new Plane());
hangar.Add(new Car());

Although they're different types, they still inherit from vehicle, so they can be stored as vehicles.

The thing is, planes have wings and cars don't. If you just take the first vehicle hangar[0], you know it's a vehicle and you can get the basic information about it (information that's common to all vehicles): hangar[0].Model, but you have to be more specific about the type of vehicle you're accessing if you want more detailed information.

Now, since you might not know what type of vehicle it is, you need to check:

if (hangar[0] is Car)
{
    string registrationNumber = ((Car)hangar[0]).RegistrationNumber;
}
else if (hangar[0] is Plane)
{
    int numberOfWings = ((Plane)hangar[0]).NumberOfWings;
}

Using the C#7 syntax you can also use this simplified form:

if (hangar[0] is Car car)
{
    string registrationNumber = car.RegistrationNumber;
}
else if (hangar[0] is Plane plane)
{
    int numberOfWings = plane.NumberOfWings;
}

The analogy with real life is that if you enter the hangar, you have to look to see where the car is, and where the plane is. It's the same here.

Polymorphism lets you treat many derived classes as their common base. In your person example, this would be useful if you wanted to be able to search for someone by name. A teacher is a person, a doctor is a person, they are all people and they all have names, so in that situation you can treat them the same.

Think of it like speed dating - you go and you meet people. What do you do first? You ask the other person's name. Then you ask "What do you do for a living?" and they say "I'm a teacher" or "I'm a doctor". Now you know what type they are, and you can ask them "What do you teach?" or "What branch of medicine do you specialise in?"

I hope this makes it clearer for you :-)


问:
What is the rule of import with curly braces in React / Redux?
I thought the line:

```<code>import { FETCH_WEATHER } from "../actions/index";
</code>```

means: we don't import the whole object, but import the obj.FETCH_WEATHER from the file ../actions/index.js

One example is, we use

```<code>import React, { Component } from "react";
</code>```

And it is like, we import from "react", let's call it here as obj, and name it React in our own file, and obj.Component, we name it as Component in our own file.

(1) is that true?

(2) in the file ../actions/index.js, the content is actually:

```<code>export const FETCH_WEATHER = "FETCH_WEATHER";
</code>```

so there is no object, and no key / value pair to speak of. So what does import { FETCH_WEATHER } mean?

答:
Mozilla Developer Network has a really good documentation on imports in ES6:

import – JavaScript | MDN

Basically the imports within the curly brackets are named imports, and must match a named export from the library you're importing from. That can be any object / function / constant that is exported.

Using import without curly brackets imports the default variable / object / function from the library. The default export has default keyword as part of the export statement: export default someVariable

Body:
I thought the line:

import { FETCH_WEATHER } from "../actions/index";

means: we don't import the whole object, but import the obj.FETCH_WEATHER from the file ../actions/index.js

One example is, we use

import React, { Component } from "react";

And it is like, we import from "react", let's call it here as obj, and name it React in our own file, and obj.Component, we name it as Component in our own file.

(1) is that true?

(2) in the file ../actions/index.js, the content is actually:

export const FETCH_WEATHER = "FETCH_WEATHER";

so there is no object, and no key / value pair to speak of. So what does import { FETCH_WEATHER } mean?


问:
Cutting down repeating code in Sass functions
I'm working on an HTML boilerplate that uses a lot of Sass to create a maintainable and easy to use code base. Part of that are a few functions:

// Returns the scale value found at $key.
@function get-type-scale($key) {
    $value: map-get($type-scale, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$type-scale` map.";
    }
}

// Returns the line-height value found at $key.
@function get-line-height($key) {
    $value: map-get($line-heights, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$line-heights` map.";
    }
}

// etc... I have 2 more functions like this where only the $map changes.```
</div>
</div>
</p>

<p>These functions then get called in a few mixins, like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>// Sets font-size and line-height based on the $level.
@mixin set-type($level: 0) {
    font-size: get-type-scale($level);
    line-height: get-line-height($level);
}</code>```

While this works just fine, I don't like the fact that I'm repeating a lot of code in the functions. I've tried writing a generic function that receives a map name as a parameter, but I cannot use interpolation in map-get().

Is there a way to make the function code more elegant and as DRY as possible?

I appreciate any insights. Cheers!

答:
You could create line-height and font-size as key/value pairs in a nested map and use interpolation to print out the property in an @each loop – like:</p>

```<code>$map:(
  0 : (line-height: 1.3, font-size: 16px),
  1 : (line-height: 1.3, font-size: 17px),
  2 : (line-height: 1.3, font-size: 18px),
  3 : (line-height: 1.4, font-size: 19px),
  4 : (line-height: 1.5, font-size: 20px)
);

@mixin set-type($level: 0){
  $found: map-get($map, $level);
  @if not $found { @warn 'Key `#{$level}` not found in $map!'; }
  @else { @each $prop, $value in $found { #{$prop} : $value; } }
}

.class { @include set-type(1); } // line-height: 1.3; font-size: 17px;
.class { @include set-type(5); } // WARN: Key `5` not found in $map!
</code>```

Body:
I'm working on an HTML boilerplate that uses a lot of Sass to create a maintainable and easy to use code base. Part of that are a few functions:

// Returns the scale value found at $key.
@function get-type-scale($key) {
    $value: map-get($type-scale, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$type-scale` map.";
    }
}

// Returns the line-height value found at $key.
@function get-line-height($key) {
    $value: map-get($line-heights, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$line-heights` map.";
    }
}

// etc... I have 2 more functions like this where only the $map changes.

These functions then get called in a few mixins, like this:

// Sets font-size and line-height based on the $level.
@mixin set-type($level: 0) {
    font-size: get-type-scale($level);
    line-height: get-line-height($level);
}

While this works just fine, I don't like the fact that I'm repeating a lot of code in the functions. I've tried writing a generic function that receives a map name as a parameter, but I cannot use interpolation in map-get().

Is there a way to make the function code more elegant and as DRY as possible?

I appreciate any insights. Cheers!

Body:
You could create line-height and font-size as key/value pairs in a nested map and use interpolation to print out the property in an @each loop – like:

$map:(
  0 : (line-height: 1.3, font-size: 16px),
  1 : (line-height: 1.3, font-size: 17px),
  2 : (line-height: 1.3, font-size: 18px),
  3 : (line-height: 1.4, font-size: 19px),
  4 : (line-height: 1.5, font-size: 20px)
);

@mixin set-type($level: 0){
  $found: map-get($map, $level);
  @if not $found { @warn 'Key `#{$level}` not found in $map!'; }
  @else { @each $prop, $value in $found { #{$prop} : $value; } }
}

.class { @include set-type(1); } // line-height: 1.3; font-size: 17px;
.class { @include set-type(5); } // WARN: Key `5` not found in $map!


问:
How to return static value from static query
In sql i need to get my own values.
For example :

Select House from dual ( here i need to return H ) from dual union all
select Build from dual ( here i need to return B) ...

I tired with this but i dont get it as  I want

select '18776' as instanceid from dual union all
select '18775' as instanceid from dual

答:
Looks like you're coming from an Oracle background. Oracle is unique in requiring a FROM clause among the DBMSes I've used (SQL Server, Oracle, MySQL).

You should be good just having:

```<code>select 'H'
union all
select 'B'
</code>```

Body:
Looks like you're coming from an Oracle background. Oracle is unique in requiring a FROM clause among the DBMSes I've used (SQL Server, Oracle, MySQL).

You should be good just having:

select 'H'
union all
select 'B'


问:
How to mark query as idempotent in spring-data-cassandra?
I'm migrating from code that uses Cassandra java driver directly to a spring-data-cassandra. Old code used com.datastax.driver.core.PreparedStatement#setIdempotent to mark some queries as idempotent (that provides performance/latency bonus in some cases)

Is there any way to set this property when working through spring-data-cassandra or through spring-cql? I would expect it to be an option for @Query annotation, or a separate annotation on query method, or at least a part of QueryOptions

The only related thing I found is https://jira.spring.io/browse/DATACASS-403 , looks like org.springframework.cassandra.core.CachedPreparedStatementCreator that is used at CassandraTemplate, does not support idempotent flag (and even resets this flag for manually-built queries). Moreover, I did not find any mention at 2.0 spring-data-cassandra branch on github

答:
No, it's not planned for 2.0 yet because the caching is broken and the whole point of idempotent query is to make it cacheable.

There won't be a built in support for this flag until caching issues are fixed. When I looked at this issue, https://jira.spring.io/browse/DATACASS-291 was the main culprit (IMHO) that was blocking this flag from being usable


问:
cgroups: user.slice is missing
I am using a debian 8.7 (jessie) and have installed cgroups. It seems to work except that the user.slice is missing. I did not find out if there is a way to activate it.
I already tried to give it a config in the systemd directory (here for the user id 1000):

```<code>~# cat /etc/systemd/system/user-1000.slice.d/MemoryLimit.conf
[Slice]
MemoryLimit=67108864
</code>```

systemd-cgls gives:

```<code>  ~# systemd-cgls
    ├─  1 /sbin/init
    ├─473 /sbin/cgmanager -m name=systemd
    └─system.slice
      ├─dbus.service
      │ └─478 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
      ├─cron.service
      │ └─474 /usr/sbin/cron -f
      ├─nfs-common.service
      │ ├─456 /sbin/rpc.statd
      │ └─470 /usr/sbin/rpc.idmapd
      ├─exim4.service
      │ └─740 /usr/sbin/exim4 -bd -q30m
      ├─networking.service
      │ └─400 dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
      ├─atd.service
      │ └─471 /usr/sbin/atd -f
      ├─systemd-journald.service
      │ └─176 /lib/systemd/systemd-journald
      ├─ssh.service
      │ ├─ 472 /usr/sbin/sshd -D
      │ ├─1099 sshd: myuser [priv
      │ ├─1101 sshd: myuser@pts/1
      │ ├─1102 -bash
      │ ├─1113 sshd: root@pts/0
      │ ├─1115 -bash
      │ ├─1153 systemd-cgls
      │ └─1154 pager
      ├─systemd-logind.service
      │ └─476 /lib/systemd/systemd-logind
      ├─system-getty.slice
      │ └─getty@tty1.service
      │   └─503 /sbin/agetty --noclear tty1 linux
      ├─systemd-udevd.service
      │ └─178 /lib/systemd/systemd-udevd
      ├─rpcbind.service
      │ └─441 /sbin/rpcbind -w
      ├─rdnssd.service
      │ ├─272 /sbin/rdnssd -u rdnssd -H /etc/rdnssd/merge-hook
      │ └─274 /sbin/rdnssd -u rdnssd -H /etc/rdnssd/merge-hook
      ├─rsyslog.service
      │ └─485 /usr/sbin/rsyslogd -n
      └─acpid.service
        └─486 /usr/sbin/acpid
</code>```

How can I enable user slices?

答: Found it out myself: I installed "libpam-systemd". This package contains the PAM module which registers user sessions in the systemd control group hierarchy.</p>

Title: cgroups: user.slice is missing

Body:
I am using a debian 8.7 (jessie) and have installed cgroups. It seems to work except that the user.slice is missing. I did not find out if there is a way to activate it.
I already tried to give it a config in the systemd directory (here for the user id 1000):

~# cat /etc/systemd/system/user-1000.slice.d/MemoryLimit.conf
[Slice]
MemoryLimit=67108864

systemd-cgls gives:

  ~# systemd-cgls
    ├─  1 /sbin/init
    ├─473 /sbin/cgmanager -m name=systemd
    └─system.slice
      ├─dbus.service
      │ └─478 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
      ├─cron.service
      │ └─474 /usr/sbin/cron -f
      ├─nfs-common.service
      │ ├─456 /sbin/rpc.statd
      │ └─470 /usr/sbin/rpc.idmapd
      ├─exim4.service
      │ └─740 /usr/sbin/exim4 -bd -q30m
      ├─networking.service
      │ └─400 dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
      ├─atd.service
      │ └─471 /usr/sbin/atd -f
      ├─systemd-journald.service
      │ └─176 /lib/systemd/systemd-journald
      ├─ssh.service
      │ ├─ 472 /usr/sbin/sshd -D
      │ ├─1099 sshd: myuser [priv
      │ ├─1101 sshd: myuser@pts/1
      │ ├─1102 -bash
      │ ├─1113 sshd: root@pts/0
      │ ├─1115 -bash
      │ ├─1153 systemd-cgls
      │ └─1154 pager
      ├─systemd-logind.service
      │ └─476 /lib/systemd/systemd-logind
      ├─system-getty.slice
      │ └─getty@tty1.service
      │   └─503 /sbin/agetty --noclear tty1 linux
      ├─systemd-udevd.service
      │ └─178 /lib/systemd/systemd-udevd
      ├─rpcbind.service
      │ └─441 /sbin/rpcbind -w
      ├─rdnssd.service
      │ ├─272 /sbin/rdnssd -u rdnssd -H /etc/rdnssd/merge-hook
      │ └─274 /sbin/rdnssd -u rdnssd -H /etc/rdnssd/merge-hook
      ├─rsyslog.service
      │ └─485 /usr/sbin/rsyslogd -n
      └─acpid.service
        └─486 /usr/sbin/acpid

How can I enable user slices?


问:
How to turn on/off Cellular Network Android?
i want to refresh android Cellular Network android, but gets error. i want to make it working.

my code:

```<code>Settings.System.putInt(getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON, mode ? 1 : 0);// Turning ON/OFF Airplane mode.

        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);// creating intent and Specifying action for AIRPLANE mode.
        intent.putExtra("state", !mode);// indicate the "state" of airplane mode is changed to ON/OFF
        sendBroadcast(intent);// Broadcasting and Intent
</code>```

my manifest file has permission.

```<code> <uses-permission android:name="android.permission.WRITE_SETTINGS" />
</code>```

Error:

```<code>  FATAL EXCEPTION: main
                                                                       Process: com.zt.refreshnetwork, PID: 20221
                                                                       java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.AIRPLANE_MODE from pid=20221, uid=10237
                                                                           at android.os.Parcel.readException(Parcel.java:1684)
                                                                           at android.os.Parcel.readException(Parcel.java:1637)
                                                                           at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:3537)
                                                                           at android.app.ContextImpl.sendBroadcast(ContextImpl.java:881)
                                                                           at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:421)
                                                                           at com.zt.refreshnetwork.MainActivity.modifyAirplanemode(MainActivity.java:140)
                                                                           at com.zt.refreshnetwork.MainActivity.airPlanemodeON(MainActivity.java:117)
                                                                           at com.zt.refreshnetwork.MainActivity$1.onClick(MainActivity.java:46)
                                                                           at android.view.View.performClick(View.java:5637)
                                                                           at android.view.View$PerformClick.run(View.java:22429)
                                                                           at android.os.Handler.handleCallback(Handler.java:751)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
You mention you are attempting to modify the Airplane Mode status. This has been removed to third-party apps as of Android 4.2. From the release notes:

Several existing settings were relocated here from either Settings.System or Settings.Secure. If your app is currently making changes to settings previously defined in Settings.System (such as AIRPLANE_MODE_ON), then you should expect that doing so will no longer work on a device running Android 4.2 or higher if those settings were moved to Settings.Global.

You can continue to read settings that are in Settings.Global, but because the settings are no longer considered safe for apps to change, attempting to do so will fail silently and the system will write a warning to the system log when running your app on Android 4.2 or higher.

Chances are you'll need to rely on reflection and digging around the AOSP source if you absolutely want to do this, but Google usually make these sorts changes for sound security reasons. Any attempt to circumvent these measures could result in your app being removed from the Play store, or may result in your app not working at all with future releases of Android if underlying methods change.

Likewise, in the original version of your question, your app was requesting the MODIFY_PHONE_STATE permission. Again, this is not available to third party apps, only System apps, which would require this app to be run on a rooted device. From the documentation (my bold):

Allows modification of the telephony state - power on, mmi, etc. Does not include placing calls.
Not for use by third-party applications.

Body:
i want to refresh android Cellular Network android, but gets error. i want to make it working.

my code:

Settings.System.putInt(getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON, mode ? 1 : 0);// Turning ON/OFF Airplane mode.

        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);// creating intent and Specifying action for AIRPLANE mode.
        intent.putExtra("state", !mode);// indicate the "state" of airplane mode is changed to ON/OFF
        sendBroadcast(intent);// Broadcasting and Intent

my manifest file has permission.

 <uses-permission android:name="android.permission.WRITE_SETTINGS" />

Error:

  FATAL EXCEPTION: main
                                                                       Process: com.zt.refreshnetwork, PID: 20221
                                                                       java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.AIRPLANE_MODE from pid=20221, uid=10237
                                                                           at android.os.Parcel.readException(Parcel.java:1684)
                                                                           at android.os.Parcel.readException(Parcel.java:1637)
                                                                           at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:3537)
                                                                           at android.app.ContextImpl.sendBroadcast(ContextImpl.java:881)
                                                                           at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:421)
                                                                           at com.zt.refreshnetwork.MainActivity.modifyAirplanemode(MainActivity.java:140)
                                                                           at com.zt.refreshnetwork.MainActivity.airPlanemodeON(MainActivity.java:117)
                                                                           at com.zt.refreshnetwork.MainActivity$1.onClick(MainActivity.java:46)
                                                                           at android.view.View.performClick(View.java:5637)
                                                                           at android.view.View$PerformClick.run(View.java:22429)
                                                                           at android.os.Handler.handleCallback(Handler.java:751)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


问:
Using pandas' groupby with shifting
I am looking to use pd.rolling_mean in a groupby operation. I want to have in each group a rolling mean of the previous elemnets within the same group. Here is an example:

```<code>id    val
0     1
0     2
0     3
1     4
1     5
2     6
</code>```

Grouping by id, this should be transformed into:

```<code>id    val
0     nan
0     1
0     1.5
1     nan
1     4
2     nan
</code>```

答:
I think you need groupby with shift and rolling, window size can be set to scalar:

```<code>df['val']=df.groupby('id')['val'].apply(lambda x: x.shift().rolling(2, min_periods=1).mean())
print (df)
   id  val
0   0  NaN
1   0  1.0
2   0  1.5
3   1  NaN
4   1  4.0
5   2  NaN
</code>```

Thank you 3novak for comment - you can set window size by max length of group:

```<code>f = lambda x: x.shift().rolling(df['id'].value_counts().iloc[0], min_periods=1).mean()
df['val'] = df.groupby('id')['val'].apply(f)
print (df)
   id  val
0   0  NaN
1   0  1.0
2   0  1.5
3   1  NaN
4   1  4.0
5   2  NaN
</code>```

Title: Using pandas' groupby with shifting

Body:
I am looking to use pd.rolling_mean in a groupby operation. I want to have in each group a rolling mean of the previous elemnets within the same group. Here is an example:

id    val
0     1
0     2
0     3
1     4
1     5
2     6

Grouping by id, this should be transformed into:

id    val
0     nan
0     1
0     1.5
1     nan
1     4
2     nan

Body:
I think you need groupby with shift and rolling, window size can be set to scalar:

df['val']=df.groupby('id')['val'].apply(lambda x: x.shift().rolling(2, min_periods=1).mean())
print (df)
   id  val
0   0  NaN
1   0  1.0
2   0  1.5
3   1  NaN
4   1  4.0
5   2  NaN

Thank you 3novak for comment - you can set window size by max length of group:

f = lambda x: x.shift().rolling(df['id'].value_counts().iloc[0], min_periods=1).mean()
df['val'] = df.groupby('id')['val'].apply(f)
print (df)
   id  val
0   0  NaN
1   0  1.0
2   0  1.5
3   1  NaN
4   1  4.0
5   2  NaN