问:
Why passing &error instead of error in Cocoa programming?
In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?</p>

```<code>NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code
</code>```

答:
The save method takes a pointer to a pointer.  There's a good explanation on Cocoa Tutorial: Using NSError to Great Effect

Passing Pointers to Pointers

Using the NSError class in the above
  example is quite simple. I just pass
  it in and if the call failed for
  whatever reason I have an NSError
  object to explain what the problem
  was. But how does the other side of
  that call work?

The first part of this is to
  understand the concept of passing a
  pointer to a pointer rather than a
  pointer to an object. Normally when a
  message is sent, a pointer to the
  object is being passed in the message.
  This is denoted with the single
  asterisk(*) in the method signature
  such as

-(void)appendString:(NSString*)newString
  This is different then passing a
  pointer to a pointer. First, that type
  of argument is denoted with two
  asterisk(**) such as:

-(BOOL)save:(NSError**)error Second, the other difference is this allows
  the receiving method to control what
  the pointer (that the pointer is
  pointing to) is referencing. This is
  arguably one of the more confusing
  parts of pointer programming but once
  you get it, it is a very powerful
  tool. To put it another way, by
  passing a pointer to the pointer, the
  receiving method can decide what your
  variable’s value is. As you can see in
  my code above, I initialized the error
  variable to nil. However, if the save
  call fails, that variable will no
  longer be nil but will reference an
  actual NSError object which I can than
  interrogate.

If you wish to understand how this
  works, I would suggest the double
  indirection wikipedia article as a
  great starting point.

Body:
In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?

NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code


来源: stackexchange

问:
Not able to connect the ssl node throgh cqlsh
Before explaining the issue which I'm facing, I will let you know the verified points from my local machine.

I have all the Cassandra related configuration and I have the required privileges (access) to my machine .

I'm able to connect the Cassandra node which is SSL disabled or the  node which is TLS disabled through  cqlsh.

E.g I'm able to connect to below C* node with the below command

cqlsh -u xxxxx -p xxxxxx 123.abc.com

But at the same time I'm not able to connect to the below node with option SSL

cqlsh --ssl -u xxxxx -p xxxxxx 123.xyz.com

Below is my content of cqlshrc file:

    [Authentication]
    Usename = xxxx
    password = xxxx
    [connection]
    hostname = 123.xyz.com
    port = 9042
    factory = cqlshlib.ssl.ssl_transport_factory
    [ssl]
    certfile=~/certfiles/xyz.pem
    validate = false

Even I tried setting the certFile path as an environment variable.

I'm getting the below exception:

Validation is enabled; SSL transport factory requires a valid certfile to be specified. Please provide path to the certfile in [ssl] section as 'certfile' option in /XXXX/XXXXX/.cassandra/cqlshrc (or use [certfiles] section) or set SSL_CERTFILE environment variable.

答:
I'm going to guess that your path is probably valid, but that your certfile may not be.  Here are some quick steps that will generate a valid certfile from the keystore of one of your nodes:

1 - Check your cassandra.yaml for the keystore location and password:

```<code>client_encryption_options:
  enabled: true
  keystore: /etc/cassandra/.keystore
  keystore_password: flynnLives
</code>```

2 - Convert your keystore to a PKCS12 keystore:

```<code>$ keytool -importkeystore -srckeystore /etc/cassandra/.keystore
    -destkeystore ~/.cassandra/p12.keystore -deststoretype PKCS12
    -srcstorepass flynnLives -deststorepass flynnLives
</code>```

3 - Generate a certfile from the PKCS12 keystore:

```<code>$ openssl pkcs12 -in ~/.cassandra/p12.keystore -nokeys -out ~/.cassandra/xyz.pem
    -passin pass:flynnLives
</code>```

4 - Specify the connection and ssl sections in your cqlshrc, as well as the default transport factory and the name of your certificate.  And unless you're using two-way SSL, set validate to false.

```<code>[connection]
factory = cqlshlib.ssl.ssl_transport_factory

[ssl]
certfile = ~/.cassandra/xyz.pem
validate = false
</code>```

5 - Connect via cqlsh:

```<code>$ bin/cqlsh 192.168.0.100 -u flynn -p reindeerFlotilla --ssl
Connected to MasterControl at 192.168.0.100:9042.
[cqlsh 5.0.1 | Cassandra 2.2.5 | CQL spec 3.3.1 | Native protocol v4]
Use HELP for help.
flynn@cqlsh>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm going to guess that your path is probably valid, but that your certfile may not be.  Here are some quick steps that will generate a valid certfile from the keystore of one of your nodes:

1 - Check your cassandra.yaml for the keystore location and password:

client_encryption_options:
  enabled: true
  keystore: /etc/cassandra/.keystore
  keystore_password: flynnLives

2 - Convert your keystore to a PKCS12 keystore:

$ keytool -importkeystore -srckeystore /etc/cassandra/.keystore
    -destkeystore ~/.cassandra/p12.keystore -deststoretype PKCS12
    -srcstorepass flynnLives -deststorepass flynnLives

3 - Generate a certfile from the PKCS12 keystore:

$ openssl pkcs12 -in ~/.cassandra/p12.keystore -nokeys -out ~/.cassandra/xyz.pem
    -passin pass:flynnLives

4 - Specify the connection and ssl sections in your cqlshrc, as well as the default transport factory and the name of your certificate.  And unless you're using two-way SSL, set validate to false.

[connection]
factory = cqlshlib.ssl.ssl_transport_factory

[ssl]
certfile = ~/.cassandra/xyz.pem
validate = false

5 - Connect via cqlsh:

$ bin/cqlsh 192.168.0.100 -u flynn -p reindeerFlotilla --ssl
Connected to MasterControl at 192.168.0.100:9042.
[cqlsh 5.0.1 | Cassandra 2.2.5 | CQL spec 3.3.1 | Native protocol v4]
Use HELP for help.
flynn@cqlsh>


问:
Big query SQL Error: Column name user_dim is ambiguous at [3:3]
how can i run a query that goes through both my android and iOS data to return what i need in one table.

currently getting the above error when i run this

```<code>#standardSQL
SELECT
  user_dim.app_info.app_instance_id,
  user_dim.device_info.device_category,
  user_dim.device_info.user_default_language,
  user_dim.device_info.platform_version,
  user_dim.device_info.device_model,
  user_dim.geo_info.country,
  user_dim.geo_info.city,
  user_dim.app_info.app_version,
  user_dim.app_info.app_store,
  user_dim.app_info.app_platform
FROM
</code>```

app.com_aaa_IOS.app_events_20171204,app.com_aaa_ANDROID.app_events_20171204

答:
Standard SQL

You are using Standard SQL, then you should to use UNION ALL operator:

```<code>SELECT
  user_dim.app_info.app_instance_id,
  ...
FROM app.com_aaa_IOS.app_events_20171204
UNION ALL
SELECT
  user_dim.app_info.app_instance_id,
  ...
FROM app.com_aaa_ANDROID.app_events_20171204`
</code>```

Remember you can use Wildcard Tables:

```<code>SELECT
FROM
  `<project-id>.<dataset-id>.<table-prefix>*`
WHERE
  bool_expression
</code>```

Legacy SQL

If you switch to Legacy SQL then you can use comma separated tables as union, like in your query.

Combinations of these data sources can be queried using the comma, which is the UNION ALL operator in BigQuery

Body:
how can i run a query that goes through both my android and iOS data to return what i need in one table.

currently getting the above error when i run this

#standardSQL
SELECT
  user_dim.app_info.app_instance_id,
  user_dim.device_info.device_category,
  user_dim.device_info.user_default_language,
  user_dim.device_info.platform_version,
  user_dim.device_info.device_model,
  user_dim.geo_info.country,
  user_dim.geo_info.city,
  user_dim.app_info.app_version,
  user_dim.app_info.app_store,
  user_dim.app_info.app_platform
FROM

app.com_aaa_IOS.app_events_20171204,app.com_aaa_ANDROID.app_events_20171204

Body:
Standard SQL

You are using Standard SQL, then you should to use UNION ALL operator:

SELECT
  user_dim.app_info.app_instance_id,
  ...
FROM app.com_aaa_IOS.app_events_20171204
UNION ALL
SELECT
  user_dim.app_info.app_instance_id,
  ...
FROM app.com_aaa_ANDROID.app_events_20171204`

Remember you can use Wildcard Tables:

SELECT
FROM
  `<project-id>.<dataset-id>.<table-prefix>*`
WHERE
  bool_expression

Legacy SQL

If you switch to Legacy SQL then you can use comma separated tables as union, like in your query.

Combinations of these data sources can be queried using the comma, which is the UNION ALL operator in BigQuery


问:
Query to list users having same profile from two tables
```<code>Table 1 : dbt_m_user (user_id, user_name, email_id, . . . . . )

Table 2 : dbt_m_user_profile (user_id, profile_id, . . . . .)
</code>```

I have e-mail id of an user who has particular profile (role).
Now I need names of users who are having same access profile.

I could get the results from below, but it looks very raw and doesn't seem to be elegant one, considering that there are only 2 tables.

```<code>  select user_name from dbt_m_user where user_id in (
  select user_id from dbt_m_user_profile where profile_id in (
  select profile_id from dbt_m_user_profile where user_id in (
  select user_id from  dbt_m_user where Email_Id = 'snehal.masne@db.com' )))
</code>```

Can this be improvised by using special clauses/joins ?

答:
Try below query</p>

```<code>SELECT    U.USER_NAME
FROM      DBT_M_USER_PROFILE P, DBT_M_USER U
WHERE     P.USER_ID = U.USER_ID
AND       P.PROFILE_ID IN  (
              SELECT P.PROFILE_ID
              FROM  DBT_M_USER_PROFILE P, DBT_M_USER U
              WHERE U.EMAIL_ID = 'snehal.masne@db.com'
              AND  P.USER_ID = U.USER_ID  )
</code>```

Body:
Table 1 : dbt_m_user (user_id, user_name, email_id, . . . . . )

Table 2 : dbt_m_user_profile (user_id, profile_id, . . . . .)

I have e-mail id of an user who has particular profile (role).
Now I need names of users who are having same access profile.

I could get the results from below, but it looks very raw and doesn't seem to be elegant one, considering that there are only 2 tables.

  select user_name from dbt_m_user where user_id in (
  select user_id from dbt_m_user_profile where profile_id in (
  select profile_id from dbt_m_user_profile where user_id in (
  select user_id from  dbt_m_user where Email_Id = 'snehal.masne@db.com' )))

Can this be improvised by using special clauses/joins ?

Body:
Try below query

SELECT    U.USER_NAME
FROM      DBT_M_USER_PROFILE P, DBT_M_USER U
WHERE     P.USER_ID = U.USER_ID
AND       P.PROFILE_ID IN  (
              SELECT P.PROFILE_ID
              FROM  DBT_M_USER_PROFILE P, DBT_M_USER U
              WHERE U.EMAIL_ID = 'snehal.masne@db.com'
              AND  P.USER_ID = U.USER_ID  )


问:
Function To Delete Table Or Query If Exists
I am attempting to use a Function that checks if a table/query that is passed into the function then delete it.  My issue is that when it hits this line of syntax

```<code>If TableExists(CStr(tableArray)) Then
</code>```

I get a type mismatch error.  However, if I change the syntax to If TableExists(CStr(amx)) Then the value is 0 so the table/query is still not deleted.  What would be the appropriate syntax to pass an array of table names and query names into a function and delete them if they exists?

```<code>    Function DeleteTables()
   tableArray = Array("Table1", "Table2", "Table3", "Table4")
   queryArray = Array("Query1", "Query2", "Query3")

    For amx = LBound(tableArray) To UBound(tableArray)
        If TableExists(CStr(tableArray)) Then
            With db.TableDefs
                .Delete CStr(tableArray)
                .Refresh
            End With
        End If
   Next

   For qdi = LBound(queryArray) To UBound(queryArray)
        If TableExists(CStr(queryArray)) Then
            With db.QueryDefs
                .Delete CStr(queryArray)
                .Refresh
            End With
        End If
   Next
End Function
Public Function TableExists(strName As String) As Boolean

   On Error GoTo HandleErr

   Dim db As DAO.Database, tDef As DAO.TableDef

   Set db = CurrentDb

   TableExists = False

   For Each tDef In db.TableDefs
      If tDef.Name = strName Then
         TableExists = True
         Exit For
      End If
   Next tDef

   For Each qDef In db.QueryDefs
    If qDef.Name = strName Then
        TableExists = True
        Exit For
    End If
   Next qDef

ExitFunction:
   db.Close
   Set db = Nothing
   Exit Function

HandleErr:
   TableExists = False
   Resume ExitFunction

End Function

Type Mismatch
</code>```

答:
You're almost there, you just need to refer to the specific item in the array you're looping through:

Change your current code to:

```<code>    If TableExists(CStr(tableArray(amx))) Then
        With db.TableDefs
            .Delete CStr(tableArray(amx))
            .Refresh
        End With
    End If
</code>```

and

```<code>    If TableExists(CStr(queryArray(qdi))) Then
        With db.QueryDefs
            .Delete CStr(queryArray(qdi))
            .Refresh
        End With
    End If
</code>```

You could also use a For Each loop in the future, they tend to be easier to understand.

Body:
I am attempting to use a Function that checks if a table/query that is passed into the function then delete it.  My issue is that when it hits this line of syntax

If TableExists(CStr(tableArray)) Then

I get a type mismatch error.  However, if I change the syntax to If TableExists(CStr(amx)) Then the value is 0 so the table/query is still not deleted.  What would be the appropriate syntax to pass an array of table names and query names into a function and delete them if they exists?

    Function DeleteTables()
   tableArray = Array("Table1", "Table2", "Table3", "Table4")
   queryArray = Array("Query1", "Query2", "Query3")

    For amx = LBound(tableArray) To UBound(tableArray)
        If TableExists(CStr(tableArray)) Then
            With db.TableDefs
                .Delete CStr(tableArray)
                .Refresh
            End With
        End If
   Next

   For qdi = LBound(queryArray) To UBound(queryArray)
        If TableExists(CStr(queryArray)) Then
            With db.QueryDefs
                .Delete CStr(queryArray)
                .Refresh
            End With
        End If
   Next
End Function
Public Function TableExists(strName As String) As Boolean

   On Error GoTo HandleErr

   Dim db As DAO.Database, tDef As DAO.TableDef

   Set db = CurrentDb

   TableExists = False

   For Each tDef In db.TableDefs
      If tDef.Name = strName Then
         TableExists = True
         Exit For
      End If
   Next tDef

   For Each qDef In db.QueryDefs
    If qDef.Name = strName Then
        TableExists = True
        Exit For
    End If
   Next qDef

ExitFunction:
   db.Close
   Set db = Nothing
   Exit Function

HandleErr:
   TableExists = False
   Resume ExitFunction

End Function

Type Mismatch

Body:
You're almost there, you just need to refer to the specific item in the array you're looping through:

Change your current code to:

    If TableExists(CStr(tableArray(amx))) Then
        With db.TableDefs
            .Delete CStr(tableArray(amx))
            .Refresh
        End With
    End If

and

    If TableExists(CStr(queryArray(qdi))) Then
        With db.QueryDefs
            .Delete CStr(queryArray(qdi))
            .Refresh
        End With
    End If

You could also use a For Each loop in the future, they tend to be easier to understand.


问:
INTERVIEW QUESTION : Perl Log file
There is a log file where each line contains fields separated by spaces. One of the fields is the IP address of the source node. We want to find the list of IP Addresses that have the most log entries. Lets say find the top 10 IP Addresses with most log entries.

This is Perl Interview Question. Interviewer wants to know how the candidate would proceed.

P.S: This question was asked to my friend

答:
Assume that the IP addresses appear in column N:

```<code>use strict;
use warnings;
use constant N => 3;

my %counts;
while (<>)
{
    my(@fields) = split /\s+/;
    $counts{$fields[N]}++;
}
</code>```

That much gives you a hash of I/P addresses and the corresponding counts.

```<code>my %iplist;
foreach my $address (keys %counts)
{
     my $count = $counts{$address};
     push @{$iplist{$count}}, $address;
}
</code>```

That much gives you a hash of counts, and associated with each count, the list of IP addresses that had that count.

```<code>use constant Wanted => 10;

my $printed = 0;
foreach my $count (sort { $b <=> $a } keys %iplist)
{
    print "$count: @{$iplist{$count}}\n";
    $printed += scalar(@{$iplist{$count}});
    last if $printed >= Wanted;
}
</code>```

That sorts the counts into reverse (descending) order, and prints out the count and the list of IP addresses that appeared that many times.  It also counts the number of addresses printed and stops the loop when that meets or exceeds the number required.

ContentLicense: CC BY-SA 2.5

Title: INTERVIEW QUESTION : Perl Log file

Body:
Assume that the IP addresses appear in column N:

use strict;
use warnings;
use constant N => 3;

my %counts;
while (<>)
{
    my(@fields) = split /\s+/;
    $counts{$fields[N]}++;
}

That much gives you a hash of I/P addresses and the corresponding counts.

my %iplist;
foreach my $address (keys %counts)
{
     my $count = $counts{$address};
     push @{$iplist{$count}}, $address;
}

That much gives you a hash of counts, and associated with each count, the list of IP addresses that had that count.

use constant Wanted => 10;

my $printed = 0;
foreach my $count (sort { $b <=> $a } keys %iplist)
{
    print "$count: @{$iplist{$count}}\n";
    $printed += scalar(@{$iplist{$count}});
    last if $printed >= Wanted;
}

That sorts the counts into reverse (descending) order, and prints out the count and the list of IP addresses that appeared that many times.  It also counts the number of addresses printed and stops the loop when that meets or exceeds the number required.


问:
Telegram: Import numbers with format .txt to telegram
I have a list numbers (about 2000 contacts) with format .txt
Now want add numbers to my telegram, best idea for add import list to telegram
idea is possible in desktop or Android?</p>

答:
I don't think you can do it with dekstop. Either convert the txt file to csv and download "import csv" from Play Store which will simply add all the contacts from your file and then you can see them in your telegram list (If they have Telegram) OR convert them to vcf and open it from your File manager, it will automatically add them into your contacts list.
Also if you search in Play Store you may find an application to directly import numbers from txt file.</p>


问:
How do I exclude python dependencies needing to be present to check using the python plugin
Some engineers in our organization are starting to use python but we find we must have the dependencies, produced by third parties, present for the analysis to be done successfully.

Is there a way to exclude python dependencies needing to be accessible for the code we produce to be analyzed?

We are using SonarQube 5.6.6 with the Sonar Python 1.8.0.1496 plugin installed.

答:
You can exclude dependencies with the sonar.exclusions property in the sonar-project.properties file.

For example:
sonar.exclusions=third-parties/lib/**/* , other/lib/**/*

See Narrowing the Focus


问:
Not able to use JpaReposiory?
I have already added the mysql connector dependency

```<code><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>
</code>```

I have made a repository package and made an interface in it.

in that when I made an Interface, name Teacher

```<code>public interface TeacherRepository extends  JpaRe
</code>```

when I press ctrl + space it is not auto completing meaning there is no available interface like that.

What could be the problem?

答:
if you want use JpaRepository you must add Spring-data-jpa Dependency

Put this dependency to pom.xml

```<code><!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.0.0.RELEASE</version>
</dependency>
</code>```

For more information you can check this

Title: Not able to use JpaReposiory?

Body:
I have already added the mysql connector dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

I have made a repository package and made an interface in it.

in that when I made an Interface, name Teacher

public interface TeacherRepository extends  JpaRe

when I press ctrl + space it is not auto completing meaning there is no available interface like that.

What could be the problem?

Body:
if you want use JpaRepository you must add Spring-data-jpa Dependency

Put this dependency to pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.0.0.RELEASE</version>
</dependency>

For more information you can check this


问:
How to dynamically append sections and use those to append other sections with JQuery?
Straight to the point. I have a problem with .append() function. I need to append a section, containing datetime-local and a button to another section, which is visible.

This new appended button must append another section, containing the same elements, but WITH DIFFERENT IDs. First part of the code is working, but second doesn’t and I can’t get why. I know my code is elegant like an elephant, but...

Your help is appreciated!

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_2">return</button>
');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var wrapper_2 = $(".input_2");
  var add_button_2 = $(".add_2");

  var x = 1;

  $(add_button_2).click(function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
    }
  });

  $(wrapper_2).on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="input_1">
  <input type="datetime-local"><br/>
  <button class="add_1">return to icu</button>
</section></code>```

答:
That's becuase when document.ready you set var wrapper_2 = $(".input_2"); but $(".input_2") is not existing yes, so it undefined.

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_2">return</button>
');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 3;

  var x = 1;

  $('body').on('click', '.add_2', function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(".input_2").append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
    }
  });

  $(".input_2").on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="input_1">
  <input type="datetime-local"><br/>
  <button class="add_1">return to icu</button>
</section></code>```

Body:
Straight to the point. I have a problem with .append() function. I need to append a section, containing datetime-local and a button to another section, which is visible.

This new appended button must append another section, containing the same elements, but WITH DIFFERENT IDs. First part of the code is working, but second doesn’t and I can’t get why. I know my code is elegant like an elephant, but...

Your help is appreciated!

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_2">return</button>
');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var wrapper_2 = $(".input_2");
  var add_button_2 = $(".add_2");

  var x = 1;

  $(add_button_2).click(function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
    }
  });

  $(wrapper_2).on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

  <input type="datetime-local">

  <button class="add_1">return to icu</button>

Body:
That's becuase when document.ready you set var wrapper_2 = $(".input_2"); but $(".input_2") is not existing yes, so it undefined.

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('<section class="input_2">-.-.-<br/><input type="datetime-local"><a href="#" class="remove_1">Remove</a><br /> <button class="add_2">return</button> </section>');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 3;

  var x = 1;

  $('body').on('click', '.add_2', function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(".input_2").append('<section>-.-.-<br/><input type="datetime-local"><a href="#" class="remove_2">Remove</a><br /> <button class="add_3">return 2</button> </section>');
    }
  });

  $(".input_2").on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="input_1">
  <input type="datetime-local"><br/>
  <button class="add_1">return to icu</button>
</section>


问:
Question regarding C loops
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

```<code>for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}
</code>```

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}
</code>```

Thanks!
Amit

答:
```<code>printf("%d", dat[nrow]);
</code>```

is not valid, because the nrow'th element of dat doesn't exist.

Title: Question regarding C loops

Body:
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}

Thanks!
Amit

Body:
printf("%d", dat[nrow]);

is not valid, because the nrow'th element of dat doesn't exist.


问:
Spring boot + Jackson. How to serialize collections which have null value as empty lists?
In my entity I have:

```<code>private Set<Account> accounts;
</code>```

Now it is being serialized like this:

```<code>"accounts": null
</code>```

I need to change it to

```<code>"accounts": []
</code>```

I have many (150+) entities which have this problem - how can configure jackson mapper to achieve this?

答:
I think declaring your set like this will work...

```<code>private Set<Account> accounts = new HashSet<>();
</code>```

It's then an empty set when marshalling and not null.

Body:
In my entity I have:

private Set<Account> accounts;

Now it is being serialized like this:

"accounts": null

I need to change it to

"accounts": []

I have many (150+) entities which have this problem - how can configure jackson mapper to achieve this?

Body:
I think declaring your set like this will work...

private Set<Account> accounts = new HashSet<>();

It's then an empty set when marshalling and not null.


问:
Enterprise Cobol 5.2 Debugger Linenumbers exceeded
I have the "wonderful" task of maintaining a legacy program that I didn't write. The Cobol program runs in a z/OS 2.2 environment and is compiled with IBM Enterprise Cobol 5.2. For debugging I would like to compile the program with the option CBL LIST, TEST (EJPD, SOURCE). Unfortunately, my source code has more than 999999 lines, so there is an error when compiling.
Is there a way to circumvent the limitation of the number of lines or is there only a way to split the program?

答:
Depending on the JES version, I believe you can you the WARNING parameter which would look something like this

```<code>//JOB10 JOB 1234,ME,LINES=(999999,WARNING)
</code>```

This tells the system to continue even if the line limit is hit and only issue a warning.

Alternatively, you could output this compile listing to a file rather than a SYSOUT. Then the line limit would not apply

Also keep in a mind the having that many line in the JES spool is not a good thing, so I would recommend going the file route.

Body:
Depending on the JES version, I believe you can you the WARNING parameter which would look something like this

//JOB10 JOB 1234,ME,LINES=(999999,WARNING)

This tells the system to continue even if the line limit is hit and only issue a warning.

Alternatively, you could output this compile listing to a file rather than a SYSOUT. Then the line limit would not apply

Also keep in a mind the having that many line in the JES spool is not a good thing, so I would recommend going the file route.


问:
Nested If Statement Using Case Statement in SQL Server
I inherited a spreadsheet from a co-worker who used a nested If statement as shown below:

```<code>  =IF(AND([@[Pred Type]]="PR_FS",[@[ST Finish]]="A"),
      0,
      IF(AND([@[Pred Type]]="PR_SS", OR([@[ACT_START_DATE]]<>0,[@[ST Start]]="A")),
         0,
         IF(AND([@[Pred Type]]="PR_SF",OR([@[ACT_START_DATE]]<>0,[@[ST Start]]="A")),
            0,
            IF(AND([@[Pred Type]]="PR_FF",[@[STFinish]]="A"),0,1)
           )
        )
     )
</code>```

I know I can write a CASE statement that would mimic this but can't figure out the syntax for it. I tried:

```<code>,CASE   WHEN #Preds.Pred_Type = 'PR_FS' and #Tbl_Sched_Act.Expected_Finish = 'A' THEN 0
    WHEN #Preds.Pred_Type = 'PR_SS' OR ACT_START_DATE IS NOT NULL OR Start_RAW IS NOT NULL THEN 0
    WHEN #Preds.Pred_Type = 'PR_SF'OR ACT_START_DATE IS NOT NULL OR Start_RAW IS NOT NULL THEN 0
    WHEN #Preds.Pred_Type = 'PR_FF' and #Tbl_Sched_Act.Expected_Finish = 'A' THEN 0
    ELSE 1
    END as PRED_MET
</code>```

However, the CASE statement does not evaluate any of the items to be equal to 1. They all evaluate to 0 which isn't correct.

Does anyone have any idea on how I could write my CASE statement correctly?

答:
You need to group the OR inside parenthesis () to force operator precedence.

```<code>CASE
    WHEN #Preds.Pred_Type = 'PR_FS' and #Tbl_Sched_Act.Expected_Finish = 'A'
    THEN 0
    WHEN #Preds.Pred_Type = 'PR_SS'
     AND (ACT_START_DATE <> 0 OR Start_RAW <> 0)
    THEN 0
    WHEN #Preds.Pred_Type = 'PR_SF'
     AND (ACT_START_DATE <> 0 OR Start_RAW <> 0)
    THEN 0
    WHEN #Preds.Pred_Type = 'PR_FF' and #Tbl_Sched_Act.Expected_Finish = 'A'
    THEN 0
    ELSE 1
END as PRED_MET
</code>```

NOTE:: If a number is <> 0 then also is NOT NULL DEMO

But that can also be simplify to:

```<code>CASE
    WHEN #Tbl_Sched_Act.Expected_Finish = 'A'
     AND #Preds.Pred_Type  IN ('PR_FS', 'PR_FF')
    THEN 0
    WHEN (ACT_START_DATE <> 0 OR Start_RAW <> 0)
     AND (#Preds.Pred_Type IN ('PR_SS','PR_SF')
    THEN 0
    ELSE 1
END as PRED_MET
</code>```

Body:
I inherited a spreadsheet from a co-worker who used a nested If statement as shown below:

  =IF(AND([@[Pred Type]]="PR_FS",[@[ST Finish]]="A"),
      0,
      IF(AND([@[Pred Type]]="PR_SS", OR([@[ACT_START_DATE]]<>0,[@[ST Start]]="A")),
         0,
         IF(AND([@[Pred Type]]="PR_SF",OR([@[ACT_START_DATE]]<>0,[@[ST Start]]="A")),
            0,
            IF(AND([@[Pred Type]]="PR_FF",[@[STFinish]]="A"),0,1)
           )
        )
     )

I know I can write a CASE statement that would mimic this but can't figure out the syntax for it. I tried:

,CASE   WHEN #Preds.Pred_Type = 'PR_FS' and #Tbl_Sched_Act.Expected_Finish = 'A' THEN 0
    WHEN #Preds.Pred_Type = 'PR_SS' OR ACT_START_DATE IS NOT NULL OR Start_RAW IS NOT NULL THEN 0
    WHEN #Preds.Pred_Type = 'PR_SF'OR ACT_START_DATE IS NOT NULL OR Start_RAW IS NOT NULL THEN 0
    WHEN #Preds.Pred_Type = 'PR_FF' and #Tbl_Sched_Act.Expected_Finish = 'A' THEN 0
    ELSE 1
    END as PRED_MET

However, the CASE statement does not evaluate any of the items to be equal to 1. They all evaluate to 0 which isn't correct.

Does anyone have any idea on how I could write my CASE statement correctly?

Body:
You need to group the OR inside parenthesis () to force operator precedence.

CASE
    WHEN #Preds.Pred_Type = 'PR_FS' and #Tbl_Sched_Act.Expected_Finish = 'A'
    THEN 0
    WHEN #Preds.Pred_Type = 'PR_SS'
     AND (ACT_START_DATE <> 0 OR Start_RAW <> 0)
    THEN 0
    WHEN #Preds.Pred_Type = 'PR_SF'
     AND (ACT_START_DATE <> 0 OR Start_RAW <> 0)
    THEN 0
    WHEN #Preds.Pred_Type = 'PR_FF' and #Tbl_Sched_Act.Expected_Finish = 'A'
    THEN 0
    ELSE 1
END as PRED_MET

NOTE:: If a number is <> 0 then also is NOT NULL DEMO

But that can also be simplify to:

CASE
    WHEN #Tbl_Sched_Act.Expected_Finish = 'A'
     AND #Preds.Pred_Type  IN ('PR_FS', 'PR_FF')
    THEN 0
    WHEN (ACT_START_DATE <> 0 OR Start_RAW <> 0)
     AND (#Preds.Pred_Type IN ('PR_SS','PR_SF')
    THEN 0
    ELSE 1
END as PRED_MET


问:
The sum amount from join tables is incorrect
I need to get the sum of the admin added into transactions. The transactions is splitted into multiple tables, and now i want to get a total from both tables separately. End up the results i'm getting is ridiculous high. I not sure is it my query multiplied the value somewhere.

```<code>User::select('user.name as name',
                DB::raw('sum(CASE WHEN current.amount > 0 THEN current.amount END) as current_positive'),
                DB::raw('sum(CASE WHEN current.amount < 0 THEN current.amount END) as current_negative'),
                DB::raw('sum(CASE WHEN cash.amount > 0 THEN cash.amount END) as cash_positive'),
                DB::raw('sum(CASE WHEN cash.amount < 0 THEN cash.amount END) as cash_negative')
                )->leftjoin('current_transaction as current', 'current.created_by', '=', 'user.id')
                ->leftjoin('cash_transaction as cash', 'cash.created_by', '=', 'user.id')
                ->whereBetween('current.created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
                ->whereBetween('cash.created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
                ->where('user.type', 3)
                ->groupBy('user.name')
                ->get();
</code>```

Update

I'm trying with the solution from M Khalid, and the following is the error message:

->mergeBindings($CUT)

Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to Illuminate\Database\Query\Builder::mergeBindings() must be an instance of Illuminate\Database\Query\Builder

->mergeBindings($CUT->getBindings())

Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to Illuminate\Database\Query\Builder::mergeBindings() must be an instance of Illuminate\Database\Query\Builder, array given

->addBinding($CUT)

ErrorException: Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

答:
You are getting wrong sum amount because of the left joins and each joined table may have more than one rows per user which makes the sum amount quite higher than the original one, to sort out this issue you need to calculation these sum amounts in indvidual sub clauses and then join these with main somewhat like

```<code>select users.name as name,cu.*,ca.*
from users
left join (
    select created_by,
    sum(CASE WHEN amount > 0 THEN amount END) as current_positive,
    sum(CASE WHEN amount < 0 THEN amount END) as current_negative
    from current_transaction
    where created_at between :start_date and :end_date
    group by created_by
) cu on users.id = cu.created_by
left join (
    select created_by,
    sum(CASE WHEN amount > 0 THEN amount END) as cash_positive,
    sum(CASE WHEN amount < 0 THEN amount END) as cash_negative
    from cash_transaction
    where created_at between :start_date and :end_date
    group by created_by
) ca on users.id = ca.created_by
where users.type = 3
</code>```

To do above in laravel is quite complex like for each sub clause get the sql and query builder object and then use them in main query somewhat like below

```<code>// For current_transaction
$CUT = CurrentTransaction::query()
    ->select('created_by',
              DB::raw('sum(CASE WHEN amount > 0 THEN amount END) as current_positive'),
              DB::raw('sum(CASE WHEN amount < 0 THEN amount END) as current_negative')
            )
    ->from('current_transaction')
    ->whereBetween('created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
    ->groupBy('created_by');
$CUTSql = $CUT->toSql();

// For cash_transaction
$CAT = CashTransaction::query()
    ->select('created_by',
              DB::raw('sum(CASE WHEN amount > 0 THEN amount END) as cash_positive'),
              DB::raw('sum(CASE WHEN amount < 0 THEN amount END) as cash_negative')
            )
    ->from('cash_transaction')
    ->whereBetween('created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
    ->groupBy('created_by');
$CATSql = $CAT->toSql();

// Main query
User::select('user.name as name','cu.*','ca.*')
    ->leftjoin(DB::raw('(' . $CUTSql. ') AS cu'),function($join) use ($CUT) {
            $join->on('user.id', '=', 'cu.created_by');
            /* ->addBinding($CUT->getBindings());*/
    })
    ->leftjoin(DB::raw('(' . $CATSql. ') AS ca'),function($join) use ($CAT) {
            $join->on('user.id', '=', 'ca.created_by');
            /* ->addBinding($CAT->getBindings());  */
    })
    ->where('user.type', 3)
    ->mergeBindings($CUT) /* or try with ->mergeBindings($CUT->getBindings()) */
    ->mergeBindings($CAT) /* or try with ->mergeBindings($CAT->getBindings()) */
    ->get();
</code>```

Body:
I need to get the sum of the admin added into transactions. The transactions is splitted into multiple tables, and now i want to get a total from both tables separately. End up the results i'm getting is ridiculous high. I not sure is it my query multiplied the value somewhere.

User::select('user.name as name',
                DB::raw('sum(CASE WHEN current.amount > 0 THEN current.amount END) as current_positive'),
                DB::raw('sum(CASE WHEN current.amount < 0 THEN current.amount END) as current_negative'),
                DB::raw('sum(CASE WHEN cash.amount > 0 THEN cash.amount END) as cash_positive'),
                DB::raw('sum(CASE WHEN cash.amount < 0 THEN cash.amount END) as cash_negative')
                )->leftjoin('current_transaction as current', 'current.created_by', '=', 'user.id')
                ->leftjoin('cash_transaction as cash', 'cash.created_by', '=', 'user.id')
                ->whereBetween('current.created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
                ->whereBetween('cash.created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
                ->where('user.type', 3)
                ->groupBy('user.name')
                ->get();

Update

I'm trying with the solution from M Khalid, and the following is the error message:

->mergeBindings($CUT)

Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to Illuminate\Database\Query\Builder::mergeBindings() must be an instance of Illuminate\Database\Query\Builder

->mergeBindings($CUT->getBindings())

Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to Illuminate\Database\Query\Builder::mergeBindings() must be an instance of Illuminate\Database\Query\Builder, array given

->addBinding($CUT)

ErrorException: Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

Body:
You are getting wrong sum amount because of the left joins and each joined table may have more than one rows per user which makes the sum amount quite higher than the original one, to sort out this issue you need to calculation these sum amounts in indvidual sub clauses and then join these with main somewhat like

select users.name as name,cu.*,ca.*
from users
left join (
    select created_by,
    sum(CASE WHEN amount > 0 THEN amount END) as current_positive,
    sum(CASE WHEN amount < 0 THEN amount END) as current_negative
    from current_transaction
    where created_at between :start_date and :end_date
    group by created_by
) cu on users.id = cu.created_by
left join (
    select created_by,
    sum(CASE WHEN amount > 0 THEN amount END) as cash_positive,
    sum(CASE WHEN amount < 0 THEN amount END) as cash_negative
    from cash_transaction
    where created_at between :start_date and :end_date
    group by created_by
) ca on users.id = ca.created_by
where users.type = 3

To do above in laravel is quite complex like for each sub clause get the sql and query builder object and then use them in main query somewhat like below

// For current_transaction
$CUT = CurrentTransaction::query()
    ->select('created_by',
              DB::raw('sum(CASE WHEN amount > 0 THEN amount END) as current_positive'),
              DB::raw('sum(CASE WHEN amount < 0 THEN amount END) as current_negative')
            )
    ->from('current_transaction')
    ->whereBetween('created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
    ->groupBy('created_by');
$CUTSql = $CUT->toSql();

// For cash_transaction
$CAT = CashTransaction::query()
    ->select('created_by',
              DB::raw('sum(CASE WHEN amount > 0 THEN amount END) as cash_positive'),
              DB::raw('sum(CASE WHEN amount < 0 THEN amount END) as cash_negative')
            )
    ->from('cash_transaction')
    ->whereBetween('created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
    ->groupBy('created_by');
$CATSql = $CAT->toSql();

// Main query
User::select('user.name as name','cu.*','ca.*')
    ->leftjoin(DB::raw('(' . $CUTSql. ') AS cu'),function($join) use ($CUT) {
            $join->on('user.id', '=', 'cu.created_by');
            /* ->addBinding($CUT->getBindings());*/
    })
    ->leftjoin(DB::raw('(' . $CATSql. ') AS ca'),function($join) use ($CAT) {
            $join->on('user.id', '=', 'ca.created_by');
            /* ->addBinding($CAT->getBindings());  */
    })
    ->where('user.type', 3)
    ->mergeBindings($CUT) /* or try with ->mergeBindings($CUT->getBindings()) */
    ->mergeBindings($CAT) /* or try with ->mergeBindings($CAT->getBindings()) */
    ->get();


问:
cordova-plugin-ble (evothings) WriteCharacteristics problems
I'm using cordova-plugin-ble of evothing and I can't send data to my device( HM10). I´m trying to send to bluetooth device a string ('a') but not working.

I have tried with these options also:

```<code> 1. 'a' letter en hexa
var data = '61';
 2. whit array
var data = new Unit8Array(2);
        data[0] = '6';
        data[2] = '1';
3. var data = new Unit8Array();
        data[0] = 'a';

4. var data = new Unit8Array();
        data[0] = '61';
</code>```

答:
I got it guys!. I was sending the information wrong, I found this function and implemented it in my code:

str2ab: function (str){
          var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
          var bufView = new Uint16Array(buf);
          for (var i = 0, strLen = str.length; i < strLen; i++) {
            bufView[i] = str.charCodeAt(i);

          return bufView;
        }
    }```

Body:
I'm using cordova-plugin-ble of evothing and I can't send data to my device( HM10). I´m trying to send to bluetooth device a string ('a') but not working.

I have tried with these options also:

 1. 'a' letter en hexa
var data = '61';
 2. whit array
var data = new Unit8Array(2);
        data[0] = '6';
        data[2] = '1';
3. var data = new Unit8Array();
        data[0] = 'a';

4. var data = new Unit8Array();
        data[0] = '61';


问:
stata15 dyndoc: markdown table
I've finally got the update for Stata 15, and one of the things I was excited about is the new functionality for dynamic documents. Although, I followed the steps described in the official stata tutorial, I was quickly disappointed when the html file dyndoc created failed to sparse the regression table. Here's what I did in the txt file:

```<code>~~~~
<<dd_do>>
webuse auto, clear
<</dd_do>>
~~~~

~~~~
<<dd_do: quietly>>
reg mpg weight
estimates store small
<</dd_do>>
~~~~

~~~~
<<dd_do:nocommand>>
_coef_table, markdown
<</dd_do>>
~~~~
</code>```

Since this has failed I've also tried the approach described here:

```<code>~~~~
<<dd_do:nocommand>>
estimates table small, b(%7.4f) se(%7.4f) stats(N r2_a) markdown
<</dd_do>>
~~~~
</code>```

This is how I sparse the txt with dyndoc:

```<code>dyndoc "`path'\auto.txt", saving(`path'\auto.html) replace
</code>```

The results in the html file look like this:

Any idea how to fix this?

I am running Stata SE 15.1 on Windows 10 Pro.

答:
I've managed, in case someone is looking at this. The problem was adding the ~~~~ as a wrapper around the code snippet. As the help file explains (p.177), the tildes are used to mark the parts which should be displayed as plain text. The correct code for the regression table is:

```<code>~~~~
<<dd_do>>
webuse auto, clear
<</dd_do>>
~~~~

<<dd_do: quietly>>
reg mpg weight
estimates store small
<</dd_do>>

<<dd_do:nocommand>>
_coef_table, markdown
<</dd_do>>
</code>```

Title: stata15 dyndoc: markdown table

Body:
I've finally got the update for Stata 15, and one of the things I was excited about is the new functionality for dynamic documents. Although, I followed the steps described in the official stata tutorial, I was quickly disappointed when the html file dyndoc created failed to sparse the regression table. Here's what I did in the txt file:

~~~~
<<dd_do>>
webuse auto, clear
<</dd_do>>
~~~~

~~~~
<<dd_do: quietly>>
reg mpg weight
estimates store small
<</dd_do>>
~~~~

~~~~
<<dd_do:nocommand>>
_coef_table, markdown
<</dd_do>>
~~~~

Since this has failed I've also tried the approach described here:

~~~~
<<dd_do:nocommand>>
estimates table small, b(%7.4f) se(%7.4f) stats(N r2_a) markdown
<</dd_do>>
~~~~

This is how I sparse the txt with dyndoc:

dyndoc "`path'\auto.txt", saving(`path'\auto.html) replace

The results in the html file look like this:

Any idea how to fix this?

I am running Stata SE 15.1 on Windows 10 Pro.

Body:
I've managed, in case someone is looking at this. The problem was adding the ~~~~ as a wrapper around the code snippet. As the help file explains (p.177), the tildes are used to mark the parts which should be displayed as plain text. The correct code for the regression table is:

~~~~
<<dd_do>>
webuse auto, clear
<</dd_do>>
~~~~

<<dd_do: quietly>>
reg mpg weight
estimates store small
<</dd_do>>

<<dd_do:nocommand>>
_coef_table, markdown
<</dd_do>>


问:
__doPostBack is not defined
Im getting that error when try to call a __doPostBack on one of my pages, every page that i have in the project use __doPostBack function but in this particular page im getting that Javascript error.

i was looking in the internet and the only thing i read is that this error happends when i have a unclose  tag but i review the site and its ok.

Error: __doPostBack is not defined
Source File: htt://localhost:99/ProjectName/Disable.aspx
Line: 1

答:
Here's why this was happening to me: I accidentally forgot that script tags must always have closing tags:

```<code><script src="/Scripts/appLogic/Regions.js" />
</code>```

I corrected the script tag:

```<code><script src="/Scripts/appLogic/Regions.js" type="text/javascript" ></script>
</code>```

and sanity returned.

Title: __doPostBack is not defined

Body:
Here's why this was happening to me: I accidentally forgot that script tags must always have closing tags:

<script src="/Scripts/appLogic/Regions.js" />

I corrected the script tag:

<script src="/Scripts/appLogic/Regions.js" type="text/javascript" ></script>

and sanity returned.


问:
Status bar is hidden but the tint is still seen
I have an Android app which has a activity that plays a video. While usually some activities in my app have dynamic status bar color, I have hidden the status bar when the video activity is in landscape. But even if I hide the status bar by fullscreen, the tint for the status bar still remains. Please tell me how I can hide the status bar tint.

Code for setting the status bar color

```<code> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(((Activity) context));
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setNavigationBarTintEnabled(false);
                tintManager.setTintColor(Color.parseColor("#" + dynamicColor));
                float f = Float.parseFloat(".7");
                tintManager.setTintAlpha(f);
            }
</code>```

The code I use for removing the status bar color

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                tintManager.setStatusBarTintEnabled(false);
                tintManager.setNavigationBarTintEnabled(false);
                float f = Float.parseFloat("0");
                tintManager.setTintAlpha(f);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
</code>```

Now in the tint removing code, I have set the flag setStatusBarEnabled to false. Even setStatusBarColor  is TRANSPARENT. Any help will be greatly appreciated.

答:
Try to add this code in onCreate()

Kotlin:

```<code>window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
</code>```

Java: ( not sure )

```<code>getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
</code>```

Body:
I have an Android app which has a activity that plays a video. While usually some activities in my app have dynamic status bar color, I have hidden the status bar when the video activity is in landscape. But even if I hide the status bar by fullscreen, the tint for the status bar still remains. Please tell me how I can hide the status bar tint.

Code for setting the status bar color

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(((Activity) context));
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setNavigationBarTintEnabled(false);
                tintManager.setTintColor(Color.parseColor("#" + dynamicColor));
                float f = Float.parseFloat(".7");
                tintManager.setTintAlpha(f);
            }

The code I use for removing the status bar color

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                tintManager.setStatusBarTintEnabled(false);
                tintManager.setNavigationBarTintEnabled(false);
                float f = Float.parseFloat("0");
                tintManager.setTintAlpha(f);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }

Now in the tint removing code, I have set the flag setStatusBarEnabled to false. Even setStatusBarColor  is TRANSPARENT. Any help will be greatly appreciated.

Body:
Try to add this code in onCreate()

Kotlin:

window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)

Java: ( not sure )

getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)


问:
VHDL: How to convert an iterator of generate block to std_logic_vector?
I want to get binary std_logic_vector from integer inside the generate.

For example,

0 -> 0000

1 -> 0001

2 -> 0010

...

15 -> 1111

I could write 16 if-else statements for each integer number, but I don't like this idea. (What if I will have much more than 16 integer numbers?)

I've tried to use two methods, but neither of them works:
address and hit are both std_logic_vector

```<code>G_1 : for i in 0 to 15 generate
    address <= conv_std_logic_vector(i, 4) when hit(i) = '1';
end generate G_1;

G_2 : for i in 0 to 15 generate
    address <= std_logic_vector(to_unsigned(i, 4)) when hit(i) = '1';
end generate G_2;
</code>```

Also I noticed that if I use number instead of the i, it works. (Example: I get "0101" when I use conv_std_logic_vector(5, 4))

What am I doing wrong? Is there any possible way to do it using vhdl?

答:
For a start, do not use ieee.std_logic_arith.all. Instead, use ieee.numeric_std.all, and get rid of any nasty conv_integer functions; the preferred style is to use types like unsigned, and then convert or cast these as you have in your second code example.

Moving on to your loop, you are using generate loop:

```<code>G_1 : for i in 0 to 15 generate
  address <= conv_std_logic_vector(i, 4) when hit(i) = '1';
end generate G_1;
</code>```

This will generate 16 lines of the form:

```<code>address <= conv_std_logic_vector(0, 4) when hit(0) = '1';
address <= conv_std_logic_vector(1, 4) when hit(1) = '1';
address <= conv_std_logic_vector(2, 4) when hit(2) = '1';
</code>```

etc. Since each concurrent assignment infers its own process, your design will have multiple drivers on the address signal, which is not allowed in a synthesis-eligible design.

It seems like the objective is to set address according to the lowest set ('1') bit in the hit vector. This is called a priority encoder. Something like this would be better:

```<code>process (hit)
begin
  for i in 0 to 15 loop
    address <= (others => '0');  -- Default assignment, any later assignment takes priority
    if (hit(i) = '1') then
      address <= std_logic_vector(to_unsigned(i, address`length));
      exit;
    end if;
  end loop;
end process;
</code>```

Since address seems to represent an unsigned number, you could use type unsigned for this signal, and save a type cast.

Body:
I want to get binary std_logic_vector from integer inside the generate.

For example,

0 -> 0000

1 -> 0001

2 -> 0010

...

15 -> 1111

I could write 16 if-else statements for each integer number, but I don't like this idea. (What if I will have much more than 16 integer numbers?)

I've tried to use two methods, but neither of them works:
address and hit are both std_logic_vector

G_1 : for i in 0 to 15 generate
    address <= conv_std_logic_vector(i, 4) when hit(i) = '1';
end generate G_1;

G_2 : for i in 0 to 15 generate
    address <= std_logic_vector(to_unsigned(i, 4)) when hit(i) = '1';
end generate G_2;

Also I noticed that if I use number instead of the i, it works. (Example: I get "0101" when I use conv_std_logic_vector(5, 4))

What am I doing wrong? Is there any possible way to do it using vhdl?

Body:
For a start, do not use ieee.std_logic_arith.all. Instead, use ieee.numeric_std.all, and get rid of any nasty conv_integer functions; the preferred style is to use types like unsigned, and then convert or cast these as you have in your second code example.

Moving on to your loop, you are using generate loop:

G_1 : for i in 0 to 15 generate
  address <= conv_std_logic_vector(i, 4) when hit(i) = '1';
end generate G_1;

This will generate 16 lines of the form:

address <= conv_std_logic_vector(0, 4) when hit(0) = '1';
address <= conv_std_logic_vector(1, 4) when hit(1) = '1';
address <= conv_std_logic_vector(2, 4) when hit(2) = '1';

etc. Since each concurrent assignment infers its own process, your design will have multiple drivers on the address signal, which is not allowed in a synthesis-eligible design.

It seems like the objective is to set address according to the lowest set ('1') bit in the hit vector. This is called a priority encoder. Something like this would be better:

process (hit)
begin
  for i in 0 to 15 loop
    address <= (others => '0');  -- Default assignment, any later assignment takes priority
    if (hit(i) = '1') then
      address <= std_logic_vector(to_unsigned(i, address`length));
      exit;
    end if;
  end loop;
end process;

Since address seems to represent an unsigned number, you could use type unsigned for this signal, and save a type cast.


问:
How to use properly BigInteger methods in Java?
I'm trying to do the factorial of a number using this method:

```<code>public static BigInteger factorial (long n) {
    BigInteger result = BigInteger.ONE;
    for(BigInteger i = BigInteger.TWO; i.compareTo(BigInteger.valueOf(n)) >= 0; i = i.add(BigInteger.ONE)) {
        result = result.multiply(i);
    }
    return result;
}
</code>```

and I'm asking why te result stays always 1 (BigInteger.ONE) ?

答:
```<code>i.compareTo(BigInteger.valueOf(n)) >= 0
</code>```

is wrong, instead use

```<code>i.compareTo(BigInteger.valueOf(n)) <= 0
</code>```

Body:
I'm trying to do the factorial of a number using this method:

public static BigInteger factorial (long n) {
    BigInteger result = BigInteger.ONE;
    for(BigInteger i = BigInteger.TWO; i.compareTo(BigInteger.valueOf(n)) >= 0; i = i.add(BigInteger.ONE)) {
        result = result.multiply(i);
    }
    return result;
}

and I'm asking why te result stays always 1 (BigInteger.ONE) ?

Body:
i.compareTo(BigInteger.valueOf(n)) >= 0

is wrong, instead use

i.compareTo(BigInteger.valueOf(n)) <= 0


问:
read file from Azure Blob Storage into Azure SQL Database
I have already tested this design using a local SQL Server Express set-up.

I uploaded several .json files to Azure Storage
In SQL Database, I created an External Data source:

CREATE EXTERNAL DATA SOURCE MyAzureStorage
  WITH
   (TYPE = BLOB_STORAGE,
    LOCATION = 'https://mydatafilestest.blob.core.windows.net/my_dir
    );

Then I tried to query the file using my External Data Source:

```<code>select *
from OPENROWSET
 (BULK 'my_test_doc.json', DATA_SOURCE = 'MyAzureStorage', SINGLE_CLOB) as data
</code>```

However, this failed with the error message "Cannot bulk load. The file "prod_EnvBlow.json" does not exist or you don't have file access rights."

Do I need to configure a DATABASE SCOPED CREDENTIAL to access the file storage, as described here?
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-database-scoped-credential-transact-sql

What else can anyone see that has gone wrong and I need to correct?

答:
Now that OPENROWSET is in public preview, the following works. Nb the key option is in case your blob is not public. I tried it on a private blob with the scoped credential option and it worked. nnb if you are using a SAS key make sure you delete the leading ? so the string should start with sv as shown below.

Make sure the blobcontainer/my_test_doc.json section specifies the correct path e.g. container/file.

```<code>CREATE DATABASE SCOPED CREDENTIAL MyAzureBlobStorageCredential
WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
SECRET = 'sv=2017****************';

CREATE EXTERNAL DATA SOURCE MyAzureBlobStorage
WITH ( TYPE = BLOB_STORAGE,
   LOCATION = 'https://yourstorage.blob.core.windows.net',
   CREDENTIAL= MyAzureBlobStorageCredential);

DECLARE @json varchar(max)
SELECT @json = BulkColumn FROM OPENROWSET(BULK 'blobcontainer/my_test_doc.json',
SINGLE_BLOB, DATA_SOURCE = 'MyAzureBlobStorage',
            FORMATFILE_DATA_SOURCE = 'MyAzureBlobStorage') as j;

select @json;
</code>```

More detail provided in these docs

Body:
I have already tested this design using a local SQL Server Express set-up.

I uploaded several .json files to Azure Storage
In SQL Database, I created an External Data source:

CREATE EXTERNAL DATA SOURCE MyAzureStorage
  WITH
   (TYPE = BLOB_STORAGE,
    LOCATION = 'https://mydatafilestest.blob.core.windows.net/my_dir
    );

Then I tried to query the file using my External Data Source:

select *
from OPENROWSET
 (BULK 'my_test_doc.json', DATA_SOURCE = 'MyAzureStorage', SINGLE_CLOB) as data

However, this failed with the error message "Cannot bulk load. The file "prod_EnvBlow.json" does not exist or you don't have file access rights."

Do I need to configure a DATABASE SCOPED CREDENTIAL to access the file storage, as described here?
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-database-scoped-credential-transact-sql

What else can anyone see that has gone wrong and I need to correct?

Body:
Now that OPENROWSET is in public preview, the following works. Nb the key option is in case your blob is not public. I tried it on a private blob with the scoped credential option and it worked. nnb if you are using a SAS key make sure you delete the leading ? so the string should start with sv as shown below.

Make sure the blobcontainer/my_test_doc.json section specifies the correct path e.g. container/file.

CREATE DATABASE SCOPED CREDENTIAL MyAzureBlobStorageCredential
WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
SECRET = 'sv=2017****************';

CREATE EXTERNAL DATA SOURCE MyAzureBlobStorage
WITH ( TYPE = BLOB_STORAGE,
   LOCATION = 'https://yourstorage.blob.core.windows.net',
   CREDENTIAL= MyAzureBlobStorageCredential);

DECLARE @json varchar(max)
SELECT @json = BulkColumn FROM OPENROWSET(BULK 'blobcontainer/my_test_doc.json',
SINGLE_BLOB, DATA_SOURCE = 'MyAzureBlobStorage',
            FORMATFILE_DATA_SOURCE = 'MyAzureBlobStorage') as j;

select @json;

More detail provided in these docs


问:
python manipulating list after user input
```<code>months=['January','February','March','April','May','June','July','August','September','October','November','December']
usermonth=input('Enter the month: ')
if usermonth >=months[0]and usermonth <=months[10]:
   nextmonth=months(usermonth+1)
   print(nextmonth)
</code>```

How would I go about defining one up in the index of the user's month?
Thanks.

答:
I suppose you're trying to display the month after the one supplied by the user:

```<code> months.index(usermonth)
</code>```

will give you the index (in the months list) of the months supplied by the user.

Then you can test if your month's index is not above 11:

```<code>months=['January','February','March','April','May','June','July','August','September','October','November','December']
usermonth=input('Enter the month: ')
if months.index(usermonth) < 11:
   print(months[months.index(usermonth) + 1])
</code>```

Body:
months=['January','February','March','April','May','June','July','August','September','October','November','December']
usermonth=input('Enter the month: ')
if usermonth >=months[0]and usermonth <=months[10]:
   nextmonth=months(usermonth+1)
   print(nextmonth)

How would I go about defining one up in the index of the user's month?
Thanks.

Body:
I suppose you're trying to display the month after the one supplied by the user:

 months.index(usermonth)

will give you the index (in the months list) of the months supplied by the user.

Then you can test if your month's index is not above 11:

months=['January','February','March','April','May','June','July','August','September','October','November','December']
usermonth=input('Enter the month: ')
if months.index(usermonth) < 11:
   print(months[months.index(usermonth) + 1])


问:
Reading data from firebase in ionic 3
I want read data from firebase database with ionic 3

I'm using this code but it's giving me error property subscribe does not exist on type AngularFireObject

```<code>this.db.object('/incident').subscribe(data => {

this.items = data;

  })
</code>```

Meanwhile I was able to send data to the firebase using the following code

```<code>sendIncident(){

this.db.list('/incident').push({
    title: this.title.value,
    detail: this.detail.value
})
 }
</code>```

I will appreciate any idea on how to overcome this

答:
You have to use something like this:</p>

```<code>this.subscription = this.db.list('/notes').valueChanges().subscribe(data =>{
 })
</code>```

Title: Reading data from firebase in ionic 3

Body:
I want read data from firebase database with ionic 3

I'm using this code but it's giving me error property subscribe does not exist on type AngularFireObject

this.db.object('/incident').subscribe(data => {

this.items = data;

  })

Meanwhile I was able to send data to the firebase using the following code

sendIncident(){

this.db.list('/incident').push({
    title: this.title.value,
    detail: this.detail.value
})
 }

I will appreciate any idea on how to overcome this

Body:
You have to use something like this:

this.subscription = this.db.list('/notes').valueChanges().subscribe(data =>{
 })


问:
Printer doesn't work receiving esc/p commands
I'm trying to start working with ESC/P commands with a label printer Brother TD-4000.
I have tested the properly software of the printer, P-touch Editor 5.1, and I can made several labels, the printer works well but, when I'm tried to make my own labels from Java code, the printer doesn't work at all, it doesn't response.
I've have worked with other label printers with EZPL and I hadn't any problems with this method.
What do I can try now?

My code is very simple, here you are:

```<code>public class PrintESC_P {
    public static void main(String[] args) {
        PrintService printService = null;
        String printerName = "Brother TD-4000";
        HashAttributeSet attributeSet = new HashAttributeSet();
        attributeSet.add(new PrinterName(printerName, null));
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, attributeSet);
        if (services.length == 0) {
            throw new IllegalArgumentException("Printer not found.");
        } else if (services.length > 1) {
            System.out.println("Found more than one printer. Only the first printer will be used.");
        }
        printService = services[0];
        System.out.println("Printer found: "+printService.getName());
        try {
            DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
            String _ESC_P_Code = "ESC i a 00h\r\n"  +
                    "ESC @\r\n" +
                    "ESC i L 01h\r\n" +
                    "ESC ( C 02h 00h FCh 02h\r\n" +
                    "ESC $ 2Bh 00h\r\n" +
                    "ESC ( V 02h 00h 6Dh 01h\r\n" +
                    "ESC k 0bh\r\n" +
                    "ESC X 00h 64h 00h\r\n" +
                    "PRINTER TEST\r\n" +
                    "ESC i C\r\n" +
                    "FF\r\n";
            SimpleDoc doc = new SimpleDoc(_ESC_P_Code.getBytes(), flavor, null);
            DocPrintJob job = printService.createPrintJob();
            job.print(doc, null);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
}
</code>```

Thanks in advance!

答:
I believe your problem is you are including spaces in the string, which is not allowed in ESC/P language.

Instead of (incorrect) string:

```<code>String _ESC_P_Code = "ESC i a 00h\r\n"
</code>```

You must write:

```<code>String _ESC_P_Code = "\x1Bia\x00" // that is 4 bytes: 0x1B, 0x69, 0x61, 0x00
</code>```

You do not have to follow the way I wrote the string, just make sure you are sending raw data.

I solved my problems printing in ESC/P by first debugging the program and viewing the string sent to the printer in binary form, and manually checking if there are no extra bytes - printer will not accept any such errors.

Body:
I'm trying to start working with ESC/P commands with a label printer Brother TD-4000.
I have tested the properly software of the printer, P-touch Editor 5.1, and I can made several labels, the printer works well but, when I'm tried to make my own labels from Java code, the printer doesn't work at all, it doesn't response.
I've have worked with other label printers with EZPL and I hadn't any problems with this method.
What do I can try now?

My code is very simple, here you are:

public class PrintESC_P {
    public static void main(String[] args) {
        PrintService printService = null;
        String printerName = "Brother TD-4000";
        HashAttributeSet attributeSet = new HashAttributeSet();
        attributeSet.add(new PrinterName(printerName, null));
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, attributeSet);
        if (services.length == 0) {
            throw new IllegalArgumentException("Printer not found.");
        } else if (services.length > 1) {
            System.out.println("Found more than one printer. Only the first printer will be used.");
        }
        printService = services[0];
        System.out.println("Printer found: "+printService.getName());
        try {
            DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
            String _ESC_P_Code = "ESC i a 00h\r\n"  +
                    "ESC @\r\n" +
                    "ESC i L 01h\r\n" +
                    "ESC ( C 02h 00h FCh 02h\r\n" +
                    "ESC $ 2Bh 00h\r\n" +
                    "ESC ( V 02h 00h 6Dh 01h\r\n" +
                    "ESC k 0bh\r\n" +
                    "ESC X 00h 64h 00h\r\n" +
                    "PRINTER TEST\r\n" +
                    "ESC i C\r\n" +
                    "FF\r\n";
            SimpleDoc doc = new SimpleDoc(_ESC_P_Code.getBytes(), flavor, null);
            DocPrintJob job = printService.createPrintJob();
            job.print(doc, null);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }
}

Thanks in advance!

Body:
I believe your problem is you are including spaces in the string, which is not allowed in ESC/P language.

Instead of (incorrect) string:

String _ESC_P_Code = "ESC i a 00h\r\n"

You must write:

String _ESC_P_Code = "\x1Bia\x00" // that is 4 bytes: 0x1B, 0x69, 0x61, 0x00

You do not have to follow the way I wrote the string, just make sure you are sending raw data.

I solved my problems printing in ESC/P by first debugging the program and viewing the string sent to the printer in binary form, and manually checking if there are no extra bytes - printer will not accept any such errors.


问:
can't find tensorflow local in Pycharm project Interpreters

I am new to tensorflow,

OS: Mac 10.13.1

Python: 2.7

tensorflow: 1.4.0(install with pip)

I want to use tensorflow from Pycharm for a project, and when I open:

"Pycharm" - "Preferences" - "Project Interpreter", There are only two local:

2.7.13/(Library/Frameworks/Python.framework.Versions.2.7/bin/python2.7)

/System/Library/Frameworks.Python.framwork.Versions.2,7.bin.python2.7

I can't find tensorflow, what should I do?

答: Click on the python 2.7 that you see. Then after you select you python you will see all the packages that come with it. One of the packages will be Tensorflow.</p>


问:
How to check if image exists in Gallery or not?
In my application when a user captures the image before saving into the gallery.

I want to check is there any image matches with the current image (at least 50%). If any image found get the image from gallery and display to the user.

I am very new to android development. Can anyone help me out to do above task.

答:
You'll have to use a Java library for this. I suggest taking a look at this thread.

If you'd like to develop something on your own, the basic idea is this. To compare two images, represent each of them as a matrix of pixels and compute similarity between those two matrices. If you do choose to implement it yourself, take a look at matrix similarity, cosine similarity in particular. A very simple example is here.

Good luck!


问:
The uploaded file exceeds the upload_max_filesize directive in php.ini error while uploading plugin
When I tried to upload a plugin for my Wordpress template in wamp 2.0 I got an error:

The uploaded file exceeds the upload_max_filesize directive in php.ini

How to fix this error?

答:
I use MAMP. To locate the 'php.ini' file, if you also use MAMP, the way Is as follows:

Go to the folder location where the MAMP is installed. For example, 'C:\MAMP' Is the folder location of MAMP.

Go to 'conf' folder.

From 'localhost:8888/MAMP', you will get 'phpinfo' link under PHP section. Click on the link and from the directed page, get the version of PHP is installed into your system.

From 'conf' folder, go to the folder with the version of PHP you got in the previous step.

Go to that folder and you will get the required php.ini file.

Open that file in any text editor and update the info:
(memory_limit = 64M, upload_max_filesize = 128M, post_max_size = 512M)

Restart MAMP.
Then you are good to go for uploading big files into your local server.

ContentLicense: CC BY-SA 4.0


问:
Is there a way to automatically collapse the Script Documents section in solution explorer?
While in debug mode, the solution explorer has a Script Documents section.  It is expanded by default.  As the debugger runs, new ScriptDocumentxxx poll.txt files are added to this section.  As I am navigating the explorer files, the adding of these new line items causes the entire contents of the explorer to shift downward.  This is quite annoying if I am trying to find a file or trying to click something.  I can collapse the section manually, but I'd rather not have to do this all of the time.

答:
Right click then 'Scope to This' to hide everything but the project in the solution you want to view.

Click on the Home/House icon to reverse it.


问:
trace method 'u' argument equivalent for trace_add?
Considering tkinter variable class' trace() method is deprecated since Python 3.6, new trace_add() method should be used:

trace('w', method) has become trace_add('write', method)

trace('r', method) has become trace_add('read', method)

I'm wondering how is the 'u' argument now specified?
For instance, consider the former:

trace('wu', method)

I can't find anything in the docs or anywhere else.

答:
In general, in such cases you can always fire up your REPL and call help on trace_add to examine its docstring.

```<code>>>> from tkinter import StringVar
>>> help(StringVar.trace_add)
</code>```

For trace_add the following is stated:

trace_add(self, mode, callback)

Define a trace callback for the variable.

Mode is one of "read", "write", "unset", or a list or tuple of
     such strings.
     Callback must be a function which is called when the variable is
     read, written or unset.

Return the name of the callback.

So, judging from that, 'wu' should now be ['write', 'unset'].

Body:
In general, in such cases you can always fire up your REPL and call help on trace_add to examine its docstring.

>>> from tkinter import StringVar
>>> help(StringVar.trace_add)

For trace_add the following is stated:

trace_add(self, mode, callback)

Define a trace callback for the variable.

Mode is one of "read", "write", "unset", or a list or tuple of
     such strings.
     Callback must be a function which is called when the variable is
     read, written or unset.

Return the name of the callback.

So, judging from that, 'wu' should now be ['write', 'unset'].


问:
Creating a FIFO Queue with Keypad Inputs
I'm trying to implement a FIFO queue for keypad inputs but cannot seem to get it to work. I'm able to get the keypad inputs to appear on an LCD screen but that is all I'm able to do. I think the code is supposed to read a keypad input and push it into a queue, then pop the keypad input and read the value onto an LCD screen. Could anyone advise on why it doesn't display all the values I've pressed? Thank you. </p>

```<code>#include "project.h"
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>

// Keypad Variables

char KeyPad[4][4] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'},
};

char ReadKeyPad();

// FIFO Variables

struct FIFO {
    char            key;
    struct  FIFO    *next;
};

struct FIFO KeyQueue[] = {
    {0, &KeyQueue[1]},  //[0]
    {0, &KeyQueue[2]},  //[1]
    {0, &KeyQueue[3]},  //[2]
    {0, &KeyQueue[4]},  //[3]
    {0, &KeyQueue[5]},  //[4]
    {0, &KeyQueue[6]},  //[5]
    {0, &KeyQueue[7]},  //[6]
    {0, &KeyQueue[8]},  //[7]
    {0, &KeyQueue[0]}   //[8]
};

struct FIFO *Head;
struct FIFO *Tail;
int KeyQueue_Size=0;
bool KeyQueue_IsEmpty();
bool KeyQueue_IsFull();
void KeyQueue_Push(char key);
char KeyQueue_Pop();
char ReadKeyPad();

int delay = 10;

int main(void)
{
    Head = Tail = &KeyQueue[0];
    char key;

    CyGlobalIntEnable; /* Enable global interrupts. */

    /* Place your initialization/startup code here (e.g. MyInst_Start()) */

    LCD_Start();
    LCD_ClearDisplay();
    LCD_Enable();

    for(;;)
    {
        /* Place your application code here. */
        key = ReadKeyPad();
        LCD_Position(1,8);
        LCD_PutChar(key);

        if (key !=0)
        {
            if (!KeyQueue_IsFull())
                KeyQueue_Push(key);
        }
        //task for poping key
        delay --;
        if(delay <= 0 && !KeyQueue_IsEmpty())
        {
            KeyQueue_Pop();
            switch (key)
            {
                case '1':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 1");
                break;
                case '2':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 2");
                break;
                case '3':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 3");
                break;
                case '4':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 4");
                break;
                case '5':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 5");
                break;
                case '6':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 6");
                break;
                case '7':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 7");
                break;
                case '8':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 8");
                break;
                case '9':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 9");
                break;
                case 'A':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed A");
                break;
                case 'B':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed B");
                break;
                case 'C':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed C");
                break;
                case 'D':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed D");
                break;
                case '*':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed *");
                break;
                case '#':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed #");
                break;
                case '0':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 0");
                break;
                delay = 10;
            }

            CyDelayUs(100);
        }

    }
}

bool KeyQueue_IsEmpty()
{
    if(KeyQueue_Size == 0) return true;
    return false;
}
bool KeyQueue_IsFull()
{
    //if (Head == Tail) return truel
    if(KeyQueue_Size ==9) return true;
    return false;
}
void KeyQueue_Push(char key)
{
    Head->key=key;
    Head = Head->next;
    KeyQueue_Size ++;
}
char KeyQueue_Pop()
{
    char key;
    key = Tail->key;
    Tail = Tail->next;
    KeyQueue_Size --;
    return key;
}
char ReadKeyPad()
{
    int     i;
    char    key;
    uint8_t col;

    for (i=0; i<4; i++)
    {
        key = 0;
        ROW_Write(1<<i);
        col=COL_Read();
        //LCD_Position(1,0);
        //LCD_PrintNumber(key);

        if (col & 0x01) key=KeyPad[i][0];
        if (col & 0x02) key=KeyPad[i][1];
        if (col & 0x04) key=KeyPad[i][2];
        if (col & 0x08) key=KeyPad[i][3];
        if (key != 0) break;
    }

    return key;
}
</code>```

答:
Some problems in your code:

As pointed before, delay = 10; is not well placed

key variable of main function is set only at the beginning of for loop.

So a corrected code could be:

```<code>for(;;)
{
    key = ReadKeyPad();
    LCD_Position(1,8);
    LCD_PutChar(key);

    if (key !=0)
    {
        if (!KeyQueue_IsFull())
            KeyQueue_Push(key);
    }
    //task for poping key
    delay --;
    if(delay <= 0 && !KeyQueue_IsEmpty())
    {
        /* don't forget to store what have been poped from fifo */
        key = KeyQueue_Pop();

        switch (key)
        {
            case '1':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 1");
                delay = 10;
            break;
            case '2':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 2");
                delay = 10;
            break;
            /*
             .
             .
             .
             */
            case '0':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 0");
                delay = 10;
            break;
        }

        CyDelayUs(100);
    }
}
</code>```

Maybe you can write it shorter:

```<code>for(;;)
{
    key = ReadKeyPad();
    LCD_Position(1,8);
    LCD_PutChar(key);

    if (key !=0)
    {
        if (!KeyQueue_IsFull())
            KeyQueue_Push(key);
    }
    //task for poping key
    delay --;
    if(delay <= 0 && !KeyQueue_IsEmpty())
    {
        /* don't forget to store what have been poped from fifo */
        key = KeyQueue_Pop();

        /* print what have been pressed */
        LCD_Position(0,1);
        LCD_PrintString("You pressed ");
        LCD_Position(0,12);
        LCD_PutChar(key);
        delay = 10;

        CyDelayUs(100);
    }
}
</code>```

Body:
I'm trying to implement a FIFO queue for keypad inputs but cannot seem to get it to work. I'm able to get the keypad inputs to appear on an LCD screen but that is all I'm able to do. I think the code is supposed to read a keypad input and push it into a queue, then pop the keypad input and read the value onto an LCD screen. Could anyone advise on why it doesn't display all the values I've pressed? Thank you.

#include "project.h"
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>

// Keypad Variables

char KeyPad[4][4] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'},
};

char ReadKeyPad();

// FIFO Variables

struct FIFO {
    char            key;
    struct  FIFO    *next;
};

struct FIFO KeyQueue[] = {
    {0, &KeyQueue[1]},  //[0]
    {0, &KeyQueue[2]},  //[1]
    {0, &KeyQueue[3]},  //[2]
    {0, &KeyQueue[4]},  //[3]
    {0, &KeyQueue[5]},  //[4]
    {0, &KeyQueue[6]},  //[5]
    {0, &KeyQueue[7]},  //[6]
    {0, &KeyQueue[8]},  //[7]
    {0, &KeyQueue[0]}   //[8]
};

struct FIFO *Head;
struct FIFO *Tail;
int KeyQueue_Size=0;
bool KeyQueue_IsEmpty();
bool KeyQueue_IsFull();
void KeyQueue_Push(char key);
char KeyQueue_Pop();
char ReadKeyPad();

int delay = 10;

int main(void)
{
    Head = Tail = &KeyQueue[0];
    char key;

    CyGlobalIntEnable; /* Enable global interrupts. */

    /* Place your initialization/startup code here (e.g. MyInst_Start()) */

    LCD_Start();
    LCD_ClearDisplay();
    LCD_Enable();

    for(;;)
    {
        /* Place your application code here. */
        key = ReadKeyPad();
        LCD_Position(1,8);
        LCD_PutChar(key);

        if (key !=0)
        {
            if (!KeyQueue_IsFull())
                KeyQueue_Push(key);
        }
        //task for poping key
        delay --;
        if(delay <= 0 && !KeyQueue_IsEmpty())
        {
            KeyQueue_Pop();
            switch (key)
            {
                case '1':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 1");
                break;
                case '2':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 2");
                break;
                case '3':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 3");
                break;
                case '4':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 4");
                break;
                case '5':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 5");
                break;
                case '6':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 6");
                break;
                case '7':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 7");
                break;
                case '8':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 8");
                break;
                case '9':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 9");
                break;
                case 'A':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed A");
                break;
                case 'B':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed B");
                break;
                case 'C':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed C");
                break;
                case 'D':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed D");
                break;
                case '*':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed *");
                break;
                case '#':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed #");
                break;
                case '0':
                    LCD_Position(0,1);
                    LCD_PrintString("You pressed 0");
                break;
                delay = 10;
            }

            CyDelayUs(100);
        }

    }
}

bool KeyQueue_IsEmpty()
{
    if(KeyQueue_Size == 0) return true;
    return false;
}
bool KeyQueue_IsFull()
{
    //if (Head == Tail) return truel
    if(KeyQueue_Size ==9) return true;
    return false;
}
void KeyQueue_Push(char key)
{
    Head->key=key;
    Head = Head->next;
    KeyQueue_Size ++;
}
char KeyQueue_Pop()
{
    char key;
    key = Tail->key;
    Tail = Tail->next;
    KeyQueue_Size --;
    return key;
}
char ReadKeyPad()
{
    int     i;
    char    key;
    uint8_t col;

    for (i=0; i<4; i++)
    {
        key = 0;
        ROW_Write(1<<i);
        col=COL_Read();
        //LCD_Position(1,0);
        //LCD_PrintNumber(key);

        if (col & 0x01) key=KeyPad[i][0];
        if (col & 0x02) key=KeyPad[i][1];
        if (col & 0x04) key=KeyPad[i][2];
        if (col & 0x08) key=KeyPad[i][3];
        if (key != 0) break;
    }

    return key;
}

Body:
Some problems in your code:

As pointed before, delay = 10; is not well placed

key variable of main function is set only at the beginning of for loop.

So a corrected code could be:

for(;;)
{
    key = ReadKeyPad();
    LCD_Position(1,8);
    LCD_PutChar(key);

    if (key !=0)
    {
        if (!KeyQueue_IsFull())
            KeyQueue_Push(key);
    }
    //task for poping key
    delay --;
    if(delay <= 0 && !KeyQueue_IsEmpty())
    {
        /* don't forget to store what have been poped from fifo */
        key = KeyQueue_Pop();

        switch (key)
        {
            case '1':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 1");
                delay = 10;
            break;
            case '2':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 2");
                delay = 10;
            break;
            /*
             .
             .
             .
             */
            case '0':
                LCD_Position(0,1);
                LCD_PrintString("You pressed 0");
                delay = 10;
            break;
        }

        CyDelayUs(100);
    }
}

Maybe you can write it shorter:

for(;;)
{
    key = ReadKeyPad();
    LCD_Position(1,8);
    LCD_PutChar(key);

    if (key !=0)
    {
        if (!KeyQueue_IsFull())
            KeyQueue_Push(key);
    }
    //task for poping key
    delay --;
    if(delay <= 0 && !KeyQueue_IsEmpty())
    {
        /* don't forget to store what have been poped from fifo */
        key = KeyQueue_Pop();

        /* print what have been pressed */
        LCD_Position(0,1);
        LCD_PrintString("You pressed ");
        LCD_Position(0,12);
        LCD_PutChar(key);
        delay = 10;

        CyDelayUs(100);
    }
}


问:
Get value from another model in case of ManyToManyField
I want to get value from foreign key from another model and subscribe it.
It works when field is declared as ForeignKey but when field is declared as ManyToManyField it not works.
How can I do it?

Please help.

```<code>class Document(models.Model):
    project = models.ForeignKey(Project)
    text = models.ForeignKey(Text, null=True, blank=True)
    language = models.ManyToManyField(Language, null=True, blank=True)

    def save(self, *args, **kwargs):
        self.text = self.project.text                     #WORKS
        self.language  = self.project.language.all()      #NOT WORKS
        super(Document, self).save(*args, **kwargs)
</code>```

答:
Does something like this works?

```<code>class Document(models.Model):
    project = models.ForeignKey(Project)
    text = models.ForeignKey(Text, null=True, blank=True)
    languages = models.ManyToManyField(Language)  # no need to null/blank + put the name on plural if using a many to many relation.

    def save(self, *args, **kwargs):
        self.text = self.project.text
        super(Document, self).save(*args, **kwargs)

        # super() must be called BEFORE feeding your many to many.
        project_languages = self.project.languages.all()
        self.languages.add(*project_languages)
</code>```

When using a many to many field attribute, you need to wait for your instance is created before adding values in your many to many attribute.
You do this with add, contrary to foreign key fields.

Body:
I want to get value from foreign key from another model and subscribe it.
It works when field is declared as ForeignKey but when field is declared as ManyToManyField it not works.
How can I do it?

Please help.

class Document(models.Model):
    project = models.ForeignKey(Project)
    text = models.ForeignKey(Text, null=True, blank=True)
    language = models.ManyToManyField(Language, null=True, blank=True)

    def save(self, *args, **kwargs):
        self.text = self.project.text                     #WORKS
        self.language  = self.project.language.all()      #NOT WORKS
        super(Document, self).save(*args, **kwargs)

Body:
Does something like this works?

class Document(models.Model):
    project = models.ForeignKey(Project)
    text = models.ForeignKey(Text, null=True, blank=True)
    languages = models.ManyToManyField(Language)  # no need to null/blank + put the name on plural if using a many to many relation.

    def save(self, *args, **kwargs):
        self.text = self.project.text
        super(Document, self).save(*args, **kwargs)

        # super() must be called BEFORE feeding your many to many.
        project_languages = self.project.languages.all()
        self.languages.add(*project_languages)

When using a many to many field attribute, you need to wait for your instance is created before adding values in your many to many attribute.
You do this with add, contrary to foreign key fields.