问:
R group time column by condition eg. hourly
I have a time column like below.

```<code>Tcol <- as.data.table(c(1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326, "NA"))
Tcol$V1= as.numeric(gsub("\\D+", "", Tcol$V1))
Tcol$V1[is.na(Tcol$V1)] <- 100
Tcol$V1 <- chron::chron(times=Tcol$V1)

Glimpse(Tcol)
Observations: 12
Variables: 1
$ V1 <S3: times> 1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326,  100
</code>```

I would like to group them by 1 hour blocks or 2 hours blocks for plotting.  ie.

```<code>100   1
1200  2
1300  2
1700  3
1900  1
2300  1
</code>```

Searching other solutions on SO, it seems, I should be using cut().  But every time I apply cut(), I get an error.

```<code>table(cut(Tcol$V1, breaks="hour"))
Error in breaks + 1 : non-numeric argument to binary operator
</code>```

I'm unable to find another post with the same issue to solve my issue.  So I'm hoping someone can help.

答:
If I get it right, then your V1 column contains time in format hm.
I do not understand what you are trying to accomplish using chron function, but in your place, I would extract from V1 only hour and then work with that.

```<code># for 1 hour intervals:
Tcol[, h := as.integer(substr(V1, 1, 2))]
Tcol[, .N, by = h]

#for different intervals
breaks <- seq(0, 24, by = 2) # define breaks
Tcol[, newintervals := cut(h, breaks = breaks)]
Tcol[, .N, by = newintervals]
</code>```

Body:
I have a time column like below.

Tcol <- as.data.table(c(1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326, "NA"))
Tcol$V1= as.numeric(gsub("\\D+", "", Tcol$V1))
Tcol$V1[is.na(Tcol$V1)] <- 100
Tcol$V1 <- chron::chron(times=Tcol$V1)

Glimpse(Tcol)
Observations: 12
Variables: 1
$ V1 <S3: times> 1211, 1237, 2106, 1348, 2136, 1745, 1740, 1330, 1755, 1939, 2326,  100

I would like to group them by 1 hour blocks or 2 hours blocks for plotting.  ie.

100   1
1200  2
1300  2
1700  3
1900  1
2300  1

Searching other solutions on SO, it seems, I should be using cut().  But every time I apply cut(), I get an error.

table(cut(Tcol$V1, breaks="hour"))
Error in breaks + 1 : non-numeric argument to binary operator

I'm unable to find another post with the same issue to solve my issue.  So I'm hoping someone can help.

Body:
If I get it right, then your V1 column contains time in format hm.
I do not understand what you are trying to accomplish using chron function, but in your place, I would extract from V1 only hour and then work with that.

# for 1 hour intervals:
Tcol[, h := as.integer(substr(V1, 1, 2))]
Tcol[, .N, by = h]

#for different intervals
breaks <- seq(0, 24, by = 2) # define breaks
Tcol[, newintervals := cut(h, breaks = breaks)]
Tcol[, .N, by = newintervals]


来源: stackexchange

问:
How to access the element at variable index of a tuple?
I'm writing a function to read vectors from stdin, and here is what I have so far:

```<code>fn read_vector() -> (i64, i64, i64) {
    let mut vec = (0, 0, 0);
    let mut value = String::new();

    for i in 0..3 {
        io::stdin().read_line(&mut value).expect("Failed to read line");
        vec.i = value.trim().parse().expect("Failed to read number!"); // error!
    }
}
</code>```

However, the annotated line contains an error:

error: no field `i` on type `({integer}, {integer}, {integer})`
  --> src/main.rs:13:13
   |
13 |         vec.i = value.trim().parse().expect("Failed to read number!");
   |             ^
```

Reading the documentation entry doesn't reveal any get, or similar function.

So, is there any way to get the ith value of a tuple?

答:
So, is there any way to get the ith value of vec?

No, there isn't. Since tuples can contain elements of different types, an expression like this wouldn't have a statically-known type in general.

You could consider using an array instead of a tuple.

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a function to read vectors from stdin, and here is what I have so far:

fn read_vector() -> (i64, i64, i64) {
    let mut vec = (0, 0, 0);
    let mut value = String::new();

    for i in 0..3 {
        io::stdin().read_line(&mut value).expect("Failed to read line");
        vec.i = value.trim().parse().expect("Failed to read number!"); // error!
    }
}

However, the annotated line contains an error:

error: no field `i` on type `({integer}, {integer}, {integer})`
  --> src/main.rs:13:13
   |
13 |         vec.i = value.trim().parse().expect("Failed to read number!");
   |             ^

Reading the documentation entry doesn't reveal any get, or similar function.

So, is there any way to get the ith value of a tuple?


问:
Cardview is not working with layertype software
I need to draw some path and show it below Recyclerview. So i have preferred following structure.

```<code>    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:contentInsetEnd="0dp"
        app:contentInsetLeft="0dp"
        app:contentInsetRight="0dp"
        app:contentInsetStart="0dp"
        app:layout_scrollFlags="scroll|enterAlways">

        <ImageView
            android:id="@+id/imageMenu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/app_name"
            android:padding="@dimen/d10dp"
            android:src="@drawable/ico_menu"/>

        <TextView
            android:id="@+id/toolbarTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/T_HEADER"
            android:textColor="@android:color/white"
            android:textSize="@dimen/d18sp"/>
        <ImageView
            android:id="@+id/imageAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:alpha="0.6"
            android:contentDescription="@string/app_name"
            android:padding="@dimen/d10dp"
            android:src="@drawable/ic_add_circle"/>

    </android.support.v7.widget.Toolbar>

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

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scrollGraph"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingTop="@dimen/d20dp">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/layoutGraph"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"/>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerViewEvents"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layoutManager="LinearLayoutManager"/>
        </FrameLayout>

    </android.support.v4.widget.NestedScrollView>

<TextView
    android:id="@+id/textNoData"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="@string/TG_NO_DATA"
    android:textColor="@android:color/black"
    android:textSize="@dimen/d14sp"
    android:visibility="gone"/>
</code>```

I am able to draw my views and fill recyclerview. It seems okay.

Now my issue is that I am using Cardview to display items in recyclerview.

Following is the code of custom cell.

```<code>    <android.support.v7.widget.CardView
        android:id="@+id/cardViewGraph"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        app:cardCornerRadius="@dimen/d5dp"
        app:cardElevation="@dimen/d5dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"
            android:baselineAligned="false"
            android:orientation="horizontal"
            android:weightSum="4">

                <ImageView
                    android:id="@+id/imageTimeMap"
                 android:layout_width="0dp"
                         android:layout_height="match_parent"
                         android:layout_weight="1.8"
                    android:contentDescription="@string/app_name"
                    android:scaleType="centerCrop"
                    android:src="@drawable/bg_gray_placeholder"/>

            <LinearLayout android:layout_width="0dp"
                          android:layout_height="match_parent"
                          android:layout_weight="2.2"
                          android:orientation="vertical"
                          android:padding="@dimen/d3dp">

                <LinearLayout android:layout_width="match_parent"
                              android:layout_height="wrap_content"
                              android:gravity="center_vertical"
                              android:orientation="horizontal">

                    <TextView android:id="@+id/textTimeMapType"
                              android:layout_width="0dp"
                              android:layout_height="wrap_content"
                              android:layout_weight="1"
                              android:drawablePadding="@dimen/d3dp"
                              android:gravity="center_vertical"
                              android:textSize="@dimen/d10sp"/>

                    <ImageView
                        android:id="@+id/imageEditEvent"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:contentDescription="@string/app_name"
                        android:padding="@dimen/d1dp"
                        android:src="@drawable/ico_edit_gray"/>

                </LinearLayout>

                <TextView android:id="@+id/textTargetHead"
                          android:layout_width="match_parent"
                          android:layout_height="0dp"
                          android:layout_marginTop="@dimen/d3dp"
                          android:layout_weight="1"
                          android:alpha="0.8"
                          android:ellipsize="end"
                          android:gravity="center_vertical"
                          android:maxLines="2"
                          android:textColor="@color/colorActivityHeader"
                          android:textSize="@dimen/d11sp"/>

            </LinearLayout>

        </LinearLayout>

    </android.support.v7.widget.CardView>

<TextView
    android:id="@+id/textDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center"
    android:maxLines="2"
    android:textSize="@dimen/d11sp"/>
</code>```

Now, As i need to draw long path in canvas, I have set layertype=Software in 'Srollview' so my view scrolls smoothly.

But when i use this property, Cardview does not set corner-radius or  elevation. If  remove this property from Scrollview then it works but my view laggs.

Any one could help me with this issue?

答:
This is what I got from Android Open Source Project - Issue Tracker

Shadows are only supported with hardware rendering.

Apart from that,

 I don't think enabling Hardware acceleration affect very much if your application uses only standard views.

Read here about when to use or not to use Hardware acceleration?

Read more about how Hardware Acceleration works!

Body:
I need to draw some path and show it below Recyclerview. So i have preferred following structure.

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:contentInsetEnd="0dp"
        app:contentInsetLeft="0dp"
        app:contentInsetRight="0dp"
        app:contentInsetStart="0dp"
        app:layout_scrollFlags="scroll|enterAlways">

        <ImageView
            android:id="@+id/imageMenu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/app_name"
            android:padding="@dimen/d10dp"
            android:src="@drawable/ico_menu"/>

        <TextView
            android:id="@+id/toolbarTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/T_HEADER"
            android:textColor="@android:color/white"
            android:textSize="@dimen/d18sp"/>
        <ImageView
            android:id="@+id/imageAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:alpha="0.6"
            android:contentDescription="@string/app_name"
            android:padding="@dimen/d10dp"
            android:src="@drawable/ic_add_circle"/>

    </android.support.v7.widget.Toolbar>

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

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scrollGraph"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingTop="@dimen/d20dp">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/layoutGraph"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"/>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerViewEvents"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layoutManager="LinearLayoutManager"/>
        </FrameLayout>

    </android.support.v4.widget.NestedScrollView>

<TextView
    android:id="@+id/textNoData"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="@string/TG_NO_DATA"
    android:textColor="@android:color/black"
    android:textSize="@dimen/d14sp"
    android:visibility="gone"/>

I am able to draw my views and fill recyclerview. It seems okay.

Now my issue is that I am using Cardview to display items in recyclerview.

Following is the code of custom cell.

    <android.support.v7.widget.CardView
        android:id="@+id/cardViewGraph"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        app:cardCornerRadius="@dimen/d5dp"
        app:cardElevation="@dimen/d5dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"
            android:baselineAligned="false"
            android:orientation="horizontal"
            android:weightSum="4">

                <ImageView
                    android:id="@+id/imageTimeMap"
                 android:layout_width="0dp"
                         android:layout_height="match_parent"
                         android:layout_weight="1.8"
                    android:contentDescription="@string/app_name"
                    android:scaleType="centerCrop"
                    android:src="@drawable/bg_gray_placeholder"/>

            <LinearLayout android:layout_width="0dp"
                          android:layout_height="match_parent"
                          android:layout_weight="2.2"
                          android:orientation="vertical"
                          android:padding="@dimen/d3dp">

                <LinearLayout android:layout_width="match_parent"
                              android:layout_height="wrap_content"
                              android:gravity="center_vertical"
                              android:orientation="horizontal">

                    <TextView android:id="@+id/textTimeMapType"
                              android:layout_width="0dp"
                              android:layout_height="wrap_content"
                              android:layout_weight="1"
                              android:drawablePadding="@dimen/d3dp"
                              android:gravity="center_vertical"
                              android:textSize="@dimen/d10sp"/>

                    <ImageView
                        android:id="@+id/imageEditEvent"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:contentDescription="@string/app_name"
                        android:padding="@dimen/d1dp"
                        android:src="@drawable/ico_edit_gray"/>

                </LinearLayout>

                <TextView android:id="@+id/textTargetHead"
                          android:layout_width="match_parent"
                          android:layout_height="0dp"
                          android:layout_marginTop="@dimen/d3dp"
                          android:layout_weight="1"
                          android:alpha="0.8"
                          android:ellipsize="end"
                          android:gravity="center_vertical"
                          android:maxLines="2"
                          android:textColor="@color/colorActivityHeader"
                          android:textSize="@dimen/d11sp"/>

            </LinearLayout>

        </LinearLayout>

    </android.support.v7.widget.CardView>

<TextView
    android:id="@+id/textDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center"
    android:maxLines="2"
    android:textSize="@dimen/d11sp"/>

Now, As i need to draw long path in canvas, I have set layertype=Software in 'Srollview' so my view scrolls smoothly.

But when i use this property, Cardview does not set corner-radius or  elevation. If  remove this property from Scrollview then it works but my view laggs.

Any one could help me with this issue?


问:
Compare different ArrayList elements
Ok so, I have several text documents containing similar format as below:

```<code>    497 Q0 WTX091-B06-138 0 0.415344133 GROUP001
    497 Q0 WTX091-B09-92 1 0.362342072 GROUP001
    497 Q0 WTX091-B09-76 2 0.354034424 GROUP001
    497 Q0 WTX091-B09-57 3 0.349649535 GROUP001
    497 Q0 WTX091-B43-79 4 0.3217919 GROUP001
    497 Q0 WTX091-B43-56 5 0.321450733 GROUP001
    .
    .
    .
    (actually there are 1000 lines in each text document)
</code>```

I have stored each document into an arraylist separated by line. The challenging part is that I have to look for the third column (WTX***-B**-**) in each document and if they are the same then I have to add their fifth (0.3********) column together.

How do I compare the third column in different text documents?

答:
Maybe something like this? Create something like an entity class and then use Stream API to turn it into map and if there is same key then add its double values:</p>

```<code>public static class Data
{
    public int id;
    public String stringId;
    public String plateNumber;
    public int numId;
    public double value;
    public String name;

    public Data(int id, String stringId, String plateNumber, int numId, double value, String name)
    {
        this.id = id;
        this.stringId = stringId;
        this.plateNumber = plateNumber;
        this.numId = numId;
        this.value = value;
        this.name = name;
    }
}

public static void main(String[] args)
{
    List<Data> ls = new ArrayList<>();
    ls.add(new Data(497, "Q0", "WTX091-B06-138", 0, 0.415344133, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B09-92", 1, 0.362342072, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B09-76", 2, 0.354034424, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B09-57", 3, 0.349649535, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B43-79", 4, 0.3217919, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B43-56", 5, 0.321450733, "GROUP001"));

    Map<String, Double> map = ls.stream()
                                .collect(Collectors.toMap(k -> k.plateNumber, v -> v.value, (v1, v2) -> v1 + v2));

    System.out.println(map);
}
</code>```

Title: Compare different ArrayList elements

Body:
Ok so, I have several text documents containing similar format as below:

    497 Q0 WTX091-B06-138 0 0.415344133 GROUP001
    497 Q0 WTX091-B09-92 1 0.362342072 GROUP001
    497 Q0 WTX091-B09-76 2 0.354034424 GROUP001
    497 Q0 WTX091-B09-57 3 0.349649535 GROUP001
    497 Q0 WTX091-B43-79 4 0.3217919 GROUP001
    497 Q0 WTX091-B43-56 5 0.321450733 GROUP001
    .
    .
    .
    (actually there are 1000 lines in each text document)

I have stored each document into an arraylist separated by line. The challenging part is that I have to look for the third column (WTX***-B**-**) in each document and if they are the same then I have to add their fifth (0.3********) column together.

How do I compare the third column in different text documents?

Body:
Maybe something like this? Create something like an entity class and then use Stream API to turn it into map and if there is same key then add its double values:

public static class Data
{
    public int id;
    public String stringId;
    public String plateNumber;
    public int numId;
    public double value;
    public String name;

    public Data(int id, String stringId, String plateNumber, int numId, double value, String name)
    {
        this.id = id;
        this.stringId = stringId;
        this.plateNumber = plateNumber;
        this.numId = numId;
        this.value = value;
        this.name = name;
    }
}

public static void main(String[] args)
{
    List<Data> ls = new ArrayList<>();
    ls.add(new Data(497, "Q0", "WTX091-B06-138", 0, 0.415344133, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B09-92", 1, 0.362342072, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B09-76", 2, 0.354034424, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B09-57", 3, 0.349649535, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B43-79", 4, 0.3217919, "GROUP001"));
    ls.add(new Data(497, "Q0", "WTX091-B43-56", 5, 0.321450733, "GROUP001"));

    Map<String, Double> map = ls.stream()
                                .collect(Collectors.toMap(k -> k.plateNumber, v -> v.value, (v1, v2) -> v1 + v2));

    System.out.println(map);
}


问:
What is the best way to query SharePoint data?
Should I just use ADO.NET to directly access the underlying data in the database or does .NET have a better way to do this?

I am currently using SharePoint 2007 but we are about to move to 2010.  I am using Visual Studio 2010.

答:
Are you talking about custom database or Sharepoint database?

You should never touch directly sharepoint database since it will put your farm in unsupported state.

If you want to access, custom database, consider using Entity Framework:
http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx

ContentLicense: CC BY-SA 2.5


问:
Firebase returns the entire database even with setting ref url
I am trying to setup Firebase's realtime database in my web app.

I have everything initialized properly and can connect to the database. However, when I try to fetch data, I get the entire database returned in the snapchat.

The code I have here is trying to determine if a key exists:

```<code>var ref = firebase.database().ref('cars/');

ref.once('value', function (snapshot) {
    if (snapshot.hasChild('toyota')) {
        alert('exists');
    } else {
        alert('does not exist');
    }
});
</code>```

This always displays the 'does not exist' dialog, so when I ran:

```<code>alert(JSON.stringify(snapshot));
</code>```

I realized that firebase was fetching everything.

Here is the structure of my database:

```<code>{
"users": {
    "uid": {
        "name": "John Doe",
        "balance": 500
    }
},
"cars": {
    "carid": {
        "name": "Name of Car",
        "cost": "250",
        "features": [
            "ac", "awd", "leather_seats"
        ]
    }
  }
}
</code>```

Does anybody know how to fix this? Every request I make just returns the entire database, which is frustrating. Thanks.

答:
I retrieve data for a node in the following way, without the preceding or trailing slash. Check if the following works. </p>

```<code>var ref = firebase.database().ref().child('cars');
</code>```

Body:
I am trying to setup Firebase's realtime database in my web app.

I have everything initialized properly and can connect to the database. However, when I try to fetch data, I get the entire database returned in the snapchat.

The code I have here is trying to determine if a key exists:

var ref = firebase.database().ref('cars/');

ref.once('value', function (snapshot) {
    if (snapshot.hasChild('toyota')) {
        alert('exists');
    } else {
        alert('does not exist');
    }
});

This always displays the 'does not exist' dialog, so when I ran:

alert(JSON.stringify(snapshot));

I realized that firebase was fetching everything.

Here is the structure of my database:

{
"users": {
    "uid": {
        "name": "John Doe",
        "balance": 500
    }
},
"cars": {
    "carid": {
        "name": "Name of Car",
        "cost": "250",
        "features": [
            "ac", "awd", "leather_seats"
        ]
    }
  }
}

Does anybody know how to fix this? Every request I make just returns the entire database, which is frustrating. Thanks.

Body:
I retrieve data for a node in the following way, without the preceding or trailing slash. Check if the following works.

var ref = firebase.database().ref().child('cars');


问:
Javascript: How can I add the values of an object that belong to a shared key?
Let's say I have an object containing states and their balances.

```<code>    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }
</code>```

How could I add the amounts that belong to each state, for example OH would have 587603.26 + 657617.83. I believe the map() method is to be used here but I am not sure how to go about using it. Thanks!

答:
Short solution using Array.prototype.forEach() function:

var arr = [{"amount": "822370.71","state": "ME"},{"amount": "968817.53","state": "FL"},{"amount": "587603.26","state": "OH"},{"amount": "657617.83","state": "OH"},{"amount": "657617.83","state": "FL"}],
    result = {};

arr.forEach(function (o) {
    var amount = Number(o.amount);
    (result[o.state])? result[o.state] += amount : result[o.state] = amount;
});

console.log(result);```

Body:
Let's say I have an object containing states and their balances.

    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }

How could I add the amounts that belong to each state, for example OH would have 587603.26 + 657617.83. I believe the map() method is to be used here but I am not sure how to go about using it. Thanks!


问:
iOS Swift Email Deep Linking
I need to make my users to click on email URL to open my App. I having some daily updates that I have forward to my Users. I am having some URL links in that email. I just need to make my users to open app when they clicking those email links.

Email URL Here:
http://kavin.com/login?redirect_to=calendar?cal_navigation=2017-03-23

答:
use the call back method for handle the referral source </p>

```<code>func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

    print("source application:\(sourceApplication)")
    let value: String = url.absoluteString as String
    print("value :\(value)")
    print("scheme: \(url.scheme)")
    print("query: \(url.query)")

    return true
}
</code>```

Title: iOS Swift Email Deep Linking

Body:
use the call back method for handle the referral source

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

    print("source application:\(sourceApplication)")
    let value: String = url.absoluteString as String
    print("value :\(value)")
    print("scheme: \(url.scheme)")
    print("query: \(url.query)")

    return true
}


问:
RecyclerView messed up data when scrolling
Having a problem when scrolling RecyclerView after scrolling down and up. The idea is to change elements color, but when I scroll down everything is great and when the scroll goes up - the elements, which are shouldn't be colored are changing color.

Here's my adapter:

```<code>public class NotificationsAdapter extends RecyclerView.Adapter<NotificationsAdapter.ViewHolder> {

private NotificationData notificationData;
private Context mContext;
private ArrayList<NotificationData> infromationList = new ArrayList<>();

public NotificationsAdapter(Context context, ArrayList<NotificationData> infromationList) {
    this.infromationList = infromationList;
    this.mContext = context;
}

@Override
public NotificationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemLayoutView;
    ViewHolder viewHolder;

    itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.notification_single_item, parent, false);
    viewHolder = new ViewHolder(itemLayoutView, viewType);

    return viewHolder;
}

@Override
public void onBindViewHolder(NotificationsAdapter.ViewHolder holder, int position) {

    notificationData = infromationList.get(position);
    holder.notificationDate.setText(convertDate(notificationData.getDate()));
    holder.notificationStatus.setText(notificationData.getNotificationStatus());
    holder.orderDescription.setText(notificationData.getNotificationLabel());

    if ("true".equals(notificationData.getReadStatus())) {
        holder.root.setBackgroundColor(mContext.getResources().getColor(R.color.white));
        holder.notificationStatus.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
    }

}

@Override
public int getItemCount() {
    return (null != infromationList ? infromationList.size() : 0);
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    public TextView notificationDate;
    public TextView notificationStatus;
    public TextView orderDescription;
    public LinearLayout root;

    public ViewHolder(View itemView, int position) {
        super(itemView);

        notificationDate = (TextView) itemView.findViewById(R.id.notificationDate);
        notificationStatus = (TextView) itemView.findViewById(R.id.notificationStatus);
        orderDescription = (TextView) itemView.findViewById(R.id.orderDescription);
        root = (LinearLayout) itemView.findViewById(R.id.root);
    }

}

private String convertDate(String date) {
    String convertedDate;

    String[] parts = new String[2];
    parts = date.split("T");
    date = parts[0];

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
    Date testDate = null;
    try {
        testDate = sdf.parse(date);
    }catch(Exception ex){
        ex.printStackTrace();
    }
    SimpleDateFormat formatter = new SimpleDateFormat("dd.mm.yyyy");
    convertedDate = formatter.format(testDate);

    return convertedDate;
}
}
</code>```

答:
Add setHasStableIds(true); in your adapter constructor and
Override these two methodes in adapter.

```<code>@Override
public long getItemId(int position) {
            return position;
}

@Override
public int getItemViewType(int position) {
       return position;
}
</code>```

Body:
Having a problem when scrolling RecyclerView after scrolling down and up. The idea is to change elements color, but when I scroll down everything is great and when the scroll goes up - the elements, which are shouldn't be colored are changing color.

Here's my adapter:

public class NotificationsAdapter extends RecyclerView.Adapter<NotificationsAdapter.ViewHolder> {

private NotificationData notificationData;
private Context mContext;
private ArrayList<NotificationData> infromationList = new ArrayList<>();

public NotificationsAdapter(Context context, ArrayList<NotificationData> infromationList) {
    this.infromationList = infromationList;
    this.mContext = context;
}

@Override
public NotificationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemLayoutView;
    ViewHolder viewHolder;

    itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.notification_single_item, parent, false);
    viewHolder = new ViewHolder(itemLayoutView, viewType);

    return viewHolder;
}

@Override
public void onBindViewHolder(NotificationsAdapter.ViewHolder holder, int position) {

    notificationData = infromationList.get(position);
    holder.notificationDate.setText(convertDate(notificationData.getDate()));
    holder.notificationStatus.setText(notificationData.getNotificationStatus());
    holder.orderDescription.setText(notificationData.getNotificationLabel());

    if ("true".equals(notificationData.getReadStatus())) {
        holder.root.setBackgroundColor(mContext.getResources().getColor(R.color.white));
        holder.notificationStatus.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
    }

}

@Override
public int getItemCount() {
    return (null != infromationList ? infromationList.size() : 0);
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    public TextView notificationDate;
    public TextView notificationStatus;
    public TextView orderDescription;
    public LinearLayout root;

    public ViewHolder(View itemView, int position) {
        super(itemView);

        notificationDate = (TextView) itemView.findViewById(R.id.notificationDate);
        notificationStatus = (TextView) itemView.findViewById(R.id.notificationStatus);
        orderDescription = (TextView) itemView.findViewById(R.id.orderDescription);
        root = (LinearLayout) itemView.findViewById(R.id.root);
    }

}

private String convertDate(String date) {
    String convertedDate;

    String[] parts = new String[2];
    parts = date.split("T");
    date = parts[0];

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
    Date testDate = null;
    try {
        testDate = sdf.parse(date);
    }catch(Exception ex){
        ex.printStackTrace();
    }
    SimpleDateFormat formatter = new SimpleDateFormat("dd.mm.yyyy");
    convertedDate = formatter.format(testDate);

    return convertedDate;
}
}

Body:
Add setHasStableIds(true); in your adapter constructor and
Override these two methodes in adapter.

@Override
public long getItemId(int position) {
            return position;
}

@Override
public int getItemViewType(int position) {
       return position;
}


问:
Qt: QIcon disappears when clicked; QIcon::Mode not being respected
I have a png format image of a play button in  which I have stored as an embedded resource in my application.

```<code><!DOCTYPE RCC><RCC version="1.0">
  <qresource prefix="icon">
    <file>play.png</file>
  </qresource>
</RCC>
</code>```

I have created a QIcon with the same source image set for both Normal and Active modes

```<code>QIcon play;
play.addFile(":icon/play.png", QSize(), QIcon::Normal);
play.addFile(":icon/play.png", QSize(), QIcon::Active);
</code>```

From what I understand, this should display the icon when unclicked (Normal mode), and continue doing so when clicked (Active mode)

QIcon::Normal: Display the pixmap when the user is not interacting with the icon, but the functionality represented by the icon is available.

QIcon::Active: Display the pixmap when the functionality represented by the icon is available and the user is interacting with the icon, for example, moving the mouse over it or clicking it.

However, when I click on it it disappears (a blank box being displayed instead).

Here is the icon unclicked

Here is the icon clicked

Minimal working example:

I have created a minimal example replicating the behaviour I see

```<code>#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>

void initIcons()
{
    Q_INIT_RESOURCE(view);
}

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QMenuBar* menu = new QMenuBar();
    window->setMenuBar(menu);

    QIcon play;
    play.addFile(":icon/play.png", QSize(), QIcon::Normal);
    play.addFile(":icon/play.png", QSize(), QIcon::Active);

    QAction* action = new QAction(play, "", nullptr);
    menu->addAction(action);

    window->show();
    return app->exec();
}
</code>```

Update:

I have also tried every combination of Mode and State with no change in behaviour:

```<code>play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::Off);
</code>```

I also tried addPixmap

```<code>QIcon play;
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::Off);
</code>```

None of these alter the behaviour at all unfortunately.

答:
The problem as I understand in style of QMenuBar,
I modified your example in such way:

```<code>#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QMenuBar* menu = new QMenuBar();
    menu->setStyleSheet(R"style(
QMenuBar {
   background-color: transparent;
}
QMenuBar::item:selected { /* when selected using mouse or keyboard */
  background: #a8a8a8;
}

QMenuBar::item:pressed {
  background: #888888;
}
)style");
    window->setMenuBar(menu);

    QIcon play;
    const char path_to_icon[] = "/home/evgeniy/Downloads/icon-play-128.png";
    play.addFile(path_to_icon, QSize(), QIcon::Normal);
    play.addFile(path_to_icon, QSize(), QIcon::Active);

    QAction* action = new QAction(play, "", nullptr);
    menu->addAction(action);

    window->show();
    return app->exec();
}
</code>```

and after press I can see icon.
Note that my default style is different then yours,
so you may need modify colors in stylesheet.

Body:
I have a png format image of a play button in  which I have stored as an embedded resource in my application.

<!DOCTYPE RCC><RCC version="1.0">
  <qresource prefix="icon">
    <file>play.png</file>
  </qresource>
</RCC>

I have created a QIcon with the same source image set for both Normal and Active modes

QIcon play;
play.addFile(":icon/play.png", QSize(), QIcon::Normal);
play.addFile(":icon/play.png", QSize(), QIcon::Active);

From what I understand, this should display the icon when unclicked (Normal mode), and continue doing so when clicked (Active mode)

QIcon::Normal: Display the pixmap when the user is not interacting with the icon, but the functionality represented by the icon is available.

QIcon::Active: Display the pixmap when the functionality represented by the icon is available and the user is interacting with the icon, for example, moving the mouse over it or clicking it.

However, when I click on it it disappears (a blank box being displayed instead).

Here is the icon unclicked

Here is the icon clicked

Minimal working example:

I have created a minimal example replicating the behaviour I see

#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>

void initIcons()
{
    Q_INIT_RESOURCE(view);
}

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QMenuBar* menu = new QMenuBar();
    window->setMenuBar(menu);

    QIcon play;
    play.addFile(":icon/play.png", QSize(), QIcon::Normal);
    play.addFile(":icon/play.png", QSize(), QIcon::Active);

    QAction* action = new QAction(play, "", nullptr);
    menu->addAction(action);

    window->show();
    return app->exec();
}

Update:

I have also tried every combination of Mode and State with no change in behaviour:

play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::Off);

I also tried addPixmap

QIcon play;
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::Off);

None of these alter the behaviour at all unfortunately.

Body:
The problem as I understand in style of QMenuBar,
I modified your example in such way:

#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QMenuBar* menu = new QMenuBar();
    menu->setStyleSheet(R"style(
QMenuBar {
   background-color: transparent;
}
QMenuBar::item:selected { /* when selected using mouse or keyboard */
  background: #a8a8a8;
}

QMenuBar::item:pressed {
  background: #888888;
}
)style");
    window->setMenuBar(menu);

    QIcon play;
    const char path_to_icon[] = "/home/evgeniy/Downloads/icon-play-128.png";
    play.addFile(path_to_icon, QSize(), QIcon::Normal);
    play.addFile(path_to_icon, QSize(), QIcon::Active);

    QAction* action = new QAction(play, "", nullptr);
    menu->addAction(action);

    window->show();
    return app->exec();
}

and after press I can see icon.
Note that my default style is different then yours,
so you may need modify colors in stylesheet.


问:
Master grid cell value as sum of detail view cell values that has unbound type
I have grid control that has master-detail views. And in detail view I have unbounded column called LinePrice. and I need to represent sum of LinePrice in master column.
I used some samples but i'm getting error that

"LinePrice" does not belong to the table

.
this is my question is any way to get sum of unbound column in master or not?
thanks in advance

答: The solution for your task depends on the place where you need to show your summary value. If you need to show it in a separate master view column, create an unbound column in your master view and populate it via the CustomUnboundColumnData event handler. In this event handler, calculate the summary value manually and pass it as the e.Value parameter.


答:
There isn't a way built in the language, because variable indexing on a heterogeneous type like a tuple makes it impossible for the compiler to infer the type of the expression.

You could use a macro that unrolls a for loop with variable indexing for a tuple if it is really, really necessary though.

If you are going to be using homogeneous tuples that require variable indexing, why not just use a fixed-length array?

Title: How to access the element at variable index of a tuple?


问:
Can anyone point me to a reference for the Drupal $account->content array?
I've been digging around all morning and I can't find any reference that defines the account object.

In particular, I want to modify another drupal admin's user hook() function to change the way it works. Currently, it comes out as dt/dd pairs without any css classes or custom styles, and I need to be able to theme the content.

```<code>  function acidfree_user($op, &$edit, &$account, $category = NULL) {
    if ($op == 'view') {
    //Pachkov.Sergey.START - MODIFIED BY MHEINZ
      $result = db_query("SELECT nid, title FROM node WHERE nid IN (SELECT nid FROM node WHERE uid=%d
                         AND type='acidfree') ORDER BY nid desc", $account->uid);

      $i=0;
      $account->content['acidfree-albums'] = array(
        '#type' => 'user_profile_category',
        '#title' => t('Photo albums'),
      );
      while ($item = db_fetch_array($result)) {
        $title_node = $item['title'];
        $nid = $item['nid'];
        $account->content['acidfree-albums'][$i] = array(
                '#title' => t(' '),
                '#value' => l($title_node, "node/{$nid}"),
                '#class' => 'acidfree-albums',
                '#type' => 'user_profile_item',
        );
        $i++;
      }
    }
    //Pachkov.Sergey.END - MODIFIED BY MHEINZ
  }
</code>```

答:
The dt/dd used to display the $account->content array you see in hook_user come from the user-profile-item.tpl.php template. Using template_preprocess_user_profile_item in your modules or theme, you can add attributes for these dt/dd.

If you need to change one of the items in the $account->content array, you should use hook_profile_alter:

```<code>function MODULE_profile_alter(&$account) {
  $account->content['acidfree-albums']['#title'] = t('Awesome photos!');
}
</code>```

Body:
I've been digging around all morning and I can't find any reference that defines the account object.

In particular, I want to modify another drupal admin's user hook() function to change the way it works. Currently, it comes out as dt/dd pairs without any css classes or custom styles, and I need to be able to theme the content.

  function acidfree_user($op, &$edit, &$account, $category = NULL) {
    if ($op == 'view') {
    //Pachkov.Sergey.START - MODIFIED BY MHEINZ
      $result = db_query("SELECT nid, title FROM node WHERE nid IN (SELECT nid FROM node WHERE uid=%d
                         AND type='acidfree') ORDER BY nid desc", $account->uid);

      $i=0;
      $account->content['acidfree-albums'] = array(
        '#type' => 'user_profile_category',
        '#title' => t('Photo albums'),
      );
      while ($item = db_fetch_array($result)) {
        $title_node = $item['title'];
        $nid = $item['nid'];
        $account->content['acidfree-albums'][$i] = array(
                '#title' => t(' '),
                '#value' => l($title_node, "node/{$nid}"),
                '#class' => 'acidfree-albums',
                '#type' => 'user_profile_item',
        );
        $i++;
      }
    }
    //Pachkov.Sergey.END - MODIFIED BY MHEINZ
  }

Body:
The dt/dd used to display the $account->content array you see in hook_user come from the user-profile-item.tpl.php template. Using template_preprocess_user_profile_item in your modules or theme, you can add attributes for these dt/dd.

If you need to change one of the items in the $account->content array, you should use hook_profile_alter:

function MODULE_profile_alter(&$account) {
  $account->content['acidfree-albums']['#title'] = t('Awesome photos!');
}


问:
css media query adjust margin-top two div
I have two div elements. I want to adjust the position second div depending on height first div. I try on to change the margin top of second div.When I resize the screen this margin-top change.

This is my initial screen

The first div is

The second div is

When I resize the screen it happens

These are the css styles second div

```<code>@media only screen and (max-width: 2560px) and (min-width: 1920px) {
   .my-list{
   margin-top:5%;}
   .my-list li {
    float: left;
    height:10%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 10%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 10%;
   font-size:18px;
   width:100%;
}

}
@media only screen and (max-width: 1920px) and (min-width: 1024px) {
 .my-list{
 }
   .my-list li {
    float: left;
    height:10%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 20%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:1%;
    text-align: center;
    text-decoration: none;
    height: 10%;
   font-size:18px;
   width:100%;
}

   }
@media only screen and (max-width: 1024px) {
   .my-list{
   }
   .my-list li {
    float: left;
    height:50%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 50%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 10%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 800px) {
    .my-list{
   }
   .my-list li {
    float: left;
    height:60%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 60%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 60%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 700px) {
    .my-list{
  }
   .my-list li {
    float: left;
    height:60%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 60%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 60%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 600px) {
    .my-list{

   width:100%;}
   .my-list li {
    float: left;
    height:50%;
    margin-right:1%;
    width: 100%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 50%;
    width:100%;
     background-size: 100% 100%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 50%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 300px) {
    .my-list{
   }
   .my-list li {
    float: left;
    height:50%;
    margin-right:5%;
    width: 100%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 50%;
    width:100%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:10%;
    text-align: center;
    text-decoration: none;
    height: 50%;
   font-size:18px;
   width:100%;
}

}
</code>```

And this is the html code

```<code><body>

<%@include file="../menu/header.jsp"%>

    <div style="position:relative;margin-top:5%;" class="my-list">
        <ul style="width:100%;position:absolute;">
            <li style="margin-left:10%;margin-top:1%;margin-bottom:1%;"><a
                href="<c:url value="/encuesta/realizar" >
                            </c:url>">Realizar Nueva Encuesta</a></li>
                <li style="margin-top:1%;margin-bottom:1%;"><a href="<c:url value="/historico/inicio" >
                              <c:param name="misEncuestas" value="T"/>
                            </c:url>">Histórico de Encuestas</a></li>
                        <li style="margin-top:1%;margin-bottom:1%;"><a href="#">Resultados Globales</a></li>

        </ul>
    </div>

</body>
</html>
</code>```

This include is the first div

```<code><%@include file="../menu/header.jsp"%>
</code>```

How can I set the position second div depending on height or position first div? Do I have to change margin-top in each media query screen?

Edited

header.jsp

```<code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page trimDirectiveWhitespaces="true"%>
<!DOCTYPE html>

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" charset=ISO-8859-1 "/>
<title>EcalcpAdmin: Cabecera imagen</title>

<script type="text/javascript"
    src="${pageContext.request.contextPath}/resources/js/jquery-1.9.1.min.js?version=<%@include file="/WEB-INF/jsp/version.txt" %>"></script>
    <script type="text/javascript"
    src="${pageContext.request.contextPath}/resources/js/jquery-ui.js">
    </script>

    <script type="text/javascript"
        src="${pageContext.request.contextPath}/resources/js/bootstrap.js?version=<%@include file="/WEB-INF/jsp/version.txt" %>"></script>

<link
            href="${pageContext.request.contextPath}/resources/css/bootstrap.css?version=<%@include file="/WEB-INF/jsp/version.txt" %>"
            rel="stylesheet" type="text/css"></link>

<style type="text/css">

.header-content-ajuste1 {
    padding-left: 20px;
    padding-right: 20px;
    vertical-align: middle;
    padding-top: 3px;
    padding-bottom: 3px;
    }

   .header-content-ajuste {
    padding-left: 1%;
    padding-right: 1%;
    vertical-align: middle;
    padding-top: 1%;
    padding-bottom: 2%;
     background: #ff230d url(${pageContext.request.contextPath}/resources/imgecalcp/fondoencabezado_marron.png) no-repeat left top;
     background-size: 100% 100%;
}

.header {
    background-color: rgb(211,38,11);
    color: #fff;
    font-size: 20px;
    margin: 0px;
    margin-bottom: 1px;
    vertical-align: middle;
    width: 100%;
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 1001;
    text-align: left;

}

@media only screen and (max-width: 1024px) {
    body {
        height:20%;
        width: 100%;
    }
}
@media only screen and (max-width: 300px) {
    body {
        height:5%;
        width: 30%;
    }
}

@media only screen and (max-width: 600px) {
    body {
        height:5%;
        width: 60%;
    }
}
.header .dropdown {

}

.header  .dropdown-menu
{
    background-color: rgb(214,230,247);
    max-height: none;
    border: 0px;
    -webkit-box-shadow: none;
    box-shadow: none;
}

.header .dropdown-toggle:focus, .dropdown-toggle:active
{
    color: #CDE8FF;
    text-decoration:none;
}

.content {
  width: 100%;
}

.paragraphs1 {

  margin-left: 60%;

}
.paragraphs2 {

   margin-left:60%;
   margin-top:1%;
}

    </style>

</head>
<body>
<fmt:parseDate pattern="ddMMyyyy HH:mm:ss" value="${datosCabeceraObj.fechaAcceso}"  var="fechaAccesoToken"/>

            <fmt:formatDate type="both" dateStyle="long"
            value="${fechaAccesoToken}" var="fechaAccesoFormat" />

<div  class="header">
<div class="header-content-ajuste">

<div style="float: left; vertical-align:middle;">
            <img src="${pageContext.request.contextPath}/resources/css/images/logo-cabecera-sedeDGCP.gif" style="margin: 0px 0px 0px 0px;" alt="Clases pasivas (LOGO)"/>
        </div>

<div>
<div class="tituloprincipal" style="float: left; vertical-align:middle;padding:10px 0px 10px 20px;">ECALCPADMIN</div>
<div class="paragraphs1">

   <div  class="titulosegundo" style="display:inline-block;" >
        <spring:message code="label.Usuario" />
</div>
<div  class="titulosegundo" style="display:inline-block;" >
        :
</div>
<div class="titulosegundo" style="display:inline-block;" >
                 ${datosCabeceraObj.nombreUsuario}
</div>

</div>

<div class="paragraphs2">
<div  class="titulosegundo" style="display:inline-block;">
        <spring:message code="label.FechaAcceso" />
</div>
<div class="titulosegundo"  style="display:inline-block;" >
        :
</div>
<div class="titulosegundo" style="display:inline-block;" >
                 ${fechaAccesoFormat}
</div>
<div style="display:inline-block;margin-left:5%;">
    <div  id="dropDownHelp" class="dropdown" style="display: inline-block; cursor:pointer;">
        <a class="dropdown-toggle"  style="color: white;display:inline-block;" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Ayuda
                            <span class="caret"></span>
                        </a>
                        <ul id="dropDownHelpHeader" class="dropdown-menu" aria-labelledby="dropdownMenu1">
                        <li><a id="linkHelpAbout" href="<c:url value="/home/about"/>">Acerca de</a></li>
                        <li><a id="linkHelpSupport" href="<c:url value="/home/support"/>">Soporte tècnico</a></li>
                                <li><a id="linkHelpDocumention" href="<c:url value="/home/documentation"/>">Documentación</a></li>

                        </ul>

                        </div>
</div>
</div>

</div>

</div>

</div>

        </body>
</html>
</code>```

答:
In

```<code>.my-list ul { }
</code>```

add

```<code>top: 100px; /*adjust as needed or try a % instead of px*/
</code>```

Body:
I have two div elements. I want to adjust the position second div depending on height first div. I try on to change the margin top of second div.When I resize the screen this margin-top change.

This is my initial screen

The first div is

The second div is

When I resize the screen it happens

These are the css styles second div

@media only screen and (max-width: 2560px) and (min-width: 1920px) {
   .my-list{
   margin-top:5%;}
   .my-list li {
    float: left;
    height:10%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 10%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 10%;
   font-size:18px;
   width:100%;
}

}
@media only screen and (max-width: 1920px) and (min-width: 1024px) {
 .my-list{
 }
   .my-list li {
    float: left;
    height:10%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 20%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:1%;
    text-align: center;
    text-decoration: none;
    height: 10%;
   font-size:18px;
   width:100%;
}

   }
@media only screen and (max-width: 1024px) {
   .my-list{
   }
   .my-list li {
    float: left;
    height:50%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 50%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 10%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 800px) {
    .my-list{
   }
   .my-list li {
    float: left;
    height:60%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 60%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 60%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 700px) {
    .my-list{
  }
   .my-list li {
    float: left;
    height:60%;
    margin-right:5%;
    width: 20%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 60%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 60%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 600px) {
    .my-list{

   width:100%;}
   .my-list li {
    float: left;
    height:50%;
    margin-right:1%;
    width: 100%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 50%;
    width:100%;
     background-size: 100% 100%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:3%;
    text-align: center;
    text-decoration: none;
    height: 50%;
   font-size:18px;
   width:100%;
}

}

@media only screen and (max-width: 300px) {
    .my-list{
   }
   .my-list li {
    float: left;
    height:50%;
    margin-right:5%;
    width: 100%;

}
.my-list ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #ACBFF6;
    height: 50%;
    width:100%;

}
   .my-list li a {
    display: block;
     color: #0c3aaa;
    text-align: center;
    padding-left: 0px;
    padding-right: 0px;
    padding-top:10%;
    text-align: center;
    text-decoration: none;
    height: 50%;
   font-size:18px;
   width:100%;
}

}

And this is the html code

<%@include file="../menu/header.jsp"%>

<a
                href="<c:url value="/encuesta/realizar" >
                            </c:url>">Realizar Nueva Encuesta

<a href="<c:url value="/historico/inicio" >
                              <c:param name="misEncuestas" value="T"/>
                            </c:url>">Histórico de Encuestas

Resultados Globales

This include is the first div

<%@include file="../menu/header.jsp"%>

How can I set the position second div depending on height or position first div? Do I have to change margin-top in each media query screen?

Edited

header.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page trimDirectiveWhitespaces="true"%>
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=Edge" charset=ISO-8859-1 "/>
<title>EcalcpAdmin: Cabecera imagen</title>

<link
            href="${pageContext.request.contextPath}/resources/css/bootstrap.css?version=<%@include file="/WEB-INF/jsp/version.txt" %>"
            rel="stylesheet" type="text/css"></link>

<fmt:parseDate pattern="ddMMyyyy HH:mm:ss" value="${datosCabeceraObj.fechaAcceso}"  var="fechaAccesoToken"/>

            <fmt:formatDate type="both" dateStyle="long"
            value="${fechaAccesoToken}" var="fechaAccesoFormat" />

ECALCPADMIN

        <spring:message code="label.Usuario" />

        :

                 ${datosCabeceraObj.nombreUsuario}

        <spring:message code="label.FechaAcceso" />

        :

                 ${fechaAccesoFormat}

                            Ayuda

<a id="linkHelpAbout" href="<c:url value="/home/about"/>">Acerca de

<a id="linkHelpSupport" href="<c:url value="/home/support"/>">Soporte tècnico

<a id="linkHelpDocumention" href="<c:url value="/home/documentation"/>">Documentación

Body:
In

.my-list ul { }

add

top: 100px; /*adjust as needed or try a % instead of px*/


问:
Apache Directory Studio java was started but returned exit code=13
I have to install Apache Directory Studio.

For this I perform the below Steps

Download ApacheDirectoryStudio-win32-x86-2.0.0.v20130628.exe

Double click on ApacheDirectoryStudio-win32-x86-2.0.0.v20130628.exe and perform Next than it ask for Java Home Directory

I browse and give the path C:\Program Files\Java\jdk1.8.0_60\ on Java Home Directory and perform Next Steps as Default Configuration

After complete installation of Apache Directory Studio when I try to Open Apache Directory Studio it gives the following Error

I am using Java 1.8 and Windows 10.

答:
This has been resolved.

The issue is that, my "Apache Directory Studio" is 64bit and my "jdk" is 32bit.
So I just uninstalled the jdk 32bit and installed jdk 64bit, after this issue has been fixed.

Thanks everyone for sharing your knowledge.

ContentLicense: CC BY-SA 4.0


问:
Finding the max of sum of the values in the inner nested defaultdict
Given a defaultdict(Counter) as such:

```<code>from collections import defaultdict, Counter

from collections import defaultdict, Counter

x = {('a', 'z'): Counter({'crazy': 1, 'lazy': 1}),
     ('b', 'r'): Counter({'brown': 1}),
     ('d', 'o'): Counter({'dog': 1}),
     ('e', 'r'): Counter({'over': 1}),
     ('f', 'o'): Counter({'fox': 1}),
     ('h', 'e'): Counter({'the': 2}),
     ('j', 'u'): Counter({'jumps': 1}),
     ('l', 'a'): Counter({'lazy': 1}),
     ('m', 'p'): Counter({'jumps': 1}),
     ('o', 'g'): Counter({'dog': 1}),
     ('o', 'v'): Counter({'over': 1}),
     ('o', 'w'): Counter({'brown': 1}),
     ('o', 'x'): Counter({'fox': 1}),
     ('p', 's'): Counter({'jumps': 1}),
     ('r', 'o'): Counter({'brown': 1}),
     ('t', 'h'): Counter({'the': 2}),
     ('u', 'm'): Counter({'jumps': 1}),
     ('v', 'e'): Counter({'over': 1}),
     ('w', 'n'): Counter({'brown': 1}),
     ('z', 'y'): Counter({'crazy': 1, 'lazy': 1})}
</code>```

I can access the values in the tuple key as such:

```<code>>>> x[('a', 'z')]
Counter({'crazy': 1, 'lazy': 1})
</code>```

If I want to find the tuple key with the highest sum of the values in the inner dictionary, i.e. the Counter, I can do this:

```<code>>>> max([(sum(x[ng].values()), ng) for ng in x])
(2, ('z', 'y'))
>>> max([(sum(x[ng].values()), ng) for ng in x])[1]
('z', 'y')
</code>```

I think the steps are a little convoluted to get the max values. Is there a more straightforward way to get the max of sum of the values in the inner nested defaultdict?

Note as much as possible don't recreate another object from x. This sample is small but the actual size of the x object can contain 1,000,000 keys and the inner counters could be in 10,000,000 in size.

答:
[] are unneeded

```<code>print ( max((sum(x[ng].values()), ng) for ng in x)[1] )
</code>```

Cleaning up with .items()

```<code>print ( max((sum(v.values()), k) for k,v in x.items())[1] )
</code>```

Max w/ lambda version

```<code>print ( max(x, key=lambda y: sum(x[y].values())) )
</code>```

The map method

```<code>print ( max(map(lambda ng: (sum(x[ng].values()), ng), x))[1] )
</code>```

Body:
Given a defaultdict(Counter) as such:

from collections import defaultdict, Counter

from collections import defaultdict, Counter

x = {('a', 'z'): Counter({'crazy': 1, 'lazy': 1}),
     ('b', 'r'): Counter({'brown': 1}),
     ('d', 'o'): Counter({'dog': 1}),
     ('e', 'r'): Counter({'over': 1}),
     ('f', 'o'): Counter({'fox': 1}),
     ('h', 'e'): Counter({'the': 2}),
     ('j', 'u'): Counter({'jumps': 1}),
     ('l', 'a'): Counter({'lazy': 1}),
     ('m', 'p'): Counter({'jumps': 1}),
     ('o', 'g'): Counter({'dog': 1}),
     ('o', 'v'): Counter({'over': 1}),
     ('o', 'w'): Counter({'brown': 1}),
     ('o', 'x'): Counter({'fox': 1}),
     ('p', 's'): Counter({'jumps': 1}),
     ('r', 'o'): Counter({'brown': 1}),
     ('t', 'h'): Counter({'the': 2}),
     ('u', 'm'): Counter({'jumps': 1}),
     ('v', 'e'): Counter({'over': 1}),
     ('w', 'n'): Counter({'brown': 1}),
     ('z', 'y'): Counter({'crazy': 1, 'lazy': 1})}

I can access the values in the tuple key as such:

>>> x[('a', 'z')]
Counter({'crazy': 1, 'lazy': 1})

If I want to find the tuple key with the highest sum of the values in the inner dictionary, i.e. the Counter, I can do this:

>>> max([(sum(x[ng].values()), ng) for ng in x])
(2, ('z', 'y'))
>>> max([(sum(x[ng].values()), ng) for ng in x])[1]
('z', 'y')

I think the steps are a little convoluted to get the max values. Is there a more straightforward way to get the max of sum of the values in the inner nested defaultdict?

Note as much as possible don't recreate another object from x. This sample is small but the actual size of the x object can contain 1,000,000 keys and the inner counters could be in 10,000,000 in size.

Body:
[] are unneeded

print ( max((sum(x[ng].values()), ng) for ng in x)[1] )

Cleaning up with .items()

print ( max((sum(v.values()), k) for k,v in x.items())[1] )

Max w/ lambda version

print ( max(x, key=lambda y: sum(x[y].values())) )

The map method

print ( max(map(lambda ng: (sum(x[ng].values()), ng), x))[1] )


问:
How to programmatically add a RibbonTab to WPF Ribbon (October 2010 release)?
Does anybody know a way to programatically add a RibbonTab to a Mircosoft WPF Ribbon? I can't find an example or at least a property to use in neither documentation nor Ribbon's intellisense.

I found many entries all over the web suggesting something like: ribbon.Tabs.Add(...)

Unfortunately "Tabs" doesn't exist in the Ribbon class at all?! Was there an API change I can't find anything about or what's the trick?

答:
I haven't used the Microsoft WPF Ribbon much so I'm afraid I don't know, but I can however recommend the Microsoft Fluent Ribbon; I've had a lot more success implementing it, and found it significantly more flexible and intuitive...it's on the codeplex site if it's something you're interested in (presuming you haven't gotten too deep using the MS WPF Ribbon) - fluent.codeplex.com

Hope it helps,

Aj


问:
Java android FCM , when application is minimalize or screen is lock I don't hear sound and vibratte
I use a FCM and when my application is minimalize or phone is lock I don't hear a sound and vibratte. I create a notification when something is come from a server (when server send to my phone a message). when my application is on top I hear a sound and vibratte</p>

```<code>    private void createNotification( String messageBody) {
 Bitmap Largeicon = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ic_launcher);
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_SYNCHRONIZE_ID);

        Intent intent = new Intent(getApplicationContext(), NotificationActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

//FLAG_UPDATE_CURRENT is important
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK/* | PowerManager.FULL_WAKE_LOCK*/ | PowerManager.ACQUIRE_CAUSES_WAKEUP), "SMOK Komunal");
            wakeLock.acquire();
            wakeLock.release();
        }
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Notification notification = new Notification.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Wiadomosc z serwera")
                .setStyle(new Notification.BigTextStyle().bigText(messageBody))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setLargeIcon(Largeicon)
                .setContentIntent(pendingIntent)
                .setVibrate(vibratePattern)
                .setLights(Color.GREEN, 2000, 2000)
                .build();
        notificationManager.notify(0, notification);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK /*| PowerManager.FULL_WAKE_LOCK |*/ | PowerManager.ACQUIRE_CAUSES_WAKEUP), "SMOK Komunal");
            if (wakeLock.isHeld())
                wakeLock.release();
        }
    }
</code>```

答:
try this</p>

```<code>.setDefaults(Notification.DEFAULT_SOUND)
</code>```

Body:
I use a FCM and when my application is minimalize or phone is lock I don't hear a sound and vibratte. I create a notification when something is come from a server (when server send to my phone a message). when my application is on top I hear a sound and vibratte

    private void createNotification( String messageBody) {
 Bitmap Largeicon = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ic_launcher);
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_SYNCHRONIZE_ID);

        Intent intent = new Intent(getApplicationContext(), NotificationActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

//FLAG_UPDATE_CURRENT is important
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK/* | PowerManager.FULL_WAKE_LOCK*/ | PowerManager.ACQUIRE_CAUSES_WAKEUP), "SMOK Komunal");
            wakeLock.acquire();
            wakeLock.release();
        }
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Notification notification = new Notification.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Wiadomosc z serwera")
                .setStyle(new Notification.BigTextStyle().bigText(messageBody))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setLargeIcon(Largeicon)
                .setContentIntent(pendingIntent)
                .setVibrate(vibratePattern)
                .setLights(Color.GREEN, 2000, 2000)
                .build();
        notificationManager.notify(0, notification);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK /*| PowerManager.FULL_WAKE_LOCK |*/ | PowerManager.ACQUIRE_CAUSES_WAKEUP), "SMOK Komunal");
            if (wakeLock.isHeld())
                wakeLock.release();
        }
    }

Body:
try this

.setDefaults(Notification.DEFAULT_SOUND)


问:
SCP a binary file using JSCH
I'm using the Java implementation of SSH, JSCH to do an scp from remote to local. Following the JSCH example code to scpfrom I'm able to receive files. I've used the same implementation as in the above link.

Problem:
Compressed files/photos sent are corrupt. Text files appear the same. However, when I send a binary (like a .tgz), the decompresser complains the file is corrupt. I suspect this is a binary vs ascii issue. Is this because of the way I am writing the data to file in Java? How do I properly receive and write binary files using JSCH?

The code I've written -

```<code>private void executeCommand(String username, String pwd, String hostname, int port)
        throws JSchException, IOException {
    JSch jSch = new JSch();
    Session session = jSch.getSession(username, hostname, port);
    session.setPassword(pwd);

    Properties properties = new Properties();
    properties.put("StrictHostKeyChecking", "no");
    session.setConfig(properties);

    session.connect();

    ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
    channelExec.setCommand("scp -f /home/rish/haha.txt");

    OutputStream outputStream = channelExec.getOutputStream();
    DataInputStream inputStream = new DataInputStream(channelExec.getInputStream());
    DataOutputStream fos;

    channelExec.connect();

    byte[] buf = new byte[1024];

    buf[0] = 0;
    outputStream.write(buf, 0, 1);
    outputStream.flush();

    while (true) {
        int c = checkAck(inputStream);
        if (c != 'C') {
            break;
        }

        // read '0644 '
        inputStream.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
            if (inputStream.read(buf, 0, 1) < 0) {
                // error
                break;
            }
            if (buf[0] == ' ') break;
            filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
            inputStream.read(buf, i, 1);
            if (buf[i] == (byte) 0x0a) {
                file = new String(buf, 0, i);
                break;
            }
        }

        // send '\0'
        buf[0] = 0;
        outputStream.write(buf, 0, 1);
        outputStream.flush();

        // String fileName = "/data/data/" + getPackageName() + "/crearofile" + new Random().nextInt(100) + ".txt";
        String fileName = "/data/data/rish.crearo.trial/haha.txt";

        File file1 = new File(fileName);
        if (file1.exists()) file1.delete();
        if (file1.createNewFile()) Log.d(TAG, "File created");
        else Log.d(TAG, "File not created");

        // read a content of lfile
        fos = new DataOutputStream(new FileOutputStream(fileName));

        String count;
        while ((count = inputStream.readUTF()) != null) {
            System.out.println(count);
            fos.writeBytes(count);
        }
        fos.close();

        if (checkAck(inputStream) != 0) {
            System.exit(0);
        }

        inputStream.close();
        // send '\0'
        buf[0] = 0;
        outputStream.write(buf, 0, 1);
        outputStream.flush();
    }

    session.disconnect();
}
</code>```

答:
The code you have posted is not the same as in ScpFrom.java example.

You obviously cannot use inputStream.readUTF() on binary files. UTF is text encoding. Any attempt to interpret binary files using any encoding will corrupt it (or actually in this case, the UTF decoder breaks on binary data, terminating the file transfer prematurely).

Actually that code cannot even work for text files, as you do not check a size of the downloaded data (you never use the filesize value). So you may read beyond the file end. Though it can possibly work by chance, as the UTF decoder may break upon NULL-terminator after the file contents.

(I understand that this was probably actually you attempt to workaround some another problem)

Title: SCP a binary file using JSCH

Body:
I'm using the Java implementation of SSH, JSCH to do an scp from remote to local. Following the JSCH example code to scpfrom I'm able to receive files. I've used the same implementation as in the above link.

Problem:
Compressed files/photos sent are corrupt. Text files appear the same. However, when I send a binary (like a .tgz), the decompresser complains the file is corrupt. I suspect this is a binary vs ascii issue. Is this because of the way I am writing the data to file in Java? How do I properly receive and write binary files using JSCH?

The code I've written -

private void executeCommand(String username, String pwd, String hostname, int port)
        throws JSchException, IOException {
    JSch jSch = new JSch();
    Session session = jSch.getSession(username, hostname, port);
    session.setPassword(pwd);

    Properties properties = new Properties();
    properties.put("StrictHostKeyChecking", "no");
    session.setConfig(properties);

    session.connect();

    ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
    channelExec.setCommand("scp -f /home/rish/haha.txt");

    OutputStream outputStream = channelExec.getOutputStream();
    DataInputStream inputStream = new DataInputStream(channelExec.getInputStream());
    DataOutputStream fos;

    channelExec.connect();

    byte[] buf = new byte[1024];

    buf[0] = 0;
    outputStream.write(buf, 0, 1);
    outputStream.flush();

    while (true) {
        int c = checkAck(inputStream);
        if (c != 'C') {
            break;
        }

        // read '0644 '
        inputStream.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
            if (inputStream.read(buf, 0, 1) < 0) {
                // error
                break;
            }
            if (buf[0] == ' ') break;
            filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
            inputStream.read(buf, i, 1);
            if (buf[i] == (byte) 0x0a) {
                file = new String(buf, 0, i);
                break;
            }
        }

        // send '\0'
        buf[0] = 0;
        outputStream.write(buf, 0, 1);
        outputStream.flush();

        // String fileName = "/data/data/" + getPackageName() + "/crearofile" + new Random().nextInt(100) + ".txt";
        String fileName = "/data/data/rish.crearo.trial/haha.txt";

        File file1 = new File(fileName);
        if (file1.exists()) file1.delete();
        if (file1.createNewFile()) Log.d(TAG, "File created");
        else Log.d(TAG, "File not created");

        // read a content of lfile
        fos = new DataOutputStream(new FileOutputStream(fileName));

        String count;
        while ((count = inputStream.readUTF()) != null) {
            System.out.println(count);
            fos.writeBytes(count);
        }
        fos.close();

        if (checkAck(inputStream) != 0) {
            System.exit(0);
        }

        inputStream.close();
        // send '\0'
        buf[0] = 0;
        outputStream.write(buf, 0, 1);
        outputStream.flush();
    }

    session.disconnect();
}


问:
begin() and end() for STL algorithms
I have a class whose data container is backed by an array, and I have the following implementations for begin() and end().

```<code>template <size_t size>
double * MyContainerClass<size>::begin(){
    return std::begin(mContainer);
}

template <size_t size>
double * MyContainerClass<size>::end(){
    return std::end(mContainer);
}
</code>```

In other member functions, I am attempting to use begin() and end() for STL algorithms such as std::transform and std::copy. When const objects are passed as parameters to these member functions, I encounter the error:

error: passing 'const MyContainerClass<size>' as 'this' argument discards qualifiers.

  note: in call to 'double* MyContainerClass<size>::begin() [with unsigned int size = size]'

Is this caused by incorrect begin() and end() implementations?

```<code>std::copy(begin(), end(), someOutputIterator);
</code>```

答:
The important word here is 'const': You need to provide additional const versions of your begin() and end() functions, that return const double*.

If you are using C++ 11, you may also want to provide cbegin() and cend().

Title: begin() and end() for STL algorithms

Body:
I have a class whose data container is backed by an array, and I have the following implementations for begin() and end().

template <size_t size>
double * MyContainerClass<size>::begin(){
    return std::begin(mContainer);
}

template <size_t size>
double * MyContainerClass<size>::end(){
    return std::end(mContainer);
}

In other member functions, I am attempting to use begin() and end() for STL algorithms such as std::transform and std::copy. When const objects are passed as parameters to these member functions, I encounter the error:

error: passing 'const MyContainerClass<size>' as 'this' argument discards qualifiers.

  note: in call to 'double* MyContainerClass<size>::begin() [with unsigned int size = size]'

Is this caused by incorrect begin() and end() implementations?

std::copy(begin(), end(), someOutputIterator);


问:
Ubuntu : 'Login-AzureRmAccount' is not recognized as the name of a cmdlet
I have installed Powershell in my Ubuntu machine. When I enter Login-AzureRmAccount into PowerShell, I get error as below:

```<code>PS> Login-AzureRmAccount
Login-AzureRmAccount : The term 'Login-AzureRmAccount' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Login-AzureRmAccount
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Login-AzureRmAccount:String) [], CommandNotFoundException
</code>```

When I enter Get-Module -ListAvailable -Name Azure -Refresh, I didn't get any result.

PowerShell version:

```<code>powershell -version
powershell v6.0.0-alpha.17
</code>```

How to solve the above error?

答:
You need to install the Azure PowerShell module first:

```<code>#Azure RM NetCore Preview Module Install
powershell Install-Module AzureRM.NetCore.Preview
powershell Import-Module AzureRM.NetCore.Preview
</code>```

This is my test.

```<code>root@shui:/home# powershell
PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS /home> Login-AzureRmAccount
VERBOSE: To sign in, use a web browser to open the page https://aka.ms/devicelogin and enter the code F2RKUXRNE to authenticate.
</code>```

For more information please refer to this link.

Body:
I have installed Powershell in my Ubuntu machine. When I enter Login-AzureRmAccount into PowerShell, I get error as below:

PS> Login-AzureRmAccount
Login-AzureRmAccount : The term 'Login-AzureRmAccount' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Login-AzureRmAccount
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Login-AzureRmAccount:String) [], CommandNotFoundException

When I enter Get-Module -ListAvailable -Name Azure -Refresh, I didn't get any result.

PowerShell version:

powershell -version
powershell v6.0.0-alpha.17

How to solve the above error?

Body:
You need to install the Azure PowerShell module first:

#Azure RM NetCore Preview Module Install
powershell Install-Module AzureRM.NetCore.Preview
powershell Import-Module AzureRM.NetCore.Preview

This is my test.

root@shui:/home# powershell
PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS /home> Login-AzureRmAccount
VERBOSE: To sign in, use a web browser to open the page https://aka.ms/devicelogin and enter the code F2RKUXRNE to authenticate.

For more information please refer to this link.


问:
AHK - Tool not clicking Chrome button in Multiloginapp
I have a GUI that contains a 'Start app' button which leads to a launch of http://multitaskapp.com, waiting 30 seconds, and clicking on the Chrome app in the Browser profiles. I thought the sleep function would allow the app to wait for the multiloginapp to complete loading and then click inside the app.

```<code>;; GUI input
: -------------------------------
: ---------------------------------------
Gui, Show, w300 h300, Steam Tool

Gui, Add, Button, x10 y20 gStart, Start the tool
return

; Labels
; -----------------------
; --------------------------------

Start:
    Run, C:\Program Files (x86)\Multiloginapp\multiloginapp.exe
    WinActivate, Multiloginapp - 01.3.15
    WinWaitActive, Multiloginapp - 01.3.15
    Sleep, 30
    Click 817, 240
</code>```

答:
WinActivate only makes sense if the window exists.
Try WinWait before it:

```<code>Start:
    Run, C:\Program Files (x86)\Multiloginapp\multiloginapp.exe
    WinWait, Multiloginapp - 01.3.15
    IfWinNotActive, Multiloginapp - 01.3.15, ,WinActivate, Multiloginapp - 01.3.15
    WinWaitActive, Multiloginapp - 01.3.15
    Sleep, 500  ; 0,5 seconds.  For waiting 30 seconds use "Sleep, 30000"
    Click 817, 240
    ; ---
return
</code>```

EDIT

If you have to wait for 30 seconds, try this:

```<code>Start:
    Run, C:\Program Files (x86)\Multiloginapp\multiloginapp.exe
    WinWait, Multiloginapp - 01.3.15
    Sleep, 30000
    IfWinNotActive, Multiloginapp - 01.3.15, ,WinActivate, Multiloginapp - 01.3.15
    WinWaitActive, Multiloginapp - 01.3.15
    Sleep, 200
    Click 817, 240
    ; ---
return
</code>```

Body:
I have a GUI that contains a 'Start app' button which leads to a launch of http://multitaskapp.com, waiting 30 seconds, and clicking on the Chrome app in the Browser profiles. I thought the sleep function would allow the app to wait for the multiloginapp to complete loading and then click inside the app.

;; GUI input
: -------------------------------
: ---------------------------------------
Gui, Show, w300 h300, Steam Tool

Gui, Add, Button, x10 y20 gStart, Start the tool
return

; Labels
; -----------------------
; --------------------------------

Start:
    Run, C:\Program Files (x86)\Multiloginapp\multiloginapp.exe
    WinActivate, Multiloginapp - 01.3.15
    WinWaitActive, Multiloginapp - 01.3.15
    Sleep, 30
    Click 817, 240

Body:
WinActivate only makes sense if the window exists.
Try WinWait before it:

Start:
    Run, C:\Program Files (x86)\Multiloginapp\multiloginapp.exe
    WinWait, Multiloginapp - 01.3.15
    IfWinNotActive, Multiloginapp - 01.3.15, ,WinActivate, Multiloginapp - 01.3.15
    WinWaitActive, Multiloginapp - 01.3.15
    Sleep, 500  ; 0,5 seconds.  For waiting 30 seconds use "Sleep, 30000"
    Click 817, 240
    ; ---
return

EDIT

If you have to wait for 30 seconds, try this:

Start:
    Run, C:\Program Files (x86)\Multiloginapp\multiloginapp.exe
    WinWait, Multiloginapp - 01.3.15
    Sleep, 30000
    IfWinNotActive, Multiloginapp - 01.3.15, ,WinActivate, Multiloginapp - 01.3.15
    WinWaitActive, Multiloginapp - 01.3.15
    Sleep, 200
    Click 817, 240
    ; ---
return


问:
Close modal on AJAX Sucess(ASP.NET MVC)
I have Modal in view for making new record in Database.

View for it in Partial View

Here is code of view

```<code><script src="~/Scripts/jquery-3.1.1.js"></script>
</code>```

For AJAX I using this code

```<code><script>
   $(document).ready(function () {
       $('#save_quest').click(function () {
        savequestion();
    });
});
    function savequestion() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                Question_new: $('#question').val(),
                Answer: $('#answer').val(),
                Preparing: $('#prepare').val(),
                Retries: $('#retries').val(),
                  },
            url: '@Url.Action("CreateNewQuestion", "Questions")',
            success: function (da) {
                if (da.Result === "Success") {
                    $('#myModal').modal('hide')
                    //window.location.href = da.RedirectUrl;

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</code>```

I need to hide modal when AJAX call is Successful

I try this $('#myModal').modal('hide')

Here is my modal on Primary View

```<code><div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
<div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
            @Html.Partial("~/Views/Questions/CreateQuestion.cshtml")
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>

</div>
</code>```

How I can hide it on AJAX Success?

答:
You can try any of the below option  in your ajax success block. Hopefully it will solve your problem.</p>

```<code>        $("#myModal").modal('hide');
    OR
        $('#myModal').modal('toggle');
    OR
        $('#myModal').removeClass('show');
    OR
        $('#myModal').modal().hide();
    OR
        $("#myModal .close").click();
    OR
        $("#myModal .close").trigger("click");
</code>```

Title: Close modal on AJAX Sucess(ASP.NET MVC)

Body:
I have Modal in view for making new record in Database.

View for it in Partial View

Here is code of view

For AJAX I using this code

Body:
You can try any of the below option  in your ajax success block. Hopefully it will solve your problem.

        $("#myModal").modal('hide');
    OR
        $('#myModal').modal('toggle');
    OR
        $('#myModal').removeClass('show');
    OR
        $('#myModal').modal().hide();
    OR
        $("#myModal .close").click();
    OR
        $("#myModal .close").trigger("click");


问:
secure include files
I'd like to know the BEST solution to secure includes files.
For now my solution is this :

in the index file :

```<code>define('KEY','security');
include('s.php';
</code>```

s.php :

```<code>if(KEY!='security') exit;
</code>```

答:
Most cases of similar code don't even check for a known value of key, but just check if it is defined.

For example Mediawiki uses this in include files:

```<code><?php
if( !defined( 'MEDIAWIKI' ) ) {
    die( 1 );
}
</code>```

Title: secure include files

Body:
I'd like to know the BEST solution to secure includes files.
For now my solution is this :

in the index file :

define('KEY','security');
include('s.php';

s.php :

if(KEY!='security') exit;

Body:
Most cases of similar code don't even check for a known value of key, but just check if it is defined.

For example Mediawiki uses this in include files:

<?php
if( !defined( 'MEDIAWIKI' ) ) {
    die( 1 );
}


问:
Matlab: How to compute the inverse of a matrix
I want to find the T inverse as given in the picture. The first picture is the matrix T and the other is T inverse.

```<code>I = eye(3);
T = [I/2, (j/2)*I, 0;
     I/2,  (-j/2)*I, 0;
     0,0,I];
</code>```

Error using horzcat
CAT arguments dimensions are not consistent.

Then I tried with I = eye(2) and got the same error. What is the proper way?

答:
Given

```<code>I = eye(3);
</code>```

you want to multiply element-wise using .* with A (make sure you use the imaginary unit 1j and not an undefined variable j)

```<code>A = [1/2, (1j/2), 0;
     1/2,  (-1j/2), 0;
     0,0,1];
</code>```

to get T

```<code>T = A.*I
</code>```

But apart from that it feels like you actually want to multiply A with a constant C = I = 1

```<code>T = A.*1
</code>```

The inverse you obtain with the inverse function:

```<code>Tinv = inv(T)
</code>```

Body:
I want to find the T inverse as given in the picture. The first picture is the matrix T and the other is T inverse.

I = eye(3);
T = [I/2, (j/2)*I, 0;
     I/2,  (-j/2)*I, 0;
     0,0,I];

Error using horzcat
CAT arguments dimensions are not consistent.

Then I tried with I = eye(2) and got the same error. What is the proper way?

Body:
Given

I = eye(3);

you want to multiply element-wise using .* with A (make sure you use the imaginary unit 1j and not an undefined variable j)

A = [1/2, (1j/2), 0;
     1/2,  (-1j/2), 0;
     0,0,1];

to get T

T = A.*I

But apart from that it feels like you actually want to multiply A with a constant C = I = 1

T = A.*1

The inverse you obtain with the inverse function:

Tinv = inv(T)