问:
Showing list empty message at the center of the screen in a FlatList using ListHeaderComponent
I am using React-Native version 0.43.0 which does not support ListEmptyComponent of FlatList. Hence I am using ListHeaderComponent to render a view when the list is empty,

```<code>import React, { Component } from 'react';
import { Text, View, StyleSheet,FlatList } from 'react-native';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      listData: []
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          renderItem={() => null}
          data={this.state.listData}
          ListHeaderComponent={() => (!this.state.listData.length?
            <Text style={styles.emptyMessageStyle}>The list is empty</Text>
            : null)
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  emptyMessageStyle: {
    textAlign: 'center',
    //My current hack to center it vertically
    //Which does not work as expected
    marginTop: '50%',
  }
});
</code>```

As you can see from the image the text is not centered vertically

Any idea how to center it vertically in a FlatList?

I have already tried applying justifyContent, alignItems etc but no use.

This is a link to the snack.expo - https://snack.expo.io/S16dDifZf

答:
You can add a style to the FlatList.

```<code>const styles = StyleSheet.create({
  container: {
    flex:1
  },
  listStyle: {
    justifyContent: 'center'
  },
  emptyMessageStyle: {
    textAlign: 'center',
    }

});

  render() {
    return (
      <View style={styles.container}>
        <FlatList style={styles.listStyle}
          renderItem={() => null}
          data={this.state.listData}
          ListHeaderComponent={() => (!this.state.listData.length ?
            <Text style={styles.emptyMessageStyle}>The list is empty</Text>
            : null)}
        />
      </View>
    );
  }
</code>```

This will center the items in the list, when the list is not empty. You may have to apply another style (when the list is not empty), if you don't prefer the non empty style.

Link to snack.expo

Another option - without changing FlatList style - conditionally rendering FlatList based on this.state.listData.length

```<code>render() {
    return (
      <View style={styles.container}>
        {
          this.state.listData.length?

          (<FlatList
            renderItem={() => null}
            data={this.state.listData}
          />)
          :
          (
            <View style={styles.emptyListStyle}>
              <Text style={styles.emptyMessageStyle}>The list is empty</Text>
            </View>
          )
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  emptyListStyle: {
    flex: 1,
    justifyContent: 'center'
  },
  emptyMessageStyle: {
    textAlign: 'center',
    }

});
</code>```

This is the snack.expo

Body:
I am using React-Native version 0.43.0 which does not support ListEmptyComponent of FlatList. Hence I am using ListHeaderComponent to render a view when the list is empty,

import React, { Component } from 'react';
import { Text, View, StyleSheet,FlatList } from 'react-native';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      listData: []
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          renderItem={() => null}
          data={this.state.listData}
          ListHeaderComponent={() => (!this.state.listData.length?
            <Text style={styles.emptyMessageStyle}>The list is empty</Text>
            : null)
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  emptyMessageStyle: {
    textAlign: 'center',
    //My current hack to center it vertically
    //Which does not work as expected
    marginTop: '50%',
  }
});

As you can see from the image the text is not centered vertically

Any idea how to center it vertically in a FlatList?

I have already tried applying justifyContent, alignItems etc but no use.

This is a link to the snack.expo - https://snack.expo.io/S16dDifZf

Body:
You can add a style to the FlatList.

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  listStyle: {
    justifyContent: 'center'
  },
  emptyMessageStyle: {
    textAlign: 'center',
    }

});

  render() {
    return (
      <View style={styles.container}>
        <FlatList style={styles.listStyle}
          renderItem={() => null}
          data={this.state.listData}
          ListHeaderComponent={() => (!this.state.listData.length ?
            <Text style={styles.emptyMessageStyle}>The list is empty</Text>
            : null)}
        />
      </View>
    );
  }

This will center the items in the list, when the list is not empty. You may have to apply another style (when the list is not empty), if you don't prefer the non empty style.

Link to snack.expo

Another option - without changing FlatList style - conditionally rendering FlatList based on this.state.listData.length

render() {
    return (
      <View style={styles.container}>
        {
          this.state.listData.length?

          (<FlatList
            renderItem={() => null}
            data={this.state.listData}
          />)
          :
          (
            <View style={styles.emptyListStyle}>
              <Text style={styles.emptyMessageStyle}>The list is empty</Text>
            </View>
          )
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex:1
  },
  emptyListStyle: {
    flex: 1,
    justifyContent: 'center'
  },
  emptyMessageStyle: {
    textAlign: 'center',
    }

});

This is the snack.expo


来源: stackexchange

问:
Add Custom Shapes to MXGraph Toolbar
I am trying to add Custom shapes to a toolbar in MXGraph like it is shown in the examples for a toolbar. For exapmle: something like this:

```<code>addVertex('assets/displayResources/images/labelIcon.png', 60, 30, 'shape=displayLabel');
</code>```

Now my own shape (in this case displayLabel) should be in the grid if u drag and drop it out of the toolbar. but it is always only the "default" shape that is visible.

I already registered my Shape like it is shown in the shape example:mxCellRenderer.prototype.defaultShapes['displayLabel'] = mxDisplayLabel;

I also tried different ways to call its style in the addVertex Method but it wont work. Even if i try the Boxshape that is shown in the "Shape" Example from mxgraph i only see the default shape...

EDIT: This is what i try at the moment:

```<code>    function BoxShape()
{
    mxCylinder.call(this);
};
mxUtils.extend(BoxShape, mxCylinder);
BoxShape.prototype.extrude = 10;
BoxShape.prototype.redrawPath = function(path, x, y, w, h, isForeground)
{
    var dy = this.extrude * this.scale;
    var dx = this.extrude * this.scale;
    if (isForeground)
    {
        path.moveTo(0, dy);
        path.lineTo(w - dx, dy);
        path.lineTo(w, 0);
        path.moveTo(w - dx, dy);
        path.lineTo(w - dx, h);
    }
    else
    {
        path.moveTo(0, dy);
        path.lineTo(dx, 0);
        path.lineTo(w, 0);
        path.lineTo(w, h - dy);
        path.lineTo(w - dx, h);
        path.lineTo(0, h);
        path.lineTo(0, dy);
        path.lineTo(dx, 0);
        path.close();
    }
};
mxCellRenderer.registerShape('box', BoxShape);

function creatingDisplayCreator(){
    if (!mxClient.isBrowserSupported()) {
            mxUtils.error('Browser is not supported!', 200, false);
    }else {
    var container = document.getElementById("graphContainer");

        mxEvent.disableContextMenu(container);

        var model = new mxGraphModel();
        graph = new mxGraph(container, model);

        mxGraphHandler.prototype.scrollOnMove = false;

        graph.dropEnabled = true;
        var parent = graph.getDefaultParent();

        var tbContainer = document.getElementById("tbContainer");

        var toolbar = new mxToolbar(tbContainer);
        toolbar.enabled = false;

        mxDragSource.prototype.getDropTarget = function (graph, x, y) {
            var cell = graph.getCellAt(x, y);

            if (!graph.isValidDropTarget(cell)) {
                 cell = null;
            }

            return cell;
        };
         var addVertex = function (icon, w, h, style) {
            var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
            vertex.setVertex(true);
            vertex.setConnectable(false);

            if(style=='shape=displayLabel'){
                vertex.value = 'label';
                graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, 'transparent', [vertex]);
                graph.setCellStyles(mxConstants.STYLE_STROKECOLOR, 'transparent', [vertex]);
                graph.setCellStyles(mxConstants.STYLE_FONTSIZE, 15, [vertex]);
            }
};
            addToolbarItem(graph, toolbar, vertex, icon);
        };
        addVertex('a.png', 60, 30, 'shape=box');
        function addToolbarItem(graph, toolbar, prototype, image) {
        var funct = function (graph, evt, cell) {
        graph.stopEditing(false);

        var pt = graph.getPointForEvent(evt);
        var vertex = graph.getModel().cloneCell(prototype);

        vertex.geometry.x = pt.x;
        vertex.geometry.y = pt.y;

        graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
    }

    var img = toolbar.addMode(null, image, funct);
    mxUtils.makeDraggable(img, graph, funct);
};
</code>```

EDIT 2:
Now i was able to register my custom shapes, but further i got a Problem that says: "shape.initStyles()" is not a function if i drop a vertex in the grid. anyone know, where this came from?

答:
Here is the solution.

Define shape like this

```<code>function BoxShape()
{
    mxCylinder.call(this);
};
mxUtils.extend(BoxShape, mxCylinder);
BoxShape.prototype.extrude = 10;
BoxShape.prototype.redrawPath = function(path, x, y, w, h, isForeground)
{
    var dy = this.extrude * this.scale;
    var dx = this.extrude * this.scale;
    if (isForeground)
    {
        path.moveTo(0, dy);
        path.lineTo(w - dx, dy);
        path.lineTo(w, 0);
        path.moveTo(w - dx, dy);
        path.lineTo(w - dx, h);
    }
    else
    {
        path.moveTo(0, dy);
        path.lineTo(dx, 0);
        path.lineTo(w, 0);
        path.lineTo(w, h - dy);
        path.lineTo(w - dx, h);
        path.lineTo(0, h);
        path.lineTo(0, dy);
        path.lineTo(dx, 0);
        path.close();
    }
};
mxCellRenderer.registerShape('box', BoxShape);
</code>```

Then add shape to toolbar like this

```<code>addVertex('a.png', 320, 100, 'shape=box');
</code>```

addVertex method:

```<code>var addVertex = function(icon, w, h, style)
{
    var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
    vertex.setVertex(true);

    var funct = function(graph, evt, cell)
    {
        graph.stopEditing(false);
        var pt = graph.getPointForEvent(evt);
        var vertex = graph.getModel().cloneCell(prototype);
        vertex.geometry.x = pt.x;
        vertex.geometry.y = pt.y;
        graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
    }

    // Creates the image which is used as the drag icon (preview)
    var img = toolbar.addMode(null, image, funct);
    mxUtils.makeDraggable(img, graph, funct);
};
</code>```

Reference

ContentLicense: CC BY-SA 3.0

Title: Add Custom Shapes to MXGraph Toolbar

Body:
I am trying to add Custom shapes to a toolbar in MXGraph like it is shown in the examples for a toolbar. For exapmle: something like this:

addVertex('assets/displayResources/images/labelIcon.png', 60, 30, 'shape=displayLabel');

Now my own shape (in this case displayLabel) should be in the grid if u drag and drop it out of the toolbar. but it is always only the "default" shape that is visible.

I already registered my Shape like it is shown in the shape example:mxCellRenderer.prototype.defaultShapes['displayLabel'] = mxDisplayLabel;

I also tried different ways to call its style in the addVertex Method but it wont work. Even if i try the Boxshape that is shown in the "Shape" Example from mxgraph i only see the default shape...

EDIT: This is what i try at the moment:

    function BoxShape()
{
    mxCylinder.call(this);
};
mxUtils.extend(BoxShape, mxCylinder);
BoxShape.prototype.extrude = 10;
BoxShape.prototype.redrawPath = function(path, x, y, w, h, isForeground)
{
    var dy = this.extrude * this.scale;
    var dx = this.extrude * this.scale;
    if (isForeground)
    {
        path.moveTo(0, dy);
        path.lineTo(w - dx, dy);
        path.lineTo(w, 0);
        path.moveTo(w - dx, dy);
        path.lineTo(w - dx, h);
    }
    else
    {
        path.moveTo(0, dy);
        path.lineTo(dx, 0);
        path.lineTo(w, 0);
        path.lineTo(w, h - dy);
        path.lineTo(w - dx, h);
        path.lineTo(0, h);
        path.lineTo(0, dy);
        path.lineTo(dx, 0);
        path.close();
    }
};
mxCellRenderer.registerShape('box', BoxShape);

function creatingDisplayCreator(){
    if (!mxClient.isBrowserSupported()) {
            mxUtils.error('Browser is not supported!', 200, false);
    }else {
    var container = document.getElementById("graphContainer");

        mxEvent.disableContextMenu(container);

        var model = new mxGraphModel();
        graph = new mxGraph(container, model);

        mxGraphHandler.prototype.scrollOnMove = false;

        graph.dropEnabled = true;
        var parent = graph.getDefaultParent();

        var tbContainer = document.getElementById("tbContainer");

        var toolbar = new mxToolbar(tbContainer);
        toolbar.enabled = false;

        mxDragSource.prototype.getDropTarget = function (graph, x, y) {
            var cell = graph.getCellAt(x, y);

            if (!graph.isValidDropTarget(cell)) {
                 cell = null;
            }

            return cell;
        };
         var addVertex = function (icon, w, h, style) {
            var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
            vertex.setVertex(true);
            vertex.setConnectable(false);

            if(style=='shape=displayLabel'){
                vertex.value = 'label';
                graph.setCellStyles(mxConstants.STYLE_FILLCOLOR, 'transparent', [vertex]);
                graph.setCellStyles(mxConstants.STYLE_STROKECOLOR, 'transparent', [vertex]);
                graph.setCellStyles(mxConstants.STYLE_FONTSIZE, 15, [vertex]);
            }
};
            addToolbarItem(graph, toolbar, vertex, icon);
        };
        addVertex('a.png', 60, 30, 'shape=box');
        function addToolbarItem(graph, toolbar, prototype, image) {
        var funct = function (graph, evt, cell) {
        graph.stopEditing(false);

        var pt = graph.getPointForEvent(evt);
        var vertex = graph.getModel().cloneCell(prototype);

        vertex.geometry.x = pt.x;
        vertex.geometry.y = pt.y;

        graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
    }

    var img = toolbar.addMode(null, image, funct);
    mxUtils.makeDraggable(img, graph, funct);
};

EDIT 2:
Now i was able to register my custom shapes, but further i got a Problem that says: "shape.initStyles()" is not a function if i drop a vertex in the grid. anyone know, where this came from?

Body:
Here is the solution.

Define shape like this

function BoxShape()
{
    mxCylinder.call(this);
};
mxUtils.extend(BoxShape, mxCylinder);
BoxShape.prototype.extrude = 10;
BoxShape.prototype.redrawPath = function(path, x, y, w, h, isForeground)
{
    var dy = this.extrude * this.scale;
    var dx = this.extrude * this.scale;
    if (isForeground)
    {
        path.moveTo(0, dy);
        path.lineTo(w - dx, dy);
        path.lineTo(w, 0);
        path.moveTo(w - dx, dy);
        path.lineTo(w - dx, h);
    }
    else
    {
        path.moveTo(0, dy);
        path.lineTo(dx, 0);
        path.lineTo(w, 0);
        path.lineTo(w, h - dy);
        path.lineTo(w - dx, h);
        path.lineTo(0, h);
        path.lineTo(0, dy);
        path.lineTo(dx, 0);
        path.close();
    }
};
mxCellRenderer.registerShape('box', BoxShape);

Then add shape to toolbar like this

addVertex('a.png', 320, 100, 'shape=box');

addVertex method:

var addVertex = function(icon, w, h, style)
{
    var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
    vertex.setVertex(true);

    var funct = function(graph, evt, cell)
    {
        graph.stopEditing(false);
        var pt = graph.getPointForEvent(evt);
        var vertex = graph.getModel().cloneCell(prototype);
        vertex.geometry.x = pt.x;
        vertex.geometry.y = pt.y;
        graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
    }

    // Creates the image which is used as the drag icon (preview)
    var img = toolbar.addMode(null, image, funct);
    mxUtils.makeDraggable(img, graph, funct);
};

Reference


问:
Grouping neighbours in separate arrays in MATLAB
I have an annotated 512x512x3 fingerprint image, with the annotations being the positions of loops and deltas in the image.  Red denotes loop, and blue denotes delta.

I need to find the position of these points. I can do this using impixel(), but I wanted a more automated approach.

I did the following:

```<code>x=[];
y=[];
for i = 1:512
    for j = 1:512
        marked = im(i,j,:);
        if marked(:,:,1)==255
            x=[x i];
            y=[y j];
        end
    end
end
x = unique(x);
y = unique(y);
</code>```

and got the positions of the pixels where the color red is the position of the loops.

My array y holds the y coordinates of all the red pixels, like this:

```<code>[116 117 118 119 120 121 122 191 192 193 194 195 196 197]
</code>```

At first glance, it is clear that the values can be grouped into 2 groups, for the two red points. But I am unsure how to divide the values into two groups. I thought about creating a threshold using the mean of the values, but that might not work if the points are close by.

Any help might be useful.

答:
If you know in advance how many red points there will be (2 in the example), you could use kmeans -

```<code>y_groups = kmeans(y',2);
</code>```

If you don't know the number of groups, then if the points always contain the same number of pixels, you could work it out from that - in the example there are 7 pixels per point so

```<code>npts = numel(y) / 7;
y_groups = kmeans(y',npts);
</code>```

We could add a loop afterwards to get the mean of each group (there are many other ways you could look into for this too e.g. grpstats):

```<code>y_means = NaN(npts,1);
for I = 1:npts
    y_means(I) = mean(y(y_groups == I));
end
</code>```

Body:
I have an annotated 512x512x3 fingerprint image, with the annotations being the positions of loops and deltas in the image.  Red denotes loop, and blue denotes delta.

I need to find the position of these points. I can do this using impixel(), but I wanted a more automated approach.

I did the following:

x=[];
y=[];
for i = 1:512
    for j = 1:512
        marked = im(i,j,:);
        if marked(:,:,1)==255
            x=[x i];
            y=[y j];
        end
    end
end
x = unique(x);
y = unique(y);

and got the positions of the pixels where the color red is the position of the loops.

My array y holds the y coordinates of all the red pixels, like this:

[116 117 118 119 120 121 122 191 192 193 194 195 196 197]

At first glance, it is clear that the values can be grouped into 2 groups, for the two red points. But I am unsure how to divide the values into two groups. I thought about creating a threshold using the mean of the values, but that might not work if the points are close by.

Any help might be useful.

Body:
If you know in advance how many red points there will be (2 in the example), you could use kmeans -

y_groups = kmeans(y',2);

If you don't know the number of groups, then if the points always contain the same number of pixels, you could work it out from that - in the example there are 7 pixels per point so

npts = numel(y) / 7;
y_groups = kmeans(y',npts);

We could add a loop afterwards to get the mean of each group (there are many other ways you could look into for this too e.g. grpstats):

y_means = NaN(npts,1);
for I = 1:npts
    y_means(I) = mean(y(y_groups == I));
end


问:
Send literal string from python-vim script to a tmux pane
I am using Vim (8.0) and tmux (2.3) together in the following way: In a tmux session I have a window split to 2 panes, one pane has some text file open in Vim, the other pane has some program to which I want to send lines of text. A typical use case is sending lines from a Python script to IPython session running in the other pane.

I am doing this by a Vim script which uses python, code snippet example (assuming the target tmux pane is 0):

```<code>py import vim
python << endpython
cmd = "print 1+2"
vim_cmd = "silent !tmux send-keys -t 0 -l \"" + cmd + "\"" # -l for literal
vim.command(vim_cmd)
endpython
</code>```

This works well, except for when cmd has some characters which has to be escaped, like %, #, $, etc. The cmd variable is read from the current line in the text file opened in Vim, so I can do something like cmd = cmd.replace('%', '\%') etc., but this has 2 disadvantages: first, I don't know all the vim characters which have to be escaped, so it has been trial and error up until now, and second, the characters " is not escaped properly - that is in the string Vim gets, the " just disappears, even if I do cmd = cmd.replace('"', '\"').
So, is there a general way to tell Vim to not interpret anything, just get a raw string and send it as is? If not, why is the " not escaped properly?

答:
Vimscript

You're looking for the shellescape() function. If you use the :! Vim command, the {special} argument needs to be 1.

```<code>silent execute '!tmux send-keys -t 0 -l ' . shellescape(cmd, 1)
</code>```

But as you're not interested in (displaying) the shell output, and do not need to interact with the launched script, I would switch from :! to the lower-level system() command.

```<code>call system('tmux send-keys -t 0 -l ' . shellescape(cmd))
</code>```

Python

The use of Python (instead of pure Vimscript) doesn't have any benefits (at least in the small snippet in your question). Instead, if you embed the Python cmd variable in a Vimscript expression, now you also need a Python function to escape the value as a Vimscript string (something like '%s'" % str(cmd).replace("'", "''"))). Alternatively, you could maintain the value in a Vim variable, and access it from Python via vim.vars.

Body:
I am using Vim (8.0) and tmux (2.3) together in the following way: In a tmux session I have a window split to 2 panes, one pane has some text file open in Vim, the other pane has some program to which I want to send lines of text. A typical use case is sending lines from a Python script to IPython session running in the other pane.

I am doing this by a Vim script which uses python, code snippet example (assuming the target tmux pane is 0):

py import vim
python << endpython
cmd = "print 1+2"
vim_cmd = "silent !tmux send-keys -t 0 -l \"" + cmd + "\"" # -l for literal
vim.command(vim_cmd)
endpython

This works well, except for when cmd has some characters which has to be escaped, like %, #, $, etc. The cmd variable is read from the current line in the text file opened in Vim, so I can do something like cmd = cmd.replace('%', '\%') etc., but this has 2 disadvantages: first, I don't know all the vim characters which have to be escaped, so it has been trial and error up until now, and second, the characters " is not escaped properly - that is in the string Vim gets, the " just disappears, even if I do cmd = cmd.replace('"', '\"').
So, is there a general way to tell Vim to not interpret anything, just get a raw string and send it as is? If not, why is the " not escaped properly?

Body:
Vimscript

You're looking for the shellescape() function. If you use the :! Vim command, the {special} argument needs to be 1.

silent execute '!tmux send-keys -t 0 -l ' . shellescape(cmd, 1)

But as you're not interested in (displaying) the shell output, and do not need to interact with the launched script, I would switch from :! to the lower-level system() command.

call system('tmux send-keys -t 0 -l ' . shellescape(cmd))

Python

The use of Python (instead of pure Vimscript) doesn't have any benefits (at least in the small snippet in your question). Instead, if you embed the Python cmd variable in a Vimscript expression, now you also need a Python function to escape the value as a Vimscript string (something like '%s'" % str(cmd).replace("'", "''"))). Alternatively, you could maintain the value in a Vim variable, and access it from Python via vim.vars.


问:
error in Generic
Why following code does not work?</p>

```<code>public void getData<T>(T ConnectionStirng)
{
    OleDbConnection con = new OleDbConnection(connectionString);  \\compile error
}
</code>```

答:
Because the connectionString should be a string, not T.

The OleDbConnection class only has two constructors:

```<code>OleDbConnection() // Empty parameter list
</code>```

and

```<code>OleDbConnection(string connectionString) // takes a connection string
</code>```

When you compile by trying to pass in an object of type T, there's no way for the compiler to know what type that is (since it's not being used in context at that point).

Therefore, since T isn't guaranteed to be a string...there is no overload for the OleDbConnection that matches the parameters you're calling it with.

In this case, since there's no return value and the connectionString must be of type string...there's no need for generics at all. It can be simply written as:

```<code>public void getData(string connectionString)
</code>```

Unless you're trying to return a collection of data of type T, then it would look like:

```<code>public IEnumerable<T> getData<T>(string connectionString)
</code>```

Edit

...and none of that addresses the fact that your parameter name doesn't match what you're trying to pass to the constructor or the fact that the slashes in your comments are backwards.

ContentLicense: CC BY-SA 2.5

Title: error in Generic

Body:
Why following code does not work?

public void getData<T>(T ConnectionStirng)
{
    OleDbConnection con = new OleDbConnection(connectionString);  \\compile error
}

Body:
Because the connectionString should be a string, not T.

The OleDbConnection class only has two constructors:

OleDbConnection() // Empty parameter list

and

OleDbConnection(string connectionString) // takes a connection string

When you compile by trying to pass in an object of type T, there's no way for the compiler to know what type that is (since it's not being used in context at that point).

Therefore, since T isn't guaranteed to be a string...there is no overload for the OleDbConnection that matches the parameters you're calling it with.

In this case, since there's no return value and the connectionString must be of type string...there's no need for generics at all. It can be simply written as:

public void getData(string connectionString)

Unless you're trying to return a collection of data of type T, then it would look like:

public IEnumerable<T> getData<T>(string connectionString)

Edit

...and none of that addresses the fact that your parameter name doesn't match what you're trying to pass to the constructor or the fact that the slashes in your comments are backwards.


问:
Looping Separator Data ORACLE 11g
I am new to Oracle and I am unaware about using for loop in Oracle SQL (not PL/SQL).

I  the query and execute the statements like this:

I have the following data

```<code>ID   NAME    DATE          SALARY
101  5A101   100411041204  12000
</code>```

I need the following result:

```<code>ID    NAME    DATE   SALARY
101   5A101   1004   12000
101   5A101   1104   12000
101   5A101   1204   12000
</code>```

How do I create a query for that result?

答:
Ignoring the weird Data structure, If you want an answer anyway, It could be

```<code>WITH test
     AS (SELECT 101 id,'5A101' name,'100411041204' date1,12000 salary FROM DUAL UNION ALL
         SELECT 1012 id,'5A102' name,'10041104' date1,12000 salary FROM DUAL)
    SELECT DISTINCT id,
                    name,
                    SUBSTR (date1, (LEVEL - 1) * 4 + 1, 4) date1
      FROM test
CONNECT BY LEVEL <= LENGTH (date1) / 4
  ORDER BY id, name, date1
</code>```

Here the date column should have data with length multiple of 4.

Title: Looping Separator Data ORACLE 11g

Body:
I am new to Oracle and I am unaware about using for loop in Oracle SQL (not PL/SQL).

I  the query and execute the statements like this:

I have the following data

ID   NAME    DATE          SALARY
101  5A101   100411041204  12000

I need the following result:

ID    NAME    DATE   SALARY
101   5A101   1004   12000
101   5A101   1104   12000
101   5A101   1204   12000

How do I create a query for that result?

Body:
Ignoring the weird Data structure, If you want an answer anyway, It could be

WITH test
     AS (SELECT 101 id,'5A101' name,'100411041204' date1,12000 salary FROM DUAL UNION ALL
         SELECT 1012 id,'5A102' name,'10041104' date1,12000 salary FROM DUAL)
    SELECT DISTINCT id,
                    name,
                    SUBSTR (date1, (LEVEL - 1) * 4 + 1, 4) date1
      FROM test
CONNECT BY LEVEL <= LENGTH (date1) / 4
  ORDER BY id, name, date1

Here the date column should have data with length multiple of 4.


问:
I am not able to do any operation when clicked on any item in my listview
This is my main file . Here I am setting a onClickListener on Listview, which results in any operation
public class Attendance extends AppCompatActivity {

```<code>private ArrayList<attendance_pojo> arrayList = new ArrayList<>();
private Attendance_adaptwr adapter;
private  int present,absent,datecntr,presents,absents;
private  String year,month,date;
ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attendance);
    init();
    fetchData();
    adapter = new Attendance_adaptwr(this, R.layout.card_attendance, arrayList);
    listview.setAdapter(adapter);
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(Attendance.this, "Hello from ROy "+position, Toast.LENGTH_SHORT).show();
        }
    });

}
</code>```

And Arrayadapter file is here

```<code>public class Attendance_adaptwr  extends ArrayAdapter{

    private Context context;
    private int layres;
    private ArrayList<attendance_pojo> arrayList;
    private LayoutInflater inflater;

    public Attendance_adaptwr(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<attendance_pojo> objects) {
        super(context, resource, objects);
        this.context = context;
        this.layres = resource;

        this.arrayList = objects;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view = inflater.inflate(layres, null);
        TextView month, workdays;
        Button present,absent;
        month= view.findViewById(R.id.tv_month);
        workdays= view.findViewById(R.id.work_Days);
        present = view.findViewById(R.id.tv_present);
        absent= view.findViewById(R.id.tv_absent);

        attendance_pojo pojo= arrayList.get(position);
        String months= pojo.getMonth();
        Log.d("months",months);
        months= checkmonth(months);
        Log.d("datess",""+pojo.getDate());
        month.setText(months+" "+pojo.getYear());
        workdays.setText(""+pojo.getDatecounter());
        present.setText("Present "+pojo.getPresent());
        absent.setText("Absent "+pojo.getAbsent());
        return  view;
    }

    private String checkmonth(String month) {
        String monthString;
        switch (month) {
            case "1":  monthString = "January";       break;
            case "2":  monthString = "February";      break;
            case "3":  monthString = "March";         break;
            case "4":  monthString = "April";         break;
            case "5":  monthString = "May";           break;
            case "6":  monthString = "June";          break;
            case "7":  monthString = "July";          break;
            case "8":  monthString = "August";        break;
            case "9":  monthString = "September";     break;
            case "10": monthString = "October";       break;
            case "11": monthString = "November";      break;
            case "12": monthString = "December";      break;
            default: monthString = "Invalid month"; break;
        }
        return  monthString;

    }

    }
</code>```

I just cant get any toast when clicked and any Intent is also not fired. I want to make sure that, it should return me position also.

Here is my Layout Code which I have inflated

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="wrap_content"

    android:layout_margin="10dp">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_marginBottom="15dp"
        android:background="#000"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#9714b3cf"
            android:orientation="vertical">
        <TextView
            android:id="@+id/tv_month"
            android:background="#b51992b7"
            android:text="January 2017"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:layout_marginTop="40dp"
            android:layout_height="wrap_content"
            android:text="WORK DAYS"
            android:gravity="center"
            android:textSize="25sp"
            />
        <TextView
            android:id="@+id/work_Days"
            android:layout_width="match_parent"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:text="18"
            android:gravity="center"
            android:textSize="45sp"

            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2">
            <Button
                android:id="@+id/tv_present"
                android:layout_width="wrap_content"
                android:background="#d3edfd07"
                android:text="PRESENT 18"
                android:textSize="12sp"
                android:layout_marginEnd="5dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
            <Button
                android:id="@+id/tv_absent"
                android:text="ABSENT 0"
                android:background="#90e775d2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
        </LinearLayout>
        </LinearLayout>

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

</LinearLayout>
</code>```

答:
If a row item of listView contains focusable view then OnItemClickListener won't work. Add following attribute to your root layout of list view's item.

```<code>android:descendantFocusability="blocksDescendants"
</code>```

This comes with a consequence that it will no longer allow you to focus on the inner button with hardware buttons.

Body:
This is my main file . Here I am setting a onClickListener on Listview, which results in any operation
public class Attendance extends AppCompatActivity {

private ArrayList<attendance_pojo> arrayList = new ArrayList<>();
private Attendance_adaptwr adapter;
private  int present,absent,datecntr,presents,absents;
private  String year,month,date;
ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attendance);
    init();
    fetchData();
    adapter = new Attendance_adaptwr(this, R.layout.card_attendance, arrayList);
    listview.setAdapter(adapter);
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(Attendance.this, "Hello from ROy "+position, Toast.LENGTH_SHORT).show();
        }
    });

}

And Arrayadapter file is here

public class Attendance_adaptwr  extends ArrayAdapter{

    private Context context;
    private int layres;
    private ArrayList<attendance_pojo> arrayList;
    private LayoutInflater inflater;

    public Attendance_adaptwr(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<attendance_pojo> objects) {
        super(context, resource, objects);
        this.context = context;
        this.layres = resource;

        this.arrayList = objects;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view = inflater.inflate(layres, null);
        TextView month, workdays;
        Button present,absent;
        month= view.findViewById(R.id.tv_month);
        workdays= view.findViewById(R.id.work_Days);
        present = view.findViewById(R.id.tv_present);
        absent= view.findViewById(R.id.tv_absent);

        attendance_pojo pojo= arrayList.get(position);
        String months= pojo.getMonth();
        Log.d("months",months);
        months= checkmonth(months);
        Log.d("datess",""+pojo.getDate());
        month.setText(months+" "+pojo.getYear());
        workdays.setText(""+pojo.getDatecounter());
        present.setText("Present "+pojo.getPresent());
        absent.setText("Absent "+pojo.getAbsent());
        return  view;
    }

    private String checkmonth(String month) {
        String monthString;
        switch (month) {
            case "1":  monthString = "January";       break;
            case "2":  monthString = "February";      break;
            case "3":  monthString = "March";         break;
            case "4":  monthString = "April";         break;
            case "5":  monthString = "May";           break;
            case "6":  monthString = "June";          break;
            case "7":  monthString = "July";          break;
            case "8":  monthString = "August";        break;
            case "9":  monthString = "September";     break;
            case "10": monthString = "October";       break;
            case "11": monthString = "November";      break;
            case "12": monthString = "December";      break;
            default: monthString = "Invalid month"; break;
        }
        return  monthString;

    }

    }

I just cant get any toast when clicked and any Intent is also not fired. I want to make sure that, it should return me position also.

Here is my Layout Code which I have inflated

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="wrap_content"

    android:layout_margin="10dp">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_marginBottom="15dp"
        android:background="#000"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#9714b3cf"
            android:orientation="vertical">
        <TextView
            android:id="@+id/tv_month"
            android:background="#b51992b7"
            android:text="January 2017"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:layout_marginTop="40dp"
            android:layout_height="wrap_content"
            android:text="WORK DAYS"
            android:gravity="center"
            android:textSize="25sp"
            />
        <TextView
            android:id="@+id/work_Days"
            android:layout_width="match_parent"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:text="18"
            android:gravity="center"
            android:textSize="45sp"

            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2">
            <Button
                android:id="@+id/tv_present"
                android:layout_width="wrap_content"
                android:background="#d3edfd07"
                android:text="PRESENT 18"
                android:textSize="12sp"
                android:layout_marginEnd="5dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
            <Button
                android:id="@+id/tv_absent"
                android:text="ABSENT 0"
                android:background="#90e775d2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
        </LinearLayout>
        </LinearLayout>

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

</LinearLayout>

Body:
If a row item of listView contains focusable view then OnItemClickListener won't work. Add following attribute to your root layout of list view's item.

android:descendantFocusability="blocksDescendants"

This comes with a consequence that it will no longer allow you to focus on the inner button with hardware buttons.


问:
QPixmap paint performance issue
I need to recreate the Windows 7 theme where the application window header is transparent and displays blurred screen contents. My idea was to capture the screen contents and display them blurred in the header. For that reason I extended QQuickPaintedItem.

Here is the header:

```<code>class DesktopImage : public QQuickPaintedItem
{
    Q_OBJECT

    Q_PROPERTY(int desktopX READ desktopX WRITE setDesktopX NOTIFY desktopXChanged)
    Q_PROPERTY(int desktopY READ desktopY WRITE setDesktopY NOTIFY desktopYChanged)

public:
    explicit DesktopImage(QQuickItem *parent = nullptr);

    void paint(QPainter *painter) override;

    int desktopX() const;
    void setDesktopX(int desktopX);

    int desktopY() const;
    void setDesktopY(int desktopY);

signals:
    void desktopXChanged();
    void desktopYChanged();

private:
    void grabScreensContent();

private:
    QPixmap mScreensContent;
    int mDesktopX;
    int mDesktopY;

};
</code>```

the grabScreensContent() method do as the name suggest. The paint() method is implemented as follows:

```<code>void DesktopImage::paint(QPainter *painter)
{
    QRectF target(0, 0, width(), height());
    QRectF source(mDesktopX, mDesktopY, width(), height());
    painter->drawPixmap(target, mScreensContent, source);
}
</code>```

on the QML side, I use the type as follows:

```<code>DesktopContent {
    id: desktop
    desktopX: window.x
    desktopY: window.y
    width: parent.width
    height: parent.height
}
</code>```

as you can see the desktopX (desktopY) properties are bound to the window x (window y) properties so that when the user moves the window the portion of the background that needs to be drawn is properly fetched. However the drawing is not as fluid as one might expect. Here is the result:

Can someone suggest an performance improvement?

答:
Take care of renderTarget by setting it to FramebufferObject. This basically should make it as efficient as normal QML rendering yet you can use QPainter which is sometimes conveninent.

```<code>DesktopImage::DesktopImage(QQuickItem *parent)
{
    // this setting is not default
    this->setRenderTarget(QQuickPaintedItem::FramebufferObject);
}
</code>```

Also, only operate with the limited screen area if you don't need the whole screen. This may or may not help depending on the platform / implementation but I always limit the scope on the target first and then position the source within it. The low level painting is not necessarily very intelligent and may expect many changes across the whole area. So we should rather specify the minimum target area and just alter it (this case works like that).

```<code>void DesktopImage::paint(QPainter *painter)
{
    QRectF target(mDesktopX, mDesktopY, width(), height()); // now limited
    QRectF source(0, 0, width(), height());                 // now within smaller target
    painter->drawPixmap(target, mScreensContent, source);
}
</code>```

Title: QPixmap paint performance issue

Body:
I need to recreate the Windows 7 theme where the application window header is transparent and displays blurred screen contents. My idea was to capture the screen contents and display them blurred in the header. For that reason I extended QQuickPaintedItem.

Here is the header:

class DesktopImage : public QQuickPaintedItem
{
    Q_OBJECT

    Q_PROPERTY(int desktopX READ desktopX WRITE setDesktopX NOTIFY desktopXChanged)
    Q_PROPERTY(int desktopY READ desktopY WRITE setDesktopY NOTIFY desktopYChanged)

public:
    explicit DesktopImage(QQuickItem *parent = nullptr);

    void paint(QPainter *painter) override;

    int desktopX() const;
    void setDesktopX(int desktopX);

    int desktopY() const;
    void setDesktopY(int desktopY);

signals:
    void desktopXChanged();
    void desktopYChanged();

private:
    void grabScreensContent();

private:
    QPixmap mScreensContent;
    int mDesktopX;
    int mDesktopY;

};

the grabScreensContent() method do as the name suggest. The paint() method is implemented as follows:

void DesktopImage::paint(QPainter *painter)
{
    QRectF target(0, 0, width(), height());
    QRectF source(mDesktopX, mDesktopY, width(), height());
    painter->drawPixmap(target, mScreensContent, source);
}

on the QML side, I use the type as follows:

DesktopContent {
    id: desktop
    desktopX: window.x
    desktopY: window.y
    width: parent.width
    height: parent.height
}

as you can see the desktopX (desktopY) properties are bound to the window x (window y) properties so that when the user moves the window the portion of the background that needs to be drawn is properly fetched. However the drawing is not as fluid as one might expect. Here is the result:

Can someone suggest an performance improvement?

Body:
Take care of renderTarget by setting it to FramebufferObject. This basically should make it as efficient as normal QML rendering yet you can use QPainter which is sometimes conveninent.

DesktopImage::DesktopImage(QQuickItem *parent)
{
    // this setting is not default
    this->setRenderTarget(QQuickPaintedItem::FramebufferObject);
}

Also, only operate with the limited screen area if you don't need the whole screen. This may or may not help depending on the platform / implementation but I always limit the scope on the target first and then position the source within it. The low level painting is not necessarily very intelligent and may expect many changes across the whole area. So we should rather specify the minimum target area and just alter it (this case works like that).

void DesktopImage::paint(QPainter *painter)
{
    QRectF target(mDesktopX, mDesktopY, width(), height()); // now limited
    QRectF source(0, 0, width(), height());                 // now within smaller target
    painter->drawPixmap(target, mScreensContent, source);
}


问:
Why is `position: fixed` relative to the document instead of viewport in this case?
I got a gallery with some kind of lightbox I created.
The lightbox is position:fixed and top:0. So, if I'm right, it should be at the same position, no matter if I scroll down or not. Unfortunately that's not the case.

I can't reproduce the problem in a fiddle. You can check it out here: http://tobiasgla.us/portfolio. You can either open in on a mobile phone or use the device toolbar in Chrome.

The following 2 object got the position:fixed property, which isn't working:

```<code>.item-content{
   width: calc(100% - 100px);
   height: calc(100vh - 100px);
   position: fixed;
   top: 0;
   left: 0;
   margin: 50px;
}
.dupe.dupAnim{
   top:0;
   left:0;
   width:calc(100% - 100px);
   height:250px;
   margin:50px;
   position:fixed;
}
</code>```

Thanks for your help!

答:
From MDN:

When an ancestor has the transform or perspective property set to something other than none, that ancestor is used as the container instead of the viewport

Your
 uses an animation which includes transform: translateY(...), which fits the exception listed in the documentation. For this reason, your fixed element is relative to the main container, which does indeed scroll with the page.

Body:
I got a gallery with some kind of lightbox I created.
The lightbox is position:fixed and top:0. So, if I'm right, it should be at the same position, no matter if I scroll down or not. Unfortunately that's not the case.

I can't reproduce the problem in a fiddle. You can check it out here: http://tobiasgla.us/portfolio. You can either open in on a mobile phone or use the device toolbar in Chrome.

The following 2 object got the position:fixed property, which isn't working:

.item-content{
   width: calc(100% - 100px);
   height: calc(100vh - 100px);
   position: fixed;
   top: 0;
   left: 0;
   margin: 50px;
}
.dupe.dupAnim{
   top:0;
   left:0;
   width:calc(100% - 100px);
   height:250px;
   margin:50px;
   position:fixed;
}

Thanks for your help!

Body:
From MDN:

When an ancestor has the transform or perspective property set to something other than none, that ancestor is used as the container instead of the viewport

Your <div class="container"> uses an animation which includes transform: translateY(...), which fits the exception listed in the documentation. For this reason, your fixed element is relative to the main container, which does indeed scroll with the page.


问:
Rails - Capistrano deployment failing
I'm trying to figure out why a deployment is failing but can't see anything in the logs:

```<code>* 2017-12-04 11:54:56 executing `staging'
triggering start callbacks for `deploy'
* 2017-12-04 11:54:56 executing `multistage:ensure'
* 2017-12-04 11:54:56 executing `deploy'
triggering before callbacks for `deploy'
* 2017-12-04 11:54:56 executing `slack:starting'
* 2017-12-04 11:54:59 executing `deploy:update'
** transaction: start
* 2017-12-04 11:54:59 executing `deploy:update_code'
updating the cached checkout on all servers
* executing "if [ -d /home/rails/apps/premium-
tours/staging/shared/cached-copy ]; then cd /home/rails/apps/premium-tours/staging/shared/cached-copy && git fetch -q origin && git fetch --tags -q origin && git reset -q --hard 6bc353816fce7aa0b70ac97c3e46f79ee6ced659 && git clean -q -d -x -f; else git clone -q -b staging git@github.com:rawnet/premium-tours /home/rails/apps/premium-tours/staging/shared/cached-copy && cd /home/rails/apps/premium-tours/staging/shared/cached-copy && git checkout -q -b deploy 6bc353816fce7aa0b70ac97c3e46f79ee6ced659; fi"
servers: ["94.236.126.220"]
*** [deploy:update_code] rolling back
* executing "rm -rf /home/rails/apps/premium-tours/staging/releases/20171204115614; true"

 servers: ["94.236.126.220"]
 ** [deploy:update_code] exception while rolling back: Capistrano::ConnectionError, connection failed for: 94.236.126.220 (Errno::ETIMEDOUT: Operation timed out - connect(2) for "94.236.126.220" port 22)
connection failed for: 94.236.126.220 (Errno::ETIMEDOUT: Operation timed out - connect(2) for "94.236.126.220" port 22)
</code>```

Any help is appreciated - like I say I don't know what to look for and can't see any error messages before it starts rolling back

答:
Its connection issue, check the ip and port.
Try this:

config/deploy/production.rb

server "#{server_ip_here}", user: "deploy", roles: %w{web app db}, port: 222

Title: Rails - Capistrano deployment failing

Body:
I'm trying to figure out why a deployment is failing but can't see anything in the logs:

* 2017-12-04 11:54:56 executing `staging'
triggering start callbacks for `deploy'
* 2017-12-04 11:54:56 executing `multistage:ensure'
* 2017-12-04 11:54:56 executing `deploy'
triggering before callbacks for `deploy'
* 2017-12-04 11:54:56 executing `slack:starting'
* 2017-12-04 11:54:59 executing `deploy:update'
** transaction: start
* 2017-12-04 11:54:59 executing `deploy:update_code'
updating the cached checkout on all servers
* executing "if [ -d /home/rails/apps/premium-
tours/staging/shared/cached-copy ]; then cd /home/rails/apps/premium-tours/staging/shared/cached-copy && git fetch -q origin && git fetch --tags -q origin && git reset -q --hard 6bc353816fce7aa0b70ac97c3e46f79ee6ced659 && git clean -q -d -x -f; else git clone -q -b staging git@github.com:rawnet/premium-tours /home/rails/apps/premium-tours/staging/shared/cached-copy && cd /home/rails/apps/premium-tours/staging/shared/cached-copy && git checkout -q -b deploy 6bc353816fce7aa0b70ac97c3e46f79ee6ced659; fi"
servers: ["94.236.126.220"]
*** [deploy:update_code] rolling back
* executing "rm -rf /home/rails/apps/premium-tours/staging/releases/20171204115614; true"

 servers: ["94.236.126.220"]
 ** [deploy:update_code] exception while rolling back: Capistrano::ConnectionError, connection failed for: 94.236.126.220 (Errno::ETIMEDOUT: Operation timed out - connect(2) for "94.236.126.220" port 22)
connection failed for: 94.236.126.220 (Errno::ETIMEDOUT: Operation timed out - connect(2) for "94.236.126.220" port 22)

Any help is appreciated - like I say I don't know what to look for and can't see any error messages before it starts rolling back


问:
How can I give an iframe video different width and height on mobile & pc browsers?
I have a textbox on my website to make the text easier to read. I have an iframe on my website that was placed outside of my box on mobile devices. So I followed this tutorial to fix that. I'm trying to get my iframe video smaller on pc browsers and the current size in my code for mobile devices. It's too big on pc right now. Is there any way to do this?

HTML code:

```<code><div class="video-container"><iframe src="https://www.youtube.com/embed/c0i88t0Kacs"></iframe>
</div>
</code>```

CSS code:

```<code>.video-container {
position:relative;
padding-bottom:56.25%;
padding-top:30px;
height:0;
overflow:hidden; }

.video-container iframe, .video-container object, .video-container embed {
position:absolute;
top:0;
left:0;
width:100%;
height:100%; }
</code>```

答:
you can use bootstrap or media query for this task ,
while using media query you have to give proper pixel for your device

bootstrap

```<code><div class="container">
 <div class="row">
   <div class="col-sm-12">
   </div>
  </div>
</div>
</code>```

media query

```<code>   @media screen and (max-width: 699px) and (min-width: 520px) {

  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a textbox on my website to make the text easier to read. I have an iframe on my website that was placed outside of my box on mobile devices. So I followed this tutorial to fix that. I'm trying to get my iframe video smaller on pc browsers and the current size in my code for mobile devices. It's too big on pc right now. Is there any way to do this?

HTML code:

CSS code:

.video-container {
position:relative;
padding-bottom:56.25%;
padding-top:30px;
height:0;
overflow:hidden; }

.video-container iframe, .video-container object, .video-container embed {
position:absolute;
top:0;
left:0;
width:100%;
height:100%; }

Body:
you can use bootstrap or media query for this task ,
while using media query you have to give proper pixel for your device

bootstrap

<div class="container">
 <div class="row">
   <div class="col-sm-12">
   </div>
  </div>
</div>

media query

   @media screen and (max-width: 699px) and (min-width: 520px) {

  }


问:
The CompileOptions.bootClasspath property has been deprecated
After upgrading to Gradle 4.x, I get the warning

The CompileOptions.bootClasspath property has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the CompileOptions.bootstrapClasspath property instead.

in one of my projects. I don't see anything called bootClasspath or similar in my build.gradle. What does this warning mean?

the warning only appears in the commons subproject, not in core.

commons/build.gradle:

```<code>apply plugin: 'com.android.library'

ext {
    PUBLISH_GROUP_ID = 'com.afollestad.material-dialogs'
    PUBLISH_ARTIFACT_ID = 'commons'
    PUBLISH_VERSION = '0.9.2.3'
    BUILD_TOOLS = "26.0.3"
    TARGET_SDK = 25
}

android {
    compileSdkVersion TARGET_SDK
    buildToolsVersion BUILD_TOOLS

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion TARGET_SDK
        versionCode 1
        versionName PUBLISH_VERSION
    }
    lintOptions {
        checkReleaseBuilds false
    }
}

dependencies {
    implementation project(':core')
}

// Changes to this block must be applied in core/build.gradle and commons/build.gradle
task("javadoc", type: Javadoc) {
    description "Generates Javadoc API documentation for the main source code."
    source = android.sourceSets.main.java.srcDirs
    ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
    classpath += files(ext.androidJar)
    exclude "**/BuildConfig.java"
    exclude "**/R.java"
    options.links("http://docs.oracle.com/javase/7/docs/api/");
    options.links("http://d.android.com/reference/");
}
</code>```

core/build.gradle:

```<code>apply plugin: 'com.android.library'

ext {
    PUBLISH_GROUP_ID = 'com.afollestad.material-dialogs'
    PUBLISH_ARTIFACT_ID = 'core'
    PUBLISH_VERSION = '0.9.2.3'
    SUPPORT_LIBRARY_VERSION = '25.4.0'
    BUILD_TOOLS = "26.0.3"
    TARGET_SDK = 25
}

android {
    compileSdkVersion TARGET_SDK
    buildToolsVersion BUILD_TOOLS

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion TARGET_SDK
        versionCode 1
        versionName PUBLISH_VERSION
        consumerProguardFiles 'progress-proguard.txt'
    }
    lintOptions {
        checkReleaseBuilds false
    }
}

dependencies {
    api "com.android.support:support-v13:$SUPPORT_LIBRARY_VERSION"
    api "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION"
    api "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
    api "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION"
    implementation "me.zhanghai.android.materialprogressbar:library:1.4.1"
}

// Changes to this block must be applied in core/build.gradle and commons/build.gradle
task("javadoc", type: Javadoc) {
    description "Generates Javadoc API documentation for the main source code."
    source = android.sourceSets.main.java.srcDirs
    ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
    classpath += files(ext.androidJar)
    exclude "**/BuildConfig.java"
    exclude "**/R.java"
    options.links("http://docs.oracle.com/javase/7/docs/api/");
    options.links("http://d.android.com/reference/");
}
</code>```

答:
My Gradle is using OpenJDK 8 from /usr/lib/jvm/java-8-openjdk-amd64/jre on Ubuntu (see by adding println System.getProperty("java.home") in build.gradle. No Android Studio involved.

I can trigger the the warning by explicitly setting sourceCompatibility and targetCompatibility to 1.7 (the default value). By changing the Java version to

```<code>android {

    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}
</code>```

the warning disappears.

The reason why the warning is shown for only one project is that it is not repeated. commons is configured before core because of alphanumerical ordering. When I set sourceCompatibility and targetCompatibility to 1.8 for commons, the warning moves to core.

Setting sourceCompatibility and targetCompatibility to 1.8 for all projects removes the warning entirely. If this is what you want for your project and why Gradle 4 cannot be used warning-free with 1.7 are two separate questions.

Body:
After upgrading to Gradle 4.x, I get the warning

The CompileOptions.bootClasspath property has been deprecated and is scheduled to be removed in Gradle 5.0. Please use the CompileOptions.bootstrapClasspath property instead.

in one of my projects. I don't see anything called bootClasspath or similar in my build.gradle. What does this warning mean?

the warning only appears in the commons subproject, not in core.

commons/build.gradle:

apply plugin: 'com.android.library'

ext {
    PUBLISH_GROUP_ID = 'com.afollestad.material-dialogs'
    PUBLISH_ARTIFACT_ID = 'commons'
    PUBLISH_VERSION = '0.9.2.3'
    BUILD_TOOLS = "26.0.3"
    TARGET_SDK = 25
}

android {
    compileSdkVersion TARGET_SDK
    buildToolsVersion BUILD_TOOLS

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion TARGET_SDK
        versionCode 1
        versionName PUBLISH_VERSION
    }
    lintOptions {
        checkReleaseBuilds false
    }
}

dependencies {
    implementation project(':core')
}

// Changes to this block must be applied in core/build.gradle and commons/build.gradle
task("javadoc", type: Javadoc) {
    description "Generates Javadoc API documentation for the main source code."
    source = android.sourceSets.main.java.srcDirs
    ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
    classpath += files(ext.androidJar)
    exclude "**/BuildConfig.java"
    exclude "**/R.java"
    options.links("http://docs.oracle.com/javase/7/docs/api/");
    options.links("http://d.android.com/reference/");
}

core/build.gradle:

apply plugin: 'com.android.library'

ext {
    PUBLISH_GROUP_ID = 'com.afollestad.material-dialogs'
    PUBLISH_ARTIFACT_ID = 'core'
    PUBLISH_VERSION = '0.9.2.3'
    SUPPORT_LIBRARY_VERSION = '25.4.0'
    BUILD_TOOLS = "26.0.3"
    TARGET_SDK = 25
}

android {
    compileSdkVersion TARGET_SDK
    buildToolsVersion BUILD_TOOLS

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion TARGET_SDK
        versionCode 1
        versionName PUBLISH_VERSION
        consumerProguardFiles 'progress-proguard.txt'
    }
    lintOptions {
        checkReleaseBuilds false
    }
}

dependencies {
    api "com.android.support:support-v13:$SUPPORT_LIBRARY_VERSION"
    api "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION"
    api "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
    api "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION"
    implementation "me.zhanghai.android.materialprogressbar:library:1.4.1"
}

// Changes to this block must be applied in core/build.gradle and commons/build.gradle
task("javadoc", type: Javadoc) {
    description "Generates Javadoc API documentation for the main source code."
    source = android.sourceSets.main.java.srcDirs
    ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
    classpath += files(ext.androidJar)
    exclude "**/BuildConfig.java"
    exclude "**/R.java"
    options.links("http://docs.oracle.com/javase/7/docs/api/");
    options.links("http://d.android.com/reference/");
}

Body:
My Gradle is using OpenJDK 8 from /usr/lib/jvm/java-8-openjdk-amd64/jre on Ubuntu (see by adding println System.getProperty("java.home") in build.gradle. No Android Studio involved.

I can trigger the the warning by explicitly setting sourceCompatibility and targetCompatibility to 1.7 (the default value). By changing the Java version to

android {

    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}

the warning disappears.

The reason why the warning is shown for only one project is that it is not repeated. commons is configured before core because of alphanumerical ordering. When I set sourceCompatibility and targetCompatibility to 1.8 for commons, the warning moves to core.

Setting sourceCompatibility and targetCompatibility to 1.8 for all projects removes the warning entirely. If this is what you want for your project and why Gradle 4 cannot be used warning-free with 1.7 are two separate questions.


问:
UINavigationController Subview not Scrolling
I am having a navigation controller and a view, which i attached to the subview of navigation controller, i used the below code to hide the navigation bar while swiping up

```<code>    [self.navigationController.view addSubview: categoryView];
    self.navigationController.hidesBarsOnSwipe = YES;
</code>```

it is hiding to the top while swiping the tableview up, but i want that subview should move up along with the navigation controller and it should fit at the top, while swiping down navigation bar should come down along with the subview.

I tried this

[self.navigationController.navigationBar addSubview: categoryView];

In this both navigationBar and the subview is hiding to the top. I guess some simple solutions will be there for this, I searched a lot but didn't find a perfect one. I tried some libraries too, those are not fitting for iPhone X and having some issues in iOS 11.

Update:  adding images for the issue before scrolling
and
after scrolling the tableview

答:
Use a custom View as a header View instead of using navigation bar (make the navigation bar hidden). Now give constraints to your header View (height constraint). When you will scroll your table view, Method -scrollViewDidScroll will be called. check the scrollview's content offset, if its greater than 0.

headerView.heightconstraint -= scrollViewContentoffset.y;

before scrolling
after scrolling

Body:
I am having a navigation controller and a view, which i attached to the subview of navigation controller, i used the below code to hide the navigation bar while swiping up

    [self.navigationController.view addSubview: categoryView];
    self.navigationController.hidesBarsOnSwipe = YES;

it is hiding to the top while swiping the tableview up, but i want that subview should move up along with the navigation controller and it should fit at the top, while swiping down navigation bar should come down along with the subview.

I tried this

[self.navigationController.navigationBar addSubview: categoryView];

In this both navigationBar and the subview is hiding to the top. I guess some simple solutions will be there for this, I searched a lot but didn't find a perfect one. I tried some libraries too, those are not fitting for iPhone X and having some issues in iOS 11.

Update:  adding images for the issue before scrolling
and
after scrolling the tableview


问:
How to determine C# compiler version in command line
Is there any command to get the C# compiler version?
The csc command seams has no option to show compiler version.

P.S
when I enter csc command in Developer Command Prompt For VS2015 it returns:

```<code>Microsoft (R) Visual C# Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.
</code>```

However I pretty sure my C# compiler is newer than 1.3!

答:
As a literal answer to the question new-ish [update: roslyn versions above 2, see comment by Cameron MacFarland] versions of csc do have a /version switch:

```<code>c:\>csc /version
2.3.2.62116 (8522b473)
</code>```

For scripting purposes (if you want to switch on version say) that may be enough, along with testing the %errorlevel% of csc /version to place in a too old bucket.

/version however does NOT appear at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/listed-alphabetically (which seems the newest version) and I can't find anything listing at what version it was added.

UPDATE: I would also be very careful of the version number reported by csc, for example my personal 'default' is in C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Roslyn and has version 2.3.2.62116 (and file date 22/9/2017) but I also have C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe with version 4.7.2046.0 (and file date 18/03/2017) (and which doesn't take the /version switch).

So in answer to

Is there any command to get the C# compiler version?

I would say, yes, perhaps, sometimes but I would treat that version with a pinch of salt,  Looking at the version stamps I have the version reported is the FIle Version of the csc.exe assembly which appears to come of the version the the 'larger entity' that compiled csc and there are at least incompatible numbering schemes for the Rosyln and 'Traditional' compilers.

Body:
Is there any command to get the C# compiler version?
The csc command seams has no option to show compiler version.

P.S
when I enter csc command in Developer Command Prompt For VS2015 it returns:

Microsoft (R) Visual C# Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.

However I pretty sure my C# compiler is newer than 1.3!

Body:
As a literal answer to the question new-ish [update: roslyn versions above 2, see comment by Cameron MacFarland] versions of csc do have a /version switch:

c:\>csc /version
2.3.2.62116 (8522b473)

For scripting purposes (if you want to switch on version say) that may be enough, along with testing the %errorlevel% of csc /version to place in a too old bucket.

/version however does NOT appear at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/listed-alphabetically (which seems the newest version) and I can't find anything listing at what version it was added.

UPDATE: I would also be very careful of the version number reported by csc, for example my personal 'default' is in C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Roslyn and has version 2.3.2.62116 (and file date 22/9/2017) but I also have C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe with version 4.7.2046.0 (and file date 18/03/2017) (and which doesn't take the /version switch).

So in answer to

Is there any command to get the C# compiler version?

I would say, yes, perhaps, sometimes but I would treat that version with a pinch of salt,  Looking at the version stamps I have the version reported is the FIle Version of the csc.exe assembly which appears to come of the version the the 'larger entity' that compiled csc and there are at least incompatible numbering schemes for the Rosyln and 'Traditional' compilers.


问:
Only display Woocommerce child product categories
I am currently using the following code to fetch WooCommerce product categories:

```<code><?php
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms( 'product_cat', $cat_args );

    if( !empty($product_categories) ){
        echo '<ul>';
        foreach ($product_categories as $key => $category) {
            echo '<li>';
            echo '<a href="'.get_term_link($category).'" >';
            echo $category->name;
            echo '</a>';
            echo '<li>';
        }
        echo '</ul>';
    }
?>
</code>```

This currently displays all categories, however I wish this to only show the child categories.

For example, if you are on the Category 1 page, it should show all children within that category only.

I've looked at many examples on here but have been unable to find something that works for what I need.

答:
Add Below Code in theme's functions.php file.

```<code>add_filter('get_child_category', 'get_child_cat', 10, 1);
function get_child_cat($term_id = 0){
    global $wpdb;
    $result = array('status' => 'fail');
    if($term_id != 0){
        $result = $wpdb->get_results( "select ".$wpdb->prefix."terms.term_id, ".$wpdb->prefix."terms.name, ".$wpdb->prefix."terms.slug, ".$wpdb->prefix."terms.term_group, ".$wpdb->prefix."term_taxonomy.term_taxonomy_id, ".$wpdb->prefix."term_taxonomy.taxonomy, ".$wpdb->prefix."term_taxonomy.description, ".$wpdb->prefix."term_taxonomy.parent, ".$wpdb->prefix."term_taxonomy.count from ".$wpdb->prefix."terms left join ".$wpdb->prefix."term_taxonomy on ".$wpdb->prefix."term_taxonomy.term_id = ".$wpdb->prefix."terms.term_id where ".$wpdb->prefix."term_taxonomy.parent = $term_id" );
    }
    return $result;
}
</code>```

Use below code for get array output for child category.

```<code>$cat = apply_filters( 'get_child_category', $term_id ); // where $term_id is your parent category id.
</code>```

NOTE: This code is only used for single level term.
change code as per your requirement.

Body:
I am currently using the following code to fetch WooCommerce product categories:

<?php
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms( 'product_cat', $cat_args );

    if( !empty($product_categories) ){
        echo '
';
        foreach ($product_categories as $key => $category) {
            echo '
';
            echo '';
            echo $category->name;
            echo '';
            echo '
';
        }
        echo '
';
    }
?>

This currently displays all categories, however I wish this to only show the child categories.

For example, if you are on the Category 1 page, it should show all children within that category only.

I've looked at many examples on here but have been unable to find something that works for what I need.

Body:
Add Below Code in theme's functions.php file.

add_filter('get_child_category', 'get_child_cat', 10, 1);
function get_child_cat($term_id = 0){
    global $wpdb;
    $result = array('status' => 'fail');
    if($term_id != 0){
        $result = $wpdb->get_results( "select ".$wpdb->prefix."terms.term_id, ".$wpdb->prefix."terms.name, ".$wpdb->prefix."terms.slug, ".$wpdb->prefix."terms.term_group, ".$wpdb->prefix."term_taxonomy.term_taxonomy_id, ".$wpdb->prefix."term_taxonomy.taxonomy, ".$wpdb->prefix."term_taxonomy.description, ".$wpdb->prefix."term_taxonomy.parent, ".$wpdb->prefix."term_taxonomy.count from ".$wpdb->prefix."terms left join ".$wpdb->prefix."term_taxonomy on ".$wpdb->prefix."term_taxonomy.term_id = ".$wpdb->prefix."terms.term_id where ".$wpdb->prefix."term_taxonomy.parent = $term_id" );
    }
    return $result;
}

Use below code for get array output for child category.

$cat = apply_filters( 'get_child_category', $term_id ); // where $term_id is your parent category id.

NOTE: This code is only used for single level term.
change code as per your requirement.


问:
How can I redirect to dynamic page on notification according the notification
I'm making a notification future in Yii using PHP with a dynamic data from database. this is come of my CSS code

```<code><style>
#notification_count
{
padding: 3px 7px 3px 7px;
background: #cc0000;
color: #ffffff;
font-weight: bold;
border-radius: 9px;
-moz-border-radius: 9px;
-webkit-border-radius: 9px;
position: absolute;
margin-top: -11px;
font-size: 11px;
}
</style>
</code>```

and this is  HTML

```<code><div id="notificationContainer" style="width:300px">
                        <div id="notificationTitle" style="padding: 8px; font-size: 13px; font-weight: bold; color:#000000; border-bottom: 1px solid #dddddd;">Notifications</div>

                        <div id="notificationsBody" class="notifications item-test"  style="padding: 8px; color:#000000; overflow-y:auto;max-height:300px" >
                            <?php
                            if($count == 0){
                                $notif = '<div align="center" style="font-style:italic;color:#d3d3d3; padding-bottom:5px;">No Notification</div>';
                                echo $notif;
                            }else{
                                for($i=1; $i<=$count; $i++){
                                    $notif_query = Yii::app()->db->createCommand("SELECT NOTIF_DETAIL FROM (SELECT NOTIF_DETAIL, ROWNUM AS RN FROM (SELECT NOTIF_DETAIL FROM TRN_NOTIFICATION WHERE RECIPIENT = '$user' AND SENDER != '$user' AND UNREAD = 'UNREAD' ORDER BY NOTIF_ID DESC)WHERE ROWNUM <= $i)WHERE RN = $i")->queryScalar();
                                    $date = Yii::app()->db->createCommand("SELECT UPDATE_DATE FROM (SELECT UPDATE_DATE, ROWNUM AS RN FROM (SELECT UPDATE_DATE FROM TRN_NOTIFICATION WHERE RECIPIENT = '$user' AND SENDER != '$user' AND UNREAD = 'UNREAD' ORDER BY NOTIF_ID DESC)WHERE ROWNUM <= $i) WHERE RN = $i")->queryScalar();
                                    $notif_value = Yii::app()->db->createCommand("SELECT NOTIF_ID FROM (SELECT NOTIF_ID, ROWNUM AS RN FROM (SELECT NOTIF_ID FROM TRN_NOTIFICATION WHERE RECIPIENT = '$user' AND SENDER != '$user' AND UNREAD = 'UNREAD' ORDER BY NOTIF_ID DESC)WHERE ROWNUM <= $i) WHERE RN = $i")->queryScalar();

                                    $notif = '<div>'.$notif_query.'</div>'; ?>
                                        <div style="border-bottom: 1px solid #dddddd;" name="notificationValue" id="notificationValue" value="<?php echo $notif_value; ?>" method="POST"><?php echo $notif; ?><div align="right" style="color:grey; font-style:italic;"><?php echo $date; ?></div></div>
                                    <?php
                                }
                            }
                            ?>
                        </div>

                        <div id="notificationFooter" style="background-color: #e9eaed; text-align: center; font-weight: bold; padding: 8px; font-size: 12px; border-top: 1px solid #dddddd;"><a href="<?php echo Yii::app()->baseUrl; ?>/index.php?r=TrnNotification/admin">See All</a></div>
                    </div>
</code>```

and this is my JavaScript that redirect to my controller

```<code>$(function(){
 $('#notificationValue').on('click',function(){
    window.location.href = "<?php echo Yii::app()->baseurl; ?>/index.php?r=TrnNotification/notif";
 });
});
</code>```

this allows me to have a notification if there's someone commend or change something that related to users. But the problem is I cant send the value of selected notification so that the value can send to my controller and change the flag of each notification to be marked as "read" and didn't display in notification list anymore.

this is some code that i try to get selected value in my controller

```<code>public function actionNotif(){
    $value = $_POST['notificationValue'];

    if(isset($value)){
        $this->redirect(array('TrnProjectIT/admin'));
    }
}
</code>```

I always get an error that says undefined index : notificationValue. How can I pass  my dynamic value of notification to the controller so that I can redirect to a specific page based on selected notification from user? I might think there's a problem in my looping and passing my value but I don't have any solution. Can anybody help me?

Thanks in advance

答:
You always get an error that says undefined index : notificationValue simply becouse you're not sending anything to the server.

You have a div with method, name and value attributes that are not allowed in
.

Simply use a href redirect and pass the parameter that you want to the server in GET. So remove the
 and the Javascript and use this instead:

```<code><a href="<?= Yii::app()->baseurl ?>/index.php?r=TrnNotification/notif&notificationValue=<?= $notif_value; ?>"><?= echo $date; ?></a>
</code>```

and server side controller:

```<code>public function actionNotif(){
    if(isset($_GET['notificationValue'])){
        $this->redirect('TrnProjectIT/admin');
    }
}
</code>```

Body:
I'm making a notification future in Yii using PHP with a dynamic data from database. this is come of my CSS code

and this is  HTML

Notifications

                            <?php
                            if($count == 0){
                                $notif = '
No Notification
';
                                echo $notif;
                            }else{
                                for($i=1; $i<=$count; $i++){
                                    $notif_query = Yii::app()->db->createCommand("SELECT NOTIF_DETAIL FROM (SELECT NOTIF_DETAIL, ROWNUM AS RN FROM (SELECT NOTIF_DETAIL FROM TRN_NOTIFICATION WHERE RECIPIENT = '$user' AND SENDER != '$user' AND UNREAD = 'UNREAD' ORDER BY NOTIF_ID DESC)WHERE ROWNUM <= $i)WHERE RN = $i")->queryScalar();
                                    $date = Yii::app()->db->createCommand("SELECT UPDATE_DATE FROM (SELECT UPDATE_DATE, ROWNUM AS RN FROM (SELECT UPDATE_DATE FROM TRN_NOTIFICATION WHERE RECIPIENT = '$user' AND SENDER != '$user' AND UNREAD = 'UNREAD' ORDER BY NOTIF_ID DESC)WHERE ROWNUM <= $i) WHERE RN = $i")->queryScalar();
                                    $notif_value = Yii::app()->db->createCommand("SELECT NOTIF_ID FROM (SELECT NOTIF_ID, ROWNUM AS RN FROM (SELECT NOTIF_ID FROM TRN_NOTIFICATION WHERE RECIPIENT = '$user' AND SENDER != '$user' AND UNREAD = 'UNREAD' ORDER BY NOTIF_ID DESC)WHERE ROWNUM <= $i) WHERE RN = $i")->queryScalar();

                                    $notif = '
'.$notif_query.'
'; ?>
                                        <div style="border-bottom: 1px solid #dddddd;" name="notificationValue" id="notificationValue" value="<?php echo $notif_value; ?>" method="POST"><?php echo $notif; ?>
<?php echo $date; ?>

                                    <?php
                                }
                            }
                            ?>

<a href="<?php echo Yii::app()->baseUrl; ?>/index.php?r=TrnNotification/admin">See All

and this is my JavaScript that redirect to my controller

$(function(){
 $('#notificationValue').on('click',function(){
    window.location.href = "<?php echo Yii::app()->baseurl; ?>/index.php?r=TrnNotification/notif";
 });
});

this allows me to have a notification if there's someone commend or change something that related to users. But the problem is I cant send the value of selected notification so that the value can send to my controller and change the flag of each notification to be marked as "read" and didn't display in notification list anymore.

this is some code that i try to get selected value in my controller

public function actionNotif(){
    $value = $_POST['notificationValue'];

    if(isset($value)){
        $this->redirect(array('TrnProjectIT/admin'));
    }
}

I always get an error that says undefined index : notificationValue. How can I pass  my dynamic value of notification to the controller so that I can redirect to a specific page based on selected notification from user? I might think there's a problem in my looping and passing my value but I don't have any solution. Can anybody help me?

Thanks in advance

Body:
You always get an error that says undefined index : notificationValue simply becouse you're not sending anything to the server.

You have a div with method, name and value attributes that are not allowed in <div>.

Simply use a href redirect and pass the parameter that you want to the server in GET. So remove the <div name="notificationValue"> and the Javascript and use this instead:

<a href="<?= Yii::app()->baseurl ?>/index.php?r=TrnNotification/notif&notificationValue=<?= $notif_value; ?>"><?= echo $date; ?></a>

and server side controller:

public function actionNotif(){
    if(isset($_GET['notificationValue'])){
        $this->redirect('TrnProjectIT/admin');
    }
}


问:
How kernel provides services to other parts of operating system?
I went through the definitions of kernel on internet and i saw  in many definitions that kernel provides services to other parts of OS.
What do they mean by kernel provides services to other parts of OS.
Can anyone explain with some valid example.
Thanks in advance.</p>

答:
kernel provides services to other parts of OS.

By "others" they mean parts of OS which works in user space (non-priveledged code). Among them are:

Libraries, provided by OS and used by 3d party applications (or 3d-party libraries).

Frameworks, e.g. one provided windows subsystem.

Applications (executables) provided by OS itself. E.g. cd command.

If any of those component needs a help from the kernel, it uses one of the kernel's service. Usually, kernel's service is provided via syscall mechanism.


问:
What could justify the complexity of Plone?
Plone is very complex. Zope2, Zope3, Five, ZCML, ZODB, ZEO, a whole bunch of acronyms and abbreviations.

It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.

Does the steep learning curve pay of? Is this complexity still justified today?

Background: I need a platform. Customers often need a CMS. I'm currently reading "Professional Plone Development", without prior knowledge of Plone.

The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "If you want to see the complexity of Plone, you have to ask for it." when you don't know the system good enough to plan.

答:
From a system administrator standpoint, Plone is just shy of being the absolute devil. Upgrading, maintaining, and installing where you want to install things is all more painful than necessary on the Linux platform. That's just my two cents though, and why I typically prefer to avoid the Zope/Plone stack.

Note: it's better with newer releases, but older releases.... ugh

OwnerDisplayName: stesch

LastEditorDisplayName: stesch


问:
android intent extra data retrieval problem
I have a wierd problem. I have the following code:

```<code>if (fbIntent.hasExtra("Link")) {
            try{
            postData[0]= fbIntent.getStringExtra("Link");
            } catch (Exception e) {Log.d("fbIntent error",e.getMessage() );}
        }
</code>```

fbIntent.hasExtra("Link") is true. So the compiler goes into the if statement. But I am not able to get the string using fbIntent.getStringExtra("Link"). This I know from debugging in eclipse. When I run it, I get :

```<code>01-21 14:12:01.030: ERROR/AndroidRuntime(311): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.examples.Kikin/com.examples.Kikin.FacebookLogin}: java.lang.NullPointerException: println needs a message
</code>```

Please help me.

答: You need to initialize postData. Try something like String[] postData = new String[1]. Obviously, if you want use postData[1], [2], and [3], you'd need to say new String[4].

Body:
I have a wierd problem. I have the following code:

if (fbIntent.hasExtra("Link")) {
            try{
            postData[0]= fbIntent.getStringExtra("Link");
            } catch (Exception e) {Log.d("fbIntent error",e.getMessage() );}
        }

fbIntent.hasExtra("Link") is true. So the compiler goes into the if statement. But I am not able to get the string using fbIntent.getStringExtra("Link"). This I know from debugging in eclipse. When I run it, I get :

01-21 14:12:01.030: ERROR/AndroidRuntime(311): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.examples.Kikin/com.examples.Kikin.FacebookLogin}: java.lang.NullPointerException: println needs a message

Please help me.


问:
how to compare elements in lists
How can I store values in lists and later compare against each other

```<code>all_click = []
all_click_red = []

while True:

    a = input('give a number: ')
    b = input('give a second number: ')

    if a == 1:
        all_click.append(a)

    if b == 1:
        all_click_red.append(b)

    if all_click_red[-1] and all_click[-1] == 1:
        print('all good')

    else:
        print('false')
</code>```

Because I get an error like this:

```<code> if all_click_red[-1] and all_click[-1] == 1:
     IndexError: list index out of range
</code>```

答:
The reason for that is that one of the lists may not have a value in it.

You'll probably want something like this:

```<code>if len(all_click) > 0 and len(all_click_red) > 0 and all_click_red[-1] == 1 and all_click[-1] == 1:
    print('all good')

else:
    print('false')
</code>```

Never hurts to check for index safety when accessing indexes in a list like this.

I also added an equality on the all_click_red number check. I'm assuming that's what you were after. Apologies if I misjudged

Title: how to compare elements in lists

Body:
How can I store values in lists and later compare against each other

all_click = []
all_click_red = []

while True:

    a = input('give a number: ')
    b = input('give a second number: ')

    if a == 1:
        all_click.append(a)

    if b == 1:
        all_click_red.append(b)

    if all_click_red[-1] and all_click[-1] == 1:
        print('all good')

    else:
        print('false')

Because I get an error like this:

 if all_click_red[-1] and all_click[-1] == 1:
     IndexError: list index out of range

Body:
The reason for that is that one of the lists may not have a value in it.

You'll probably want something like this:

if len(all_click) > 0 and len(all_click_red) > 0 and all_click_red[-1] == 1 and all_click[-1] == 1:
    print('all good')

else:
    print('false')

Never hurts to check for index safety when accessing indexes in a list like this.

I also added an equality on the all_click_red number check. I'm assuming that's what you were after. Apologies if I misjudged


问:
Asp.net MVC Session state Overlap
I have a website created by ASP.Net MVC, and I use the session to keep the users logged in.  In this case, when logging in a multi tabs with different users, previous sessions are erased and only the last one will remain.  How can I access the application to log in from several browser using Server?</p>

答: By default, session should exist one per server, which will be shared across multiple tabs (unless using tricks like File > New Session in IE, etc.).  By default this shouldn't be happening, so we'll need to see some code around how you are managing your session to solve this.</p>

Title: Asp.net MVC Session state Overlap


问:
How to get multiple buttons from a single tableViewcell?
I am making a quiz in a tableView that has 4 Buttons (options), I tagged them on a story board like 201,202,203,204 and got all of them successfully in tableView methods. But after adding targets to buttons, I am not able to get particular buttons in buttonClicked method.

```<code>func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questions.count }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    (cell.viewWithTag(100) as! UILabel).text = "Q : " + (questions[indexPath.row].objectForKey("MocQuestion")! as? String)!
    (cell.viewWithTag(100) as! UILabel).font = themeFont
    (cell.viewWithTag(101) as! UILabel).text = questions[indexPath.row].objectForKey("Op1")! as? String
    (cell.viewWithTag(102) as! UILabel).text = questions[indexPath.row].objectForKey("Op2")! as? String
    (cell.viewWithTag(103) as! UILabel).text = questions[indexPath.row].objectForKey("Op3")! as? String
    (cell.viewWithTag(104) as! UILabel).text = questions[indexPath.row].objectForKey("Op4")! as? String

    let btn1 = (cell.viewWithTag(201) as! UIButton)
    let btn2 = (cell.viewWithTag(202) as! UIButton)
    let btn3 = (cell.viewWithTag(203) as! UIButton)
    let btn4 = (cell.viewWithTag(204) as! UIButton)

//        btn1.tag = indexPath.row * 100 + 0
//        btn1.tag = indexPath.row * 100 + 1
//        btn1.tag = indexPath.row * 100 + 2
//        btn1.tag = indexPath.row * 100 + 3

    btn1.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
    btn2.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
    btn3.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
    btn4.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)

    return cell
}

func buttonClicked(sender:UIButton)
{
    let tag = sender.tag
    print(tag)
}
</code>```

答:
In swift 3 You can try bellow like

My  table cell class

```<code>class Custom_Cell: UITableViewCell {

  @IBOutlet weak var ButtonA: UIButton!
  @IBOutlet weak var ButtonB: UIButton!
  @IBOutlet weak var ButtonC: UIButton!

 }
</code>```

Set Tag in table view

```<code>  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custom_Cell;

   cell.ButtonA.tag = indexPath.row;
   cell.ButtonB.tag = indexPath.row;
   cell.ButtonA.tag = indexPath.row;

    //Add Action Methods to UIButtons
     cell.ButtonA.addTarget(self, action: #selector(ButtonAAction), for: .touchUpInside)
    cell.ButtonB.addTarget(self, action: #selector(ButtonBAction), for: .touchUpInside)
    cell.ButtonA.addTarget(self, action: #selector(ButtonCAction), for: .touchUpInside)

   return cell;
}
</code>```

Button Action will look like ..

```<code>func ButtonAAction(_ sender: Any)  {
   //Get Button cell position.
   let ButtonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableView)
   let indexPath = tableView.indexPathForRow(at: ButtonPosition)
   if indexPath != nil {

       print("Cell indexPath: \(indexPath?.row)")
    }
  }
</code>```

Body:
I am making a quiz in a tableView that has 4 Buttons (options), I tagged them on a story board like 201,202,203,204 and got all of them successfully in tableView methods. But after adding targets to buttons, I am not able to get particular buttons in buttonClicked method.

func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questions.count }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    (cell.viewWithTag(100) as! UILabel).text = "Q : " + (questions[indexPath.row].objectForKey("MocQuestion")! as? String)!
    (cell.viewWithTag(100) as! UILabel).font = themeFont
    (cell.viewWithTag(101) as! UILabel).text = questions[indexPath.row].objectForKey("Op1")! as? String
    (cell.viewWithTag(102) as! UILabel).text = questions[indexPath.row].objectForKey("Op2")! as? String
    (cell.viewWithTag(103) as! UILabel).text = questions[indexPath.row].objectForKey("Op3")! as? String
    (cell.viewWithTag(104) as! UILabel).text = questions[indexPath.row].objectForKey("Op4")! as? String

    let btn1 = (cell.viewWithTag(201) as! UIButton)
    let btn2 = (cell.viewWithTag(202) as! UIButton)
    let btn3 = (cell.viewWithTag(203) as! UIButton)
    let btn4 = (cell.viewWithTag(204) as! UIButton)

//        btn1.tag = indexPath.row * 100 + 0
//        btn1.tag = indexPath.row * 100 + 1
//        btn1.tag = indexPath.row * 100 + 2
//        btn1.tag = indexPath.row * 100 + 3

    btn1.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
    btn2.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
    btn3.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
    btn4.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)

    return cell
}

func buttonClicked(sender:UIButton)
{
    let tag = sender.tag
    print(tag)
}

Body:
In swift 3 You can try bellow like

My  table cell class

class Custom_Cell: UITableViewCell {

  @IBOutlet weak var ButtonA: UIButton!
  @IBOutlet weak var ButtonB: UIButton!
  @IBOutlet weak var ButtonC: UIButton!

 }

Set Tag in table view

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custom_Cell;

   cell.ButtonA.tag = indexPath.row;
   cell.ButtonB.tag = indexPath.row;
   cell.ButtonA.tag = indexPath.row;

    //Add Action Methods to UIButtons
     cell.ButtonA.addTarget(self, action: #selector(ButtonAAction), for: .touchUpInside)
    cell.ButtonB.addTarget(self, action: #selector(ButtonBAction), for: .touchUpInside)
    cell.ButtonA.addTarget(self, action: #selector(ButtonCAction), for: .touchUpInside)

   return cell;
}

Button Action will look like ..

func ButtonAAction(_ sender: Any)  {
   //Get Button cell position.
   let ButtonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableView)
   let indexPath = tableView.indexPathForRow(at: ButtonPosition)
   if indexPath != nil {

       print("Cell indexPath: \(indexPath?.row)")
    }
  }


问:
How to find a string in char Array without using string functions?(c++)
I have following code:

```<code>char x[30]="computer";
char y[30]="put";
</code>```

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

答:
In C++ you could use strings and string::find

With char arrays tho,

```<code>if (strstr(x, y) != NULL) {
    // contains
}
</code>```

Body:
I have following code:

char x[30]="computer";
char y[30]="put";

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

Body:
In C++ you could use strings and string::find

With char arrays tho,

if (strstr(x, y) != NULL) {
    // contains
}