问:
Oracle PL/SQL return array of rows
Dear Oracle Developers,

I have searched and googled to find a solution for my problem but nothing helped me.

Situation :

TABLE : CUSTOMER(....);

My problem is : I want to create a stored procedure say get_customers to return an array of customer rows. I have no idea how to get this working.

I tried to create a type customer_rec and using a cursor to retrieve no more than maxRows

```<code>create or replace procedure get_customers(maxRows IN NUMBER, ??? OUT ????)
</code>```

How to define the OUT parameter ?

How to retrieve the rows in the array using a cursor ?

Thanks a lot

答:
First you have to define a collection :

```<code>TYPE customers_array IS TABLE OF customer%ROWTYPE
    INDEX BY BINARY_INTEGER;
</code>```

Then your procedure simply have to fetch the result into that collection.
You're procedure could be written as follow:

```<code>CREATE OR REPLACE PACKAGE your_pkg
AS

    TYPE customers_array IS TABLE OF customer%ROWTYPE
        INDEX BY BINARY_INTEGER;

    PROCEDURE get_customers(pn_max_rows    IN NUMBER,
                            pt_coustomers OUT customers_array);
END your_pkg;

CREATE OR REPLACE PACKAGE BODY your_pkg
AS

    PROCEDURE get_customers(pn_max_rows    IN NUMBER,
                            pt_coustomers OUT customers_array)
    IS
    BEGIN
        SELECT *
          BULK COLLECT INTO pt_coustomers
          FROM customers
         WHERE rownum <= pn_max_rows;
    END get_customers;

END your_pkg;
</code>```

Title: Oracle PL/SQL return array of rows

Body:
Dear Oracle Developers,

I have searched and googled to find a solution for my problem but nothing helped me.

Situation :

TABLE : CUSTOMER(....);

My problem is : I want to create a stored procedure say get_customers to return an array of customer rows. I have no idea how to get this working.

I tried to create a type customer_rec and using a cursor to retrieve no more than maxRows

create or replace procedure get_customers(maxRows IN NUMBER, ??? OUT ????)

How to define the OUT parameter ?

How to retrieve the rows in the array using a cursor ?

Thanks a lot

Body:
First you have to define a collection :

TYPE customers_array IS TABLE OF customer%ROWTYPE
    INDEX BY BINARY_INTEGER;

Then your procedure simply have to fetch the result into that collection.
You're procedure could be written as follow:

CREATE OR REPLACE PACKAGE your_pkg
AS

    TYPE customers_array IS TABLE OF customer%ROWTYPE
        INDEX BY BINARY_INTEGER;

    PROCEDURE get_customers(pn_max_rows    IN NUMBER,
                            pt_coustomers OUT customers_array);
END your_pkg;

CREATE OR REPLACE PACKAGE BODY your_pkg
AS

    PROCEDURE get_customers(pn_max_rows    IN NUMBER,
                            pt_coustomers OUT customers_array)
    IS
    BEGIN
        SELECT *
          BULK COLLECT INTO pt_coustomers
          FROM customers
         WHERE rownum <= pn_max_rows;
    END get_customers;

END your_pkg;


来源: stackexchange

问:
What are the reasons for using parser combinators?
I'm looking at the following approach to using parser combinators in Haskell. The author gives the following example of Parser Combinators:

```<code>windSpeed :: String -> Maybe Int
windSpeed windInfo =
    parseMaybe windSpeedParser windInfo

windSpeedParser :: ReadP Int
windSpeedParser = do
    direction <- numbers 3
    speed <- numbers 2 <|> numbers 3
    unit <- string "KT" <|> string "MPS"
    return speed
</code>```

The author gives the following reasons for this approach:

easy to read (I agree with this)

similar format to the specification ie the parser itself is basically a description of what it parses (I agree with this)

I can't help but feel I'm missing some of the reasons for choosing parser combinators. Some benefit of either using Haskell, compile-time guarantees, elimination of runtime errors. Or some subsequent benefit when you starting parsing DSLs and using free monads.

My question is: What are the reasons for using parser combinators?

答:
I see several benefits of using parser combinators:

Parser combinators are a generalization of hand-written top-down parsers. In the case that you hand-write a parser, use parser combinators to abstract away common patterns.

Unlike parser generators, parser combinators are potentially dynamic, allowing for decisions during runtime. This aspect may be useful if the language's grammar may be redefined based on the input.

Parsers are first-class objects.

ContentLicense: CC BY-SA 3.0

Body:
I'm looking at the following approach to using parser combinators in Haskell. The author gives the following example of Parser Combinators:

windSpeed :: String -> Maybe Int
windSpeed windInfo =
    parseMaybe windSpeedParser windInfo

windSpeedParser :: ReadP Int
windSpeedParser = do
    direction <- numbers 3
    speed <- numbers 2 <|> numbers 3
    unit <- string "KT" <|> string "MPS"
    return speed

The author gives the following reasons for this approach:

easy to read (I agree with this)

similar format to the specification ie the parser itself is basically a description of what it parses (I agree with this)

I can't help but feel I'm missing some of the reasons for choosing parser combinators. Some benefit of either using Haskell, compile-time guarantees, elimination of runtime errors. Or some subsequent benefit when you starting parsing DSLs and using free monads.

My question is: What are the reasons for using parser combinators?


问:
Random special character with JS regex
I'm trying to use regular expressions in JS to return a random special character from a selection, for example ?, !, *, $.

I'm able to generate random non-special characters using the following code:

```<code>Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 1);
</code>```

However, I simply don't know how to make it return special characters.

I am of course aware of the need to escape special characters in the regex, but so far no combination of backslashes and/or slashes has produced the chracters (it always returns either whitespace or 0 in an alert). For example I tried something like:

```<code>Math.random().toString(36).replace(/[^\?\!\$]+/g, '').substr(0, 1);
</code>```

To be honest, I simply don't understand regular expressions well enough, the problem might be due to any number of things (maybe the 36 is wrong in this case?) and I would really appreciate if someone could give me some advice!

答:
You haven't made clear why you want to use regexen to address your problem.

Adopting the idea from @sweaver2112's comment,try something like

```<code>function randomSpecialChar () {
    // example set of special chars as a string in no particular order
    var s = "!\"§$%&/()=?\u{20ac}";

    // generating a random index into the string and extracting the character at that position
    return s.substr(Math.floor(s.length*Math.random()), 1);
}
</code>```

Title: Random special character with JS regex

Body:
I'm trying to use regular expressions in JS to return a random special character from a selection, for example ?, !, *, $.

I'm able to generate random non-special characters using the following code:

Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 1);

However, I simply don't know how to make it return special characters.

I am of course aware of the need to escape special characters in the regex, but so far no combination of backslashes and/or slashes has produced the chracters (it always returns either whitespace or 0 in an alert). For example I tried something like:

Math.random().toString(36).replace(/[^\?\!\$]+/g, '').substr(0, 1);

To be honest, I simply don't understand regular expressions well enough, the problem might be due to any number of things (maybe the 36 is wrong in this case?) and I would really appreciate if someone could give me some advice!

Body:
You haven't made clear why you want to use regexen to address your problem.

Adopting the idea from @sweaver2112's comment,try something like

function randomSpecialChar () {
    // example set of special chars as a string in no particular order
    var s = "!\"§$%&/()=?\u{20ac}";

    // generating a random index into the string and extracting the character at that position
    return s.substr(Math.floor(s.length*Math.random()), 1);
}


问:
std::array with unknown length as a type for template function specification
I want to pass std::array class with a known type, but unknown size to the template function specialization:

```<code>class foo {
public:
void bar<class T>(T arg1, int arg2, int arg3) {
    //For any other T
}
void bar<std::array<rs::float3, size>>(T arg1, arg2) {
    //Specific function for type std::array of rs::float3's and unknown length (size is not a type, just variable).
}
</code>```

答:
If you want the function to accept array objects of different sizes, you pretty much need to make it a function template, and pass the size as a template parameter:

```<code>template<size_t N>
void bar(std::array<rs::float3, N> const &arg1,
         std::array<rs::float3, N> cons t&arg2)
{
   // ...
}
</code>```

In this case, I guess you also want it to be a partial specialization of another template. Unfortunately, there is no partial specialization of function templates. There is a part of the standard that deals with partial ordering of function templates, but the usual recommendation is that you just use overloading instead.

Body:
I want to pass std::array class with a known type, but unknown size to the template function specialization:

class foo {
public:
void bar<class T>(T arg1, int arg2, int arg3) {
    //For any other T
}
void bar<std::array<rs::float3, size>>(T arg1, arg2) {
    //Specific function for type std::array of rs::float3's and unknown length (size is not a type, just variable).
}

Body:
If you want the function to accept array objects of different sizes, you pretty much need to make it a function template, and pass the size as a template parameter:

template<size_t N>
void bar(std::array<rs::float3, N> const &arg1,
         std::array<rs::float3, N> cons t&arg2)
{
   // ...
}

In this case, I guess you also want it to be a partial specialization of another template. Unfortunately, there is no partial specialization of function templates. There is a part of the standard that deals with partial ordering of function templates, but the usual recommendation is that you just use overloading instead.


问:
Amazon Redshift order by specific values
I'm new to Redshift and looking for a way to specify the order I want the results in, the accepted answer here is exactly what I want, but the FIELD function does not exist in Redshift. Is there a way to accomplish the same result in Redshift?

Current Query looks like this:

```<code>SELECT DISTINCT audit_type, audit_category FROM "schema"."table"

ORDER BY audit_type,
CASE WHEN audit_category = 'string_1' THEN 1
  WHEN audit_category = 'string_2' THEN 2
  WHEN audit_category = 'string_3' THEN 3
  WHEN audit_category = 'string_4' THEN 4
  WHEN audit_category = 'string_5' THEN 5
  WHEN audit_category = 'string_6' THEN 6
  WHEN audit_category = 'string_7' THEN 7
ELSE 8 END
</code>```

答:
you can just use CASE statement to achieve the same:

```<code>ORDER BY CASE WHEN "name"='core' THEN 1 ELSE 2 END, priority
</code>```

you can extend the list with another option besides core by adding a new WHEN / THEN part before ELSE, so what you ultimately do is map a list of possible name options to integers that are used for sorting the rows

Body:
I'm new to Redshift and looking for a way to specify the order I want the results in, the accepted answer here is exactly what I want, but the FIELD function does not exist in Redshift. Is there a way to accomplish the same result in Redshift?

Current Query looks like this:

SELECT DISTINCT audit_type, audit_category FROM "schema"."table"

ORDER BY audit_type,
CASE WHEN audit_category = 'string_1' THEN 1
  WHEN audit_category = 'string_2' THEN 2
  WHEN audit_category = 'string_3' THEN 3
  WHEN audit_category = 'string_4' THEN 4
  WHEN audit_category = 'string_5' THEN 5
  WHEN audit_category = 'string_6' THEN 6
  WHEN audit_category = 'string_7' THEN 7
ELSE 8 END

Body:
you can just use CASE statement to achieve the same:

ORDER BY CASE WHEN "name"='core' THEN 1 ELSE 2 END, priority

you can extend the list with another option besides core by adding a new WHEN / THEN part before ELSE, so what you ultimately do is map a list of possible name options to integers that are used for sorting the rows


问:
Using a beta version of Material-UI for a long-term React web applicationwith a lot of content if beta beta features are a necessity
Is using a beta version of Material-UI for a long-term vision React web application with a lot of content a good idea if the beta features are a necessity and using a UI library that follows Google's Material Design Guidelines is a requirement.

I looked at alternatives like React-Toolbox, MUI and Material Design Lite and they are close to what we need but a product as big and popular as Material-UI would be preferable, which is why I'm hesitating.

I have been searching for the risks of using a beta version and looked at the 22 pre-release notes of the v1.0.0-betaXX versions of Material-UI and it doesn't seem to be that bad, but maybe

I could use the stable version v0.20.0 and try to find a way to add the features that I need (flex grid being one of them) and eventually will migrate to a newer version of Material-UI (which would also include migrating from react v15 to react v16 because Material-UI v1.0.0 is only going to support React v15 temporarily).

I could use the beta version v1.0.0-beta.22 and work around the bugs (if/when I encounter them and if there are any), gradually migrate to React v16 and eventually migrate to a released version of Material-UI v1.0.0.

Either way, I'm thinking the migration from a beta of v1 to a release of v1 will be much easier than migrating from 0.20.0 to 1.0.0, no ? But, at the same time, a beta is a beta, so it,s not a final product and I'm not guaranteed anything.

答:
mui-org is focused on releasing a stable v1 and has an informal target of early 2018.

There will be breaking changes along the way, but dealing with them will be far easier than porting your application from v0 (or your proposed hybrid solution).

If you choose a specific version of v1 and periodically update, the continual refactoring to account for any breaking changes should be relatively painless.
 The release notes are very good and always describe the breaking changes introduced with each release.

Bite the bullet and go for v1.


问:
Font awesome 5 on pseudo elements
In font awesome 4 you could easily apply an icon to a :before/:after element using CSS.

Is the same possible with the new font awesome 5 JS/SVG implementation? As from what i can see this requires the relevant  tag to exist in html which isn't always practical e.g. you have a CMS and want to apply an icon to all user created content
 elements

I know in FA5 you can still use the old css/webfonts but it would be nice if the same functionality was available in the recommended method of using JS

答:
You need to enable it (it's disabled by default).

```<code><script>
  window.FontAwesomeConfig = {
    searchPseudoElements: true
  }
</script>
</code>```

Css:

```<code>.class:before{
  display: none;
  content: "\f16c";
  font-family: "Font Awesome 5 Brands";
}
</code>```

Other types:
Font Awesome 5 + Solid or Regular or Light or Brands

Title: Font awesome 5 on pseudo elements

Body:
You need to enable it (it's disabled by default).

<script>
  window.FontAwesomeConfig = {
    searchPseudoElements: true
  }
</script>

Css:

.class:before{
  display: none;
  content: "\f16c";
  font-family: "Font Awesome 5 Brands";
}

Other types:
Font Awesome 5 + Solid or Regular or Light or Brands


问:
RAII and factory design pattern?
Let's say I have Foo class:

```<code>struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};
</code>```

Am I right and there is no guarantee that ~Foo will be called only once in such block?

```<code>{
   Foo foo = Foo::create();
   foo.f();
}
</code>```

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?

答:
Copy elision won't help you, since it is an optimization and may or may not be applied.

Move semantics do help, and you get guaranteed moves in function return of local variables. But that means you have to write the move constructor, and you have to modify the destructor so that it doesn't unlock the resource of an object that was moved from.

Title: RAII and factory design pattern?

Body:
Let's say I have Foo class:

struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};

Am I right and there is no guarantee that ~Foo will be called only once in such block?

{
   Foo foo = Foo::create();
   foo.f();
}

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?


问:
How to assign QScintilla shortcuts
I'm trying to implement shortcuts to my editor, but I haven't had any success so far.

I'd like to override some of the default QScintilla shortcuts. I have read this answer, but I'm not sure if this helps to solve my problem.

I have also read the Scintilla (SCI_ASSIGNCMDKEY) documentation, but I don't know how I'm supposed to use it in a pythonic way.

To make it clear:

I'd like to override the QScintilla shortcut Ctrl+L and use my custom solution (assign it to one of my functions).

I'd like to assign the command SCI_LINEDELETE to the shortcut Ctrl+D.

This is my idea:

```<code>    from PyQt5.Qsci import QsciScintilla
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    import sys

    class mainWindow(QMainWindow):
        def __init__(self, parent = None):
            super(mainWindow, self).__init__(parent)
            self.initUI()

        def initUI(self):
            self.center_window = centerWindow(parent=self)
            self.setCentralWidget(self.center_window)

    class centerWindow(QWidget):
        def __init__(self, parent=None):
            super(centerWindow, self).__init__(parent)

            self.hhEditor_te = QsciScintilla()

            vbox = QVBoxLayout(self)
            vbox.addWidget(self.hhEditor_te)
            self.setLayout(vbox)

            # 1)
            # assign a key binding to this function
            # self.my_shortcut

            # 2)
            # assign a key binding to the QScintilla command
            # SCI_LINEDELETE

        def my_shortcut(self):
            pass
            # my custom shortcut function

    if __name__ == '__main__':
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        else:
            print('QApplication instance already exists: %s' % str(app))

        ex = mainWindow()
        ex.setGeometry(0,100,1500,600)
        ex.show()
        sys.exit(app.exec_())
</code>```

答:
if you are using a toolbar in your QScintilla, action shortcuts is as followeded</p>

```<code>self.toolBar.newAction = QtWidgets.QAction(QtGui.QIcon(":/ico/new.png"),"New",self.toolBar)
self.toolBar.newAction.setStatusTip("Clear TextBox or make new document.")
self.toolBar.newAction.setShortcut("Ctrl+N")
self.toolBar.newAction.triggered.connect(self.newfile)

    #actions
self.toolBar.addAction(self.toolBar.newAction)
self.toolBar.addSeparator()
</code>```

Title: How to assign QScintilla shortcuts

Body:
I'm trying to implement shortcuts to my editor, but I haven't had any success so far.

I'd like to override some of the default QScintilla shortcuts. I have read this answer, but I'm not sure if this helps to solve my problem.

I have also read the Scintilla (SCI_ASSIGNCMDKEY) documentation, but I don't know how I'm supposed to use it in a pythonic way.

To make it clear:

I'd like to override the QScintilla shortcut Ctrl+L and use my custom solution (assign it to one of my functions).

I'd like to assign the command SCI_LINEDELETE to the shortcut Ctrl+D.

This is my idea:

    from PyQt5.Qsci import QsciScintilla
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtWidgets import *
    import sys

    class mainWindow(QMainWindow):
        def __init__(self, parent = None):
            super(mainWindow, self).__init__(parent)
            self.initUI()

        def initUI(self):
            self.center_window = centerWindow(parent=self)
            self.setCentralWidget(self.center_window)

    class centerWindow(QWidget):
        def __init__(self, parent=None):
            super(centerWindow, self).__init__(parent)

            self.hhEditor_te = QsciScintilla()

            vbox = QVBoxLayout(self)
            vbox.addWidget(self.hhEditor_te)
            self.setLayout(vbox)

            # 1)
            # assign a key binding to this function
            # self.my_shortcut

            # 2)
            # assign a key binding to the QScintilla command
            # SCI_LINEDELETE

        def my_shortcut(self):
            pass
            # my custom shortcut function

    if __name__ == '__main__':
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        else:
            print('QApplication instance already exists: %s' % str(app))

        ex = mainWindow()
        ex.setGeometry(0,100,1500,600)
        ex.show()
        sys.exit(app.exec_())

Body:
if you are using a toolbar in your QScintilla, action shortcuts is as followeded

self.toolBar.newAction = QtWidgets.QAction(QtGui.QIcon(":/ico/new.png"),"New",self.toolBar)
self.toolBar.newAction.setStatusTip("Clear TextBox or make new document.")
self.toolBar.newAction.setShortcut("Ctrl+N")
self.toolBar.newAction.triggered.connect(self.newfile)

    #actions
self.toolBar.addAction(self.toolBar.newAction)
self.toolBar.addSeparator()


问:
Design Approach With Data Containing Several Columns

I am designing an application which will process statistics data and produce various visual and data outputs. The current data has around 1500 records, but around 3000 columns! All the columns are important and will be required by the system.

The database of choice is SQL Server. The issue is that SQL server limits each table to 1024 columns. I could normalize the data to 5 tables of 600 columns each. The issue with this is that I have not found a way to import more than 250 columns into SQL  server. Does anyone have any suggestions as to a better design? Or a method to actually import all these columns? I do not expect detrimental performance issues as a lot of the data in the columns will be NULL.

答:
Do you have to store the data in a table?  Or can you handle your processing on the fly?  Not sure what your response-time requirements are, but if it's only 1500 rows, maybe you can just handle all your data processing real-time using a stored procedure/function:

Import data into an array-structure

Process data from array

Run whatever query results you need

Or maybe a better option, depending on if your DB supports it - store the columns for each row as a JSON / array data type.  Then you could do everything from one table.

I'd say your best bet, though, is to create three tables (each with the same row PK) and multiple import jobs.  Then just join the tables to get all the columns into one result set.


问:
Two layers for loop in `JavaScript`

function convertObjectToList(obj) {
  var innerArr= [];
  var outerArr=[];
  for (var prop in obj) {
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    console.log(innerArr);
    outerArr.push(innerArr);
    console.log(outerArr);
  } return outerArr;
}

convertObjectToList({
  name: 'Holly',
  age: 35,
})```

Can someone help me to figure out what happened inside the for loop?

Q: my question is on the second round: outerArr[0]= [ ‘name’, ‘Holly’ ], but the console shows me outerArr[0]= [ ‘name’, ‘Holly’, ‘age’, 35 ]

Actual output:

1. first round: innerArr=[ ‘name’, ‘Holly’ ]  & outerArr = [ [ ‘name’, ‘Holly’ ] ]

2. second round:
 innerArr=[ ‘name’, ‘Holly’, ‘age’, 35 ] & outerArr=[ [ ‘name’, ‘Holly’, ‘age’, 35 ],[ ‘name’, ‘Holly’, ‘age’, 35 ] ]

But I expeced: outerArr= [ [ ‘name’, ‘Holly’ ], [ ‘name’, ‘Holly’, ‘age’, 35 ] ]

答:
You are not pushing a deep copy of the array, but rather pushing the same array again. Each element of outerArr will contain the innerArr.

I think what you want to do is create a new innerArr for each iteration.

function convertObjectToList(obj) {

  var outerArr=[];
  for (var prop in obj) {
    var innerArr= [];
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    outerArr.push(innerArr);
  } return outerArr;
}

convertObjectToList({
  name: 'Holly',
  age: 35,
}) ```

Title: Two layers for loop in `JavaScript`

Body:
function convertObjectToList(obj) {
  var innerArr= [];
  var outerArr=[];
  for (var prop in obj) {
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    console.log(innerArr);
    outerArr.push(innerArr);
    console.log(outerArr);
  } return outerArr;
}

convertObjectToList({
  name: 'Holly',
  age: 35,
})

Can someone help me to figure out what happened inside the for loop?

Q: my question is on the second round: outerArr[0]= [ ‘name’, ‘Holly’ ], but the console shows me outerArr[0]= [ ‘name’, ‘Holly’, ‘age’, 35 ]

Actual output:

1. first round: innerArr=[ ‘name’, ‘Holly’ ]  & outerArr = [ [ ‘name’, ‘Holly’ ] ]

2. second round:
 innerArr=[ ‘name’, ‘Holly’, ‘age’, 35 ] & outerArr=[ [ ‘name’, ‘Holly’, ‘age’, 35 ],[ ‘name’, ‘Holly’, ‘age’, 35 ] ]

But I expeced: outerArr= [ [ ‘name’, ‘Holly’ ], [ ‘name’, ‘Holly’, ‘age’, 35 ] ]


问:
VS2015 nuget package manager not finding packages
I installed VS2015 Update 2 and now nuget package manager does not find any packages outside of the "Microsoft and .net" package source. It looks like the nuget package source was removed. When I add it back as "http://www.nuget.org" I get an error "Unable to retrieve results from one or more sources".

Anyone else having this problem?

答: For me it was a genuine temporary network problem. IVe tried again a bit later, and the error  disappeared.</p>


问:
Trying to fadein divs in a sequence, over time, using JQuery
I'm trying to figure out how to make 4 images fade in sequentially when the page loads.

The following is my (amateurish) code:

Here is the HTML:

```<code><div id="outercorners">

 <img id="corner1" src="images/corner1.gif" width="6" height="6" alt=""/>
 <img id="corner2" src="images/corner2.gif" width="6" height="6" alt=""/>
 <img id="corner3" src="images/corner3.gif" width="6" height="6" alt=""/>
 <img id="corner4" src="images/corner4.gif" width="6" height="6" alt=""/>

</div><!-- end #outercorners-->
</code>```

Here is the JQuery:

```<code>$(document).ready(function() {

$("#corner1").fadeIn("2000", function(){

$("#corner3").fadeIn("4000", function(){

  $("#corner2").fadeIn("6000", function(){

    $("#corner4").fadeIn("8000", function(){

    });

   });

 });

 });
</code>```

Here is the css:

```<code>#outercorners {
position: fixed;
top:186px;
left:186px;
width:558px;
height:372px;
}

#corner1 {
position: fixed;
top:186px;
left:186px;
display: none;
}

#corner2 {
position: fixed;
top:186px;
left:744px;
display: none;
}

#corner3 {
position: fixed;
top:558px;
left:744px;
display: none;
}

#corner4 {
position: fixed;
top:558px;
left:186px;
display: none;
}
</code>```

They seem to just wink at me, rather than fade in in the order I've ascribed to them. Should I be using the queue() function? And, if so, how would I implement it in this case?

Thank you for any assistance.

答:
I know this is a couple of months old question but I just thought to post a solution which might help someone. I would do something like this:

```<code>var d= 0;
$('#outercorners > img').each(function() {
    $(this).delay(d).fadeIn(1000);
    d += 1000;
});
</code>```

You can change the 1000ms to any figure to suit your need. Note that they don't have to be equal.

Demo:

http://jsfiddle.net/e5H5Y/

http://jsfiddle.net/e5H5Y/2/

Good luck

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to figure out how to make 4 images fade in sequentially when the page loads.

The following is my (amateurish) code:

Here is the HTML:

Here is the JQuery:

$(document).ready(function() {

$("#corner1").fadeIn("2000", function(){

$("#corner3").fadeIn("4000", function(){

  $("#corner2").fadeIn("6000", function(){

    $("#corner4").fadeIn("8000", function(){

    });

   });

 });

 });

Here is the css:

#outercorners {
position: fixed;
top:186px;
left:186px;
width:558px;
height:372px;
}

#corner1 {
position: fixed;
top:186px;
left:186px;
display: none;
}

#corner2 {
position: fixed;
top:186px;
left:744px;
display: none;
}

#corner3 {
position: fixed;
top:558px;
left:744px;
display: none;
}

#corner4 {
position: fixed;
top:558px;
left:186px;
display: none;
}

They seem to just wink at me, rather than fade in in the order I've ascribed to them. Should I be using the queue() function? And, if so, how would I implement it in this case?

Thank you for any assistance.

Body:
I know this is a couple of months old question but I just thought to post a solution which might help someone. I would do something like this:

var d= 0;
$('#outercorners > img').each(function() {
    $(this).delay(d).fadeIn(1000);
    d += 1000;
});

You can change the 1000ms to any figure to suit your need. Note that they don't have to be equal.

Demo:

http://jsfiddle.net/e5H5Y/

http://jsfiddle.net/e5H5Y/2/

Good luck


问:
How do I create a DataTable, then add rows to it?
I've tried creating a DataTable and adding rows to it like this:

```<code> DataTable dt = new DataTable();
 dt.clear();
 dt.Columns.Add("Name");
 dt.Columns.Add("Marks");
</code>```

How do I see the structure of DataTable?

Now I want to add ravi for Name and 500 for Marks. How can I do this?

答:
You can add Row in a single line</p>

```<code>    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've tried creating a DataTable and adding rows to it like this:

 DataTable dt = new DataTable();
 dt.clear();
 dt.Columns.Add("Name");
 dt.Columns.Add("Marks");

How do I see the structure of DataTable?

Now I want to add ravi for Name and 500 for Marks. How can I do this?

Body:
You can add Row in a single line

    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);


问:
multiple multi-column selections in pandas
I am trying do multiple multi-column selections from a pandas dataframe and can't seem to find an elegant way to do accomplish it.

Set up:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 8)),columns=list('ABCDEFGH'))
</code>```

Let's say I want to find the rows of the dataframe for which columns 'A' and 'B' are greater than 50, I would do something like this:

```<code>df[['A', 'B']].where(lambda x: x > 50).dropna()
</code>```

Now let's say I also want to select on columns 'E' and 'F' where they are less than 25.

How do I accomplish this?

Note: In the actual dataset ['A', 'B'] can be a set of 10+ columns that are non-sequential, and ['E', 'F'] can also be a set of 10+ columns that are non-sequential. I have lists of column names for each set of criteria. So I want to avoid ('A' > 50) & ('B' > 50) as I would then have to string together 30+ boolean criteria.

答:
```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 8)),columns=list('ABCDEFGH'))
</code>```

Define the columns you want to constrain:

```<code>columns1 = ['A', 'B', 'C', 'E']
columns2 = ['D', 'F']
</code>```

Define and apply constraints

```<code>constraint1 = (df[columns1] > 50).all(axis =1)
constraint2 = (df[columns2] < 50).any(axis =1)
print df[constraint1 & constraint2]
</code>```

Note:

.any(axis=1) acts as OR operator when applying the constraint to columns.

.all(axis=1) acts as AND operator when applying the constraint to columns.

Body:
I am trying do multiple multi-column selections from a pandas dataframe and can't seem to find an elegant way to do accomplish it.

Set up:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 8)),columns=list('ABCDEFGH'))

Let's say I want to find the rows of the dataframe for which columns 'A' and 'B' are greater than 50, I would do something like this:

df[['A', 'B']].where(lambda x: x > 50).dropna()

Now let's say I also want to select on columns 'E' and 'F' where they are less than 25.

How do I accomplish this?

Note: In the actual dataset ['A', 'B'] can be a set of 10+ columns that are non-sequential, and ['E', 'F'] can also be a set of 10+ columns that are non-sequential. I have lists of column names for each set of criteria. So I want to avoid ('A' > 50) & ('B' > 50) as I would then have to string together 30+ boolean criteria.

Body:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 8)),columns=list('ABCDEFGH'))

Define the columns you want to constrain:

columns1 = ['A', 'B', 'C', 'E']
columns2 = ['D', 'F']

Define and apply constraints

constraint1 = (df[columns1] > 50).all(axis =1)
constraint2 = (df[columns2] < 50).any(axis =1)
print df[constraint1 & constraint2]

Note:

.any(axis=1) acts as OR operator when applying the constraint to columns.

.all(axis=1) acts as AND operator when applying the constraint to columns.


问:
How to test / debug GNOME Shell extensions? Is there any tool for that?
I would like to develop GNOME Shell extensions and found it's really easy to step into the development process but I still can't figure out how to debug / test my extensions effectively.

Are there any tools for that purpose? Is there any kind of real time console like we have on modern browsers or javascript servers environments?

答:
We are developing a emacs package aimed at gnome-shell extension development here: https://github.com/paperwm/gnome-shell-mode

It's still in "beta" (dec. 2017), but its already very useful.

Features

Autocompletion (muuuch better than what looking glass provides)

Eval of line, selection, current function, buffer (optionally pasting the result into the buffer in a comment)

Highlight of error when evaling

Documentation lookup helper

Helper to reload the module you're working on without restarting gnome-shell


问:
Obtaining an average from if statement Python 3
Ok so I got everything figured out. But now I am trying to use an if statement to tell the loop to take the average mpg (from the .txt file) from vehicles that get less than 22 mpg and then just average that up and output it IDLE. I feel like I should run the if statement before the loop. I am just not sure what I really need to change. I figure I should be able to slice variable holding the text file data. anyways here is my code. Can someone help me understand what I am not doing right?

```<code>def cityGasGuzzler():
# Input:that assigns a text file to a value and provides other definition
 values
cityGuzz = open("carModelData_city.","r")
# Process: For loop to get average of gas guzzling city street driving
  vehicles
for line in cityGuzz:
# Process: Uses if statement to get the average of lower mpg or gas guzzlers
    if cityGuzz[0:-1] < 22:
        sum = sum + eval(line)
        count = count + 1
        avrg = sum / count
# Output: using the round function to get average to the 2nd decimal place
#         and prints string and rounded variable to IDLE.
print("The average city MPG is,", round(avrg, 2))

cityGasGuzzler()
</code>```

Just to clarify, my main objective is as follows, take the numeric values from the text file that are less than 22, average those up and output the average to IDLE.

答:
Your problem is that you are trying to divide to quantity in each iteration of loop. Also you have several mistakes in your code. Try this out. </p>

```<code>sum = 0.0
quantity = 0
with open('file.txt', 'r') as f:
    for line in f.readline():
        if line.isdigit():
            sum += float(line)
            quantity += 1
average = sum/quantity
print average
</code>```

Body:
Ok so I got everything figured out. But now I am trying to use an if statement to tell the loop to take the average mpg (from the .txt file) from vehicles that get less than 22 mpg and then just average that up and output it IDLE. I feel like I should run the if statement before the loop. I am just not sure what I really need to change. I figure I should be able to slice variable holding the text file data. anyways here is my code. Can someone help me understand what I am not doing right?

def cityGasGuzzler():
# Input:that assigns a text file to a value and provides other definition
 values
cityGuzz = open("carModelData_city.","r")
# Process: For loop to get average of gas guzzling city street driving
  vehicles
for line in cityGuzz:
# Process: Uses if statement to get the average of lower mpg or gas guzzlers
    if cityGuzz[0:-1] < 22:
        sum = sum + eval(line)
        count = count + 1
        avrg = sum / count
# Output: using the round function to get average to the 2nd decimal place
#         and prints string and rounded variable to IDLE.
print("The average city MPG is,", round(avrg, 2))

cityGasGuzzler()

Just to clarify, my main objective is as follows, take the numeric values from the text file that are less than 22, average those up and output the average to IDLE.

Body:
Your problem is that you are trying to divide to quantity in each iteration of loop. Also you have several mistakes in your code. Try this out.

sum = 0.0
quantity = 0
with open('file.txt', 'r') as f:
    for line in f.readline():
        if line.isdigit():
            sum += float(line)
            quantity += 1
average = sum/quantity
print average


问:
How to solve comparing structs as key map c++
None topic solved my problem of comparing structs as key map in C++.

Structs code following:

```<code>struct XYZ{
  int x, y, z;
}

struct XYZComp{
  bool operator()(const XYZ& l, const XYZ& r)
  {
    return ((l.x==r.x)&&(l.y==r.y)&&(l.z==r.z));
  }
}
</code>```

Main looks like

```<code>int main()
{
  map<XYZ, int, XYZComp> m;
  m.insert(std::make_pair<XYZ,int>({1,2,3}, 1)); //ok

  map<XYZ, int, XYZComp>::iterator it = m.find({1,0,3});
  if(it!=m.end())
  {
    std::cout<<"Key exists in map";
  }
  else
  {
    m.insert(std::make_pair<XYZ,int>({1,0,3}, 1));
    //never come here
    //compiler thinks key already exists in map
  }

return 0;
}
</code>```

I just tried without XYZComparer but it still doesn't work.

```<code>struct XYZ{
  int x,y,z;
  bool operator==(const XYZ& xyz)
  {
    return (x=xyz.x) && (y=xyz.y) && (z=xyz.z);
  }
  bool operator<(const XYZ& xyz)
  {
    return (x>xyz.x) && (y>xyz.y) && (z>xyz.z);
  }
}
</code>```

How to solve comparing these structs XYZ while i am trying existing item in map.

Edit: Compiler thinks structs are the same when at least one number is correct.

答:
The comparator of std::set and std::map should function as <, not ==. The binary search tree not only needs to know if objects are equal; it needs to give them an order because the data structure is sorted. Overload the < operator for your objects.

The objects are considered equal if !comp(a, b) && !comp(b, a). (Source)

If you overload <, you need not explicitly supply the comparator to the container type because the default is comparator is std::less, which wraps the < operator.

Body:
None topic solved my problem of comparing structs as key map in C++.

Structs code following:

struct XYZ{
  int x, y, z;
}

struct XYZComp{
  bool operator()(const XYZ& l, const XYZ& r)
  {
    return ((l.x==r.x)&&(l.y==r.y)&&(l.z==r.z));
  }
}

Main looks like

int main()
{
  map<XYZ, int, XYZComp> m;
  m.insert(std::make_pair<XYZ,int>({1,2,3}, 1)); //ok

  map<XYZ, int, XYZComp>::iterator it = m.find({1,0,3});
  if(it!=m.end())
  {
    std::cout<<"Key exists in map";
  }
  else
  {
    m.insert(std::make_pair<XYZ,int>({1,0,3}, 1));
    //never come here
    //compiler thinks key already exists in map
  }

return 0;
}

I just tried without XYZComparer but it still doesn't work.

struct XYZ{
  int x,y,z;
  bool operator==(const XYZ& xyz)
  {
    return (x=xyz.x) && (y=xyz.y) && (z=xyz.z);
  }
  bool operator<(const XYZ& xyz)
  {
    return (x>xyz.x) && (y>xyz.y) && (z>xyz.z);
  }
}

How to solve comparing these structs XYZ while i am trying existing item in map.

Edit: Compiler thinks structs are the same when at least one number is correct.


问:
PHP & MYSQL - Display user-uploaded photos from Database according to date photos were uploaded
I created photo upload form. Different users are able to upload multiple photos at once and the photos, the user's details and input get stored in the database as shown in picture below:

I want to be able to display the users and their photos in my index.php page according to the date the photos were uploaded. I would like the index.php page to look something like this

I tried to use GROUP_CONCAT() and GROUP BY in my SQL statement hoping to achieve something like the table below which might allow me to loop through the table data in order to display the photos alongside the users

This is my code which did not work:

```<code>$sql = "SELECT id, unique_id, GROUP_CONCAT(fileName) as fileName,  title,date GROUP BY unique_id FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // This is the line 22 in my code.
    while($row = $result->fetch_assoc()) {
        echo $row['fileName']; //I wanted to know if echo $row['fileName']; would print something like cow1.jpg, cow2,jpg etc.
    }
}
</code>```

But I am getting error as follows:

Notice: Trying to get property of non-object in C:\xampp\htdocs\display.php on line 22

Someone suggested the GROUP_CONCAT() to me. I have done some search but all tutorials give example of how the table will look after using GROUP_CONCAT() but not how to get data from the final table to use in e.g index.php. I am new to GROUP_CONCAT() and I don't really know how to work with that.

答:
After giving you a bit of a rebuke in comments for deleting the previous question, now let's try some "teaching" ;-)

As I said in a comment on the earlier question, this is something where I would not try and get fancy with GROUP_CONCAT. Foremost because it has the disadvantage that a) it is MySQL-specific, so using it kinda hinders portability of your code, and b) more severely, the length of the resulting string you can assemble is limited. File names (plus paths) could easily get longer, if you have different upload directories for different users or additional parameters to include in the URLs, so that would limit the amount of photos a group could contain, before this "explodes" ...

The control break I mentioned is a pretty basic programming principle. You loop over a sorted(!) set of data, and compare one or more criteria to see whether they have changed between the previous row and the current one.

Your example requires a simple one-level control break - the date is the only grouping criterion here. But this same principle can be extended to cover multiple levels - say if you had a list of your credit card purchases covering several years, and you want to output them grouped by year first, and then by month second.

The following example loops over an array more or less matching your example data; but looping over a database query result this works pretty much the same.

But remember, in any case, the input data must already be sorted by the break criterion (or criteria, for a multi-level control break; and in that case, also "ordered in the right order", meaning for above example with your CC purchases by year first and then by month second.)

Example with comments should be pretty self-explanatory from here on, so:

```<code><?php

// example data - I left out a few of your columns; the important part is that
// it is sorted by the control group break criterion, in this case the date
$data = [
 ['id' => '1', 'name' => 'John', 'file' => 'cow1.jpg', 'date' => '07-12-2017 01:05'],
 ['id' => '2', 'name' => 'John', 'file' => 'cow2.jpg', 'date' => '07-12-2017 01:05'],
 ['id' => '3', 'name' => 'Dan', 'file' => 'cat1.jpg', 'date' => '08-12-2107 02:09'],
 ['id' => '4', 'name' => 'Dan', 'file' => 'cat2.jpg', 'date' => '08-12-2107 02:09'],
 ['id' => '5', 'name' => 'John', 'file' => 'dog.jpg', 'date' => '09-12-2107 03:10'],
];

echo '<ul>'; // open unordered list
echo '<li>'; // opening list item tag for first grouped set of data

$previousDate = null;
foreach($data as $row) {
  // check if group break has occurred - is the date of this row different
  // from that of the previous one? (since we initialized $previousDate as null,
  // this will be true for the first row in any case)
  if($row['date'] != $previousDate) {
    // break has occured
    if(null != $previousDate) {
      // if this is not the first row, then we have created output before, so
      // now we need to close the previous list item, and open an new one.
      echo '</li>';
      echo '<li>';
    }

    // now we output whatever is needed at the start of a new group - in this case,
    // user name and date, since we want those only once
    echo 'User: ' . $row['name'] . '<br>';
    echo 'Date: ' . $row['date'] . '<br>';
  }

  // now, handle the output of the actual "per-row" data - in this case, the individual image
  echo '[img src="' . $row['file'] . '"]<br>'; // pseudo image tag in lack of real image files

  // remember current row's date as the new previous one, so that we can compare against
  // that in the next loop iteration
  $previousDate = $row['date'];
}

echo '</li>'; // closing list item tag for last grouped set of data
echo '</ul>'; // close unordered list
</code>```

If you want something different than an unordered list (a bit ironic not using an ordered list here, I know, but I did not want to spoil the example output with the default item numbering that causes, that might be confusing), you can output the data in other structures as well of course - say, a table instead of a list. Just needs a little thought put into what to output and where/when exactly in each case. Say you wanted a table with three columns name, date and image, and leave name and date blank in each row where they still match the previous one - then you still have to output empty table cells for name and date, so as not to mess up the basic HTML table structure required. So the logic might need slight tweaks, depending on the specific output desired.

Body:
I created photo upload form. Different users are able to upload multiple photos at once and the photos, the user's details and input get stored in the database as shown in picture below:

I want to be able to display the users and their photos in my index.php page according to the date the photos were uploaded. I would like the index.php page to look something like this

I tried to use GROUP_CONCAT() and GROUP BY in my SQL statement hoping to achieve something like the table below which might allow me to loop through the table data in order to display the photos alongside the users

This is my code which did not work:

$sql = "SELECT id, unique_id, GROUP_CONCAT(fileName) as fileName,  title,date GROUP BY unique_id FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // This is the line 22 in my code.
    while($row = $result->fetch_assoc()) {
        echo $row['fileName']; //I wanted to know if echo $row['fileName']; would print something like cow1.jpg, cow2,jpg etc.
    }
}

But I am getting error as follows:

Notice: Trying to get property of non-object in C:\xampp\htdocs\display.php on line 22

Someone suggested the GROUP_CONCAT() to me. I have done some search but all tutorials give example of how the table will look after using GROUP_CONCAT() but not how to get data from the final table to use in e.g index.php. I am new to GROUP_CONCAT() and I don't really know how to work with that.

Body:
After giving you a bit of a rebuke in comments for deleting the previous question, now let's try some "teaching" ;-)

As I said in a comment on the earlier question, this is something where I would not try and get fancy with GROUP_CONCAT. Foremost because it has the disadvantage that a) it is MySQL-specific, so using it kinda hinders portability of your code, and b) more severely, the length of the resulting string you can assemble is limited. File names (plus paths) could easily get longer, if you have different upload directories for different users or additional parameters to include in the URLs, so that would limit the amount of photos a group could contain, before this "explodes" ...

The control break I mentioned is a pretty basic programming principle. You loop over a sorted(!) set of data, and compare one or more criteria to see whether they have changed between the previous row and the current one.

Your example requires a simple one-level control break - the date is the only grouping criterion here. But this same principle can be extended to cover multiple levels - say if you had a list of your credit card purchases covering several years, and you want to output them grouped by year first, and then by month second.

The following example loops over an array more or less matching your example data; but looping over a database query result this works pretty much the same.

But remember, in any case, the input data must already be sorted by the break criterion (or criteria, for a multi-level control break; and in that case, also "ordered in the right order", meaning for above example with your CC purchases by year first and then by month second.)

Example with comments should be pretty self-explanatory from here on, so:

<?php

// example data - I left out a few of your columns; the important part is that
// it is sorted by the control group break criterion, in this case the date
$data = [
 ['id' => '1', 'name' => 'John', 'file' => 'cow1.jpg', 'date' => '07-12-2017 01:05'],
 ['id' => '2', 'name' => 'John', 'file' => 'cow2.jpg', 'date' => '07-12-2017 01:05'],
 ['id' => '3', 'name' => 'Dan', 'file' => 'cat1.jpg', 'date' => '08-12-2107 02:09'],
 ['id' => '4', 'name' => 'Dan', 'file' => 'cat2.jpg', 'date' => '08-12-2107 02:09'],
 ['id' => '5', 'name' => 'John', 'file' => 'dog.jpg', 'date' => '09-12-2107 03:10'],
];

echo '<ul>'; // open unordered list
echo '<li>'; // opening list item tag for first grouped set of data

$previousDate = null;
foreach($data as $row) {
  // check if group break has occurred - is the date of this row different
  // from that of the previous one? (since we initialized $previousDate as null,
  // this will be true for the first row in any case)
  if($row['date'] != $previousDate) {
    // break has occured
    if(null != $previousDate) {
      // if this is not the first row, then we have created output before, so
      // now we need to close the previous list item, and open an new one.
      echo '</li>';
      echo '<li>';
    }

    // now we output whatever is needed at the start of a new group - in this case,
    // user name and date, since we want those only once
    echo 'User: ' . $row['name'] . '<br>';
    echo 'Date: ' . $row['date'] . '<br>';
  }

  // now, handle the output of the actual "per-row" data - in this case, the individual image
  echo '[img src="' . $row['file'] . '"]<br>'; // pseudo image tag in lack of real image files

  // remember current row's date as the new previous one, so that we can compare against
  // that in the next loop iteration
  $previousDate = $row['date'];
}

echo '</li>'; // closing list item tag for last grouped set of data
echo '</ul>'; // close unordered list

If you want something different than an unordered list (a bit ironic not using an ordered list here, I know, but I did not want to spoil the example output with the default item numbering that causes, that might be confusing), you can output the data in other structures as well of course - say, a table instead of a list. Just needs a little thought put into what to output and where/when exactly in each case. Say you wanted a table with three columns name, date and image, and leave name and date blank in each row where they still match the previous one - then you still have to output empty table cells for name and date, so as not to mess up the basic HTML table structure required. So the logic might need slight tweaks, depending on the specific output desired.


问:
iOS - managing trusted roots on an SSL connection
By adding to the kCFStreamPropertySSLSettings dictionary the usual kCFStreamSSLValidatesCertificateChain, kCFStreamSSLAllowsAnyRoot, etc - I can make server & client authentication work.

However I fail to see how I can get this more fine grained; i.e.

detect a cert of server/CA never seen - and escalate acceptance up to the user.

validate a cert of the server I am connected to against a narrow trust list (e.g. the cert learned about during a previous connect).

I.e. what I am looking for is 1) something like the SSLSetTrustedRoots() on MacOSX and 2) something like the error/domain callbacks in kCFStreamErrorDomainSSL (e.g. errSSLPeerCertUnknown) - none which seems defined/accesible on the ipad/iphone 4.2.1.

Or am I missing something ? Or do I need to do something explicit on the callback ? Examples appreciated (the AdvancedURLConnections example is not quite applicable - I have a raw (IRC) socket).

Thanks,

Dw.

答:
Set kCFStreamSSLValidatesCertificateChain to kBooleanFalse and manually verify the cert with the  APIs.

Specifically, use

```<code>SecTrustCreateWithCertificates
</code>```

with the certificates you get from

```<code>CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates);
</code>```

Then, you can use

```<code>SecTrustSetAnchorCertificates
</code>```

and finally call

```<code>SecTrustEvaluate
</code>```

Body:
Set kCFStreamSSLValidatesCertificateChain to kBooleanFalse and manually verify the cert with the  APIs.

Specifically, use

SecTrustCreateWithCertificates

with the certificates you get from

CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates);

Then, you can use

SecTrustSetAnchorCertificates

and finally call

SecTrustEvaluate


问:
Notepad++ and regex with removal of unmatching sections
I'm using this regex string I've crafted...

```<code>['"]{1}\w+@\w+\.{1}\w\w\w?['"]
</code>```

To hunt for email addresses contained in quotes in an old badly formatted legacy file.

Example:

```<code> ADF325@#%jkdaf-@#%j-afd(#$w52'leroyjenkins@myguild.edu'@#%kladfjkla-235dsaf-'thisemail@example.com'2l35jk2dz-dl1jkozf-afajelj'gooselick@somebodyspastries.co'l2#%Jk23l5jlafafljewo8972509357
j2k3l5jadfjeljwfoobar'foobar@barfoo.foo'jk23j-zv8902354jlfa
('352lj53k2ljkumquat'fakeemail@realemail.wtf')lajflsdf
etc.
</code>```

The regex is working beautifully for me... except for one thing. I want to replace everything that -doesn't- match with whitespace so I can work on formatting this to migrate this to the proper DB. How can I delete everything that doesn't match (and preferably, throw a newline between each match)?

答:
When you have to deal with large files, the way to process them consists to not load them entirely. Instead you have to read them as a stream. You can't do that using npp, but it's possible using a script language like php.
If you want to make changes or to extract something in particular when you load a file as a stream, you can write a user-defined stream filter:

```<code>class EmailFilter extends php_user_filter
{
    public function filter($in, $out, &$consumed, $closing)
    {
        while ( $bucket = stream_bucket_make_writeable($in) ) {
            if ( preg_match_all('~\'\K\w+@\w+\.\w{2,3}(?=\')|"\K\w+@\w+\.\w{2,3}(?=")~S', $bucket->data, $matches) ) {
                 $bucket->data = implode("\n", $matches[0]);
            }
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }
}

stream_filter_register('email_filter', 'EmailFilter');
$handle = fopen('php://filter/read=email_filter/resource=yourfile.txt', 'rb');

while (feof($handle) !== true) {
    echo fgets($handle);
}

fclose($handle);
</code>```

When you adopt this kind of approach, nothing forbids to insert mails in your table five by five, ten by ten, twenty by twenty or the number you want. The goal is to not load all the file in memory.

(more examples in O'Reilly Modern PHP)

Body:
I'm using this regex string I've crafted...

['"]{1}\w+@\w+\.{1}\w\w\w?['"]

To hunt for email addresses contained in quotes in an old badly formatted legacy file.

Example:

 ADF325@#%jkdaf-@#%j-afd(#$w52'leroyjenkins@myguild.edu'@#%kladfjkla-235dsaf-'thisemail@example.com'2l35jk2dz-dl1jkozf-afajelj'gooselick@somebodyspastries.co'l2#%Jk23l5jlafafljewo8972509357
j2k3l5jadfjeljwfoobar'foobar@barfoo.foo'jk23j-zv8902354jlfa
('352lj53k2ljkumquat'fakeemail@realemail.wtf')lajflsdf
etc.

The regex is working beautifully for me... except for one thing. I want to replace everything that -doesn't- match with whitespace so I can work on formatting this to migrate this to the proper DB. How can I delete everything that doesn't match (and preferably, throw a newline between each match)?

Body:
When you have to deal with large files, the way to process them consists to not load them entirely. Instead you have to read them as a stream. You can't do that using npp, but it's possible using a script language like php.
If you want to make changes or to extract something in particular when you load a file as a stream, you can write a user-defined stream filter:

class EmailFilter extends php_user_filter
{
    public function filter($in, $out, &$consumed, $closing)
    {
        while ( $bucket = stream_bucket_make_writeable($in) ) {
            if ( preg_match_all('~\'\K\w+@\w+\.\w{2,3}(?=\')|"\K\w+@\w+\.\w{2,3}(?=")~S', $bucket->data, $matches) ) {
                 $bucket->data = implode("\n", $matches[0]);
            }
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }
}

stream_filter_register('email_filter', 'EmailFilter');
$handle = fopen('php://filter/read=email_filter/resource=yourfile.txt', 'rb');

while (feof($handle) !== true) {
    echo fgets($handle);
}

fclose($handle);

When you adopt this kind of approach, nothing forbids to insert mails in your table five by five, ten by ten, twenty by twenty or the number you want. The goal is to not load all the file in memory.

(more examples in O'Reilly Modern PHP)


问:
Convert a 2 column dataframe into a symmetric binary matrix
I am trying to make a symmetric matrix in R where if column A=dataSet1 and column B=dataSet2 appear together in the same row, then set in the matrix to 1 else it is 0.  However, I can not seem to understand the tcrossprod() function in R.  I have been able use table to make a unsymmetrical matrix but no luck with the (symmetric/square) matrix.

I tried follow this example but no success:
Building a symmetric binary matrix

My data:

```<code>   structure(list(dataSet1 = c("g14773.t1", "g6302.t1", "g399.t1",
"g15590.t1", "g2595.t1", "g149.t1"), dataSet2 = c("g6302.t1",
"g14773.t1", "g482.t1", "g14053.t1", "g1006.t1", "g6302.t1")), .Names = c("dataSet1",
"dataSet2"), row.names = c(NA, -6L), class = "data.frame")
</code>```

Whenever I use the tcrossprod function I get incorrect binary present and values are missing:

```<code> tcrossprod(table(head(Data)))
              dataSet2
  dataSet1    g14773.t1 g149.t1 g15590.t1 g2595.t1 g399.t1 g6302.t1
  g14773.t1         1       1         0        0       0        0
  g149.t1           1       1         0        0       0        0
  g15590.t1         0       0         1        0       0        0
  g2595.t1          0       0         0        1       0        0
  g399.t1           0       0         0        0       1        0
  g6302.t1          0       0         0        0       0        1
</code>```

Any recommendations for how to make it into a symmetric matrix like below:

```<code>structure(list(g14773.t1 = c(0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,
0L), g6302.t1 = c(1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), g399.t1 = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), g15590.t1 = c(0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L), g2595.t1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L), g149.t1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), g482.t1 = c(0L,
0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), g14053.t1 = c(0L, 0L, 0L, 1L,
0L, 0L, 0L, 0L, 0L), g1006.t1 = c(0L, 0L, 0L, 0L, 1L, 0L, 0L,
0L, 0L)), .Names = c("g14773.t1", "g6302.t1", "g399.t1", "g15590.t1",
"g2595.t1", "g149.t1", "g482.t1", "g14053.t1", "g1006.t1"), class = "data.frame", row.names = c("g14773.t1",
"g6302.t1", "g399.t1", "g15590.t1", "g2595.t1", "g149.t1", "g482.t1",
"g14053.t1", "g1006.t1"))
</code>```

答:
You can convert your columns df$dataSet1 and df$dataSet2 to factor, specifying that their levels are the union of values found in both columns. And then simply use table:

```<code>df$dataSet1 = factor(df$dataSet1,levels=union(df$dataSet1,df$dataSet2))
df$dataSet2 = factor(df$dataSet2,levels=union(df$dataSet1,df$dataSet2))
res = table(df)
</code>```

Table will include a count rather than a 0/1 value, so for example if two values are found twice together, the value in the matrix will be 2.
If that's an issue, you can add:

```<code>res[res>0] = 1
</code>```

Result:

```<code>           dataSet2
dataSet1    g14773.t1 g6302.t1 g399.t1 g15590.t1 g2595.t1 g149.t1 g482.t1 g14053.t1 g1006.t1
  g14773.t1         0        1       0         0        0       0       0         0        0
  g6302.t1          1        0       0         0        0       0       0         0        0
  g399.t1           0        0       0         0        0       0       1         0        0
  g15590.t1         0        0       0         0        0       0       0         1        0
  g2595.t1          0        0       0         0        0       0       0         0        1
  g149.t1           0        1       0         0        0       0       0         0        0
  g482.t1           0        0       0         0        0       0       0         0        0
  g14053.t1         0        0       0         0        0       0       0         0        0
  g1006.t1          0        0       0         0        0       0       0         0        0
</code>```

Body:
I am trying to make a symmetric matrix in R where if column A=dataSet1 and column B=dataSet2 appear together in the same row, then set in the matrix to 1 else it is 0.  However, I can not seem to understand the tcrossprod() function in R.  I have been able use table to make a unsymmetrical matrix but no luck with the (symmetric/square) matrix.

I tried follow this example but no success:
Building a symmetric binary matrix

My data:

   structure(list(dataSet1 = c("g14773.t1", "g6302.t1", "g399.t1",
"g15590.t1", "g2595.t1", "g149.t1"), dataSet2 = c("g6302.t1",
"g14773.t1", "g482.t1", "g14053.t1", "g1006.t1", "g6302.t1")), .Names = c("dataSet1",
"dataSet2"), row.names = c(NA, -6L), class = "data.frame")

Whenever I use the tcrossprod function I get incorrect binary present and values are missing:

 tcrossprod(table(head(Data)))
              dataSet2
  dataSet1    g14773.t1 g149.t1 g15590.t1 g2595.t1 g399.t1 g6302.t1
  g14773.t1         1       1         0        0       0        0
  g149.t1           1       1         0        0       0        0
  g15590.t1         0       0         1        0       0        0
  g2595.t1          0       0         0        1       0        0
  g399.t1           0       0         0        0       1        0
  g6302.t1          0       0         0        0       0        1

Any recommendations for how to make it into a symmetric matrix like below:

structure(list(g14773.t1 = c(0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,
0L), g6302.t1 = c(1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), g399.t1 = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), g15590.t1 = c(0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L), g2595.t1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L), g149.t1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), g482.t1 = c(0L,
0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), g14053.t1 = c(0L, 0L, 0L, 1L,
0L, 0L, 0L, 0L, 0L), g1006.t1 = c(0L, 0L, 0L, 0L, 1L, 0L, 0L,
0L, 0L)), .Names = c("g14773.t1", "g6302.t1", "g399.t1", "g15590.t1",
"g2595.t1", "g149.t1", "g482.t1", "g14053.t1", "g1006.t1"), class = "data.frame", row.names = c("g14773.t1",
"g6302.t1", "g399.t1", "g15590.t1", "g2595.t1", "g149.t1", "g482.t1",
"g14053.t1", "g1006.t1"))

Body:
You can convert your columns df$dataSet1 and df$dataSet2 to factor, specifying that their levels are the union of values found in both columns. And then simply use table:

df$dataSet1 = factor(df$dataSet1,levels=union(df$dataSet1,df$dataSet2))
df$dataSet2 = factor(df$dataSet2,levels=union(df$dataSet1,df$dataSet2))
res = table(df)

Table will include a count rather than a 0/1 value, so for example if two values are found twice together, the value in the matrix will be 2.
If that's an issue, you can add:

res[res>0] = 1

Result:

           dataSet2
dataSet1    g14773.t1 g6302.t1 g399.t1 g15590.t1 g2595.t1 g149.t1 g482.t1 g14053.t1 g1006.t1
  g14773.t1         0        1       0         0        0       0       0         0        0
  g6302.t1          1        0       0         0        0       0       0         0        0
  g399.t1           0        0       0         0        0       0       1         0        0
  g15590.t1         0        0       0         0        0       0       0         1        0
  g2595.t1          0        0       0         0        0       0       0         0        1
  g149.t1           0        1       0         0        0       0       0         0        0
  g482.t1           0        0       0         0        0       0       0         0        0
  g14053.t1         0        0       0         0        0       0       0         0        0
  g1006.t1          0        0       0         0        0       0       0         0        0


问:
I'm not sure what I am doing wrong in this try catch block
```<code>int memberChoice;
    boolean accountLoop = true;
    while (accountLoop) {
        try {
            System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
            memberChoice = input.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
        }
    }
</code>```

Whenever I type a string it should say invalid input go back to the beginning of the loop and direct me to input a number again. Instead it gives me an infinite loop. I feel like its something really small but I've been at this for 5 hours and can't figure it out. Any suggestions?

答:
Using a try/catch block to route your code logic is bad practice.  Exceptions should be reserved for exceptional cases, and never used to control the flow of information through an application.

Instead, you can use other methods of the (assumed) Scanner Object to verify the incoming element before trying to assign it a type.

```<code>public static void main(String[] args)  {
    int memberChoice=0;
    System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");

    //Use Try with Resources to ensure the Scanner is closed when we're done (requires Java 1.7+)
    try (Scanner input = new Scanner(System.in)){

        //hasNextLine tells us the user has entered a value.
        while (input.hasNextLine() && (memberChoice != 1 && memberChoice != 2)) {

            //Is that value actually an int?
            if (input.hasNextInt()) {
                //YES - Read as int and check for the value we're expecting
                int inValue = input.nextInt();
                if (inValue == 1 || inValue == 2) {
                    memberChoice = inValue;
                } else {
                    System.out.println("Invalid choice.  Try again");
                    System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
                    System.out.println();
                }
            } else {

                //NO - Read the line, provide feedback and prompt the user for a correction.
                String line = input.nextLine();
                System.out.println("You have to enter an integer value. '"+ line + "' is not valid.");
                System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
                System.out.println();
            }
        }
    }
}
</code>```

Body:
int memberChoice;
    boolean accountLoop = true;
    while (accountLoop) {
        try {
            System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
            memberChoice = input.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
        }
    }

Whenever I type a string it should say invalid input go back to the beginning of the loop and direct me to input a number again. Instead it gives me an infinite loop. I feel like its something really small but I've been at this for 5 hours and can't figure it out. Any suggestions?

Body:
Using a try/catch block to route your code logic is bad practice.  Exceptions should be reserved for exceptional cases, and never used to control the flow of information through an application.

Instead, you can use other methods of the (assumed) Scanner Object to verify the incoming element before trying to assign it a type.

public static void main(String[] args)  {
    int memberChoice=0;
    System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");

    //Use Try with Resources to ensure the Scanner is closed when we're done (requires Java 1.7+)
    try (Scanner input = new Scanner(System.in)){

        //hasNextLine tells us the user has entered a value.
        while (input.hasNextLine() && (memberChoice != 1 && memberChoice != 2)) {

            //Is that value actually an int?
            if (input.hasNextInt()) {
                //YES - Read as int and check for the value we're expecting
                int inValue = input.nextInt();
                if (inValue == 1 || inValue == 2) {
                    memberChoice = inValue;
                } else {
                    System.out.println("Invalid choice.  Try again");
                    System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
                    System.out.println();
                }
            } else {

                //NO - Read the line, provide feedback and prompt the user for a correction.
                String line = input.nextLine();
                System.out.println("You have to enter an integer value. '"+ line + "' is not valid.");
                System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
                System.out.println();
            }
        }
    }
}


问:
How do I learn about unknown children exiting in Go on Unix/Liunx?
It doesn't look like Go has a way to register a signal handler, so I can't catch SIGCHLD. So, how do I learn about a process exiting that I may not known about because my process has its CHILD_SUBREAPER flag set or is PID 1 in a PID namespace.

答: You can register signal handlers using signal.Notify</p>


答:
This is how I solved your problem:

```<code>int memberChoice = -1;
boolean accountLoop = true;
Scanner reader = new Scanner(System.in);
while (accountLoop) {
        System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
        try {
            memberChoice = reader.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                System.out.println(" Answer was valid ");
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
            reader.next(); // this consumes the invalid token
        }
    }
    reader.close();
</code>```

This problems was solved using the following link:
How to handle infinite loop caused by invalid input using Scanner

Summary of this answer:

You need to "consume" the invalid answer. Otherwise, that input will stay in the buffer which will cause the infinite loop.

Title: I'm not sure what I am doing wrong in this try catch block

Body:
This is how I solved your problem:

int memberChoice = -1;
boolean accountLoop = true;
Scanner reader = new Scanner(System.in);
while (accountLoop) {
        System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
        try {
            memberChoice = reader.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                System.out.println(" Answer was valid ");
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
            reader.next(); // this consumes the invalid token
        }
    }
    reader.close();

This problems was solved using the following link:
How to handle infinite loop caused by invalid input using Scanner

Summary of this answer:

You need to "consume" the invalid answer. Otherwise, that input will stay in the buffer which will cause the infinite loop.


问:
Put a view on the edge of its parent view
I am trying to create layout on Android, to look the same as on the image. Problem is, I don't know how put only half of button inside parent view, and another one outside. I need something to align center of button to the edge of parent. I know, it's possible with java code, but I want to avoid it. Any sugestions? Sorry for my english.

答:
You don't have to put the button into that view as a child, but over the view in a higher Z order with a different bottom margin.

You can start from this example:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="30dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="40dp"
        android:background="@android:color/darker_gray"
        android:orientation="vertical">

    </LinearLayout>

    <Button
        android:layout_width="150dp"
        android:layout_height="80dp"
        android:background="@android:color/holo_green_dark"
        android:layout_gravity="bottom|center_horizontal"/>

</FrameLayout>
</code>```

This is how it looks like:

Body:
You don't have to put the button into that view as a child, but over the view in a higher Z order with a different bottom margin.

You can start from this example:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="30dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="40dp"
        android:background="@android:color/darker_gray"
        android:orientation="vertical">

    </LinearLayout>

    <Button
        android:layout_width="150dp"
        android:layout_height="80dp"
        android:background="@android:color/holo_green_dark"
        android:layout_gravity="bottom|center_horizontal"/>

</FrameLayout>

This is how it looks like:


问:
how do vertically align login form between banner and footer
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

```<code>.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}
</code>```

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="root">
    <div class="main-content">
      <div class="app-layout__body">
        <div class="app-layout__container">
          <div class="banner__container">
            <div class="banner__top">
              <div>
                <div>
                  <h2>Banner</h2></div>
              </div>
            </div>
          </div>
          <div class="login-layout__container">
            <div class="login-layout__positioner">
              <div class="form__group">
                <div>
                  <form>
                    <div class="login__container">
                      <div class="login__wrapper">
                        <div>
                          <div>
                            <div class="login__form__elements">
                              <div>
                                <div>
                                  <h2 class="">Sign In</h2></div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="email" id="email-label" class="label__default label__strong label__double-margin">Email</label>
                                    <div>
                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">
                                    </div>
                                    <div id="email-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="password" id="password-label">Password</label>
                                    <div>
                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">
                                    </div>
                                    <div id="password-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>Forgotten your password?</div>
                                <div>
                                  <button type="submit">LOGIN</button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
        <footer>
          <div>
            <div>
              <div>
                <ul>
                  <li>About</li>
                  <li>Accessibility</li>
                  <li>Cookies</li>
                  <li>Privacy</li>
                </ul>
              </div>
            </div>
          </div>
        </footer>
      </div>
    </div>
  </div>
</body></code>```

答:
Both Ron and Jeh's answer are correct. Though I'm wondering why do you have so many container wrappers then if you can just use certain wrappers to display your entire login form, banner and footer.

Here's my template for my custom login forms.

You will noticed that I use calc on height to differentiate the height of banner and footer and then less it to the height of your .section-login container, in which it will automatically adjusted the height no matter what the browser height does. And I declared min-height just to avoid overlaying above to each container wrapper.

Hope this helps.

.login {
  background: pink;
  margin: 0;
  padding: 0;
}

.body-wrapper {
  background: white;
  width: 100%;
  height: 100vh;
}

.hero-wrapper,
.globalfooter {
  background: #CCC;
  text-align: center;
}

.hero-wrapper {
  line-height: 200px; /* just for the text v-alignment only */
  height: 200px;
}

.globalfooter {
  line-height: 100px; /* just for the text v-alignment only */
  height: 100px;
}

.section-login {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #EEE;
  min-height: calc(100% - (200px + 100px));
  padding: 30px;
  box-sizing: border-box;
}

.help-text-wrapper {
  font: 300 12px sans-serif;
  color: red;
  text-align: center;
  margin: 15px 0 0;
}

.help-text-wrapper.hidden {
  /* Remove comment to enable
  display: none; */
}

h1 {
  font: 600 24px sans-serif;
  text-align: center;
  text-transform: uppercase;
  margin: 0 0 15px;
}

form {
  background: #FFF;
  font: 300 12px sans-serif;
  text-transform: uppercase;
  width: 260px;
  padding: 30px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.50);
  box-sizing: border-box;
  border-radius: 3px;
}

form > fieldset {
  margin: 0 0 15px;
  padding: 0;
  border: 0;
}

form > fieldset label:first-child {
  display: block;
  margin-bottom: 15px;
}

form input {
  display: block;
  width: 100%;
  height: 30px;
  margin: 5px 0;
  padding: 6px;
  box-sizing: border-box;
}

form button {
  display: block;
  background: #888;
  color: #FFF;
  text-transform: uppercase;
  height: 30px;
  margin: auto;
  padding: 7px 15px;
  border: 0;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body class="login page">
  <div class="body-wrapper">
    <header class="hero-wrapper">
      Banner
    </header>

    <section class="section-login">
      <h1>Sign In</h1>
      <form action="" method="post">
        <fieldset>
          <label for="username">
            Username
            <input type="text" id="username" value="" placeholder="Username" autofocus>
          </label>
          <label for="password">
            Password
            <input type="password" id="password" value="" placeholder="Password">
          </label>
        </fieldset>
        <button type="submit">Login / Sign In</button>
      </form>
      <div class="help-text-wrapper hidden">
        Something around here after fallback.
      </div>
    </section>

    <footer class="globalfooter">
      Footer
    </footer>
  </div>
</body></code>```

Body:
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}

Banner

                  <form>

Sign In

                                    Email

                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">

                                    Password

                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">

Forgotten your password?

                                  <button type="submit">LOGIN</button>

                  </form>

About

Accessibility

Cookies

Privacy

Body:
Both Ron and Jeh's answer are correct. Though I'm wondering why do you have so many container wrappers then if you can just use certain wrappers to display your entire login form, banner and footer.

Here's my template for my custom login forms.

You will noticed that I use calc on height to differentiate the height of banner and footer and then less it to the height of your .section-login container, in which it will automatically adjusted the height no matter what the browser height does. And I declared min-height just to avoid overlaying above to each container wrapper.

Hope this helps.

.login {
  background: pink;
  margin: 0;
  padding: 0;
}

.body-wrapper {
  background: white;
  width: 100%;
  height: 100vh;
}

.hero-wrapper,
.globalfooter {
  background: #CCC;
  text-align: center;
}

.hero-wrapper {
  line-height: 200px; /* just for the text v-alignment only */
  height: 200px;
}

.globalfooter {
  line-height: 100px; /* just for the text v-alignment only */
  height: 100px;
}

.section-login {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #EEE;
  min-height: calc(100% - (200px + 100px));
  padding: 30px;
  box-sizing: border-box;
}

.help-text-wrapper {
  font: 300 12px sans-serif;
  color: red;
  text-align: center;
  margin: 15px 0 0;
}

.help-text-wrapper.hidden {
  /* Remove comment to enable
  display: none; */
}

h1 {
  font: 600 24px sans-serif;
  text-align: center;
  text-transform: uppercase;
  margin: 0 0 15px;
}

form {
  background: #FFF;
  font: 300 12px sans-serif;
  text-transform: uppercase;
  width: 260px;
  padding: 30px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.50);
  box-sizing: border-box;
  border-radius: 3px;
}

form > fieldset {
  margin: 0 0 15px;
  padding: 0;
  border: 0;
}

form > fieldset label:first-child {
  display: block;
  margin-bottom: 15px;
}

form input {
  display: block;
  width: 100%;
  height: 30px;
  margin: 5px 0;
  padding: 6px;
  box-sizing: border-box;
}

form button {
  display: block;
  background: #888;
  color: #FFF;
  text-transform: uppercase;
  height: 30px;
  margin: auto;
  padding: 7px 15px;
  border: 0;
  cursor: pointer;
}

<body class="login page">
  <div class="body-wrapper">
    <header class="hero-wrapper">
      Banner
    </header>

    <section class="section-login">
      <h1>Sign In</h1>
      <form action="" method="post">
        <fieldset>
          <label for="username">
            Username
            <input type="text" id="username" value="" placeholder="Username" autofocus>
          </label>
          <label for="password">
            Password
            <input type="password" id="password" value="" placeholder="Password">
          </label>
        </fieldset>
        <button type="submit">Login / Sign In</button>
      </form>
      <div class="help-text-wrapper hidden">
        Something around here after fallback.
      </div>
    </section>

    <footer class="globalfooter">
      Footer
    </footer>
  </div>
</body>


问:
Null pointer with self injection EJB
I am using JEE7, I have a Stateless EJB that is using self injection to solve a problem with transactionality.
When I make the call to the method selfMethod and it is public, everything works. If it is private, the injected components are null.
I guess it is somehow related to the proxy model and the self injection, but do not really understand why.

```<code>@Stateless
public class AnEjb {

    @Inject
    @EJB
    private AnEjb self;

    @Inject
    private AClass anObject;

    public void normalMethod() {
        self.selfMethod();
    }

    public/private void selfMethod() {
        anObject.anyMethod();  // Null pointer exception if selfMethod is private, no problem if it is public
    }
}
</code>```

答:
The EJB APIs provide a mechanism for self invocation:

```<code>    @Stateless
    public class AnEjb {

        @Resource
        private SessionContext sessionContext;

        private AnEjb self;

        @PostConstruct
        void initialise() {
            self = sessionContext.getBusinessObject(AnEjb.class);
        }

        public void normalMethod() {
            self.selfMethod();
        }

        public void selfMethod() {
            anObject.anyMethod();
        }

    }
</code>```

Note that the SessionContext.getBusinessObject method returns the same "view" of the EJB that external clients will see, therefore only its public methods will be accessible.

Title: Null pointer with self injection EJB

Body:
I am using JEE7, I have a Stateless EJB that is using self injection to solve a problem with transactionality.
When I make the call to the method selfMethod and it is public, everything works. If it is private, the injected components are null.
I guess it is somehow related to the proxy model and the self injection, but do not really understand why.

@Stateless
public class AnEjb {

    @Inject
    @EJB
    private AnEjb self;

    @Inject
    private AClass anObject;

    public void normalMethod() {
        self.selfMethod();
    }

    public/private void selfMethod() {
        anObject.anyMethod();  // Null pointer exception if selfMethod is private, no problem if it is public
    }
}

Body:
The EJB APIs provide a mechanism for self invocation:

    @Stateless
    public class AnEjb {

        @Resource
        private SessionContext sessionContext;

        private AnEjb self;

        @PostConstruct
        void initialise() {
            self = sessionContext.getBusinessObject(AnEjb.class);
        }

        public void normalMethod() {
            self.selfMethod();
        }

        public void selfMethod() {
            anObject.anyMethod();
        }

    }

Note that the SessionContext.getBusinessObject method returns the same "view" of the EJB that external clients will see, therefore only its public methods will be accessible.


问:
How to use external ".js" files
I have the following two javascript functions:

1

```<code>showCountry()
</code>```

2

```<code>showUser()
</code>```

I would like to put them in external ".js" files

1

```<code><a href="javascript:showCountry('countryCode')">countryCode</a>
</code>```

2

```<code><form>
 <select name="users" onChange="showUser(this.value)">
 <option value="1">Tom</option>
 <option value="2">Bob</option>
 <option value="3">Joe</option>
 </select>
</form>
</code>```

What is the correct syntax to call these functions?

答: I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the  tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the  tag and bingo every part of the script started to respond fine again.

Title: How to use external ".js" files

Body:
I have the following two javascript functions:

1

showCountry()

2

showUser()

I would like to put them in external ".js" files

1

countryCode

2

<form>
 <select name="users" onChange="showUser(this.value)">
 <option value="1">Tom</option>
 <option value="2">Bob</option>
 <option value="3">Joe</option>
 </select>
</form>

What is the correct syntax to call these functions?

Body: I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.


问:
Design Approach With Data Containing Several Columns

I am designing an application which will process statistics data and produce various visual and data outputs. The current data has around 1500 records, but around 3000 columns! All the columns are important and will be required by the system.

The database of choice is SQL Server. The issue is that SQL server limits each table to 1024 columns. I could normalize the data to 5 tables of 600 columns each. The issue with this is that I have not found a way to import more than 250 columns into SQL  server. Does anyone have any suggestions as to a better design? Or a method to actually import all these columns? I do not expect detrimental performance issues as a lot of the data in the columns will be NULL.

答:
SQL server limits each table to 1024 columns

No it doesn't.  The limit is 30,000, but you have to make it a "wide table"

Wide Tables

Wide tables use sparse columns to increase the total of
  columns that a table can have to 30,000. Sparse columns are ordinary
  columns that have an optimized storage for null values. Sparse columns
  reduce the space requirements for null values at the cost of more
  overhead to retrieve nonnull values. A wide table has defined a column
  set, which is an untyped XML representation that combines all the
  sparse columns of a table into a structured output. The number of
  indexes and statistics is also increased to 1,000 and 30,000,
  respectively. The maximum size of a wide table row is 8,019 bytes.
  Therefore, most of the data in any particular row should be NULL. The
  maximum number of nonsparse columns plus computed columns in a wide
  table remains 1,024.

Or you could use XML or JSON to store many of the attributes in a semi-structured document if you prefer.