问:
"MYSCHEMA.sessions" is an undefined name
When I try to connect to SESSIONS table which I created in the appropriate schema, I get this error:

[IBM][CLI Driver][DB2/LINUXX8664] SQL0204N "MYSCHEMA.sessions" is an undefined name. SQLSTATE=42704

I pass the DSN to the session like this:

```<code>var session = require("express-session")
  , Db2Store = require('connect-db2')(session);
var options = {
  dsn: 'DATABASE=MyDB;HOSTNAME=IpAddr;PORT=myPort;PROTOCOL=TCPIP;UID=db2_admin;PWD=db2_pwd;CurrentSchema=MYSCHEMA;'
}
var sessionStore = new Db2Store(options);
app.use(session({
  store: sessionStore,
  secret: "AAAAA:ZZZZZ:EEEEE"
}));
</code>```

Did I miss something here ?

答: Due to DB2 auto-capitalize issue: https://www.ibm.com/developerworks/data/library/techarticle/0203adamache/0203adamache.html#N1011C, I had to put table name, columns and As clause between quotes when creating sessions table and also inside the module in connect-db2/lib/connect-db2.js file</p>

Body:
When I try to connect to SESSIONS table which I created in the appropriate schema, I get this error:

[IBM][CLI Driver][DB2/LINUXX8664] SQL0204N "MYSCHEMA.sessions" is an undefined name. SQLSTATE=42704

I pass the DSN to the session like this:

var session = require("express-session")
  , Db2Store = require('connect-db2')(session);
var options = {
  dsn: 'DATABASE=MyDB;HOSTNAME=IpAddr;PORT=myPort;PROTOCOL=TCPIP;UID=db2_admin;PWD=db2_pwd;CurrentSchema=MYSCHEMA;'
}
var sessionStore = new Db2Store(options);
app.use(session({
  store: sessionStore,
  secret: "AAAAA:ZZZZZ:EEEEE"
}));

Did I miss something here ?


来源: stackexchange

问:
Scala/Java Redis In Memory
I'd like to write code that writes to Redis and I hate writing code that doesn't have unit tests, so I'm looking for an in-memory Redis in Scala or Java.

I've searched Dr. Google and came across a few mocks, they are all either unstable or not active (i.e. no commits in the past few months) and I'm looking for something closer to the real thing.

So the question is: an in-memory Redis available for Scala/Java?

答: instead of mocking redis you can use a redis container in your unit test using tools like https://github.com/whisklabs/docker-it-scala</p>

ContentLicense: CC BY-SA 3.0

Title: Scala/Java Redis In Memory


问:
How to make my internal callback function reactive for mobx state change?
I have created a internal callback function as below.

```<code>render() {
    const profiles = this
      .props
      .store
      .profiles;
    const renderCell = (rowIndex: number) => {
      console.log('rendering...');

      return <Cell>{profiles[rowIndex].alias}</Cell>;
    };
    return (
      <div className="profileList">
        <Table
          allowMultipleSelection={false}
          numRows={this.props.store.profiles.size}
          isRowHeaderShown={false}
          selectionModes={SelectionModes.ROWS_AND_CELLS}
          isColumnResizable={false}
          isRowResizable={false}
          defaultColumnWidth={1024}
          onSelection={(region) => this.onSelection(region)}
        >
          <Column name="Connection Profiles" renderCell={renderCell.bind(this)}/>
        </Table>
      </div>
    );
  }
</code>```

From above code, you can see that there is a renderCell function created inside the render() function. When I update the mbox state for profile.alias this function is not triggered. If I put the profile.alias under render() method directly, it works fine. How to make my renderCell reactive for state changes?

答:
If the Cell component is not external, you could decorate it with @observer

If it's external, you could wrap your function in observer, something like this:

```<code>const RenderCell = observer(({ rowIndex }) => {
    console.log('rendering...');

    return <Cell>{profiles[rowIndex].alias}</Cell>;
};
</code>```

There's great documentation about Understanding what MobX reacts to in their website, I recommend reading it, it helps you understand MobX better.

Body:
I have created a internal callback function as below.

render() {
    const profiles = this
      .props
      .store
      .profiles;
    const renderCell = (rowIndex: number) => {
      console.log('rendering...');

      return <Cell>{profiles[rowIndex].alias}</Cell>;
    };
    return (

 this.onSelection(region)}
        >
          <Column name="Connection Profiles" renderCell={renderCell.bind(this)}/>

    );
  }

From above code, you can see that there is a renderCell function created inside the render() function. When I update the mbox state for profile.alias this function is not triggered. If I put the profile.alias under render() method directly, it works fine. How to make my renderCell reactive for state changes?

Body:
If the Cell component is not external, you could decorate it with @observer

If it's external, you could wrap your function in observer, something like this:

const RenderCell = observer(({ rowIndex }) => {
    console.log('rendering...');

    return <Cell>{profiles[rowIndex].alias}</Cell>;
};

There's great documentation about Understanding what MobX reacts to in their website, I recommend reading it, it helps you understand MobX better.


问:
How to compare if any of the elements in a row is same
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

```<code>DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA
</code>```

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

```<code> > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)
</code>```

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

答:
This solution compares the two rows with %in% (after unlist()):

```<code>DT[, result:=as.integer(c(NA, sapply(2:DT[,.N], function(i) any(na.omit(unlist(DT[i])) %in% unlist(DT[i-1])))))]
#> DT
#   A  B  C result
#1: a  a  a     NA
#2: a  b  b      1
#3: b  c  c      1
#4: d  c  b      1
#5: e  f  g      0
#6: f  g  h      1
#7: h NA NA      1
#8: i  j NA      0
#9: j NA NA      1
</code>```

Body:
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

 > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

Body:
This solution compares the two rows with %in% (after unlist()):

DT[, result:=as.integer(c(NA, sapply(2:DT[,.N], function(i) any(na.omit(unlist(DT[i])) %in% unlist(DT[i-1])))))]
#> DT
#   A  B  C result
#1: a  a  a     NA
#2: a  b  b      1
#3: b  c  c      1
#4: d  c  b      1
#5: e  f  g      0
#6: f  g  h      1
#7: h NA NA      1
#8: i  j NA      0
#9: j NA NA      1


问:
Displaying TinyMCE plugins the correct way
I have a problem with the tinyMCE editor thats included with Joomla! 1.5 . I want to have the editor displayed in Simple mode, but I want to include the hyperlink button and I do not want the Format and Styles dropdown list to be included, I tried to switch from Advanced and Extended and adjusted every option included but I just could not get it to display the hyperlink button without displaying the Format and the Styles dropdown menu? Is there anything I can do about this, maybe hacking and modifying the code etc? Any advise is accepted. Thanks!!</p>

答:
When you think you all you need to do is to configure tinymce the right way - that is not the case.

You can use a slightly stripped down version of the advanced theme (maybe coming close to what you want); id do not know joomla that well, but it might be that you need to set the config variables in another way:

```<code>tinyMCE.init({
    mode : "textareas",
    theme : "advanced",
    theme_advanced_buttons1 : "bold,italic,underline,link,unlink,bullist,blockquote,undo",
});
</code>```

For sure you can code it yourself to make it work with the simple plugin (you would need to search through the core code in order to find the important parts in the code), but i would try to take the easier way.

ContentLicense: CC BY-SA 2.5

Body:
When you think you all you need to do is to configure tinymce the right way - that is not the case.

You can use a slightly stripped down version of the advanced theme (maybe coming close to what you want); id do not know joomla that well, but it might be that you need to set the config variables in another way:

tinyMCE.init({
    mode : "textareas",
    theme : "advanced",
    theme_advanced_buttons1 : "bold,italic,underline,link,unlink,bullist,blockquote,undo",
});

For sure you can code it yourself to make it work with the simple plugin (you would need to search through the core code in order to find the important parts in the code), but i would try to take the easier way.


问:
Django CMS per-site cache not working for CMS pages
I'm trying to setup Django's per-site cache (https://docs.djangoproject.com/en/1.10/topics/cache/#the-per-site-cache) with Django CMS and I can't get the cache to work for the CMS pages, however it works for apphooked pages.

This is a snippet of my settings:

```<code>MIDDLEWARE_CLASSES = [
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.gzip.GZipMiddleware',
    'htmlmin.middleware.HtmlMinifyMiddleware',
    'htmlmin.middleware.MarkRequestMiddleware',
    'cms.middleware.utils.ApphookReloadMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cms.middleware.language.LanguageCookieMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
]

CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = 'mysite-'
CMS_PAGE_CACHE = True

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'cache_table',
        'TIMEOUT' : 60*60*24,
        'OPTIONS': {
            'MAX_ENTRIES': 10000,
        }
    }
}
</code>```

If I navigate to an apphooked page, the response header is:

```<code>Cache-Control: max-age=60
</code>```

Which is correct. However with a CMS page I get the header:

```<code>Cache-Control: max-age=0, no-store, no-cache, must-revalidate
</code>```

Which is incorrect.

The Django CMS documentation (http://docs.django-cms.org/en/release-3.4.x/how_to/caching.html) says that the UpdateCacheMiddleware should be first FetchFromCacheMiddleware last, which is what I've done and have no luck.

I've restarted the server, tried updating content on the page and re-publishing but still having no luck.

What am I missing here?!

Any help would be much appreciated.

答:
After many hours of pain and suffering, I've finally managed to figure out the problem here. The problem was due was to the fact that I had a few custom plugins that I had set to not cache, eg:

```<code>from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

class MyPlugin(CMSPluginBase):
    name = 'My plugin'
    cache = False
    ...

plugin_pool.register_plugin(MyPlugin)
</code>```

On pages where there is a plugin set to not cache, the cache-control header is showing as:

```<code>Cache-Control: max-age=0, no-store, no-cache, must-revalidate
</code>```

Which I suppose is correct. If you remove the plugin from that page, you get the expected header:

```<code>Cache-Control: max-age=60
</code>```

Hopefully this helps somebody else one day.

Body:
I'm trying to setup Django's per-site cache (https://docs.djangoproject.com/en/1.10/topics/cache/#the-per-site-cache) with Django CMS and I can't get the cache to work for the CMS pages, however it works for apphooked pages.

This is a snippet of my settings:

MIDDLEWARE_CLASSES = [
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.gzip.GZipMiddleware',
    'htmlmin.middleware.HtmlMinifyMiddleware',
    'htmlmin.middleware.MarkRequestMiddleware',
    'cms.middleware.utils.ApphookReloadMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cms.middleware.language.LanguageCookieMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
]

CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = 'mysite-'
CMS_PAGE_CACHE = True

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'cache_table',
        'TIMEOUT' : 60*60*24,
        'OPTIONS': {
            'MAX_ENTRIES': 10000,
        }
    }
}

If I navigate to an apphooked page, the response header is:

Cache-Control: max-age=60

Which is correct. However with a CMS page I get the header:

Cache-Control: max-age=0, no-store, no-cache, must-revalidate

Which is incorrect.

The Django CMS documentation (http://docs.django-cms.org/en/release-3.4.x/how_to/caching.html) says that the UpdateCacheMiddleware should be first FetchFromCacheMiddleware last, which is what I've done and have no luck.

I've restarted the server, tried updating content on the page and re-publishing but still having no luck.

What am I missing here?!

Any help would be much appreciated.

Body:
After many hours of pain and suffering, I've finally managed to figure out the problem here. The problem was due was to the fact that I had a few custom plugins that I had set to not cache, eg:

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

class MyPlugin(CMSPluginBase):
    name = 'My plugin'
    cache = False
    ...

plugin_pool.register_plugin(MyPlugin)

On pages where there is a plugin set to not cache, the cache-control header is showing as:

Cache-Control: max-age=0, no-store, no-cache, must-revalidate

Which I suppose is correct. If you remove the plugin from that page, you get the expected header:

Cache-Control: max-age=60

Hopefully this helps somebody else one day.


问:
How to substring Android logcat output and show only the message itself
I would like to use logcat and output only the messages themselves.
Not the method name, not the time, not the tag - just the message.

Example, from this message:

D/ConnectivityService(  471): Setting tx/rx TCP buffers to
  524288,1048576,2097152,262144,524288,1048576

I only want the

Setting tx/rx TCP buffers to
  524288,1048576,2097152,262144,524288,1048576

Is that possible ?

答: Have a look at Jake Wharton's Pidcat.

Body: Have a look at Jake Wharton's Pidcat.


问:
Powershell Invoke-RestMethod "Unable to connect to the remote server"
I write a very simple powershell script to post a json string to server. I have a strange issue when I execute the script.

The server is inside our intranet, the firewall is disable for all intranet server.

I tried to execute the script in different places:

Powershell window in my own computer (windows 7, powershel 5)

Powershell ISE in my computer

start powershell.exe in a command prompt in my own computer

start powershell.exe in a third party command prompt application in my own computer

Powershell window in a citrix seesion (windows 10, powershel 5)

start powershell.exe in a command prompt in a citrix seesion

I checked all of 6 places have ExecutionPolicy "RemoteSigned",

But, I can only successfully execute the script in last 3 places,

In first 3 place, I get an error

```<code> Invoke-RestMethod : Unable to connect to the remote server
 At F:\Temp\test.ps1:46 char:9
 + $resp = Invoke-RestMethod -Method POST -Body $result ...
 +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 + CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod],
 WebException
 + FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Com
 mands.InvokeRestMethodCommand
</code>```

Besides, I also tried Invoke-WebRequest, I got same error message.

Any idea why this is happen? What should I do with it?

答:
I had similar issue few days back and I resolved it by applying the proxy settings in the "Invoke-WebRequest" call.

Something like this;

```<code>Invoke-WebRequest -URI $url -Proxy 'http://10.10.7.11:80' -ProxyCredential $creds
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I write a very simple powershell script to post a json string to server. I have a strange issue when I execute the script.

The server is inside our intranet, the firewall is disable for all intranet server.

I tried to execute the script in different places:

Powershell window in my own computer (windows 7, powershel 5)

Powershell ISE in my computer

start powershell.exe in a command prompt in my own computer

start powershell.exe in a third party command prompt application in my own computer

Powershell window in a citrix seesion (windows 10, powershel 5)

start powershell.exe in a command prompt in a citrix seesion

I checked all of 6 places have ExecutionPolicy "RemoteSigned",

But, I can only successfully execute the script in last 3 places,

In first 3 place, I get an error

 Invoke-RestMethod : Unable to connect to the remote server
 At F:\Temp\test.ps1:46 char:9
 + $resp = Invoke-RestMethod -Method POST -Body $result ...
 +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 + CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod],
 WebException
 + FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Com
 mands.InvokeRestMethodCommand

Besides, I also tried Invoke-WebRequest, I got same error message.

Any idea why this is happen? What should I do with it?

Body:
I had similar issue few days back and I resolved it by applying the proxy settings in the "Invoke-WebRequest" call.

Something like this;

Invoke-WebRequest -URI $url -Proxy 'http://10.10.7.11:80' -ProxyCredential $creds


问:
Navigation Item not visible in interface builder after adding segue
I have custom UIView, that uses .xib file. I'm adding this view in storyboard inside view controller. After that I added TapGestureRecognizer to it. Then I attach segue to tap gesture recognizer (no code needed to perform segue from custom view this way).

Problem is, navigation Item is not shown in interface builder. When I build and run app, navigation is on screen and everything works like expected.

When I add segue from VC to VC, navigation bar is shown in interface builder. Why I'm getting such behavior?

答:
That seems like a bug in Interface Builder to me.

I see two possible workarounds for this situation:

Wire the segue from ViewController to ViewController.  Give it an identifier.  Call it programmatically with performSegue(withIdentifier:sender:) in an @IBAction for your Tap Gesture Recognizer.  The downside of this is that you need to add code.

Add the Navigation Bar to your ViewController by setting Attributes Inspector -> Simulated Metrics -> Top Bar to Translucent Navigation Bar.  This allows you to see the Navigation Bar in Interface Builder. The downside of this is that you need to do this for every ViewController down the chain.


问:
How do I find a runtime list of all routes that ActiveAdmin has registered?
I have an activeadmin controller like

```<code>ActiveAdmin.register UserThing do

  action_item :moderate, only: [:show, :edit] do
    if resource.can_moderate?
      link_to 'Moderate', moderate_admin_user_thing_path(resource), target: :blank
    end
  end

  member_action :moderate do
    # This will render app/views/admin/user_thing/moderate.html.arb
  end

end
</code>```

The call to moderate_admin_user_thing_path fails with "undefined method".

the method isn't listed in methods.select{|e| e.to_s.match(/.*_path/) }

It is not in (ActionController::Base.helpers.methods - Object.methods).select{|e| e.to_s.match(/.*_path/) }

How can I find the registered routes, to see why the above route fails?

答:
The list can be found in </p>

```<code>ActiveAdmin::Helpers::Routes.methods
</code>```

Body:
I have an activeadmin controller like

ActiveAdmin.register UserThing do

  action_item :moderate, only: [:show, :edit] do
    if resource.can_moderate?
      link_to 'Moderate', moderate_admin_user_thing_path(resource), target: :blank
    end
  end

  member_action :moderate do
    # This will render app/views/admin/user_thing/moderate.html.arb
  end

end

The call to moderate_admin_user_thing_path fails with "undefined method".

the method isn't listed in methods.select{|e| e.to_s.match(/.*_path/) }

It is not in (ActionController::Base.helpers.methods - Object.methods).select{|e| e.to_s.match(/.*_path/) }

How can I find the registered routes, to see why the above route fails?

Body:
The list can be found in

ActiveAdmin::Helpers::Routes.methods


问:
Why aren't my tables being altered when I run sequelize.sync()?
When I run sequelize.sync(), it can create tables, but it doesn't alter existing ones, making it really difficult for development when I have to delete the tables every single time I want to make a change to the database.

Do I have to use migrations for development or is there a better way to do this?

答:
For development, there is now an option to sync the current tables by altering their structure. Using the latest version from the sequelize github repo, you can now run sync with the alter parameter.

```<code>Table.sync({alter: true})
</code>```

This will alter the table to fit into the new models, but please note that this may cause some data to be deleted if you are removing or changing columns.

Body:
For development, there is now an option to sync the current tables by altering their structure. Using the latest version from the sequelize github repo, you can now run sync with the alter parameter.

Table.sync({alter: true})

This will alter the table to fit into the new models, but please note that this may cause some data to be deleted if you are removing or changing columns.


问:
Django: choose 'company' from company model, if company not present create one
I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name.

```<code>class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company_name = models.CharField(max_length=254)
</code>```

Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB.
Suppose I have a Company model as such:

```<code>class Company(BaseModel):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name
</code>```

What should be my Field Choice in the UserProfile model for user_company_name field.

答:
Why don't just add ForeignKey to UserProfile model? Example below.

```<code>class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company = models.ForeignKey(Company)
</code>```

Body:
I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name.

class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company_name = models.CharField(max_length=254)

Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB.
Suppose I have a Company model as such:

class Company(BaseModel):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

What should be my Field Choice in the UserProfile model for user_company_name field.

Body:
Why don't just add ForeignKey to UserProfile model? Example below.

class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company = models.ForeignKey(Company)


问:
What to use instead of disable textarea?
Currently there is a bug in Firefox that doesn't let you to copy stuff from disabled textarea (in chrome it works fine) and I've been thinking how can I replace my code so that it works ok in firefox as well. i'm using GSP files but can use normal html tags within them as well.

Here is my code snippet:

```<code><g:textArea rows="5" cols="1" name="description" value="${forecast?.description}" class="description-t-area" disabled="${!canEdit}"/>
</code>```

And here is image how it looks on the web:

答:
You could use pre tag e.g.</p>

```<code><pre id="description" contenteditable="${!canEdit}">${forecast?.description}```
</code>```

Body:
Currently there is a bug in Firefox that doesn't let you to copy stuff from disabled textarea (in chrome it works fine) and I've been thinking how can I replace my code so that it works ok in firefox as well. i'm using GSP files but can use normal html tags within them as well.

Here is my code snippet:

<g:textArea rows="5" cols="1" name="description" value="${forecast?.description}" class="description-t-area" disabled="${!canEdit}"/>

And here is image how it looks on the web:

Body:
You could use pre tag e.g.

<pre id="description" contenteditable="${!canEdit}">${forecast?.description}</pre>


问:
unable to add ng2-materialize to github.com/angular/quickstart
I tried to add github.com/sherweb/ng2-materialize to  github.com/angular/quickstart  with below changes

```<code>"materialize-css": "",
"mdi": "",
"jQuery": "",
"ng2-materialize": "",
//in Package.json 'dependencies' and 'devDependencies'
</code>```

systemjs.config.js Image, code below

```<code>  'jquery':                    'npm:jquery',
  'materialize-css':           'npm:materialize-css',
  'mdi':                       'npm:mdi',
  'ng2-materialize':           'npm:ng2-materialize',
</code>```

Please check component and module image here, code below for component and module

component

```<code>import { MaterializeModule } from 'ng2-materialize';
</code>```

module

```<code>@Component({   selector: 'my-app',   template: `
             <h1>Hello {{name}}</h1>
             <div class="card-panel teal lighten-2">This is a card panel with a teal lighten-2 class</div>
            `, }) export class AppComponent  { name = 'Angular'; }
</code>```

but i am getting the error and itsnot loading

```<code>[0] 1:10:56 PM - Compilation complete. Watching for file changes
[1] 17.02.26 13:10:57 200 GET /main.js
[1] 17.02.26 13:10:57 304 GET /@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js
[1] 17.02.26 13:10:57 200 GET /app/app.module.js
[1] 17.02.26 13:10:57 304 GET /@angular/compiler/bundles/compiler.umd.js
[1] 17.02.26 13:10:57 304 GET /@angular/core/bundles/core.umd.js
[1] 17.02.26 13:10:57 304 GET /@angular/platform-browser/bundles/platform-browser.umd.js
[1] 17.02.26 13:10:57 200 GET /app/app.component.js
........
[1] 17.02.26 13:10:57 404 GET /node_modules/ng2-materialize/
</code>```

Without materialize its loading correctly, its not picking up the external materialize design modules only , its also doing NPM start - no error there except the above

答:
I had the same problem. As workaround you can use the following code

File: systemjs.config.js

```<code>var packages = {
    ...
    'ng2-materialize': {
        main: 'dist/index.js'
    }
    ...
};

var paths = {
    'npm:': 'node_modules/'
};

map = {
...
    'ng2-materialize': 'npm:ng2-materialize'
...
}

var ngMaterializePackageNames = [
        'button',
        'card',
        'checkbox',
        'collapsible',
        'dropdown',
        'input',
        'navbar',
        'parallax',
        'progress',
        'radio-button',
        'icon',
        'select',

        'sidenav',
        'sidenav/sidenav-collapsible',
        'sidenav/sidenav-divider',
        'sidenav/sidenav-header',
        'sidenav/sidenav-link',
        'sidenav/sidenav-subheader',

        'spinner',
        'textarea',
        'tooltip',

        'toast',
        'toast/services'
  ];

 function packMaterialize(pkgName) {
        packages['ng2-materialize/dist/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }

ngMaterializePackageNames.forEach(packMaterialize);

var config = {
        map: map,
        paths: paths,
        packages: packages
 };

System.config(config);
</code>```

Body:
I tried to add github.com/sherweb/ng2-materialize to  github.com/angular/quickstart  with below changes

"materialize-css": "",
"mdi": "",
"jQuery": "",
"ng2-materialize": "",
//in Package.json 'dependencies' and 'devDependencies'

systemjs.config.js Image, code below

  'jquery':                    'npm:jquery',
  'materialize-css':           'npm:materialize-css',
  'mdi':                       'npm:mdi',
  'ng2-materialize':           'npm:ng2-materialize',

Please check component and module image here, code below for component and module

component

import { MaterializeModule } from 'ng2-materialize';

module

@Component({   selector: 'my-app',   template: `

Hello {{name}}

This is a card panel with a teal lighten-2 class

            `, }) export class AppComponent  { name = 'Angular'; }

but i am getting the error and itsnot loading

[0] 1:10:56 PM - Compilation complete. Watching for file changes
[1] 17.02.26 13:10:57 200 GET /main.js
[1] 17.02.26 13:10:57 304 GET /@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js
[1] 17.02.26 13:10:57 200 GET /app/app.module.js
[1] 17.02.26 13:10:57 304 GET /@angular/compiler/bundles/compiler.umd.js
[1] 17.02.26 13:10:57 304 GET /@angular/core/bundles/core.umd.js
[1] 17.02.26 13:10:57 304 GET /@angular/platform-browser/bundles/platform-browser.umd.js
[1] 17.02.26 13:10:57 200 GET /app/app.component.js
........
[1] 17.02.26 13:10:57 404 GET /node_modules/ng2-materialize/

Without materialize its loading correctly, its not picking up the external materialize design modules only , its also doing NPM start - no error there except the above

Body:
I had the same problem. As workaround you can use the following code

File: systemjs.config.js

var packages = {
    ...
    'ng2-materialize': {
        main: 'dist/index.js'
    }
    ...
};

var paths = {
    'npm:': 'node_modules/'
};

map = {
...
    'ng2-materialize': 'npm:ng2-materialize'
...
}

var ngMaterializePackageNames = [
        'button',
        'card',
        'checkbox',
        'collapsible',
        'dropdown',
        'input',
        'navbar',
        'parallax',
        'progress',
        'radio-button',
        'icon',
        'select',

        'sidenav',
        'sidenav/sidenav-collapsible',
        'sidenav/sidenav-divider',
        'sidenav/sidenav-header',
        'sidenav/sidenav-link',
        'sidenav/sidenav-subheader',

        'spinner',
        'textarea',
        'tooltip',

        'toast',
        'toast/services'
  ];

 function packMaterialize(pkgName) {
        packages['ng2-materialize/dist/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }

ngMaterializePackageNames.forEach(packMaterialize);

var config = {
        map: map,
        paths: paths,
        packages: packages
 };

System.config(config);


问:
android webview use  load a image from sdcard
i'm trying use webview to load a image from sdcard

i use this path :

file///sdcard/1.png

but i didn't see the picture.

is anything wrong?

答: One solution is to put your HTML and image file in the asset folder, and load the HTML file from there. Another solution is to use the method loadDataWithBaseURL() of WebView.</p>

Title: android webview use <img> load a image from sdcard


问:
Zxing Camera in Portrait mode on Android
I want to show portrait orientation on Zxing's camera.

How can this be done?

答:
Additionally to @roylee's modification I had to apply the following to the CameraConfigurationManager.java in order to get best possible preview and QR code recognition quality

```<code>    diff --git a/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java b/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java
index cd9d0d8..4f12c8c 100644
--- a/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java
+++ b/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java
@@ -56,21 +56,24 @@ public final class CameraConfigurationManager {
     Display display = manager.getDefaultDisplay();
     int width = display.getWidth();
     int height = display.getHeight();
-    // We're landscape-only, and have apparently seen issues with display thinking it's portrait
+    // We're landscape-only, and have apparently seen issues with display thinking it's portrait
     // when waking from sleep. If it's not landscape, assume it's mistaken and reverse them:
+    /*
     if (width < height) {
       Log.i(TAG, "Display reports portrait orientation; assuming this is incorrect");
       int temp = width;
       width = height;
       height = temp;
     }
+    */
     screenResolution = new Point(width, height);
     Log.i(TAG, "Screen resolution: " + screenResolution);
-    cameraResolution = findBestPreviewSizeValue(parameters, screenResolution, false);
+    cameraResolution = findBestPreviewSizeValue(parameters, screenResolution, true);//
     Log.i(TAG, "Camera resolution: " + cameraResolution);
   }

   void setDesiredCameraParameters(Camera camera) {
+    camera.setDisplayOrientation(90);
     Camera.Parameters parameters = camera.getParameters();

     if (parameters == null) {
@@ -99,7 +102,7 @@ public final class CameraConfigurationManager {
   Point getScreenResolution() {
     return screenResolution;
   }
-
+
   public void setFrontCamera(boolean newSetting) {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
     boolean currentSetting = prefs.getBoolean(PreferencesActivity.KEY_FRONT_CAMERA, false);
@@ -109,12 +112,12 @@ public final class CameraConfigurationManager {
       editor.commit();
     }
   }
-
+
   public boolean getFrontCamera() {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
     return prefs.getBoolean(PreferencesActivity.KEY_FRONT_CAMERA, false);
   }
-
+
   public boolean getTorch() {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
     return prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false);
@@ -181,7 +184,14 @@ public final class CameraConfigurationManager {
       Camera.Size defaultSize = parameters.getPreviewSize();
       bestSize = new Point(defaultSize.width, defaultSize.height);
     }
+
+    // FIXME: test the bestSize == null case!
+    // swap width and height in portrait case back again
+    if (portrait) {
+        bestSize = new Point(bestSize.y, bestSize.x);
+    }
     return bestSize;
+
   }

   private static String findSettableValue(Collection<String> supportedValues,
</code>```

Body:
Additionally to @roylee's modification I had to apply the following to the CameraConfigurationManager.java in order to get best possible preview and QR code recognition quality

    diff --git a/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java b/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java
index cd9d0d8..4f12c8c 100644
--- a/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java
+++ b/android/src/com/google/zxing/client/android/camera/CameraConfigurationManager.java
@@ -56,21 +56,24 @@ public final class CameraConfigurationManager {
     Display display = manager.getDefaultDisplay();
     int width = display.getWidth();
     int height = display.getHeight();
-    // We're landscape-only, and have apparently seen issues with display thinking it's portrait
+    // We're landscape-only, and have apparently seen issues with display thinking it's portrait
     // when waking from sleep. If it's not landscape, assume it's mistaken and reverse them:
+    /*
     if (width < height) {
       Log.i(TAG, "Display reports portrait orientation; assuming this is incorrect");
       int temp = width;
       width = height;
       height = temp;
     }
+    */
     screenResolution = new Point(width, height);
     Log.i(TAG, "Screen resolution: " + screenResolution);
-    cameraResolution = findBestPreviewSizeValue(parameters, screenResolution, false);
+    cameraResolution = findBestPreviewSizeValue(parameters, screenResolution, true);//
     Log.i(TAG, "Camera resolution: " + cameraResolution);
   }

   void setDesiredCameraParameters(Camera camera) {
+    camera.setDisplayOrientation(90);
     Camera.Parameters parameters = camera.getParameters();

     if (parameters == null) {
@@ -99,7 +102,7 @@ public final class CameraConfigurationManager {
   Point getScreenResolution() {
     return screenResolution;
   }
-
+
   public void setFrontCamera(boolean newSetting) {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
     boolean currentSetting = prefs.getBoolean(PreferencesActivity.KEY_FRONT_CAMERA, false);
@@ -109,12 +112,12 @@ public final class CameraConfigurationManager {
       editor.commit();
     }
   }
-
+
   public boolean getFrontCamera() {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
     return prefs.getBoolean(PreferencesActivity.KEY_FRONT_CAMERA, false);
   }
-
+
   public boolean getTorch() {
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
     return prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false);
@@ -181,7 +184,14 @@ public final class CameraConfigurationManager {
       Camera.Size defaultSize = parameters.getPreviewSize();
       bestSize = new Point(defaultSize.width, defaultSize.height);
     }
+
+    // FIXME: test the bestSize == null case!
+    // swap width and height in portrait case back again
+    if (portrait) {
+        bestSize = new Point(bestSize.y, bestSize.x);
+    }
     return bestSize;
+
   }

   private static String findSettableValue(Collection<String> supportedValues,


问:
VB.Net: LUIS Dialog context.Wait(MessageReceived) issue
As a challenge to myself, I've created a Visual Basic app that uses the Microsoft Bot Framework and LUIS API. To my own amusement, I've largely gotten it working .. almost.
After getting over some C# to VB hurdles, there's one I can't get over, which is stopping my app from keeping the conversation stack from functioning properly (it bails out after one interaction).
Specifically, I have the following code fragment inside of my dialog code:

```<code>Imports System
Imports System.Threading.Tasks
Imports Microsoft.Bot.Builder.Dialogs
Imports Microsoft.Bot.Builder.Luis
Imports Microsoft.Bot.Builder.Luis.Models

<LuisModel(“xxxxxxxxxxxxxxxxxxxxxxxxxx”, "xxxxxxxxxxxxxxxxxxxxxxxxxx")>
<Serializable>
Public Class MyLuisDialog
    Inherits LuisDialog(Of Object)

    <LuisIntent("None")>
    Public Async Function NoneIntent(context As IDialogContext, result As LuisResult) As Task
        Await context.PostAsync(“this is boring chat ..“)
        context.Wait(MessageReceived)
    End Function
</code>```

but I cannot interpret the context.wait(MessageReceived) from C# into VB.

The compiler wants to do:

```<code>context.wait(MessageReceived(context,????????))
</code>```

but I cannot figure out what to put in for ?????.

Irritatingly, the C# version just works in the form context.wait(MessageReceived).

Assistance as to what syntax/code should be used when using VB gratefully accepted :)

答: Try with context.Wait(AddressOf MessageReceived)

Body:
As a challenge to myself, I've created a Visual Basic app that uses the Microsoft Bot Framework and LUIS API. To my own amusement, I've largely gotten it working .. almost.
After getting over some C# to VB hurdles, there's one I can't get over, which is stopping my app from keeping the conversation stack from functioning properly (it bails out after one interaction).
Specifically, I have the following code fragment inside of my dialog code:

Imports System
Imports System.Threading.Tasks
Imports Microsoft.Bot.Builder.Dialogs
Imports Microsoft.Bot.Builder.Luis
Imports Microsoft.Bot.Builder.Luis.Models

<LuisModel(“xxxxxxxxxxxxxxxxxxxxxxxxxx”, "xxxxxxxxxxxxxxxxxxxxxxxxxx")>
<Serializable>
Public Class MyLuisDialog
    Inherits LuisDialog(Of Object)

    <LuisIntent("None")>
    Public Async Function NoneIntent(context As IDialogContext, result As LuisResult) As Task
        Await context.PostAsync(“this is boring chat ..“)
        context.Wait(MessageReceived)
    End Function

but I cannot interpret the context.wait(MessageReceived) from C# into VB.

The compiler wants to do:

context.wait(MessageReceived(context,????????))

but I cannot figure out what to put in for ?????.

Irritatingly, the C# version just works in the form context.wait(MessageReceived).

Assistance as to what syntax/code should be used when using VB gratefully accepted :)


答:
You need ForeignKey for this field
user_company_name

https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey
 read this doc

Title: Django: choose 'company' from company model, if company not present create one


问:
iphone Reporting Score to Game Center
When reporting scores to Game Center, if the method -reportScoreWithCompletionHandler encounters an error does that necessarily imply the score was not posted? Or are there occasions where the score can be posted but an error was encountered? I'd like to have this clear so that my handling block (which conditions on error being nil or not) can handle this better.

答: If there is a problem with the posting -> you get an error. If there is no problem -> no error. I'm sure it does imply.</p>

Title: iphone Reporting Score to Game Center


问:
Split URL query in Swift
I have the following URL query:

```<code>encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN
</code>```

How can I split the query to get the of encodedMessage and signature values?

答:
You can get the key value pairs this way:

```<code>let str = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let arr = str.components(separatedBy:"&")
var data = [String:Any]()
for row in arr {
    let pairs = row.components(separatedBy:"=")
    data[pairs[0]] = pairs[1]
}
let message = data["encodedMessage"]
let sig = data["signature"]
</code>```

I am not sure if that's what you were looking for or not. If it is not, could you please clarify a bit further as to what you are looking for?

Title: Split URL query in Swift

Body:
I have the following URL query:

encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN

How can I split the query to get the of encodedMessage and signature values?

Body:
You can get the key value pairs this way:

let str = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let arr = str.components(separatedBy:"&")
var data = [String:Any]()
for row in arr {
    let pairs = row.components(separatedBy:"=")
    data[pairs[0]] = pairs[1]
}
let message = data["encodedMessage"]
let sig = data["signature"]

I am not sure if that's what you were looking for or not. If it is not, could you please clarify a bit further as to what you are looking for?


问:
UINavigationBar failing to change color
I'm trying to change the background color / bar tint color of my nav bars programatically.

I have tried several examples, but some required writing code in every view controller which doesn't make the most sense to me, as I would like to have it subclassed to reduce repeated code.

I created a subclass of UINavigationBar (as I also wanted to change the height).

I have successfully changed the height and it works in my application. However, when changing the color, it doesn't appear to work.

```<code>class Navbars: UINavigationBar {

override init(frame: CGRect) {
    super.init(frame: frame)
    //self.backgroundColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    //self.barTintColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    self.backgroundColor = UIColor.blue
    self.barTintColor = UIColor.blue
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
}

override func draw(_ rect: CGRect) {

}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    return CGSize(width: UIScreen.main.bounds.width, height: 205)
}
}
</code>```

The height changes, so I presumed having the code to change it's color in the init function would work, but it doesn't, and I'm not sure why.

I even then tried to subclass UINavigationController and still nothing happens.

```<code>class NavControllers: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationBar.barTintColor = UIColor.brown

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
</code>```

If anyone knows where I am going wrong, that would be much appreciated. Thank you!

答:
Try out this code

```<code>////////////////// set navigation bar tint color ///////////////
    self.navigationController.navigationBar.barTintColor = (your color here);
</code>```

Worked for me :) .

Title: UINavigationBar failing to change color

Body:
I'm trying to change the background color / bar tint color of my nav bars programatically.

I have tried several examples, but some required writing code in every view controller which doesn't make the most sense to me, as I would like to have it subclassed to reduce repeated code.

I created a subclass of UINavigationBar (as I also wanted to change the height).

I have successfully changed the height and it works in my application. However, when changing the color, it doesn't appear to work.

class Navbars: UINavigationBar {

override init(frame: CGRect) {
    super.init(frame: frame)
    //self.backgroundColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    //self.barTintColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    self.backgroundColor = UIColor.blue
    self.barTintColor = UIColor.blue
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
}

override func draw(_ rect: CGRect) {

}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    return CGSize(width: UIScreen.main.bounds.width, height: 205)
}
}

The height changes, so I presumed having the code to change it's color in the init function would work, but it doesn't, and I'm not sure why.

I even then tried to subclass UINavigationController and still nothing happens.

class NavControllers: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationBar.barTintColor = UIColor.brown

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

If anyone knows where I am going wrong, that would be much appreciated. Thank you!

Body:
Try out this code

////////////////// set navigation bar tint color ///////////////
    self.navigationController.navigationBar.barTintColor = (your color here);

Worked for me :) .


问:
RxJava2 get event when Observable/Completed is completed or disposed
I need to show a progress dialog when I subscribe to a Completable and hide it after the operation is completed(successfully or with an error) or is canceled.

So I do

```<code>final Completable completable = notificationRepository.markAllAsRead()
        .doOnSubscribe(d -> progressDialog.show())
        .doOnError(error -> progressDialog.dismiss())
        .doOnComplete(() -> progressDialog.dismiss())
        .doOnDispose(() -> progressDialog.dismiss());
</code>```

Is there any elegant way to get single callback when
onError, onComplete or onDispose happens?

答:
I have done some tests, so

doOnDispose is called when the subscriber cancels the subscription, it is never called after completion.

doOnComplete is called when the Observable/Completable completes successfully. (Error doesn't happen)

doOnError is called when Observable/Completable emits an error. (OnComplete is not called).

doOnTerminate is called when Observable/Completable emits an error or completes. So it's doOnComplete + doOnError

doFinally is called when Completable/Observable signals onError or onComplete or gets disposed. So it is doOnDispose + doOnError +doOnComplete.

So doFinally is what I was looking for, Thank you akarnokd for help.

Body:
I need to show a progress dialog when I subscribe to a Completable and hide it after the operation is completed(successfully or with an error) or is canceled.

So I do

final Completable completable = notificationRepository.markAllAsRead()
        .doOnSubscribe(d -> progressDialog.show())
        .doOnError(error -> progressDialog.dismiss())
        .doOnComplete(() -> progressDialog.dismiss())
        .doOnDispose(() -> progressDialog.dismiss());

Is there any elegant way to get single callback when
onError, onComplete or onDispose happens?


问:
Calculate percentage based on row_number in sql
I'm trying to write a sql query that for each returned row, will also return a percentage (0-100) based on its row position. To further complicate this, the query is also currently grouped. Here's some example data to play with:

```<code>create table #test(StockId int)
insert into #test values (101), (101), (202), (202), (303), (404), (505)

select
StockId,
count(*) as BinMovements
from #test
group by StockId
order by BinMovements desc
</code>```

This query currently returns:

StockId, BinMovements

  101, 2

  202, 2

  303, 1

  404, 1

  505, 1

(Though obviously, because BinMovements is either 2 or 1 it would be equally correct to return the StockIds in a different order such as):

202, 2

  101, 2

  404, 1

  303, 1

  505, 1

I'd like to add a 'percentage' column, but this is really just based on row position, so I'd like to see values like:

101, 2, 100

  202, 2, 80

  303, 1, 60

  404, 1, 40

  505, 1, 20

I imagine the solution may involve ROW_NUMBER, and I started down this path thinking I could just get ROW_NUMBER / total rows * 100, but this isn't working for some reason. Possibly because of the group by clause?

```<code>select
StockId,
count(*) as BinMovements,
ROW_NUMBER() OVER(order by (count(*))) as RowNumber,
count(*) over () as TotalCount,
(ROW_NUMBER() OVER(order by (count(*)))) / (count(*) over ()) * 100 as Percentage
from #test
group by StockId
order by RowNumber desc
</code>```

returns:

```<code>StockId BinMovements    RowNumber   TotalCount  Percentage
202     2               5           5           100
101     2               4           5           0
505     1               3           5           0
404     1               2           5           0
303     1               1           5           0
</code>```

I'd prefer to do this in a single select if possible, though if not wrapping it in an outer select may be a solution. Thanks

答:
Both COUNT and ROW_NUMBER functions returns BIGINT.
Therefore result of division is also converted to BIGINT.

This works (you should multiply before divide):

```<code>(ROW_NUMBER() OVER(order by (count(*)))) * 100 / (count(*) over ()) as Percentage
</code>```

Body:
I'm trying to write a sql query that for each returned row, will also return a percentage (0-100) based on its row position. To further complicate this, the query is also currently grouped. Here's some example data to play with:

create table #test(StockId int)
insert into #test values (101), (101), (202), (202), (303), (404), (505)

select
StockId,
count(*) as BinMovements
from #test
group by StockId
order by BinMovements desc

This query currently returns:

StockId, BinMovements

  101, 2

  202, 2

  303, 1

  404, 1

  505, 1

(Though obviously, because BinMovements is either 2 or 1 it would be equally correct to return the StockIds in a different order such as):

202, 2

  101, 2

  404, 1

  303, 1

  505, 1

I'd like to add a 'percentage' column, but this is really just based on row position, so I'd like to see values like:

101, 2, 100

  202, 2, 80

  303, 1, 60

  404, 1, 40

  505, 1, 20

I imagine the solution may involve ROW_NUMBER, and I started down this path thinking I could just get ROW_NUMBER / total rows * 100, but this isn't working for some reason. Possibly because of the group by clause?

select
StockId,
count(*) as BinMovements,
ROW_NUMBER() OVER(order by (count(*))) as RowNumber,
count(*) over () as TotalCount,
(ROW_NUMBER() OVER(order by (count(*)))) / (count(*) over ()) * 100 as Percentage
from #test
group by StockId
order by RowNumber desc

returns:

StockId BinMovements    RowNumber   TotalCount  Percentage
202     2               5           5           100
101     2               4           5           0
505     1               3           5           0
404     1               2           5           0
303     1               1           5           0

I'd prefer to do this in a single select if possible, though if not wrapping it in an outer select may be a solution. Thanks

Body:
Both COUNT and ROW_NUMBER functions returns BIGINT.
Therefore result of division is also converted to BIGINT.

This works (you should multiply before divide):

(ROW_NUMBER() OVER(order by (count(*)))) * 100 / (count(*) over ()) as Percentage


问:
How can I correct my PHP code for this SQL query?
I've been messing with this for a while and I'm nearly there. Just need to get past this wall I've hit.

I have the following tables:

```<code>tracks (trackid, tracktitle, albumid, composerid)
albums (albumid, albumname)
composers (composerid, composername)
</code>```

I can insert a new record via PhpMyAdmin SQL tab with

```<code>INSERT INTO tracks (tracktitle, albumid, composerid) VALUES ('New Song', 1, 1);
</code>```

and it works fine.

My PHP form though isn't doing the same thing and I must have overlooked something.
Please can someone check out the code for my addtrack page and tell me what is wrong?

```<code> if (isset($_POST['tracktitle'])):
 // A new track has been entered
 // using the form.

 $cid= $_POST['cid'];
 $tracktitle = $_POST['tracktitle'];
 $albs = $_POST['albs'];

 if ($cid == '') {
 exit('<p>You must choose an composer for this track.
 Click "Back" and try again.</p>');
  }

  $sql = "INSERT INTO tracks SET
  tracks.tracktitle='$tracktitle'" ;
  if (@mysql_query($sql)) {
  echo '<p>New track added</p>';
  } else {
  exit('<p>Error adding new track' . mysql_error() . '</p>');
  }

  $trackid = mysql_insert_id();

  if (isset($_POST['albs'])) {
   $albs = $_POST['albs'];
   } else {
   $albs = array();
   }

  $numAlbs = 0;
  foreach ($albs as $albID) {
  $sql = "INSERT IGNORE INTO tracks (trackid, albumid,
  composerid) VALUES " .
"($trackid, $albs, $cid)";

if ($ok) {
  $numAlbs = $numAlbs + 1;
} else {
  echo "<p>Error inserting track into album $albID: " .
      mysql_error() . '</p>';
}
}
 ?>

<p>Track was added to <?php echo $numAlbs; ?> albums.</p>

 <p><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Add another
 track</a></p>
 <p><a href="tracks.php">Return to track search</a></p>

 <?php
 else: // Allow the user to enter a new track

 $composers = @mysql_query('SELECT composerid, composername
 FROM composers');
  if (!$composers) {
 exit('<p>Unable to obtain composer list from the
database.</p>');
 }

$albs = @mysql_query('SELECT albumid, albumname FROM albums');
 if (!$albs) {
 exit('<p>Unable to obtain album list from the
 database.</p>');
 }
 ?>

 <form action="<?php echo $_SERVER['PHP_SELF']; ?>"
 method="post">
 <p>Enter the new track:<br />
 <textarea name="tracktitle" rows="1" cols="20">
 </textarea></p>
 <p>Composer:
 <select name="cid" size="1">
  <option selected value="">Select One</option>
  <option value="">---------</option>
  <?php
   while ($composer= mysql_fetch_array($composers)) {
    $cid = $composer['composerid'];
    $cname = htmlspecialchars($composer['composername']);
    echo "<option value='$cid'>$cname</option>\n";
     }
    ?>
    </select></p>
    <p>Place in albums:<br />
   <?php
   while ($alb = mysql_fetch_array($albs)) {
    $aid = $alb['albumid'];
    $aname = htmlspecialchars($alb['albumname']);
     echo "<label><input type='checkbox' name='albs[]'
    value='$aid' />$aname</label><br />\n";
    }
   ?>
</code>```

Once I have this sorted, I can move on to expanding it and also sorting out the security issues. Someone on here recommended I look into PDO's which are a new thing to me.
But one hurdle at a time....

Thanks

答:
My previous answer was wrong (and is deleted). I've learned now that your Insert syntax is indeed valid.

But what you don't do, is escape the value you put in the query. If $tracktitle contains any invalid characters, like a single quote, it could break your query.

You should add this line before building your insert query:

```<code>$tracktitle = mysql_real_escape_string($tracktitle);
</code>```

You current code is very dangarous. If I was to insert a song, and in the song name I would type YourF...ed, oh by the way'; drop database YourDataBaseName; you should try to imagine what happens..

This is known as SQL-injection. Because you don't correctly escape the value, someone else can close the statment en start a new statement by just inserting it into a html form field.

I don't know if this is the reason that your query doesn't work right now (it only breaks if you type an invalid character), but it is a serious problem at the moment.

To find out your exact error, you should display the results of mysql_error() when mysql_query() returns false. This will probably help you more than any random guesses we can make here.

Body:
I've been messing with this for a while and I'm nearly there. Just need to get past this wall I've hit.

I have the following tables:

tracks (trackid, tracktitle, albumid, composerid)
albums (albumid, albumname)
composers (composerid, composername)

I can insert a new record via PhpMyAdmin SQL tab with

INSERT INTO tracks (tracktitle, albumid, composerid) VALUES ('New Song', 1, 1);

and it works fine.

My PHP form though isn't doing the same thing and I must have overlooked something.
Please can someone check out the code for my addtrack page and tell me what is wrong?

 if (isset($_POST['tracktitle'])):
 // A new track has been entered
 // using the form.

 $cid= $_POST['cid'];
 $tracktitle = $_POST['tracktitle'];
 $albs = $_POST['albs'];

 if ($cid == '') {
 exit('
You must choose an composer for this track.
 Click "Back" and try again.
');
  }

  $sql = "INSERT INTO tracks SET
  tracks.tracktitle='$tracktitle'" ;
  if (@mysql_query($sql)) {
  echo '
New track added
';
  } else {
  exit('
Error adding new track' . mysql_error() . '
');
  }

  $trackid = mysql_insert_id();

  if (isset($_POST['albs'])) {
   $albs = $_POST['albs'];
   } else {
   $albs = array();
   }

  $numAlbs = 0;
  foreach ($albs as $albID) {
  $sql = "INSERT IGNORE INTO tracks (trackid, albumid,
  composerid) VALUES " .
"($trackid, $albs, $cid)";

if ($ok) {
  $numAlbs = $numAlbs + 1;
} else {
  echo "
Error inserting track into album $albID: " .
      mysql_error() . '
';
}
}
 ?>

Track was added to <?php echo $numAlbs; ?> albums.

<a href="<?php echo $_SERVER['PHP_SELF']; ?>">Add another
 track

Return to track search

 <?php
 else: // Allow the user to enter a new track

 $composers = @mysql_query('SELECT composerid, composername
 FROM composers');
  if (!$composers) {
 exit('
Unable to obtain composer list from the
database.
');
 }

$albs = @mysql_query('SELECT albumid, albumname FROM albums');
 if (!$albs) {
 exit('
Unable to obtain album list from the
 database.
');
 }
 ?>

 <form action="<?php echo $_SERVER['PHP_SELF']; ?>"
 method="post">

Enter the new track:

 <textarea name="tracktitle" rows="1" cols="20">
 </textarea>

Composer:
 <select name="cid" size="1">
  <option selected value="">Select One</option>
  <option value="">---------</option>
  <?php
   while ($composer= mysql_fetch_array($composers)) {
    $cid = $composer['composerid'];
    $cname = htmlspecialchars($composer['composername']);
    echo "<option value='$cid'>$cname</option>\n";
     }
    ?>
    </select>

Place in albums:

   <?php
   while ($alb = mysql_fetch_array($albs)) {
    $aid = $alb['albumid'];
    $aname = htmlspecialchars($alb['albumname']);
     echo "<input type='checkbox' name='albs[]'
    value='$aid' />$aname
\n";
    }
   ?>

Once I have this sorted, I can move on to expanding it and also sorting out the security issues. Someone on here recommended I look into PDO's which are a new thing to me.
But one hurdle at a time....

Thanks

Body:
My previous answer was wrong (and is deleted). I've learned now that your Insert syntax is indeed valid.

But what you don't do, is escape the value you put in the query. If $tracktitle contains any invalid characters, like a single quote, it could break your query.

You should add this line before building your insert query:

$tracktitle = mysql_real_escape_string($tracktitle);

You current code is very dangarous. If I was to insert a song, and in the song name I would type YourF...ed, oh by the way'; drop database YourDataBaseName; you should try to imagine what happens..

This is known as SQL-injection. Because you don't correctly escape the value, someone else can close the statment en start a new statement by just inserting it into a html form field.

I don't know if this is the reason that your query doesn't work right now (it only breaks if you type an invalid character), but it is a serious problem at the moment.

To find out your exact error, you should display the results of mysql_error() when mysql_query() returns false. This will probably help you more than any random guesses we can make here.


问:
How do I download the Android SDK without downloading Android Studio?
As of the moment, I am running a Windows 8.1 PC that does not have the storage or the RAM for a IDE like Android Studio or Eclipse. I want to download the Android SDK tools, without the IDE. How can this be accomplished?</p>

答:
What worked for me on Windows:

Downloaded command line tools from https://developer.android.com/studio/index.html

Put the whole tools folder from the ZIP archive to C:\Program Files (x86)\Android SDK\

Launched tools\android.bat as administrator, which opened the usual SDK Manager window

Installed required components. The files were downloaded to ...\Android SDK\ directory (that is build-tools, platforms, platform-tools, etc. directories appeared alongside tools inside ...\Android SDK\)

Opened the Android project in Intellij IDEA, navigated to File->Project Structure->SDKs, and added Android SDK by directing to ...\Android SDK\ directory


问:
problem in activity finish() and on pressing back button in android
I am very confused in using finish() for activity and using back button of keypad.I have created many activities so on moving from one activity to another I finish the last activity. And also I have used back button in my activity so I can go back (from where I came)
by pressing back button but problem arises when I use keypad's back button I go to any other  activity .I want it should work as my activity's back button.

And I think this can be done by using onKeyListener and chekcing keypad's back buttons and there I start activity same as my activity's back button.
I want to know is it right to do this way or there is a way better than this?

Please Help

答:
If you want to call finish() and also want your device back button work as activity back button then override the onBackPressed() method.

Suppose you are in Activity 2 and and want to back in Activity 1 which is your first actvity then inside Activity2.java write below code ....

```<code>public void onBackPressed()
    {
        Intent setIntent = new Intent(this,Activity1.class);
        startActivity(setIntent);
        return;
    }
</code>```

Body:
If you want to call finish() and also want your device back button work as activity back button then override the onBackPressed() method.

Suppose you are in Activity 2 and and want to back in Activity 1 which is your first actvity then inside Activity2.java write below code ....

public void onBackPressed()
    {
        Intent setIntent = new Intent(this,Activity1.class);
        startActivity(setIntent);
        return;
    }


问:
Selenium Webdriver fails in open Firefox
I was learning how to create a new project using Maven for Selenium Webdriver. I created a pom.xml file and one basic test file containing the test.

Here they are:

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>CleanSubmission</groupId>
<artifactId>CleanSubmission</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>CleanSubmissions</name>
<url>http://maven.apache.org</url>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.10</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>com.github.yev</groupId>
        <artifactId>screenshot</artifactId>
        <version>0.2</version>
    </dependency>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.13</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>2.13</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-testng</artifactId>
                        <version>2.13</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>selenium-maven-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <id>xvfb</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>xvfb</goal>
                        </goals>
                        <configuration>
                            <displayPropertiesFile>2.3</displayPropertiesFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
</code>```

and the Test File:

```<code>import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class ClearSubmissionTest  {
    public WebDriver driver;
    String baseUrlAdmin = "http://www.google.pl/";

    @Before
    public void setUp() throws Exception {
        WebDriver driver = new FirefoxDriver();
    }

  @Test
  public void Testno1() throws Exception  {
      driver.get(baseUrlAdmin);
      Thread.sleep(5000);
  }

    @After
    public void tearDown() throws Exception {
        driver.close();
    }
}
</code>```

But somehow there is always an error
java.lang.NullPointerException: null at COS2Clean.CleanSubmissions.ClearSubmissionTest.Testno1(ClearSubmissionTest.java:21) which points to the line driver.get(baseUrlAdmin);.
I was looking for an answer, including updating Selenium, choosing Firefox Webdriver as Binary file, but all methods failed.

As I was debbuging, I can see that the problem is with org.apache.maven.plugin.MojoFailureException instead of my code, therefore something in the pom.xml file must be missing - for now I haven't got any idea what more can be wrong...

答:
You have already declared webdriver instance as 'driver' after class on line number 8. And inside setUp method of Before annotation you are again declaring the instance.

Just use below inside setUp() and try :-

```<code>driver = new FirefoxDriver();
</code>```

Body:
I was learning how to create a new project using Maven for Selenium Webdriver. I created a pom.xml file and one basic test file containing the test.

Here they are:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>CleanSubmission</groupId>
<artifactId>CleanSubmission</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>CleanSubmissions</name>
<url>http://maven.apache.org</url>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.10</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>com.github.yev</groupId>
        <artifactId>screenshot</artifactId>
        <version>0.2</version>
    </dependency>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.13</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>2.13</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-testng</artifactId>
                        <version>2.13</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>selenium-maven-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <id>xvfb</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>xvfb</goal>
                        </goals>
                        <configuration>
                            <displayPropertiesFile>2.3</displayPropertiesFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

and the Test File:

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class ClearSubmissionTest  {
    public WebDriver driver;
    String baseUrlAdmin = "http://www.google.pl/";

    @Before
    public void setUp() throws Exception {
        WebDriver driver = new FirefoxDriver();
    }

  @Test
  public void Testno1() throws Exception  {
      driver.get(baseUrlAdmin);
      Thread.sleep(5000);
  }

    @After
    public void tearDown() throws Exception {
        driver.close();
    }
}

But somehow there is always an error
java.lang.NullPointerException: null at COS2Clean.CleanSubmissions.ClearSubmissionTest.Testno1(ClearSubmissionTest.java:21) which points to the line driver.get(baseUrlAdmin);.
I was looking for an answer, including updating Selenium, choosing Firefox Webdriver as Binary file, but all methods failed.

As I was debbuging, I can see that the problem is with org.apache.maven.plugin.MojoFailureException instead of my code, therefore something in the pom.xml file must be missing - for now I haven't got any idea what more can be wrong...

Body:
You have already declared webdriver instance as 'driver' after class on line number 8. And inside setUp method of Before annotation you are again declaring the instance.

Just use below inside setUp() and try :-

driver = new FirefoxDriver();


问:
Name not matched in creating zip folder with bash
I'm trying to create a zip folder in a bash script that contains the current date (YYYY_MM_DD).
I have this code:

```<code>currentArchive=$(date '+%Y_%m_%d')
zip -r ./aktuell ./Archive/${currentArchive}-bkt
</code>```

But when I run the script I get the following error:

zip warning: name not matched: ./Archive/2017_03_30-bkt

I want the folder "aktuell" as a zip folder named "2017_03_30-bkt.zip" in the folder "Archive". The current folder "aktuell" exists.

What am I doing wrong?

答:
You have the source and destination directories backwards in your zip command. Also, make sure the destination directory exists before executing zip.</p>

```<code>currentArchive=$(date '+%Y_%m_%d')
mkdir -p ./Archive/
zip -r ./Archive/${currentArchive}-bkt ./aktuell
</code>```

Body:
I'm trying to create a zip folder in a bash script that contains the current date (YYYY_MM_DD).
I have this code:

currentArchive=$(date '+%Y_%m_%d')
zip -r ./aktuell ./Archive/${currentArchive}-bkt

But when I run the script I get the following error:

zip warning: name not matched: ./Archive/2017_03_30-bkt

I want the folder "aktuell" as a zip folder named "2017_03_30-bkt.zip" in the folder "Archive". The current folder "aktuell" exists.

What am I doing wrong?

Body:
You have the source and destination directories backwards in your zip command. Also, make sure the destination directory exists before executing zip.

currentArchive=$(date '+%Y_%m_%d')
mkdir -p ./Archive/
zip -r ./Archive/${currentArchive}-bkt ./aktuell


问:
Postgres - detect overlapping lines from 2 tables
QUESTION: I have 2 tables with bike and hike trails of a country (Poland).

```<code>Table bicycle_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |bicycle |szlak1       |ncn        |blue      |proposed
{geo2}   |bicycle |szlak2       |lcn        |red       |null
{geo3}   |bicycle |szlak3       |ncn        |green     |proposed
{geo4}   |bicycle |szlak4       |rcn        |blue      |proposed
{geo5}   |bicycle |szlak5       |lcn        |blue      |null
{geo6}   |bicycle |szlak6       |ncn        |yellow    |proposed
....and so on

Table hiking_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |hiking  |szlak1       |ncn        |blue      |proposed
{geo2}   |hiking  |szlak2       |ncn        |red       |null
{geo3}   |hiking  |szlak3       |ncn        |green     |proposed
{geo4}   |hiking  |szlak4       |ncn        |blue      |proposed
{geo5}   |hiking  |szlak5       |ncn        |blue      |null
{geo6}   |hiking  |szlak6       |ncn        |yellow    |proposed
...and so on
</code>```

{geo1},{geo2} etc. is a unique geometry of every trail.

Every trail has a unique geometry but sometimes bicycle and hiking routes overlap.
The picture below shows example in QGIS:

I would like to delete the overlapping parts as I already have them in a different database.

EDIT:
I have tried a solution suggested by Julia Leder :

```<code>create table intersections as
(select st_intersection(b.way, h.way) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(g.way, h.way));
</code>```

Not all overlapping lines were detected. I'm not sure why?
Here's a picture to show the issue:

答:
```<code>select *
from
    (
        select *
        from bicycle_merge bm
        where not exists (
            select 1
            from hiking_merge
            where geometry = bm.geometry
        )
    )
    union
    (
        select *
        from hicking_merge hm
        where not exists (
            select 1
            from bicycle_merge
            where geometry = hm.geometry
        )
    )
</code>```

Body:
QUESTION: I have 2 tables with bike and hike trails of a country (Poland).

Table bicycle_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |bicycle |szlak1       |ncn        |blue      |proposed
{geo2}   |bicycle |szlak2       |lcn        |red       |null
{geo3}   |bicycle |szlak3       |ncn        |green     |proposed
{geo4}   |bicycle |szlak4       |rcn        |blue      |proposed
{geo5}   |bicycle |szlak5       |lcn        |blue      |null
{geo6}   |bicycle |szlak6       |ncn        |yellow    |proposed
....and so on

Table hiking_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |hiking  |szlak1       |ncn        |blue      |proposed
{geo2}   |hiking  |szlak2       |ncn        |red       |null
{geo3}   |hiking  |szlak3       |ncn        |green     |proposed
{geo4}   |hiking  |szlak4       |ncn        |blue      |proposed
{geo5}   |hiking  |szlak5       |ncn        |blue      |null
{geo6}   |hiking  |szlak6       |ncn        |yellow    |proposed
...and so on

{geo1},{geo2} etc. is a unique geometry of every trail.

Every trail has a unique geometry but sometimes bicycle and hiking routes overlap.
The picture below shows example in QGIS:

I would like to delete the overlapping parts as I already have them in a different database.

EDIT:
I have tried a solution suggested by Julia Leder :

create table intersections as
(select st_intersection(b.way, h.way) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(g.way, h.way));

Not all overlapping lines were detected. I'm not sure why?
Here's a picture to show the issue:


问:
Reducing repeated information in database design
I am designing an application that when users create a new account, their account is populated with several hundred rows of data (predefined options, settings, etc). Most of the users will rarely, if ever, change the information contained in these tables. Are there any good design patterns to reduce the amount of duplicated data in the database tables?

Some ideas I had so far:

Keep the predefined options in their
own tables, and only save custom
options to the user tables. This
would seem to reduce the overhead,
but I can see the database calls
getting really tricky.

Create a new
database for every 100 users or so,
with a separate database for accounts
that points to the users database.
This is, well, not optimal.

Idea 3?

答:
Definitely, create a base profile (or possibly a group of base profiles, for example based on nationality, or any other meaningful partition) where all the default rules and values are represented.

At the user-level create only "exceptions", i.e. only values that have been changed by the user, and always access the profile as a join between the relevant base profile and the user-specific exceptions (that hopefully will be empty, i.e. non-existing in the DB).

The only concern is that the various defaults should be grouped in a number of smaller (in the sense of number of fields) tables, otherwise you won't get any benefit from this approach (i.e. if you put all the possible settings in a single table record you will have to duplicate everything as soon as the user changes just one field, and this will give no benefit at all).


问:
How to substring Android logcat output and show only the message itself
I would like to use logcat and output only the messages themselves.
Not the method name, not the time, not the tag - just the message.

Example, from this message:

D/ConnectivityService(  471): Setting tx/rx TCP buffers to
  524288,1048576,2097152,262144,524288,1048576

I only want the

Setting tx/rx TCP buffers to
  524288,1048576,2097152,262144,524288,1048576

Is that possible ?

答:
Logcat has a format parameter, one of which is the message alone with no metadata.

```<code>adb logcat -v raw
</code>```

You can still apply filters after this, e.g. *:S ConnectivityService:D, even though the tag is no longer part of the output.

Body:
Logcat has a format parameter, one of which is the message alone with no metadata.

adb logcat -v raw

You can still apply filters after this, e.g. *:S ConnectivityService:D, even though the tag is no longer part of the output.


问:
JSON Array of objects to plain old java object
this is my first time making an external api call in Java, so please bear with me as I'm not very experienced. I got the http request working and got a response, but now I need to parse it.

I'm trying to convert a json array to java objects. I understand the gist of it, but all examples I've seen don't apply to my issue.

I need the 'entities' objects from the json string. The details (which are an array, too) can contain any key/value pair, so I was thinking of putting that in a hashmap in each Entity object. I've tried the gson library, but I can't find any gson example that goes deeper than a single dimensional json array.

I realize this is kind of a broad question, and I don't expect anyone to deliver me a working solution, but a few tips or a link to a relevant guide would go a long way. :)

```<code>{
   "return": {
      "entities": [
         {
            "id": 2385,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "John Wick",
                  "match": false
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2385"
         },
         {
            "id": 2384,
            "details": [
               {
                  "name": "Discord ID",
                  "value": "159985870458322944",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561197991558078",
                  "match": true
               },
               {
                  "name": "SteamVanity",
                  "value": "test",
                  "match": false
               },
               {
                  "name": "PS4",
                  "value": "John_S",
                  "match": false
               },
               {
                  "name": "XBox",
                  "value": "John S",
                  "match": false
               },
               {
                  "name": "Email",
                  "value": "john_smith@gmail.com",
                  "match": true
               },
               {
                  "name": "Comment",
                  "value": "Test user",
                  "match": false
               },
               {
                  "name": "Other Known Name",
                  "value": "Jonathan",
                  "match": false
               },
               {
                  "name": "Reddit",
                  "value": "/u/johns",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2384"
         },
         {
            "id": 1680,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "Johny",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198213003675",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1680"
         },
         {
            "id": 1689,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "JohnnyPeto",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198094228192",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1689"
         }
      ],
      "notice": "Showing 4 out of 4 matches."
   }
}
</code>```

答:
Despite there are answers suggesting you to use Jackson, you can still accomplish easily with Gson with its default configuration just creating proper relations between mappings:

// A generic response, parameterized with <T>, can hold any type except of primitives
final class Response<T> {

    @SerializedName("return")
    final T ret = null;

}

final class EntitiesAndNotice {

    final List<Entity> entities = null;
    final String notice = null;

}

final class Entity {

    // Unlike Object and any its subclasses, `int` being a primitive cannot be nulled
    // Simple 0 won't work either, because the compiler will inline it
    // So it's a sort of cheating javac to return a value that holds 0 already
    final int id = Integer.valueOf(0);
    final List<Detail> details = null;
    // Your JSON document does not provide enough info on the elements type
    // So it depends on how Gson parses JSON tokens
    final List<Object> proofs = null;
    final URL link = null;

}

final class Detail {

    final String name = null;
    final String value = null;
    // The same for primitive booleans, or Boolean.FALSE
    final boolean match = Boolean.valueOf(false);

}
```

<p>Example use:</p>

<pre class="lang-java prettyprint-override"><code>private static final String JSON = "{\"return\":{\"entities\":[{\"id\":2385,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"John Wick\",\"match\":false}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=2385\"},{\"id\":2384,\"details\":[{\"name\":\"Discord ID\",\"value\":\"159985870458322944\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561197991558078\",\"match\":true},{\"name\":\"SteamVanity\",\"value\":\"test\",\"match\":false},{\"name\":\"PS4\",\"value\":\"John_S\",\"match\":false},{\"name\":\"XBox\",\"value\":\"John S\",\"match\":false},{\"name\":\"Email\",\"value\":\"john_smith@gmail.com\",\"match\":true},{\"name\":\"Comment\",\"value\":\"Test user\",\"match\":false},{\"name\":\"Other Known Name\",\"value\":\"Jonathan\",\"match\":false},{\"name\":\"Reddit\",\"value\":\"/u/johns\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=2384\"},{\"id\":1680,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"Johny\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561198213003675\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=1680\"},{\"id\":1689,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"JohnnyPeto\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561198094228192\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=1689\"}],\"notice\":\"Showing 4 out of 4 matches.\"}}";

private static final Gson gson = new Gson();

private static final TypeToken<Response<EntitiesAndNotice>> responseTypeToken = new TypeToken<Response<EntitiesAndNotice>>() {
};

public static void main(final String... args) {
    final Response<EntitiesAndNotice> response = gson.fromJson(JSON, responseTypeToken.getType());
    final String value = response.ret.entities.get(1).details.get(3).value;
    System.out.println(value);
}
</code>```

Output:

John_S

Body:
this is my first time making an external api call in Java, so please bear with me as I'm not very experienced. I got the http request working and got a response, but now I need to parse it.

I'm trying to convert a json array to java objects. I understand the gist of it, but all examples I've seen don't apply to my issue.

I need the 'entities' objects from the json string. The details (which are an array, too) can contain any key/value pair, so I was thinking of putting that in a hashmap in each Entity object. I've tried the gson library, but I can't find any gson example that goes deeper than a single dimensional json array.

I realize this is kind of a broad question, and I don't expect anyone to deliver me a working solution, but a few tips or a link to a relevant guide would go a long way. :)

{
   "return": {
      "entities": [
         {
            "id": 2385,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "John Wick",
                  "match": false
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2385"
         },
         {
            "id": 2384,
            "details": [
               {
                  "name": "Discord ID",
                  "value": "159985870458322944",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561197991558078",
                  "match": true
               },
               {
                  "name": "SteamVanity",
                  "value": "test",
                  "match": false
               },
               {
                  "name": "PS4",
                  "value": "John_S",
                  "match": false
               },
               {
                  "name": "XBox",
                  "value": "John S",
                  "match": false
               },
               {
                  "name": "Email",
                  "value": "john_smith@gmail.com",
                  "match": true
               },
               {
                  "name": "Comment",
                  "value": "Test user",
                  "match": false
               },
               {
                  "name": "Other Known Name",
                  "value": "Jonathan",
                  "match": false
               },
               {
                  "name": "Reddit",
                  "value": "/u/johns",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=2384"
         },
         {
            "id": 1680,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "Johny",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198213003675",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1680"
         },
         {
            "id": 1689,
            "details": [
               {
                  "name": "Other Known Name",
                  "value": "JohnnyPeto",
                  "match": false
               },
               {
                  "name": "SteamID64",
                  "value": "76561198094228192",
                  "match": true
               }
            ],
            "proofs": [],
            "link": "http://domain.gg/users?id=1689"
         }
      ],
      "notice": "Showing 4 out of 4 matches."
   }
}

Body:
Despite there are answers suggesting you to use Jackson, you can still accomplish easily with Gson with its default configuration just creating proper relations between mappings:

// A generic response, parameterized with <T>, can hold any type except of primitives
final class Response<T> {

    @SerializedName("return")
    final T ret = null;

}

final class EntitiesAndNotice {

    final List<Entity> entities = null;
    final String notice = null;

}

final class Entity {

    // Unlike Object and any its subclasses, `int` being a primitive cannot be nulled
    // Simple 0 won't work either, because the compiler will inline it
    // So it's a sort of cheating javac to return a value that holds 0 already
    final int id = Integer.valueOf(0);
    final List<Detail> details = null;
    // Your JSON document does not provide enough info on the elements type
    // So it depends on how Gson parses JSON tokens
    final List<Object> proofs = null;
    final URL link = null;

}

final class Detail {

    final String name = null;
    final String value = null;
    // The same for primitive booleans, or Boolean.FALSE
    final boolean match = Boolean.valueOf(false);

}

Example use:

private static final String JSON = "{\"return\":{\"entities\":[{\"id\":2385,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"John Wick\",\"match\":false}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=2385\"},{\"id\":2384,\"details\":[{\"name\":\"Discord ID\",\"value\":\"159985870458322944\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561197991558078\",\"match\":true},{\"name\":\"SteamVanity\",\"value\":\"test\",\"match\":false},{\"name\":\"PS4\",\"value\":\"John_S\",\"match\":false},{\"name\":\"XBox\",\"value\":\"John S\",\"match\":false},{\"name\":\"Email\",\"value\":\"john_smith@gmail.com\",\"match\":true},{\"name\":\"Comment\",\"value\":\"Test user\",\"match\":false},{\"name\":\"Other Known Name\",\"value\":\"Jonathan\",\"match\":false},{\"name\":\"Reddit\",\"value\":\"/u/johns\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=2384\"},{\"id\":1680,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"Johny\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561198213003675\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=1680\"},{\"id\":1689,\"details\":[{\"name\":\"Other Known Name\",\"value\":\"JohnnyPeto\",\"match\":false},{\"name\":\"SteamID64\",\"value\":\"76561198094228192\",\"match\":true}],\"proofs\":[],\"link\":\"http://domain.gg/users?id=1689\"}],\"notice\":\"Showing 4 out of 4 matches.\"}}";

private static final Gson gson = new Gson();

private static final TypeToken<Response<EntitiesAndNotice>> responseTypeToken = new TypeToken<Response<EntitiesAndNotice>>() {
};

public static void main(final String... args) {
    final Response<EntitiesAndNotice> response = gson.fromJson(JSON, responseTypeToken.getType());
    final String value = response.ret.entities.get(1).details.get(3).value;
    System.out.println(value);
}

Output:

John_S


问:
How to convert comma-separated String to List?
Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for that?</p>
```<code>String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??
</code>```

答:
```<code>List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(Collectors.toList());
</code>```

Body:
Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for that?

String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??