问:
Python Function returning string with quotes
I have a function and returning three values, The return value for my function is

```<code>(1, 3, "<class 'int'>")
</code>```

while I want to return

```<code>(1, 3, <class 'int'>)
</code>```

How do I remove the quotes from my return value.str(type(element)) is the value which is returning the 3rd value

```<code>def is_list_permutation(L1, L2):
    L1set = set(L1)
    L2set = set(L2)
    count = 0
    element = ''
    if L1 == [] and L2 == []:
        return(None,None,None)
    elif len(L1) == len(L2) and L1set == L2set:
       for a in L1:
          if L1.count(a) == L2.count(a):
              if L1.count(a) > count:
                  count = L1.count(a)
                  element = a
                  return(element,count,str(type(element)))
          else:
              return False
              break

    else:
       return False
</code>```

so if i give

```<code>L1 = [1, 'b', 1, 'c', 'c', 1]
L2 = ['c', 1, 'b', 1, 1, 'c']
</code>```

then the result is (1, 3, "<class 'int'>") while I want (1, 3, <class 'int'>)

答:
Your function is returning a tuple with three elements: element, count and the string representation of the type of element. At no point, this has any string representation which you’re seeing there. You just get back a tuple.

Now, when you print that tuple, then the print function will actually try to convert it into a string. For a tuple, this string representation is defined to be a set of parentheses (), and the repr() string representation of each tuple element inside.

For numbers, this will look fine since repr(5) happens to be the string '5'. But for strings, the repr will add quotes to make sure that the return string would be valid Python code:

```<code>>>> repr('foo')
"'foo'"
>>> print(repr('foo'))
'foo'
</code>```

Now, when you say, you want the result without those quotes, you have to think about what that actually means. You could easily format the result string yourself. For example like this:

```<code>return '({0}, {1}, {2})'.format(element, count, str(type(element)))
</code>```

This will return a string that would look like the way you want.

However, by doing that, you also lose the information you had when you returned a tuple. Now, you just return a string that has no information about the actual source values. So you cannot take the count value out without parsing the string again.

So, think about what you want to do: Do you actually just want something nice to print, or do you actually want to get those three values individually as a return value to be able to use them for something else afterwards?

You could always consider printing the text in the desired format later, if you already have the return values as a tuple…

Btw.: Note that when not calling str(type(element)) but just type(element), you would get back a type element (instead of a string). And the repr() of a type element happens to be exactly what you would want to have. So as a quick fix, you could always get rid of that str() call there.

Body:
I have a function and returning three values, The return value for my function is

(1, 3, "<class 'int'>")

while I want to return

(1, 3, <class 'int'>)

How do I remove the quotes from my return value.str(type(element)) is the value which is returning the 3rd value

def is_list_permutation(L1, L2):
    L1set = set(L1)
    L2set = set(L2)
    count = 0
    element = ''
    if L1 == [] and L2 == []:
        return(None,None,None)
    elif len(L1) == len(L2) and L1set == L2set:
       for a in L1:
          if L1.count(a) == L2.count(a):
              if L1.count(a) > count:
                  count = L1.count(a)
                  element = a
                  return(element,count,str(type(element)))
          else:
              return False
              break

    else:
       return False

so if i give

L1 = [1, 'b', 1, 'c', 'c', 1]
L2 = ['c', 1, 'b', 1, 1, 'c']

then the result is (1, 3, "<class 'int'>") while I want (1, 3, <class 'int'>)

Body:
Your function is returning a tuple with three elements: element, count and the string representation of the type of element. At no point, this has any string representation which you’re seeing there. You just get back a tuple.

Now, when you print that tuple, then the print function will actually try to convert it into a string. For a tuple, this string representation is defined to be a set of parentheses (), and the repr() string representation of each tuple element inside.

For numbers, this will look fine since repr(5) happens to be the string '5'. But for strings, the repr will add quotes to make sure that the return string would be valid Python code:

>>> repr('foo')
"'foo'"
>>> print(repr('foo'))
'foo'

Now, when you say, you want the result without those quotes, you have to think about what that actually means. You could easily format the result string yourself. For example like this:

return '({0}, {1}, {2})'.format(element, count, str(type(element)))

This will return a string that would look like the way you want.

However, by doing that, you also lose the information you had when you returned a tuple. Now, you just return a string that has no information about the actual source values. So you cannot take the count value out without parsing the string again.

So, think about what you want to do: Do you actually just want something nice to print, or do you actually want to get those three values individually as a return value to be able to use them for something else afterwards?

You could always consider printing the text in the desired format later, if you already have the return values as a tuple…

Btw.: Note that when not calling str(type(element)) but just type(element), you would get back a type element (instead of a string). And the repr() of a type element happens to be exactly what you would want to have. So as a quick fix, you could always get rid of that str() call there.


来源: stackexchange

问:
SELECT statement not working after INSERT INTO
So I've finished my first year programming so I know a bit about sql however I can't seem to find a solution/explanation to this problem.
I know you can execute statements after each other with ; but when I try to do it after an insert into [table] statement it doesn't work for me.
I've tried this so far:

```<code>INSERT INTO employees(employee_id, last_name, email, hire_date, job_id)
VALUES(208, 'King', 'king@hotmail.com', sysdate, 'AC_MGR'); SELECT * FROM employees;
</code>```

I always get an error saying the first semicolon is invalid.
Really would appreciate if someone could explain why it happens like this.
Also it only the SELECT statement that does this or is it every command after INSERT INTO

EDIT:

OP posted this image of the table definition as an answer. Just adding it here for everyone's sake.

EDIT2:
I did only use those values as an example, they weren't the actual values I used in my query but now I've updated them with the real values, still it makes no difference...

答:
I know you can execute statements after each other with ;

As you have discovered, no you cannot.

With Oracle, there are two langauges to keep seperate. SQL, like what you are doing, and PL/SQL used in packages, functions, anonymous PL/SQL blocks, triggers, etc.

In PL/SQL the semicolon is a statement terminator, and can be used in the middle of a line to place more than one statement on the line, much like normal languages.

In Oracle's SQL a semicolon is invalid. What is confusing is that the client tools, such as SQLPlus use a semicolon at the end of a line as a terminator for SQL statements, but that semicolon is stripped before the statement is sent to the database server. The client is responsible for seperating the SQL statements before they are parsed by the server. Many other tools follow the lead of SQL*Plus in using the semicolon.

So, SQL*PLus, seeing insert says to itself, "A SQL statement" and then reads until a line ends with a semicolon. Then it sends what it read minus the trailing semicolon to the database server to execute a single SQL statement. Oracle's SQL parser doesn't know what to make of the internal semicolon and chokes.

Note, it is possible in SQLPlus to change the SQL statement terminator with set sqlterminator ..., but I have rarely seen that done in practice.

ContentLicense: CC BY-SA 3.0

Body:
So I've finished my first year programming so I know a bit about sql however I can't seem to find a solution/explanation to this problem.
I know you can execute statements after each other with ; but when I try to do it after an insert into [table] statement it doesn't work for me.
I've tried this so far:

INSERT INTO employees(employee_id, last_name, email, hire_date, job_id)
VALUES(208, 'King', 'king@hotmail.com', sysdate, 'AC_MGR'); SELECT * FROM employees;

I always get an error saying the first semicolon is invalid.
Really would appreciate if someone could explain why it happens like this.
Also it only the SELECT statement that does this or is it every command after INSERT INTO

EDIT:

OP posted this image of the table definition as an answer. Just adding it here for everyone's sake.

EDIT2:
I did only use those values as an example, they weren't the actual values I used in my query but now I've updated them with the real values, still it makes no difference...


问:
need to convert posted sql query to LINQ
How do i make that query in linq please advise </p>

```<code>select *
from tblPermission
where RoleId in (select roleid from tbluserrole where userid = @userID)
</code>```

答:
When converting from SQL to LINQ, convert in the order of the LINQ phrases. If your SQL has table aliases, use them as the range variables. If a query contains a sub-query, translate it first in the same way. Translate IN into Contains.

```<code>var roles = from ur in tbluserrole where ur.userid == parmUserId select ur.RoleId;
var ans = from p in tblPermission
          where roles.Contains(p.RoleId)
          select p;
</code>```

Body:
How do i make that query in linq please advise

select *
from tblPermission
where RoleId in (select roleid from tbluserrole where userid = @userID)

Body:
When converting from SQL to LINQ, convert in the order of the LINQ phrases. If your SQL has table aliases, use them as the range variables. If a query contains a sub-query, translate it first in the same way. Translate IN into Contains.

var roles = from ur in tbluserrole where ur.userid == parmUserId select ur.RoleId;
var ans = from p in tblPermission
          where roles.Contains(p.RoleId)
          select p;


问:
Return value in atoi function
Currently I have an Atoi function in Java which returns an int value on passing a string input. The initial return value is set to 0. However, the value returned will be 0 if invalid characters or all characters are passed in input string and if the actual string passed is just "0". How can I use return values for these two cases? Or is this okay and I should leave it upto the client to handle this ?</p>

答:
One of the option is to throw an exception which the client would need to handle and then act appropriately, doing so you are delegating the error handling to the client so that as the API implementer you do not have to worry about whether this situation is error, exception or normal for the clients. They will decide and handle the exception (suppress the noise, alert client, ask client to re-enter etc).

Another option would be to return -1 if there is any error in parsing the string, in this case also client will take the decision what to do next.

Although the advantage with throwing an exception is you can always pass details about what the error was in Exception message which is not possible if you pass -1.

```<code>private static int getDecValue(char hex) {
    int dec = 0;
    switch (hex) {
    case '0':
        dec = 0;
        break;
    case '1':
        dec = 1;
        break;
    case '2':
        dec = 2;
        break;
    case '3':
        dec = 3;
        break;
    case '4':
        dec = 4;
        break;
    case '5':
        dec = 5;
        break;
    case '6':
        dec = 6;
        break;
    case '7':
        dec = 7;
        break;
    case '8':
        dec = 8;
        break;
    case '9':
        dec = 9;
        break;
    default:
        // do nothing
    }
    return dec;
}

public static int atoi(String ascii) throws Exception {
    int integer = 0;
    for (int index = 0; index < ascii.length(); index++) {
        if (ascii.charAt(index) >= '0' && ascii.charAt(index) <= '9') {
            integer = (integer * 10) + getDecValue(ascii.charAt(index));
        } else {
            throw new Exception("Is not an Integer : " + ascii.charAt(index));
        }
    }
    return integer;
}
</code>```

Title: Return value in atoi function

Body:
One of the option is to throw an exception which the client would need to handle and then act appropriately, doing so you are delegating the error handling to the client so that as the API implementer you do not have to worry about whether this situation is error, exception or normal for the clients. They will decide and handle the exception (suppress the noise, alert client, ask client to re-enter etc).

Another option would be to return -1 if there is any error in parsing the string, in this case also client will take the decision what to do next.

Although the advantage with throwing an exception is you can always pass details about what the error was in Exception message which is not possible if you pass -1.

private static int getDecValue(char hex) {
    int dec = 0;
    switch (hex) {
    case '0':
        dec = 0;
        break;
    case '1':
        dec = 1;
        break;
    case '2':
        dec = 2;
        break;
    case '3':
        dec = 3;
        break;
    case '4':
        dec = 4;
        break;
    case '5':
        dec = 5;
        break;
    case '6':
        dec = 6;
        break;
    case '7':
        dec = 7;
        break;
    case '8':
        dec = 8;
        break;
    case '9':
        dec = 9;
        break;
    default:
        // do nothing
    }
    return dec;
}

public static int atoi(String ascii) throws Exception {
    int integer = 0;
    for (int index = 0; index < ascii.length(); index++) {
        if (ascii.charAt(index) >= '0' && ascii.charAt(index) <= '9') {
            integer = (integer * 10) + getDecValue(ascii.charAt(index));
        } else {
            throw new Exception("Is not an Integer : " + ascii.charAt(index));
        }
    }
    return integer;
}


问:
JDBC ERROR : AbstractMethodError: com.microsoft.sqlserver.jdbc.SQLServerConnection.createArrayOf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/sql/Array
Hi am just selecting Data from SQL SERVER and stroing it in Result set.
I am getting below error.

```<code>**JDBC ERROR : AbstractMethodError: com.microsoft.sqlserver.jdbc.SQLServerConnection.createArrayOf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/sql/Array**
</code>```

The problem with this below line

```<code>    java.sql.Array sqlarray = sqlcon.createArrayOf(null, rowValues.toArray());
</code>```

I am not sure why this issue occurs and what exact parameter should I pass createArrayOf().. Please help for this below issue

Here is full my code

```<code>    public void getDatafromsql(ArrayList rowValues) throws SQLException,ClassNotFoundException
    {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    System.out.println("SQL Server Start Connecting ");
    Connection sqlcon = DriverManager
            .getConnection(s_url, s_username, s_password);
    System.out.println("Sql server Connection valid");
    System.out.println(rowValues);
    PreparedStatement s1 = sqlcon.prepareStatement("SELECT TOP 6 myid,document,name FROM table1 where DATEMODIFIED between ? and ? and myid in (?)");
    s1.setTimestamp( 1,V_DOC_LAST_REFRESH_TIMESTAMP);
    s1.setTimestamp( 2,V_DOC_CURRENT_REFRESH_TIMESTAMP);
    //Below line throwing error
    java.sql.Array sqlarray = sqlcon.createArrayOf(null, rowValues.toArray());
    s1.setArray(3, sqlarray);
    sql_rs = s1.executeQuery();
    setdataOracle(sql_rs);
    System.out.println("SQL Server Storage Completed ");
    sqlcon.close();
    }
</code>```

答:
The SQL Server JDBC driver doesn't support that method:

```<code>public java.sql.Array createArrayOf(String typeName,

        Object[] elements) throws SQLException {

    // Not implemented

    throw new SQLFeatureNotSupportedException(SQLServerException.getErrString("R_notSupported"));

}
</code>```

https://github.com/Microsoft/mssql-jdbc/blob/master/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java

Instead use Table Valued Parameters, or pass the data as XML, JSON, or CSV and parse it on the server.

Body:
Hi am just selecting Data from SQL SERVER and stroing it in Result set.
I am getting below error.

**JDBC ERROR : AbstractMethodError: com.microsoft.sqlserver.jdbc.SQLServerConnection.createArrayOf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/sql/Array**

The problem with this below line

    java.sql.Array sqlarray = sqlcon.createArrayOf(null, rowValues.toArray());

I am not sure why this issue occurs and what exact parameter should I pass createArrayOf().. Please help for this below issue

Here is full my code

    public void getDatafromsql(ArrayList rowValues) throws SQLException,ClassNotFoundException
    {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    System.out.println("SQL Server Start Connecting ");
    Connection sqlcon = DriverManager
            .getConnection(s_url, s_username, s_password);
    System.out.println("Sql server Connection valid");
    System.out.println(rowValues);
    PreparedStatement s1 = sqlcon.prepareStatement("SELECT TOP 6 myid,document,name FROM table1 where DATEMODIFIED between ? and ? and myid in (?)");
    s1.setTimestamp( 1,V_DOC_LAST_REFRESH_TIMESTAMP);
    s1.setTimestamp( 2,V_DOC_CURRENT_REFRESH_TIMESTAMP);
    //Below line throwing error
    java.sql.Array sqlarray = sqlcon.createArrayOf(null, rowValues.toArray());
    s1.setArray(3, sqlarray);
    sql_rs = s1.executeQuery();
    setdataOracle(sql_rs);
    System.out.println("SQL Server Storage Completed ");
    sqlcon.close();
    }

Body:
The SQL Server JDBC driver doesn't support that method:

public java.sql.Array createArrayOf(String typeName,

        Object[] elements) throws SQLException {

    // Not implemented

    throw new SQLFeatureNotSupportedException(SQLServerException.getErrString("R_notSupported"));

}

https://github.com/Microsoft/mssql-jdbc/blob/master/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java

Instead use Table Valued Parameters, or pass the data as XML, JSON, or CSV and parse it on the server.


问:
Join two mysql queries and include column values with zero count as well
I have two MySQL tables

```<code>desc table_name1;
Field, Type, Null, Key, Default, Extra
'id', 'int(11)', 'NO', 'PRI', '0', ''
'name', 'varchar(100)', 'YES', '', NULL, ''
'active', 'int(1)', 'YES', '', NULL, ''

desc table_name2;
Field, Type, Null, Key, Default, Extra
'date', 'date', 'NO', 'PRI', '0000-00-00', ''
'col_name1', 'varchar(40)', 'YES', '', '0', ''
'host', 'varchar(100)', 'NO', '', '', ''
'ip', 'varchar(100)', 'NO', 'PRI', '', ''
'snapdate', 'date', 'YES', '', NULL, ''
'col_name2', 'int(11)', 'NO', 'PRI', '0', ''
</code>```

And two sql queries:
sql1:

```<code>select id, name from .table_name1 where active = 1 and id not in (2954,2914) order by name;
</code>```

sql2:

```<code>select count(*) from .table_name2 where date= '2017-07-03' and col_name2 = $code; #$code = values in id column from sql1
</code>```

So sql1 returns 9 rows then sql2 is run 9 times (for each value in column id from sql1)

What I want to do:
I wanted to join these two queries so that I can run a single query and still get the same result. And I want the result in for of a table with two columns:

```<code>name   count
value1 89
value2 184
value3 528
</code>```

What I have tried so far:
So I used inner join and came up with following sql:
sql3:

```<code>    select d.name, count(m.col_name2) as count
      from .table_name1 as d
inner join .table_name2 as m
        on d.id = m.col_name2
     where d.active = 1
       and d.id not in (2954,2914)
       and m.date = '2017-07-03'
  group by d.name
  order by d.name;
</code>```

Problem I am facing:

Though above sql3 does what I want but it skips those values in id column (from sql1) which would return zero as count. (when used in sql2).

For example if sql1 is returing 9 rows then the sql3 is returing only 8 rows as it is skipping that one value which will have count as zero.

I have tried using CASE (and removed "and m.date = '2017-07-03'"):

```<code>select d.name, case count(m.col_name2) when m.date = '2017-07-03' then 1 else 0 end as count
</code>```

Also, I have tried using if (and removed "and m.date = '2017-07-03'"):

```<code>select d.name, if (m.date = '2017-07-03', count(m.col_name2), 0) as count
</code>```

But both above attempts give 8 rows (same as sql3) but the count is returned zero.

My question:
What am I missing while using CASE or if? How can I get this missing value in the result as well with a count of zero for it using modified sql3 or any other single query?

答:
You are missing zero values since they dont have a match in the inner join. Try left join instead:

```<code>  select d.name, count(m.col_name2) as count
  from .table_name1 as d
  left join .table_name2 as m
  on d.id = m.col_name2
  where d.active = 1
   and d.id not in (2954,2914)
   and (m.date = '2017-07-03' or m.date is Null)
  group by d.name
  order by d.name;
</code>```

Note that m.date condition is combined with Null, in case there are no values per this name.

Body:
I have two MySQL tables

desc table_name1;
Field, Type, Null, Key, Default, Extra
'id', 'int(11)', 'NO', 'PRI', '0', ''
'name', 'varchar(100)', 'YES', '', NULL, ''
'active', 'int(1)', 'YES', '', NULL, ''

desc table_name2;
Field, Type, Null, Key, Default, Extra
'date', 'date', 'NO', 'PRI', '0000-00-00', ''
'col_name1', 'varchar(40)', 'YES', '', '0', ''
'host', 'varchar(100)', 'NO', '', '', ''
'ip', 'varchar(100)', 'NO', 'PRI', '', ''
'snapdate', 'date', 'YES', '', NULL, ''
'col_name2', 'int(11)', 'NO', 'PRI', '0', ''

And two sql queries:
sql1:

select id, name from .table_name1 where active = 1 and id not in (2954,2914) order by name;

sql2:

select count(*) from .table_name2 where date= '2017-07-03' and col_name2 = $code; #$code = values in id column from sql1

So sql1 returns 9 rows then sql2 is run 9 times (for each value in column id from sql1)

What I want to do:
I wanted to join these two queries so that I can run a single query and still get the same result. And I want the result in for of a table with two columns:

name   count
value1 89
value2 184
value3 528

What I have tried so far:
So I used inner join and came up with following sql:
sql3:

    select d.name, count(m.col_name2) as count
      from .table_name1 as d
inner join .table_name2 as m
        on d.id = m.col_name2
     where d.active = 1
       and d.id not in (2954,2914)
       and m.date = '2017-07-03'
  group by d.name
  order by d.name;

Problem I am facing:

Though above sql3 does what I want but it skips those values in id column (from sql1) which would return zero as count. (when used in sql2).

For example if sql1 is returing 9 rows then the sql3 is returing only 8 rows as it is skipping that one value which will have count as zero.

I have tried using CASE (and removed "and m.date = '2017-07-03'"):

select d.name, case count(m.col_name2) when m.date = '2017-07-03' then 1 else 0 end as count

Also, I have tried using if (and removed "and m.date = '2017-07-03'"):

select d.name, if (m.date = '2017-07-03', count(m.col_name2), 0) as count

But both above attempts give 8 rows (same as sql3) but the count is returned zero.

My question:
What am I missing while using CASE or if? How can I get this missing value in the result as well with a count of zero for it using modified sql3 or any other single query?

Body:
You are missing zero values since they dont have a match in the inner join. Try left join instead:

  select d.name, count(m.col_name2) as count
  from .table_name1 as d
  left join .table_name2 as m
  on d.id = m.col_name2
  where d.active = 1
   and d.id not in (2954,2914)
   and (m.date = '2017-07-03' or m.date is Null)
  group by d.name
  order by d.name;

Note that m.date condition is combined with Null, in case there are no values per this name.


问:
awk to extract lines in file that contain matching pattern and variable digit
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa
</code>```

desired output tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa
</code>```

awk

```<code> awk '$2 ~ /^exon [0-9][0-9] sequence$/' file
</code>```

答:
using awk

```<code>awk   '/exon\s+[0-9]+\s+sequence/  {print $0}'  file
</code>```

or grep

```<code> grep -P 'exon\s+[0-9]+\s+sequence' file
</code>```

Body:
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa

desired output tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa

awk

 awk '$2 ~ /^exon [0-9][0-9] sequence$/' file

Body:
using awk

awk   '/exon\s+[0-9]+\s+sequence/  {print $0}'  file

or grep

 grep -P 'exon\s+[0-9]+\s+sequence' file


问:
Lineheight in HTMLView
Somehow this is not working for Android but works on iOS:

```<code><HTMLView value={itemDetail.description} stylesheet={htmlstyle}/>

const htmlstyle = StyleSheet.create({
  p:{
    lineHeight:28,
    fontSize:16,
    color:'#444343'
  }
});
</code>```

You can find the component here:
https://github.com/jsdf/react-native-htmlview

The description is something like this:

```<code><p>Hello, world!</p>
</code>```

On Android the color and fontSize change, but not the lineHeight. On iOS emulator everything works.

If there's an alternative to set the lineheight, please let me know.

答: This is working on Android in the current version (0.10).</p>

Title: Lineheight in HTMLView

Body:
Somehow this is not working for Android but works on iOS:

<HTMLView value={itemDetail.description} stylesheet={htmlstyle}/>

const htmlstyle = StyleSheet.create({
  p:{
    lineHeight:28,
    fontSize:16,
    color:'#444343'
  }
});

You can find the component here:
https://github.com/jsdf/react-native-htmlview

The description is something like this:

Hello, world!

On Android the color and fontSize change, but not the lineHeight. On iOS emulator everything works.

If there's an alternative to set the lineheight, please let me know.


问:
retrieving data with mongodb java driver 3.4 using find()-method with projection
I am using mongodb java driver 3.4.

In the mongodb database documents are saved according to the following structure:

```<code>{
    "_id" : ObjectId("595a9fc4fe3f36402b7edf0e"),
    "id" : "123",
    "priceInfo" : [
        {object1: value1}, {object2: value2}, {object3: value3}
    ]
}
</code>```

In order to retrieve the "priceInfo"-Array of a Document with a specific id, I wrote the following code:

```<code>collection.find(eq("id", id)).first().projection(fields(include("priceInfo"), excludeId()));
</code>```

I wrote this code according too the documentation, which you can find here:

http://mongodb.github.io/mongo-java-driver/3.4/javadoc/?com/mongodb/client/model/Projections.html

The problem is that my IDE won't accept this code.

It's giving me the following error indication:

I have no clue why this code doesn't work. At first the IDE suggested including several classes - which I did. But after that I still got an error indication, namely the one you see above.

What's wrong with the code? How can I retrieve the priceInfo array of a Document with ID id?

********************************UPDATE**********************************

As per request, here's the whole class:

```<code>package DatabaseAccess;

import Models.GasStation;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.model.Updates;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import org.bson.Document;

public class databaseAccess {

    private final String DB_HOST = "localhost";
    private final int DB_PORT = 27017;
    private final String DB_NAME = "db1";
    private final String DB_COLLECTION = "prices";
    private final MongoClient mongoClient;
    private final MongoDatabase database;
    private final MongoCollection<Document> collection;

    public databaseAccess(){
        mongoClient = new MongoClient(DB_HOST, DB_PORT);
        database = mongoClient.getDatabase(DB_NAME);
        collection = database.getCollection(DB_COLLECTION);
    }

    public String readFromDB(String id){
        collection.find(eq("id", id)).first().projection(fields(include("priceInfo"), excludeId()));
        return null;
    }

}
</code>```

答:
You're operating on chain of calls in your method.
Let's analyze each element in chain:

MongoCollection:

FindIterable< TDocument> find() - Finds all documents in  the collection.

Return type is FindIterable<TDocument> and you calling the next method in chain on it:

FindIterable< TDocument>

Methods inherited from interface com.mongodb.async.client.MongoIterable:

batchCursor, first, forEach, into, map

Okay, we are going to MongoIterable:

MongoIterable< TResult>:

void  first(SingleResultCallback callback) - Helper to return the first item in the iterator or null.

That means first(...) is returned nothing. You're calling projection(...) from nothing, of course this is not applicable, so the compiler marks this as an error.

For calling projection(Bson projection) you shoud have FindIterable<T> instance. MongoCollection.find() can provide you with this instance:

```<code>collection.find(eq("id", id)).projection(fields(include("priceInfo"), excludeId()));
</code>```

Body:
I am using mongodb java driver 3.4.

In the mongodb database documents are saved according to the following structure:

{
    "_id" : ObjectId("595a9fc4fe3f36402b7edf0e"),
    "id" : "123",
    "priceInfo" : [
        {object1: value1}, {object2: value2}, {object3: value3}
    ]
}

In order to retrieve the "priceInfo"-Array of a Document with a specific id, I wrote the following code:

collection.find(eq("id", id)).first().projection(fields(include("priceInfo"), excludeId()));

I wrote this code according too the documentation, which you can find here:

http://mongodb.github.io/mongo-java-driver/3.4/javadoc/?com/mongodb/client/model/Projections.html

The problem is that my IDE won't accept this code.

It's giving me the following error indication:

I have no clue why this code doesn't work. At first the IDE suggested including several classes - which I did. But after that I still got an error indication, namely the one you see above.

What's wrong with the code? How can I retrieve the priceInfo array of a Document with ID id?

********************************UPDATE**********************************

As per request, here's the whole class:

package DatabaseAccess;

import Models.GasStation;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.model.Updates;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import org.bson.Document;

public class databaseAccess {

    private final String DB_HOST = "localhost";
    private final int DB_PORT = 27017;
    private final String DB_NAME = "db1";
    private final String DB_COLLECTION = "prices";
    private final MongoClient mongoClient;
    private final MongoDatabase database;
    private final MongoCollection<Document> collection;

    public databaseAccess(){
        mongoClient = new MongoClient(DB_HOST, DB_PORT);
        database = mongoClient.getDatabase(DB_NAME);
        collection = database.getCollection(DB_COLLECTION);
    }

    public String readFromDB(String id){
        collection.find(eq("id", id)).first().projection(fields(include("priceInfo"), excludeId()));
        return null;
    }

}

Body:
You're operating on chain of calls in your method.
Let's analyze each element in chain:

MongoCollection:

FindIterable< TDocument> find() - Finds all documents in  the collection.

Return type is FindIterable<TDocument> and you calling the next method in chain on it:

FindIterable< TDocument>

Methods inherited from interface com.mongodb.async.client.MongoIterable:

batchCursor, first, forEach, into, map

Okay, we are going to MongoIterable:

MongoIterable< TResult>:

void  first(SingleResultCallback callback) - Helper to return the first item in the iterator or null.

That means first(...) is returned nothing. You're calling projection(...) from nothing, of course this is not applicable, so the compiler marks this as an error.

For calling projection(Bson projection) you shoud have FindIterable<T> instance. MongoCollection.find() can provide you with this instance:

collection.find(eq("id", id)).projection(fields(include("priceInfo"), excludeId()));


问:
Route not defined error in laravel , even though route is defined
I have the followning method in my controller:

```<code>public function showQualityResult($qualityData) {
        return $qualityData;
}
</code>```

When clicked on a link , i want that method to be invoked , so i have the following in my view file:

```<code><a href="{{ route('showQualityResult' , Session::get('quality-data')) }}">Submited Quality Check</a>
</code>```

Also, I have the following route setup:

```<code>Route::get('/showQualityResult', 'QualityCheckController@showQualityResult');
</code>```

But having the below line of code:

```<code><a href="{{ route('showQualityResult' , Session::get('quality-data')) }}">Submited Quality Check</a>
</code>```

Does't really work , i get the following error in the frontEnd:

Now how can i solve this problem , and why am i getting this error of Route not defined , even though i have the route defined ??

答:
In my case I had simply made a stupid mistake.

Further down in my code I had another named route (properly named with a unique name) but an identical path to the one Laravel told me it couldn't find.

A quick update to the path fixed it.

Body:
I have the followning method in my controller:

public function showQualityResult($qualityData) {
        return $qualityData;
}

When clicked on a link , i want that method to be invoked , so i have the following in my view file:

Submited Quality Check

Also, I have the following route setup:

Route::get('/showQualityResult', 'QualityCheckController@showQualityResult');

But having the below line of code:

Submited Quality Check

Does't really work , i get the following error in the frontEnd:

Now how can i solve this problem , and why am i getting this error of Route not defined , even though i have the route defined ??


问:
CSS @media query not working correctly
There is a need to scale media requests with one image (logo) for each mobile device: iPhone 5, 6, 6+, iPad's, as well as on large screens.
Accordingly, I almost need to specify a style in the form of width, etc. For portrait and landscape orientation.
Of all works only for the iPhone 6, iPad's and large screens (=> 1600px)
For small screens (320x480) and iPhone 6+ does not work (check in Chrome)

For iPhone 6+ media query applied as for iPhone 5...

Tell me please, what's wrong in my code?
I will be extremely grateful!

Here's the CSS:

```<code>@media only screen and (max-width: 320px) and (max-width : 480px) {
.logo-mobile img {
    width: 150px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 321px) and (max-width : 480px) {
.logo-mobile img {
    width: 150px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 320px) and (max-height: 568px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 144px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 320px) and (max-height: 568px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 144px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 375px) and (max-height: 667px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 144px;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 375px) and (max-height: 667px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 100%;
    transform: translateY(-11px);
}
}

@media only screen and (min-width: 414px) and (max-height: 736px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
    width: 144px;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 414px) and (max-height: 736px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
    width: 144px;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 768px) and (max-width: 1024px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
    width: 100%;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 768px) and (max-width: 1024px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
     width: 100%;
    transform: translateY(5px);
}

@media only screen and (min-width: 1600px) {
.logo-mobile img {`enter code here`
    width: 100%;
}
}
</code>```

答:
Well you could start by ensuring you added the meta tag

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0" />
</code>```

You could also consider adding appropriate prefixes to your CSS3 selectors like so...

```<code>-webkit-transform: translateY(8px)//Chrome
-o-transform: translateY(8px) //Opera
</code>```

and so on. You could check w3schools for a complete list of css3 prefixes. I hope this helps...

Title: CSS @media query not working correctly

Body:
There is a need to scale media requests with one image (logo) for each mobile device: iPhone 5, 6, 6+, iPad's, as well as on large screens.
Accordingly, I almost need to specify a style in the form of width, etc. For portrait and landscape orientation.
Of all works only for the iPhone 6, iPad's and large screens (=> 1600px)
For small screens (320x480) and iPhone 6+ does not work (check in Chrome)

For iPhone 6+ media query applied as for iPhone 5...

Tell me please, what's wrong in my code?
I will be extremely grateful!

Here's the CSS:

@media only screen and (max-width: 320px) and (max-width : 480px) {
.logo-mobile img {
    width: 150px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 321px) and (max-width : 480px) {
.logo-mobile img {
    width: 150px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 320px) and (max-height: 568px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 144px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 320px) and (max-height: 568px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 144px;
    transform: translateY(-7px);
}
}

@media only screen and (min-width: 375px) and (max-height: 667px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 144px;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 375px) and (max-height: 667px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2){
.logo-mobile img {
    width: 100%;
    transform: translateY(-11px);
}
}

@media only screen and (min-width: 414px) and (max-height: 736px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
    width: 144px;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 414px) and (max-height: 736px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
    width: 144px;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 768px) and (max-width: 1024px) and
(orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
    width: 100%;
    transform: translateY(-8px);
}
}

@media only screen and (min-width: 768px) and (max-width: 1024px) and
(orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
.logo-mobile img {
     width: 100%;
    transform: translateY(5px);
}

@media only screen and (min-width: 1600px) {
.logo-mobile img {`enter code here`
    width: 100%;
}
}

Body:
Well you could start by ensuring you added the meta tag

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

You could also consider adding appropriate prefixes to your CSS3 selectors like so...

-webkit-transform: translateY(8px)//Chrome
-o-transform: translateY(8px) //Opera

and so on. You could check w3schools for a complete list of css3 prefixes. I hope this helps...


问:
Nuget: how can I tell which project is referencing a package?
My project on UAT is throwing an exception concerning a NuGet package that exists on my dev environment (that is, I found under my /packages folder), but does not seems to be part of my solution (that is, I launch NuGet Package Manager but I cannot find it under the list of Installed packages).

The code runs fine on dev, but crashes on UAT.

My question is: how do I figure out where this library is being used?

答:
Some NuGet packages have trouble uninstalling completely, so there may still be leftover references in your project files (.csproj, .vbproj,...).

First, check for <Reference Include=".."> elements containing a <HintPath> pointing to the missing folder. you should remove them.

Then check for <Project Import="..." /> elements pointing to the missing folder. There may also be some conditions (for <Error> elements) checking if paths exists. Remove all of these.

Then delete your packages folder containing all the NuGet packages and re-open the solution in VS and restore the packages.

This can result in two outcomes:

It works and you successfully removed all "dangling" references to NuGet packages that are no longer in use.

You cannot compile because auf missing NuGet packages. In this case, install the NuGet packages again via the package management UI.


问:
Best practices for consuming WebAPI backend from MVC WebApp
I'm creating a WebAPI based SaaS application. This WebAPI can be used alone without the need for a user interface, requires a basic authentication sent with every request made to the WebAPI and returns some objects when the methods are called and authenticated.

Now I'm facing a big problem: I'm creating a WebApp in MVC (but it could be any language) and I can't figure out how to call my WebAPI endpoint without the need to keep username and password in order to authenticate the WebAPI request every time I call a method.

What are the best practices in this particular case?
I can't seem to find any suitable solutions...

So far I have tried to create a custom cookie with the help of a custom implementation of the HttpContext.Response.Cookies.Add method, where I store in the userData of the Cookie the pair of username and password encrypted. In this way I can call the WebAPI methods specifying each time the BasicAuthenticationCredentials with the correct username and password, but this seems to me a very unmaintainable way to do the job in the long run.

I also wanted to try the OAuth2 way, but I can't find a well written guide on how to implement an authentication server based on a custom user table from SQL Server (and the first five pages of the Google result list didn't help me, they did actually make me even more confused about this topic, the whole OWIN and Katana thing...).

I can provide further information in case someone is willing to help me out.

Thanks in advance,
Stefano.

答:
Here's a good tutorial about how to implement your own OAuth2 server:

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

The main idea behind using OAuth is that you'll only need a username and password for your first request, and after that, you'll get an access token that will be used to get access to the API. This access token will have a lifetime, and once it has expired, the user will need to request a new access token (either by sending the user credentials again, or by using a refresh token that will be used as a credentials substitute).

The nice part behind this approach is that since the access tokens have a lifetime, even if one of those tokens gets compromised, you can just revoke it (or wait until it expires, for example, you can create tokens that will be renewed every 5 minutes or even less. It's up to you), the client will automatically ask for a new one, and that will be the end of the story. On the other hand, if you were always receiving the user credentials and those credentials got compromised, the user will need to change them and the risk will be there until the user finally changes his credentials (and here's a manual process where the user needs to be aware about this problem, while the OAuth approach is just refreshing those tokens all the time).

Also, remember to keep all the communication over HTTPS, since the tokens are sensitive information, and you don't want an eavesdropper getting the access token or even worse, the refresh token by just intercepting the communication. If he's able to do something like this, then even tokens refreshing every minute will be a useless approach against someone getting every token that you send.


问:
ag-grid - Tree data feature/ Group rows for Angular 2 like in javascript?
I am working on Angular 2 app using ag-grid. I am looking for Tree data feature just like shown in the link for javascript. Or any other solution in Angular 2 using ag-grid.

Question -

Please let me know if there is any way to group rows in ag grid - Angular 2 as seen in below sample -

答:
Within your colDefs, you need two properties to be set:

```<code>showRowGroup: true,
cellRenderer: 'group'
</code>```

Apply this to the column definition and you should see the expanding icon beside it.

Body:
Within your colDefs, you need two properties to be set:

showRowGroup: true,
cellRenderer: 'group'

Apply this to the column definition and you should see the expanding icon beside it.


问:
Solutions for testing entire features of an app
EDIT: to clarify - I am asking for advice on both unit testing and user interface testing.

Currently, I don't use TDD. While I am developing an application I am constantly testing what I am working on. Testing iteration could be anything from minor function changes to entire models. I try not to code too much before I test. I like instant feedback.

Of course, with experience I can see potential problems or bugs occurring as I'm coding.

BUT, after an application is complete I will usually go through the entire app on the frontend and ensure all functions are working as expected. This means literally everything. Every add/edit/delete, sort, filter, even broken links and such.

This can take a lot of time sometimes but it does ensure my work hardly ever contains bugs after deployment.

However, I'm looking for a more standard solution. What do experienced developers do? Assume for a moment I am a single developer and so do not have a testing department etc

Do you hire beta testers (no good if app is sensitive to public use)?

Is it viable to build a series of 'general' unit tests which can for example test ALL sorting, filter functions. One for testing ALL add/edit/delete functions.

Love to hear your feedback. Will be changing the way I develop based on suggestions.

答:
Usually what you code works is not that the problem, very nice if you also write tests for it. The problem is that you need to test the integration of your changes every time you make commit.
If you like instant feedback,as I do, probably you should have a look at Continuous Integration.
I've started using Hudson as CI server and I am not regretting it!</p>

ContentLicense: CC BY-SA 2.5


问:
Linking CSS and JS files for accordion list - not functioning as separate files
I am learning how to make an accordion list and have found the following code (HTML, CSS, and JS) from www.w3schools.com. If I run the code locally, as one .html file, it works as intended. However, if I separate it into three files, and link the CSS and JS files in my HTML file, the drop down list does not work. I am (very) new to web development and would appreciate any explanation I can get for this! Thanks in advance.

Original Code (all in one document):

```<code><!DOCTYPE html>
<html>
<head>
<style>
button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ddd;
}

button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
</style>
</head>
<body>

<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the     user clicks on the button, the "plus" sign is replaced with a "minus"     sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
  <p>TEXT 1</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>TEXT 2</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>TEXT 3</p>
</div>

<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
</script>

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

And the HTML file linking the CSS and JS as separate files:

```<code><!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="./mystyling.css">
    <title>Page TItle</title>
</head>
<body>
<script src="./myjavascript.js"></script>

<h2>Accordion with symbols</h2>

<p>In this example we have added a "plus" sign to each button. When     the user clicks on the button, the "plus" sign is replaced with a "minus"     sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
      <p>TEXT 1</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>TEXT 2</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>TEXT 3</p>
</div>
</body>
</html>
</code>```

My JS and CSS files are just the JS and CSS files copy-and-pasted to other files (saves as .js, and .css, respectively).

答:
As a quick note, you want to link your  at the bottom of the body. You'll want your HTML to load before the JavaScript does:

```<code><script src="./myjavascript.js"></script>
</body>
</code>```

Second note, Mozilla Developer Network is more informative and reliable than W3 Schools. You'll want to train yourself to visit MDN over W3.

Where are your js and css files located? Can we see the code for those as well?

To debug more efficiently, open the html file in the browser and use the developer tools to let us know the errors you are getting (if there are any). option+command+j for mac and control+shift+j on windows, or just right-click inspect element.

OwnerDisplayName: Adam K

Body:
I am learning how to make an accordion list and have found the following code (HTML, CSS, and JS) from www.w3schools.com. If I run the code locally, as one .html file, it works as intended. However, if I separate it into three files, and link the CSS and JS files in my HTML file, the drop down list does not work. I am (very) new to web development and would appreciate any explanation I can get for this! Thanks in advance.

Original Code (all in one document):

<!DOCTYPE html>

Accordion with symbols

In this example we have added a "plus" sign to each button. When the     user clicks on the button, the "plus" sign is replaced with a "minus"     sign.

<button class="accordion">Section 1</button>

TEXT 1

<button class="accordion">Section 2</button>

TEXT 2

<button class="accordion">Section 3</button>

TEXT 3

And the HTML file linking the CSS and JS as separate files:

<!DOCTYPE html>

    <link rel="stylesheet" href="./mystyling.css">
    <title>Page TItle</title>

Accordion with symbols

In this example we have added a "plus" sign to each button. When     the user clicks on the button, the "plus" sign is replaced with a "minus"     sign.

<button class="accordion">Section 1</button>

TEXT 1

<button class="accordion">Section 2</button>

TEXT 2

<button class="accordion">Section 3</button>

TEXT 3

My JS and CSS files are just the JS and CSS files copy-and-pasted to other files (saves as .js, and .css, respectively).

Body:
As a quick note, you want to link your  at the bottom of the body. You'll want your HTML to load before the JavaScript does:

<script src="./myjavascript.js"></script>
</body>

Second note, Mozilla Developer Network is more informative and reliable than W3 Schools. You'll want to train yourself to visit MDN over W3.

Where are your js and css files located? Can we see the code for those as well?

To debug more efficiently, open the html file in the browser and use the developer tools to let us know the errors you are getting (if there are any). option+command+j for mac and control+shift+j on windows, or just right-click inspect element.


问:
Adding a new Field to FDMemTable when loading an existing data
I'm using TFDMemTable, i have created a dataset and populated my table with data and then used FDMemTable.saveToFile to save my data.

Now here is the question, how can i add a new Field to this already saved data and fill all records with a default value ?

I tried adding the new Field to the FDMemTable and then loading the information hoping it would automatically fill each Field using it's FieldName and the new field with an empty space, but i got an error saying  :
`---------------------------

Debugger Exception Notification

Project Project1.exe raised exception class EDatabaseError with message 'Field 'Episode' not found'.

Break   Continue   Help

`

How can i fix this ? is there a work around for adding a new field with default value to an already existing data ?

Here is a testcase:

```<code>// here is a simple example, i have a few fields
FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i fill the the table with some value
FDMemTable1.Open;
FDMemTable1.AppendRecord([1, 'Movie1', 1]);
FDMemTable1.AppendRecord([2, 'Movie2', 2]);
FDMemTable1.AppendRecord([3, 'Movie3', 1]);

// after seeing the value on the grid, i push a button and save the table as XML
FDMemTable1.saveToFile('Data.xml');

// now after closing the program and running it again, i want to load the data with a new FieldDef Called Episode with a default value 0
// the table is connected to cxGrid, and the moment i try to load, i get the error i mentioned.

FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
// this line is NEW
FDMemTable1.FieldDefs.Add('Episode', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i try to load but i get an error
FDMemTable1.loadFromFile('Data.xml');
</code>```

Update 1 (based on Victoria's answer) :

```<code>//All the codes below are executed after the code at the top, after the loadFromFile.
  FDMemTable1.ResourceOptions.StoreItems := FDMemTable1.ResourceOptions.StoreItems + [siMeta];
  FDMemTable1.Close;

  //i tried putting FDMemTable1 as the owner but when i try the line "FDMemTable1.Fields.add" i get an Duplicate error!
  // and when i try putting nil, i get access violation ! so i tried putting the owner someother random table and it fixed the problem
  fieldDefs := TFieldDefs.Create(someRandomFDMemTable);
  fieldDefs.Add('Episodes', ftString, 30, false);

  FDMemTable1.Fields.Add(fieldDefs.Items[0].CreateField(FDMemTable1));
  FDMemTable1.Open;
</code>```

As you can see i have two problem,

1- I have a problem with adding a new field! where i get an error, i first tried using TFieldDef instead of TFieldDefs but i couldn't get it to work.

2- Is the fact that all the columns are empty and there is no data on the grid.

Problem 2 occurs when i try solving the problem 1 forcefully.

答:
Add that field (not field definition) after you load dataset from the file (assuming siMeta is included in the StoreItems property of the ResourceOptions of your TFDMemTable). Be aware, dataset must be closed at the time you add the field to the field collection.

So, close the dataset right after loading from file, add the field and open it again.

Body:
I'm using TFDMemTable, i have created a dataset and populated my table with data and then used FDMemTable.saveToFile to save my data.

Now here is the question, how can i add a new Field to this already saved data and fill all records with a default value ?

I tried adding the new Field to the FDMemTable and then loading the information hoping it would automatically fill each Field using it's FieldName and the new field with an empty space, but i got an error saying  :
`---------------------------

Debugger Exception Notification

Project Project1.exe raised exception class EDatabaseError with message 'Field 'Episode' not found'.

Break   Continue   Help

`

How can i fix this ? is there a work around for adding a new field with default value to an already existing data ?

Here is a testcase:

// here is a simple example, i have a few fields
FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i fill the the table with some value
FDMemTable1.Open;
FDMemTable1.AppendRecord([1, 'Movie1', 1]);
FDMemTable1.AppendRecord([2, 'Movie2', 2]);
FDMemTable1.AppendRecord([3, 'Movie3', 1]);

// after seeing the value on the grid, i push a button and save the table as XML
FDMemTable1.saveToFile('Data.xml');

// now after closing the program and running it again, i want to load the data with a new FieldDef Called Episode with a default value 0
// the table is connected to cxGrid, and the moment i try to load, i get the error i mentioned.

FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
// this line is NEW
FDMemTable1.FieldDefs.Add('Episode', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i try to load but i get an error
FDMemTable1.loadFromFile('Data.xml');

Update 1 (based on Victoria's answer) :

//All the codes below are executed after the code at the top, after the loadFromFile.
  FDMemTable1.ResourceOptions.StoreItems := FDMemTable1.ResourceOptions.StoreItems + [siMeta];
  FDMemTable1.Close;

  //i tried putting FDMemTable1 as the owner but when i try the line "FDMemTable1.Fields.add" i get an Duplicate error!
  // and when i try putting nil, i get access violation ! so i tried putting the owner someother random table and it fixed the problem
  fieldDefs := TFieldDefs.Create(someRandomFDMemTable);
  fieldDefs.Add('Episodes', ftString, 30, false);

  FDMemTable1.Fields.Add(fieldDefs.Items[0].CreateField(FDMemTable1));
  FDMemTable1.Open;

As you can see i have two problem,

1- I have a problem with adding a new field! where i get an error, i first tried using TFieldDef instead of TFieldDefs but i couldn't get it to work.

2- Is the fact that all the columns are empty and there is no data on the grid.

Problem 2 occurs when i try solving the problem 1 forcefully.


问:
Enable saving core in Impala
I am having a very hard time figuring out how to save impala cores. I am trying to run some queries with UDFs and they are failing. In the impala log, all I see is the message like this:

Failed to write core dump. Core dumps have been disabled. To enable core dumping, try ulimit -c unlimited before starting Java again

I tried running ulimit -c unlimited and then restarted impala service. However, it does not save the core. Anyone had similar issues and know how to fix it?

答:
On clusters managed by Cloudera Manager, go to the Impala service, then under the "Configuration" tab search for "Enable Core Dump" and check the box.  Then restart Impala.

For unmanaged clusters, the document https://www.cloudera.com/documentation/enterprise/5-9-x/topics/impala_config_options.html#config_options_noncm states:

Core dump enablement. To enable core dumps on systems not managed by Cloudera Manager, change:

```<code>export ENABLE_CORE_DUMPS=${ENABLE_COREDUMPS:-false}
</code>```

to:

```<code>export ENABLE_CORE_DUMPS=${ENABLE_COREDUMPS:-true}
</code>```

This is done in the defaults file /etc/default/impala.  Then restart the Impala services you are interested in.

https://www.cloudera.com/documentation/enterprise/5-9-x/topics/impala_config_options.html
https://cwiki.apache.org/confluence/display/IMPALA/Impala+Debugging+Tips

Title: Enable saving core in Impala

Body:
On clusters managed by Cloudera Manager, go to the Impala service, then under the "Configuration" tab search for "Enable Core Dump" and check the box.  Then restart Impala.

For unmanaged clusters, the document https://www.cloudera.com/documentation/enterprise/5-9-x/topics/impala_config_options.html#config_options_noncm states:

Core dump enablement. To enable core dumps on systems not managed by Cloudera Manager, change:

export ENABLE_CORE_DUMPS=${ENABLE_COREDUMPS:-false}

to:

export ENABLE_CORE_DUMPS=${ENABLE_COREDUMPS:-true}

This is done in the defaults file /etc/default/impala.  Then restart the Impala services you are interested in.

https://www.cloudera.com/documentation/enterprise/5-9-x/topics/impala_config_options.html
https://cwiki.apache.org/confluence/display/IMPALA/Impala+Debugging+Tips


问:
Find a text in a range and copy the next Activecell.offset(1,1)16 cells to destination
I have a range I13 to I6076. I am starting at first I13 cell and finding a match in Range("D12:D103333"). If it finds a match in Col D then it should offset Activecell.offset(1,1) from Col D cell and copy the next 16 cells(vertical copy) to corresponding I13 row(horizontal paste). and then move on to I14 and so on. I have created a do while loop to find the cells in the range Range("D12:D103333"), but how do I offset and copy the next 16 cells. and then go to next cell in col I.
Any help would be greatly appreciated. Many Thanks. Code is below.

```<code>Sub Kantar()

    Dim Category As String
    i As Integer

    Range("I13").Select
    Do While Not IsEmpty(ActiveCell)
        Category = ActiveCell.Value
        Range("D12:D103333").Find(What:=Category, MatchCase:=True).Select

        ActiveCell.Offset(1, 0).Select
    Loop

End Sub
</code>```

答:
Firstly I would like to Thank Busse for providing me the logical steps to get my answer. It was Super helpful. So I am copying my code below which might help several users with similar issues. Thanks:))</p>

```<code>Sub Kantar2()

    Dim Category As String, i As Long, FinalRow As Long
    Dim Rng As Range, MyCell As Range

    Application.ScreenUpdating = False
    i = 10
    FinalRow = Cells(Rows.Count, 4).End(xlUp).Row
    Set Rng = Range("I13:I6086")
    For Each MyCell In Rng
        Category = MyCell.Value
        Range(Cells(i, 4), Cells(FinalRow, 4)).Find(What:=Category, MatchCase:=True).Select
        i = ActiveCell.Row
        ActiveCell.Offset(1, 1).Select
        Range(Cells(ActiveCell.Row, 5), Cells(ActiveCell.Row + 15, 5)).Copy
        MyCell.Offset(0, 1).PasteSpecial Transpose:=True
    Next MyCell
    Application.ScreenUpdating = True
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a range I13 to I6076. I am starting at first I13 cell and finding a match in Range("D12:D103333"). If it finds a match in Col D then it should offset Activecell.offset(1,1) from Col D cell and copy the next 16 cells(vertical copy) to corresponding I13 row(horizontal paste). and then move on to I14 and so on. I have created a do while loop to find the cells in the range Range("D12:D103333"), but how do I offset and copy the next 16 cells. and then go to next cell in col I.
Any help would be greatly appreciated. Many Thanks. Code is below.

Sub Kantar()

    Dim Category As String
    i As Integer

    Range("I13").Select
    Do While Not IsEmpty(ActiveCell)
        Category = ActiveCell.Value
        Range("D12:D103333").Find(What:=Category, MatchCase:=True).Select

        ActiveCell.Offset(1, 0).Select
    Loop

End Sub

Body:
Firstly I would like to Thank Busse for providing me the logical steps to get my answer. It was Super helpful. So I am copying my code below which might help several users with similar issues. Thanks:))

Sub Kantar2()

    Dim Category As String, i As Long, FinalRow As Long
    Dim Rng As Range, MyCell As Range

    Application.ScreenUpdating = False
    i = 10
    FinalRow = Cells(Rows.Count, 4).End(xlUp).Row
    Set Rng = Range("I13:I6086")
    For Each MyCell In Rng
        Category = MyCell.Value
        Range(Cells(i, 4), Cells(FinalRow, 4)).Find(What:=Category, MatchCase:=True).Select
        i = ActiveCell.Row
        ActiveCell.Offset(1, 1).Select
        Range(Cells(ActiveCell.Row, 5), Cells(ActiveCell.Row + 15, 5)).Copy
        MyCell.Offset(0, 1).PasteSpecial Transpose:=True
    Next MyCell
    Application.ScreenUpdating = True
End Sub


问:
Getting started with Django on Amazon Web Services
I'm starting to migrate a few applications to Amazon Web Services. My applications are Python/Django apps, running over MySQL.

I plan on using EC2 and EBS for starters.

I'm looking for a few things:

A good step-by-step tutorial explaining how to deploy Django on AWS. I've looked around, but most tutorials are from 2 years ago, so I'm worried they're outdated.

I'm trying to understand, with which AMI should I start? I know there's a BitNami AMI that comes preconfigured with Django goodiness, but I've seen a lot of other sources say you should start with a basic (clean) linux box and install everything yourself. Why?

Are there any other important things I should be thinking about? I have very little sysadmining experience (the apps are currently on WebFaction), so I'm not sure what I should be thinking about.

A few extra points:

I plan on running several applications on the same EC2 instance, I assume that's possible?

I'm using virtualenv to separate between the various apps right now, I assume I can continue doing the same on the EC2 instance?

Thanks!

答:
There is nothing "special" with EC2 here. It just provides bare (or generally preconfigured from custom AMI) system instance - you have access to whole virtualized system, so you can safely break things on your own. Think about it as a specific VPS.

You have to prepare deployment by yourself, which is not so difficult - just follow the documentation. I'd advice to run with basic linux distro and add needed stuff than to rely on some preconfigured image. As for you questions:

You need to do two things: setup your instance (accounts, needed software, other custom setup, so some linux administration guide should be handy) and prepare django app deployment (deploy python code, hook up to web server). For the latter, general deployment instructions for django can be applied here ( http://docs.djangoproject.com/en/dev/howto/deployment/ ).

Start with AMI with your favorite linux distro, and then add necessary software from it's repository.

Mount and use EBS as soon as possible for all your data. When rebooted, EC2 instance will wipe out all it's data, so be prepared for this. Do system snapshots to AMI to have quick recovery on failure.

Yes, you can deploy several applications on one instance, but mind that EC2 instance is virtualized (with quite high "virtualization tax" imo, especially for smaller instances), so you might run into general performance problems. Assume that you'd need migrate to bigger instance/multiple instances after some time.

Virtualenv should be your default deployment tool. Yes, you can use it here too.


问:
How do I select a checkbox bound to a checkbox control from within c# code?
```<code> BillingEntity = (string)rdr["BillingEntity"];
 string[] split = BillingEntity.Split(',');

 for (int i = 0; i < split.Length; i++)
     {
      split[i] = split[i].Trim();
      if (split[i] == "Clinic")
       {
        BillingEntityCheckBox.Items[i].Checked = true;
        Session["billingEntitySessionVar"] = Session["billingEntitySessionVar"]
        + " Clinic";
        }
</code>```

How can I check an item in a checkbox list from the underlying code?

I know with a single checkbox you use checkbox.checked = true. I had that working fine in my code, but I need to link the checkboxes together in a control so that I can trigger an event based on whether any of them has been changed by the user.

To give a little background, I'm pulling in data from a SQL database and outputting to the user interface through a WebForm.

答:
I think you're missing the concept of databinding, is this what you're looking for?:

```<code>public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] myStrings = new string[] { "Example Value", "Not a Thing", "Many Things", "All the Thing" };
        cblThingy.DataSource = myStrings;
        cblThingy.DataBind();
    }

    protected void btnPushMe_Click(object sender, EventArgs e)
    {
        //for all the things
        foreach(ListItem itemThing in cblThingy.Items)
        {
            //set a default of not selected
            itemThing.Selected = false;

            //if the text is the same
            //you can have any check you like here
            if (itemThing.Text == txtThing.Text)

                //say that it's selected
                itemThing.Selected = true;
        }
    }
}
</code>```

^The "code behind"

```<code><asp:Label ID="lblThing" runat="server" Text="If you type the text and push the button the thing with select." />

<asp:TextBox ID="txtThing" runat="server" Text="Example Value" />

<asp:Button ID="btnPushMe" runat="server" Text="Push My Button" OnClick="btnPushMe_Click" />

<asp:CheckBoxList ID="cblThingy" runat="server" />
</code>```

^The webform xml

Hopefully that helps!

p.s.  I think it would be a good idea to make a readonly property on the BillingEntity type, which would return a bool which does the check for "clinic" inside that class, making it more object oriented..

Body:
 BillingEntity = (string)rdr["BillingEntity"];
 string[] split = BillingEntity.Split(',');

 for (int i = 0; i < split.Length; i++)
     {
      split[i] = split[i].Trim();
      if (split[i] == "Clinic")
       {
        BillingEntityCheckBox.Items[i].Checked = true;
        Session["billingEntitySessionVar"] = Session["billingEntitySessionVar"]
        + " Clinic";
        }

How can I check an item in a checkbox list from the underlying code?

I know with a single checkbox you use checkbox.checked = true. I had that working fine in my code, but I need to link the checkboxes together in a control so that I can trigger an event based on whether any of them has been changed by the user.

To give a little background, I'm pulling in data from a SQL database and outputting to the user interface through a WebForm.

Body:
I think you're missing the concept of databinding, is this what you're looking for?:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] myStrings = new string[] { "Example Value", "Not a Thing", "Many Things", "All the Thing" };
        cblThingy.DataSource = myStrings;
        cblThingy.DataBind();
    }

    protected void btnPushMe_Click(object sender, EventArgs e)
    {
        //for all the things
        foreach(ListItem itemThing in cblThingy.Items)
        {
            //set a default of not selected
            itemThing.Selected = false;

            //if the text is the same
            //you can have any check you like here
            if (itemThing.Text == txtThing.Text)

                //say that it's selected
                itemThing.Selected = true;
        }
    }
}

^The "code behind"

<asp:Label ID="lblThing" runat="server" Text="If you type the text and push the button the thing with select." />

<asp:TextBox ID="txtThing" runat="server" Text="Example Value" />

<asp:Button ID="btnPushMe" runat="server" Text="Push My Button" OnClick="btnPushMe_Click" />

<asp:CheckBoxList ID="cblThingy" runat="server" />

^The webform xml

Hopefully that helps!

p.s.  I think it would be a good idea to make a readonly property on the BillingEntity type, which would return a bool which does the check for "clinic" inside that class, making it more object oriented..


问:
How to use UnsafeMutablePointer<OpaquePointer> in Swift?
How does one use an UnsafeMutablePointer<OpaquePointer> in Swift with some Core Foundation framework?  Why have an UnsafeMutablePointer<OpaquePointer>?

Given, general: some UnsafeMutablePointer<SomeType> where typealias SomeType = OpaquePointer

Specific Example API

// SOURCE: import ApplicationServices.PrintCore
typealias PMPrinter = OpaquePointer
func PMSessionGetCurrentPrinter(_ printSession: PMPrintSession, _ currentPrinter: UnsafeMutablePointer<PMPrinter>)
func PMPrinterGetPaperList(PMPrinter, UnsafeMutablePointer<Unmanaged<CFArray>?>)
```

<p><em>Specific Example Use Case: get list of papers supported by a printer</em></p>

<pre class="lang-swift prettyprint-override"><code>let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())
var currentPrinterOptional: PMPrinter? = nil
PMSessionGetCurrentPrinter(printSession, &currentPrinterOptional!)
guard let currentPrinter = currentPrinterOptional else { return }

// Get the array of pre-defined PMPapers this printer supports.
// PMPrinterGetPaperList(PMPrinter, UnsafeMutablePointer<Unmanaged<CFArray>?>)
var paperListUnmanaged: Unmanaged<CFArray>?
PMPrinterGetPaperList(currentPrinter, &paperListUnmanaged)
guard let paperList = paperListUnmanaged?.takeUnretainedValue() as [AnyObject]? else { return }
</code>```

Observed Errors

What compiles does not run.  What seems like (maybe) reasonable syntax does not compile.

The above example gets the following (expected) Runtime "fatal error: unexpectedly found nil while unwrapping an Optional value".

Some select other attempts:

// Compile Error: Address of variable 'currentPrinter' taken before is is initialized
var currentPrinter: PMPrinter
PMSessionGetCurrentPrinter(printSession, &currentPrinter)

// Compile Error: Nil cannot initialze specified type 'PMPrinter' (aka 'OpaquePointer')
var currentPrinter: PMPrinter = nil
PMSessionGetCurrentPrinter(printSession, &currentPrinter)

// Compile Error: Variable 'currentPrinterPtr' used before being initialized
var currentPrinterPtr: UnsafeMutablePointer<PMPrinter>
PMSessionGetCurrentPrinter(printSession, currentPrinterPtr)

// Compile OK: actually compiles
// Runtime Error: unexpectedly found nil while unwrapping an Optional value
var currentPrinterOptional: PMPrinter? = nil
PMSessionGetCurrentPrinter(printSession, &currentPrinterOptional!)
```

Resources

Apple: Core Printing ⇗

Apple: Using Swift with Cocoa and Objective-C ⇗

While the docs have useful information, a workable implementation for UnsafeMutablePointer<PMPrinter> with typealias as UnsafeMutablePointer<OpaquePointer> has been elusive.

答:
PMPrinter and PMPaper are defined in the PrintCore framework
as pointer to an "incomplete type"

```<code>typedef struct OpaquePMPrinter*         PMPrinter;
typedef struct OpaquePMPaper*           PMPaper;
</code>```

Those are imported into Swift as OpaquePointer, and are a bit
cumbersome to use.

The second argument to PMSessionGetCurrentPrinter() is a pointer to
a non-optional PMPrinter variable, and in Swift it must be
initialized before being passed as an inout argument. One possible way
to initialize a null-pointer is to use unsafeBitCast.

The easiest way to get the PMPaper objects from the array seems to
be to use CFArrayGetValueAtIndex() instead of bridging it to a
Swift array. That returns a UnsafeRawPointer which can be converted
to an OpaquePointer.

This worked in my test:

```<code>let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())

var currentPrinter = unsafeBitCast(0, to: PMPrinter.self)
PMSessionGetCurrentPrinter(printSession, &currentPrinter);

var paperListUnmanaged: Unmanaged<CFArray>?
PMPrinterGetPaperList(currentPrinter, &paperListUnmanaged)
guard let paperList = paperListUnmanaged?.takeUnretainedValue() else {
    fatalError()
}
for idx in 0..<CFArrayGetCount(paperList) {
    let paper = PMPaper(CFArrayGetValueAtIndex(paperList, idx))!
    var width = 0.0, height = 0.0
    PMPaperGetWidth(paper, &width)
    PMPaperGetHeight(paper, &height)
    print(width, height)
}
</code>```

Body:
How does one use an UnsafeMutablePointer<OpaquePointer> in Swift with some Core Foundation framework?  Why have an UnsafeMutablePointer<OpaquePointer>?

Given, general: some UnsafeMutablePointer<SomeType> where typealias SomeType = OpaquePointer

Specific Example API

// SOURCE: import ApplicationServices.PrintCore
typealias PMPrinter = OpaquePointer
func PMSessionGetCurrentPrinter(_ printSession: PMPrintSession, _ currentPrinter: UnsafeMutablePointer<PMPrinter>)
func PMPrinterGetPaperList(PMPrinter, UnsafeMutablePointer<Unmanaged<CFArray>?>)

Specific Example Use Case: get list of papers supported by a printer

let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())
var currentPrinterOptional: PMPrinter? = nil
PMSessionGetCurrentPrinter(printSession, &currentPrinterOptional!)
guard let currentPrinter = currentPrinterOptional else { return }

// Get the array of pre-defined PMPapers this printer supports.
// PMPrinterGetPaperList(PMPrinter, UnsafeMutablePointer<Unmanaged<CFArray>?>)
var paperListUnmanaged: Unmanaged<CFArray>?
PMPrinterGetPaperList(currentPrinter, &paperListUnmanaged)
guard let paperList = paperListUnmanaged?.takeUnretainedValue() as [AnyObject]? else { return }

Observed Errors

What compiles does not run.  What seems like (maybe) reasonable syntax does not compile.

The above example gets the following (expected) Runtime "fatal error: unexpectedly found nil while unwrapping an Optional value".

Some select other attempts:

// Compile Error: Address of variable 'currentPrinter' taken before is is initialized
var currentPrinter: PMPrinter
PMSessionGetCurrentPrinter(printSession, &currentPrinter)

// Compile Error: Nil cannot initialze specified type 'PMPrinter' (aka 'OpaquePointer')
var currentPrinter: PMPrinter = nil
PMSessionGetCurrentPrinter(printSession, &currentPrinter)

// Compile Error: Variable 'currentPrinterPtr' used before being initialized
var currentPrinterPtr: UnsafeMutablePointer<PMPrinter>
PMSessionGetCurrentPrinter(printSession, currentPrinterPtr)

// Compile OK: actually compiles
// Runtime Error: unexpectedly found nil while unwrapping an Optional value
var currentPrinterOptional: PMPrinter? = nil
PMSessionGetCurrentPrinter(printSession, &currentPrinterOptional!)

Resources

Apple: Core Printing ⇗

Apple: Using Swift with Cocoa and Objective-C ⇗

While the docs have useful information, a workable implementation for UnsafeMutablePointer<PMPrinter> with typealias as UnsafeMutablePointer<OpaquePointer> has been elusive.

Body:
PMPrinter and PMPaper are defined in the PrintCore framework
as pointer to an "incomplete type"

typedef struct OpaquePMPrinter*         PMPrinter;
typedef struct OpaquePMPaper*           PMPaper;

Those are imported into Swift as OpaquePointer, and are a bit
cumbersome to use.

The second argument to PMSessionGetCurrentPrinter() is a pointer to
a non-optional PMPrinter variable, and in Swift it must be
initialized before being passed as an inout argument. One possible way
to initialize a null-pointer is to use unsafeBitCast.

The easiest way to get the PMPaper objects from the array seems to
be to use CFArrayGetValueAtIndex() instead of bridging it to a
Swift array. That returns a UnsafeRawPointer which can be converted
to an OpaquePointer.

This worked in my test:

let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())

var currentPrinter = unsafeBitCast(0, to: PMPrinter.self)
PMSessionGetCurrentPrinter(printSession, &currentPrinter);

var paperListUnmanaged: Unmanaged<CFArray>?
PMPrinterGetPaperList(currentPrinter, &paperListUnmanaged)
guard let paperList = paperListUnmanaged?.takeUnretainedValue() else {
    fatalError()
}
for idx in 0..<CFArrayGetCount(paperList) {
    let paper = PMPaper(CFArrayGetValueAtIndex(paperList, idx))!
    var width = 0.0, height = 0.0
    PMPaperGetWidth(paper, &width)
    PMPaperGetHeight(paper, &height)
    print(width, height)
}


问:
Read csv from zip into shiny app without relying on local directories
I've written a shiny app (server & ui) and it runs fine on my computer. Today I'm trying to host it on shinyapps.io and having some trouble. I can't pull data from my local machine, it needs to be housed online somewhere. But the source data is only available online as a zip. I've found a few resources on how to use R to download a zip to one's local machine, but they all seem to require putting the file in a local temporary directory, and I don't think I can do that with a hosted shiny app. So my question is
how to unzip and then access/load/use CSV files directly within R/Shiny.

Relevant snippet of code is below. This is the section I need to replace. Let me know if it would be helpful to post more code--I know that's expected but in this case I'm not sure it would help.

```<code>#load data
library(shiny)
base <- read.csv("/Users/OldJess/Dropbox/R Stuff(Home)/ShinyNames/data/NationalNames.csv",
                 stringsAsFactors = FALSE,
                 na.strings = c("NA","","#MULTIVALUE"))
</code>```

My shiny app is here: https://jesstme.shinyapps.io/shinynames/

答:
Would it be feasible to let the user upload the data from local computer using shiny browser button and then unzip it using read.table? For that read.table functionality, see this answer: https://stackoverflow.com/a/36047026/7860688  (copied here for the sake of completeness, assuming you only have one csv file inside that zip):

```<code>    data <- read.table("Sales.zip", nrows=10, header=T, quote="\"", sep=",")
</code>```

Files can be uploaded using shiny fileInput function as below:

```<code>     fileInput("file1", "Choose CSV File",
    accept = c(
      "text/csv",
      "text/comma-separated-values,text/plain",
      ".csv")
    )
</code>```

See the documentation here: https://shiny.rstudio.com/reference/shiny/latest/fileInput.html

Body:
I've written a shiny app (server & ui) and it runs fine on my computer. Today I'm trying to host it on shinyapps.io and having some trouble. I can't pull data from my local machine, it needs to be housed online somewhere. But the source data is only available online as a zip. I've found a few resources on how to use R to download a zip to one's local machine, but they all seem to require putting the file in a local temporary directory, and I don't think I can do that with a hosted shiny app. So my question is
how to unzip and then access/load/use CSV files directly within R/Shiny.

Relevant snippet of code is below. This is the section I need to replace. Let me know if it would be helpful to post more code--I know that's expected but in this case I'm not sure it would help.

#load data
library(shiny)
base <- read.csv("/Users/OldJess/Dropbox/R Stuff(Home)/ShinyNames/data/NationalNames.csv",
                 stringsAsFactors = FALSE,
                 na.strings = c("NA","","#MULTIVALUE"))

My shiny app is here: https://jesstme.shinyapps.io/shinynames/

Body:
Would it be feasible to let the user upload the data from local computer using shiny browser button and then unzip it using read.table? For that read.table functionality, see this answer: https://stackoverflow.com/a/36047026/7860688  (copied here for the sake of completeness, assuming you only have one csv file inside that zip):

    data <- read.table("Sales.zip", nrows=10, header=T, quote="\"", sep=",")

Files can be uploaded using shiny fileInput function as below:

     fileInput("file1", "Choose CSV File",
    accept = c(
      "text/csv",
      "text/comma-separated-values,text/plain",
      ".csv")
    )

See the documentation here: https://shiny.rstudio.com/reference/shiny/latest/fileInput.html


问:
Spring MVC using different part of hibernate validator in Java
My problem is that I wanna use just username and userpassword  hibernate validation for login page. Not  for also useremail.I kept useremail hibernate validation annotation for registration  page or something.So when I try at login page to login errors occured.(Please enter your email) But I dont want to include that.Just check for username and userpassword.How can I handle that?

```<code>@RequestMapping(value = "/",method=RequestMethod.GET)
        public String displayUserForm(ModelMap model,HttpServletRequest request){
            model.addAttribute("usertable",new usertable());
            return "login";
        }
</code>```

Above is for going to login.jsp

```<code>private Integer userid;
     @NotEmpty(message = "Please enter your username.")
     private String username;
     @NotEmpty(message = "Please enter your password.")
     private String userpw;
      @NotEmpty(message = "Please enter your email.")
      private String useremail;
</code>```

Above is  part of pojo class

```<code><div style="color:red">${errorMessage}</div>
    <form:form method="POST" commandName="usertable" action="/Proje/loginiscorrect">
        <form:errors path="*" cssClass="errorblock" element="div" />
        <table>
            <tr>
                <td>User Name :</td>
                <td><form:input path="username" /></td>
                <td><form:errors path="username" cssClass="error" /></td>
            </tr>
            <tr>
                <td>User Password  :</td>
                <td><form:input path="userpw" /></td>
                <td><form:errors path="userpw" cssClass="error" /></td>
            </tr>
            <tr>
                            <td colspan="3"><input type="submit" value="LOGIN"/></td>
            </tr>
        </table>
    </form:form>
</code>```

Above is login jsp page for checking errors if any errors coming up display message at same page

```<code>@RequestMapping(value="/loginiscorrect",method=RequestMethod.POST)
    public String LoginUser(@Valid kisitablo kisitablo, BindingResult result,HttpServletRequest request,HttpServletResponse response) {

        if (result.hasErrors()) {
            return "login";
        } else {
bla bla}
</code>```

Above is for check via hibernate validator from pojo class annotations .

答:
It can be done this way using Hibernate Group.

Create a marker interface for the group name

```<code>public interface LoginGroup {}
</code>```

In you Domain object

```<code>private Integer userid;

@NotEmpty(message = "Please enter your username.", groups={LoginGroup.class})
private String username;

@NotEmpty(message = "Please enter your password.", groups={LoginGroup.class})
private String userpw;

@NotEmpty(message = "Please enter your email.")
private String useremail;
</code>```

In your controller method, use @Validated to specify the group

```<code>@RequestMapping(value="/loginiscorrect",method=RequestMethod.POST)
public String LoginUser(@Validated(LoginGroup.class) kisitablo kisitablo, BindingResult result,HttpServletRequest request,HttpServletResponse response) {
    if (result.hasErrors()) {
        return "login";
    }
    //Your logic.....
}
</code>```

Moreover, for your registration page, if you want all username, password and email validated, you can specify as below.

Create a new Interface as RegistratonGroup

```<code>public interface RegistrationGroup {}
</code>```

Your model:

```<code>private Integer userid;

@NotEmpty(message = "Please enter your username.", groups={LoginGroup.class, RegistrationGroup.class})
private String username;

@NotEmpty(message = "Please enter your password.", groups={LoginGroup.class, RegistrationGroup.class})
private String userpw;

@NotEmpty(message = "Please enter your email.", groups={RegistrationGroup.class})
private String useremail;
</code>```

And do same as before in your controller method and specify the RegistrationGroup.class as @Validated(RegistrationGroup.class)

```<code>@RequestMapping(value="/{registration_path}",method=RequestMethod.POST)
public String register(@Validated(RegistrationGroup.class) kisitablo kisitablo, BindingResult result.....) {
        if (result.hasErrors()) {
            return "login";
        }
        //Your logic.....
    }
</code>```

For more information, please see here

Body:
My problem is that I wanna use just username and userpassword  hibernate validation for login page. Not  for also useremail.I kept useremail hibernate validation annotation for registration  page or something.So when I try at login page to login errors occured.(Please enter your email) But I dont want to include that.Just check for username and userpassword.How can I handle that?

@RequestMapping(value = "/",method=RequestMethod.GET)
        public String displayUserForm(ModelMap model,HttpServletRequest request){
            model.addAttribute("usertable",new usertable());
            return "login";
        }

Above is for going to login.jsp

private Integer userid;
     @NotEmpty(message = "Please enter your username.")
     private String username;
     @NotEmpty(message = "Please enter your password.")
     private String userpw;
      @NotEmpty(message = "Please enter your email.")
      private String useremail;

Above is  part of pojo class

${errorMessage}

    <form:form method="POST" commandName="usertable" action="/Proje/loginiscorrect">
        <form:errors path="*" cssClass="errorblock" element="div" />

                User Name :
                <form:input path="username" />
                <form:errors path="username" cssClass="error" />

                User Password  :
                <form:input path="userpw" />
                <form:errors path="userpw" cssClass="error" />

                            <input type="submit" value="LOGIN"/>

    </form:form>

Above is login jsp page for checking errors if any errors coming up display message at same page

@RequestMapping(value="/loginiscorrect",method=RequestMethod.POST)
    public String LoginUser(@Valid kisitablo kisitablo, BindingResult result,HttpServletRequest request,HttpServletResponse response) {

        if (result.hasErrors()) {
            return "login";
        } else {
bla bla}

Above is for check via hibernate validator from pojo class annotations .

Body:
It can be done this way using Hibernate Group.

Create a marker interface for the group name

public interface LoginGroup {}

In you Domain object

private Integer userid;

@NotEmpty(message = "Please enter your username.", groups={LoginGroup.class})
private String username;

@NotEmpty(message = "Please enter your password.", groups={LoginGroup.class})
private String userpw;

@NotEmpty(message = "Please enter your email.")
private String useremail;

In your controller method, use @Validated to specify the group

@RequestMapping(value="/loginiscorrect",method=RequestMethod.POST)
public String LoginUser(@Validated(LoginGroup.class) kisitablo kisitablo, BindingResult result,HttpServletRequest request,HttpServletResponse response) {
    if (result.hasErrors()) {
        return "login";
    }
    //Your logic.....
}

Moreover, for your registration page, if you want all username, password and email validated, you can specify as below.

Create a new Interface as RegistratonGroup

public interface RegistrationGroup {}

Your model:

private Integer userid;

@NotEmpty(message = "Please enter your username.", groups={LoginGroup.class, RegistrationGroup.class})
private String username;

@NotEmpty(message = "Please enter your password.", groups={LoginGroup.class, RegistrationGroup.class})
private String userpw;

@NotEmpty(message = "Please enter your email.", groups={RegistrationGroup.class})
private String useremail;

And do same as before in your controller method and specify the RegistrationGroup.class as @Validated(RegistrationGroup.class)

@RequestMapping(value="/{registration_path}",method=RequestMethod.POST)
public String register(@Validated(RegistrationGroup.class) kisitablo kisitablo, BindingResult result.....) {
        if (result.hasErrors()) {
            return "login";
        }
        //Your logic.....
    }

For more information, please see here