答:
You could define such a methode to find out if a given permutation p has those triple zeros or two double zeros:

```<code>def has_triple_zeros(p):
    for i, e in enumerate(p[:-2]):  # e are elements (0s and 1s) of the perm
        if e == 0:  # we encounter a 0
            if p[i+1] == 0 and p[i+2] == 0:  # the two following are also 0s
                return True
    return False  # we made it to the end, no triple 0s

def has_two_double_zeros(p):
    nb_doubles = 0
    i = 0  # init loop
    while i < len(p[:-1]):
        if p[i] == 0:  # we encounter a first 0
            if p[i+1] == 0:  # there is one next to it
                nb_doubles += 1
            i += 1  # skip the next element (already treated, cannot start new double)
        i += 1  # increment the loop
    return nb_doubles == 2

for p in lst:  # here, lst is your list of permutations
    print(p, has_two_double_zeros(p), has_triple_zeros(p))
</code>```

Then just read your list of permutations and delete if it matches one of your criteria. This is an idea:

```<code>res = list()  # result
for p in lst:
    if not (has_two_double_zeros(p) or has_triple_zeros(p)):
        res.append(p)

print(res)
</code>```

Title: Python: Remove sublist from a nested list following a criterion

Body:
I'm trying to remove sublists from a nested list containing all the possible permutation of [1, 1, 1, 0, 0, 0, 0]

[[0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 0, 1, 1, 0, 0, 1], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 1], [1, 1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0], [1, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 0], [1, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1, 1], [1, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1], [1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1], [0, 0, 1, 1, 0, 1, 0]]

I want to remove all the sublists in which there are 3 consecutive 0 or two couples of consecutive 0 (eg. i want to remove [1, 0, 1, 0, 0, 0, 1] or [0, 0, 1, 1, 0, 0, 1]).

Can someone give me an advice on how to proceed? Thanks in advance!

Body:
You could define such a methode to find out if a given permutation p has those triple zeros or two double zeros:

def has_triple_zeros(p):
    for i, e in enumerate(p[:-2]):  # e are elements (0s and 1s) of the perm
        if e == 0:  # we encounter a 0
            if p[i+1] == 0 and p[i+2] == 0:  # the two following are also 0s
                return True
    return False  # we made it to the end, no triple 0s

def has_two_double_zeros(p):
    nb_doubles = 0
    i = 0  # init loop
    while i < len(p[:-1]):
        if p[i] == 0:  # we encounter a first 0
            if p[i+1] == 0:  # there is one next to it
                nb_doubles += 1
            i += 1  # skip the next element (already treated, cannot start new double)
        i += 1  # increment the loop
    return nb_doubles == 2

for p in lst:  # here, lst is your list of permutations
    print(p, has_two_double_zeros(p), has_triple_zeros(p))

Then just read your list of permutations and delete if it matches one of your criteria. This is an idea:

res = list()  # result
for p in lst:
    if not (has_two_double_zeros(p) or has_triple_zeros(p)):
        res.append(p)

print(res)


来源: stackexchange

问:
How do I hide anchor text without hiding the anchor?
Say I have the following markup:

```<code><li><a href="somehwere">Link text</a></li>
</code>```

If I have a background image on the a tag, how would I hide the link text using just css? font-size:0 seems to work fine on the a tag apart from in ie7 little blobs show.

Thanks for help so far I have used line-height: 0; and font-size: 0; and text-indent: -999px. But it still shows up some blobs in safari, any ideas?

答: I was able to fix this problem by setting <b> font-size: 0 </b>. </p>

ContentLicense: CC BY-SA 4.0

Body:
Say I have the following markup:

Link text

If I have a background image on the a tag, how would I hide the link text using just css? font-size:0 seems to work fine on the a tag apart from in ie7 little blobs show.

Thanks for help so far I have used line-height: 0; and font-size: 0; and text-indent: -999px. But it still shows up some blobs in safari, any ideas?

Body: I was able to fix this problem by setting  font-size: 0 .

ContentLicense: CC BY-SA 3.0


问:
.htaccess rewritecond rewrite case level 2 folder=info
I wanted to set .htaccess to rewrite:

```<code>example.com/bla/info/
</code>```

to

```<code>example.com/info/index.php?q=bla

example.com/bla/info/txt/
</code>```

to

```<code>example.com/info/index.php?q=bla&t=txt
</code>```

I wanted the browser still to display:

```<code>example.com/bla/info/txt/
</code>```

I didn't want rewrite in the level 2 rewrites, like:

```<code>example.com/bla/xxx/
</code>```

or

```<code>example.com/ccc/zzz/aaa/
</code>```

but

```<code>example.com/silly/info/
</code>```

would work as well as

```<code>example.com/strange/info/mytxt/
</code>```

Did this make sense?

Any help?

答:
you got me in the right track.

i ended up with something like this:

```<code>RewriteRule ^([^/\.]+)/info/?$ example/info/index.php?q=$1 [L]
</code>```

thanks a lot

OwnerDisplayName: Hugo Gameiro

Body:
I wanted to set .htaccess to rewrite:

example.com/bla/info/

to

example.com/info/index.php?q=bla

example.com/bla/info/txt/

to

example.com/info/index.php?q=bla&t=txt

I wanted the browser still to display:

example.com/bla/info/txt/

I didn't want rewrite in the level 2 rewrites, like:

example.com/bla/xxx/

or

example.com/ccc/zzz/aaa/

but

example.com/silly/info/

would work as well as

example.com/strange/info/mytxt/

Did this make sense?

Any help?

Body:
you got me in the right track.

i ended up with something like this:

RewriteRule ^([^/\.]+)/info/?$ example/info/index.php?q=$1 [L]

thanks a lot

ContentLicense: CC BY-SA 2.5


问:
.hasClass() seem to always return true when used inside a .click() function, why?
```<code><ul id="list">
    <li>item 1</li>
    <li>item 2</li>
</ul>

$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});
</code>```

Why does "$(this).hasClass('active')" always return true?

答:
No it doesn't

http://jsbin.com/ubocu3/2

it returns false (the first time)

Body:
item 1

item 2

$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});

Why does "$(this).hasClass('active')" always return true?


问:
How to use Tensorflow's PTB model example?
I'm trying out Tensorflow's rnn example.
With some problems at the start I could run the example in order to train the ptb and now I have a model trained.

How do I exactly use the model now to create sentences without having to train every time again?

I'm running it with a command like python ptb_word_lm.py --data_path=/home/data/ --model medium --save_path=/home/medium

Is there a example somewhere on how to use the trained model to make sentences?

答:
This website has an answer with an alteration on the PTB word script, working currently with Tensorflow version 1.0

http://deeplearningathome.com/2016/10/Text-generation-using-deep-recurrent-neural-networks.html


问:
using multiple return statements in a c++ function
I was wondering if it might be sort of advantageous for a c++ compiler if there's only one return statement in a function. one of my ex-bosses once told me so but I don't get the point if there would be any difference between declaring a return variable or simply having multiple return statements, e.g. in a switch-case statement.

So my question is: is there any difference, maybe in quality, performance or stack memory savings?

答:
Ideally, you always want one return statement, as this ensures that your code will ALWAYS return a value, and you set that value before returning it, such as:

```<code>int getNumber(int x){
    int toReturn = 0;
    if (x == 0){
        toReturn = 5;
    } else {
         toReturn = 10;
    }
    return toReturn;
}
</code>```

If you were to return in the "if" statement, then you would also have to return in the "else" statement, and if you ever wanted to add more cases, you'd have to add more "return" statements - which could prove to be very confusing if you have a multitude of cases, and could eventually impact your compile time if you're not careful.

However, there are some times when you definitely want more than one return statement. This occurs when there is some further operation that you want to stop - such as in recursion, or in scoring algorithms that have some sort of threshold for one or more parameters that disqualifies the object being scored.

For example, if you want to score something based on its distance, but you always want the score to be zero if the distance is less than ten, then:

```<code>float scoreObject(float distance){
    if(distance < 10){
        return 0;
    }
    float score;
    //Scoring function continues here, presumably with some time-intensive
    //calculations that the above return statement avoids doing.
    return score;
    //Please note that this would result in a crash as score is not initialized.
}
</code>```

Body:
Ideally, you always want one return statement, as this ensures that your code will ALWAYS return a value, and you set that value before returning it, such as:

int getNumber(int x){
    int toReturn = 0;
    if (x == 0){
        toReturn = 5;
    } else {
         toReturn = 10;
    }
    return toReturn;
}

If you were to return in the "if" statement, then you would also have to return in the "else" statement, and if you ever wanted to add more cases, you'd have to add more "return" statements - which could prove to be very confusing if you have a multitude of cases, and could eventually impact your compile time if you're not careful.

However, there are some times when you definitely want more than one return statement. This occurs when there is some further operation that you want to stop - such as in recursion, or in scoring algorithms that have some sort of threshold for one or more parameters that disqualifies the object being scored.

For example, if you want to score something based on its distance, but you always want the score to be zero if the distance is less than ten, then:

float scoreObject(float distance){
    if(distance < 10){
        return 0;
    }
    float score;
    //Scoring function continues here, presumably with some time-intensive
    //calculations that the above return statement avoids doing.
    return score;
    //Please note that this would result in a crash as score is not initialized.
}


问:
HTML5 save Canvas image every few seconds
How can I save every few seconds a canvas Image to a Folder.

I have a Basic canvas drawing function and a download function to save the image like this:

```<code><canvas></canvas>

var link = document.createElement('a');
    link.innerHTML = 'download image';
link.addEventListener('click', function(ev) {
    link.href = canvas.toDataURL();
    link.download = "mypainting.png";
}, false);
document.body.appendChild(link);
</code>```

I want to implemente a button named start / stop.

If the user clicks on that button I want to save every second the canvas Image.

Every Image shall be saved as a new file.

How would this be possible?
Is it even possible?

答:
I use this script.

```<code>    function saveImageAs(canvas, filename, type, quality){      // No IE <10 support. Chrome URL bug for very large images may crash
        var anchorElement, event, blob;
        type = type ? "png" : type;

        // for IE >= 10
        if(canvas.msToBlob !== undefined && navigator.msSaveBlob !== undefined){
           blob = canvas.msToBlob();
           navigator.msSaveBlob(blob, filename + "." + type);
           return;
        }
        anchorElement = document.createElement('a');    // Create a download link
        if(type.toLowerCase() === "jpg" || type.toLowerCase() === "jpeg"){
            quality = quality ? quality : 0.9;
            anchorElement.href = canvas.toDataURL("image/jpeg",quality);         // attach the image data URL
        }else{
            anchorElement.href = canvas.toDataURL();         // attach the image data URL
        }
        // check for download attribute
        if ( anchorElement.download !== undefined ) {
            anchorElement.download = filename + "." + type; // set the download filename
            if (typeof MouseEvent === "function") {     // does the browser support the object MouseEvent
                event = new MouseEvent( "click", {view  : window, bubbles: true,cancelable : true} );
                anchorElement.dispatchEvent(event); // simulate a click on the download link.
            } else
            if (anchorElement.fireEvent) {          // if no MouseEvent object try fireEvent
                anchorElement.fireEvent("onclick");
            }
        }
    }
</code>```

Then a simple download timer.

```<code>var timeoutHandle;
function startDownloads(){
    saveImageAs(canvas,"snap.jpg","jpeg");
    timeoutHandle = setTimeout(startDownloads,2000);
}
function stopDownloads(){
    clearTimeout(timeoutHandle);
}
</code>```

Where the file is put and what name it gets is up to the client. There is no guarantee that the file will end up on the client's drive, nor is there any way to know if the download has completed.

Note Shame that the original answer was deleted. Not everyone will agree on methods, but it does not mean the method is wrong. "Will not work" only applies to bad code, not client preferences. Or should we all remove answers because some users block Javascript and thus any javascript answer will not work..

Good to see the original answer back.

Body:
How can I save every few seconds a canvas Image to a Folder.

I have a Basic canvas drawing function and a download function to save the image like this:

<canvas></canvas>

var link = document.createElement('a');
    link.innerHTML = 'download image';
link.addEventListener('click', function(ev) {
    link.href = canvas.toDataURL();
    link.download = "mypainting.png";
}, false);
document.body.appendChild(link);

I want to implemente a button named start / stop.

If the user clicks on that button I want to save every second the canvas Image.

Every Image shall be saved as a new file.

How would this be possible?
Is it even possible?

Body:
I use this script.

    function saveImageAs(canvas, filename, type, quality){      // No IE <10 support. Chrome URL bug for very large images may crash
        var anchorElement, event, blob;
        type = type ? "png" : type;

        // for IE >= 10
        if(canvas.msToBlob !== undefined && navigator.msSaveBlob !== undefined){
           blob = canvas.msToBlob();
           navigator.msSaveBlob(blob, filename + "." + type);
           return;
        }
        anchorElement = document.createElement('a');    // Create a download link
        if(type.toLowerCase() === "jpg" || type.toLowerCase() === "jpeg"){
            quality = quality ? quality : 0.9;
            anchorElement.href = canvas.toDataURL("image/jpeg",quality);         // attach the image data URL
        }else{
            anchorElement.href = canvas.toDataURL();         // attach the image data URL
        }
        // check for download attribute
        if ( anchorElement.download !== undefined ) {
            anchorElement.download = filename + "." + type; // set the download filename
            if (typeof MouseEvent === "function") {     // does the browser support the object MouseEvent
                event = new MouseEvent( "click", {view  : window, bubbles: true,cancelable : true} );
                anchorElement.dispatchEvent(event); // simulate a click on the download link.
            } else
            if (anchorElement.fireEvent) {          // if no MouseEvent object try fireEvent
                anchorElement.fireEvent("onclick");
            }
        }
    }

Then a simple download timer.

var timeoutHandle;
function startDownloads(){
    saveImageAs(canvas,"snap.jpg","jpeg");
    timeoutHandle = setTimeout(startDownloads,2000);
}
function stopDownloads(){
    clearTimeout(timeoutHandle);
}

Where the file is put and what name it gets is up to the client. There is no guarantee that the file will end up on the client's drive, nor is there any way to know if the download has completed.

Note Shame that the original answer was deleted. Not everyone will agree on methods, but it does not mean the method is wrong. "Will not work" only applies to bad code, not client preferences. Or should we all remove answers because some users block Javascript and thus any javascript answer will not work..

Good to see the original answer back.


问:
Prerendering Vue.js form
I'm using the prerendering plugin suggested in the Vue.js documentation. When I am using a network throttling (good 3G in chrome devtools), I'm receiving my html with the prerendered content and then the app JS. I have some inputs that are two-way data-binded to components data (with v-model).

If my user starts typing before the app is loaded, when the app loads, it binds the input to the data and place its default value ('') in the input. Is there any way to keep the user inputs ?

答:
I was hoping you could do it in mounted using refs to pull the value, but it seems the binding is already done by then.

Instead, you can look at what's in the DOM in created or beforeMount and set the value from there. The snippet below gives you 4 seconds to type before mounting.

setTimeout(() => {
  new Vue({
    el: '#app',
    data: {
      foo: null
    },
    created() {
      this.foo = document.querySelector('#app [v-model="foo"]').value;
    }
  });
}, 4000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <input v-model="foo" />
  {{foo}}
</div></code>```

Title: Prerendering Vue.js form

Body:
I was hoping you could do it in mounted using refs to pull the value, but it seems the binding is already done by then.

Instead, you can look at what's in the DOM in created or beforeMount and set the value from there. The snippet below gives you 4 seconds to type before mounting.

setTimeout(() => {
  new Vue({
    el: '#app',
    data: {
      foo: null
    },
    created() {
      this.foo = document.querySelector('#app [v-model="foo"]').value;
    }
  });
}, 4000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <input v-model="foo" />
  {{foo}}
</div>


问:
Run an Ansible task only when the variable contains a specific string
I have multiple tasks depend from the value of variable1. I want to check if the value is in {{ variable1 }} but I get an error:

- name: do something when the value in variable1
  command: <command>
  when: "'value' in {{ variable1 }}"
```

I'm using ansible 2.0.2

答:
I used

```<code>failed_when: not(promtool_version.stdout.find('1.5.2') != -1)
</code>```

means - failed only when the previously registered variable "promtool_version" doesn't contains string '1.5.2'.

Body:
I have multiple tasks depend from the value of variable1. I want to check if the value is in {{ variable1 }} but I get an error:

- name: do something when the value in variable1
  command: <command>
  when: "'value' in {{ variable1 }}"

I'm using ansible 2.0.2

Body:
I used

failed_when: not(promtool_version.stdout.find('1.5.2') != -1)

means - failed only when the previously registered variable "promtool_version" doesn't contains string '1.5.2'.


问:
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 ?

答: After opening your Logcat (Inside Android Studio), on the left side you will see menu icons, select the Settings one and you can check which information you would like to see in the Logcat.


问:
Rails post model for news and blog view
I have a post model and posts controller with an attribute format so id like to split the views out based on this attribute i.e. foo.com/blog/xxx if the format is blog and foo.com/news/xxx if the format is news.

resources :posts

```<code>def index
  @posts = Post.where(draft: 'false').order(publish_date: :desc)
end

def show
  @post = Post.find_by!(slug: params[:id])
end
</code>```

I can easily so something like this for the index view but im unsure about the show route

get '/new', to: 'posts#news'

```<code>def news
  @posts = Post.where(draft: 'false', format: 'news').order(publish_date: :desc)
end
</code>```

答:
You can try this way:

Create two different methods to use within your routes.rb, they will be inside the only one controller you want to have "PostsController", and make a verification of the params attribute in every @post that pass through the show method, something like:

```<code>class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
    if @post.format == 'news'
      redirect_to news_index_path
    elsif @post.format == 'blog'
      redirect_to blog_index_path
    end
  end

  def blog_index
  end

  def news_index
  end
  ...
</code>```

Then specify in your routes.rb the path to every method, as you made within the show method in order to use the redirect_to method:

```<code>  get '/blog/:id',  to: 'posts#blog_index', as: 'blog_index'
  get '/news/:id',  to: 'posts#news_index', as: 'news_index'
</code>```

This is, when you pass a @post with the format attribute equal to blog you'll be redirected to the blog_index_path, which will load the blog_index view within your posts folder in app/views/posts. Something seemed will happen when the @post.format is news.

```<code>├── blog_index.html.erb
├── index.html.erb
├── news_index.html.erb
└── show.html.erb

0 directories, 4 files
</code>```

This will have a very little delay and a very quick change in the route, everytime you have to pass from posts#show to the next route.

I've made a repo, in order you can check how this works.

Title: Rails post model for news and blog view

Body:
I have a post model and posts controller with an attribute format so id like to split the views out based on this attribute i.e. foo.com/blog/xxx if the format is blog and foo.com/news/xxx if the format is news.

resources :posts

def index
  @posts = Post.where(draft: 'false').order(publish_date: :desc)
end

def show
  @post = Post.find_by!(slug: params[:id])
end

I can easily so something like this for the index view but im unsure about the show route

get '/new', to: 'posts#news'

def news
  @posts = Post.where(draft: 'false', format: 'news').order(publish_date: :desc)
end

Body:
You can try this way:

Create two different methods to use within your routes.rb, they will be inside the only one controller you want to have "PostsController", and make a verification of the params attribute in every @post that pass through the show method, something like:

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
    if @post.format == 'news'
      redirect_to news_index_path
    elsif @post.format == 'blog'
      redirect_to blog_index_path
    end
  end

  def blog_index
  end

  def news_index
  end
  ...

Then specify in your routes.rb the path to every method, as you made within the show method in order to use the redirect_to method:

  get '/blog/:id',  to: 'posts#blog_index', as: 'blog_index'
  get '/news/:id',  to: 'posts#news_index', as: 'news_index'

This is, when you pass a @post with the format attribute equal to blog you'll be redirected to the blog_index_path, which will load the blog_index view within your posts folder in app/views/posts. Something seemed will happen when the @post.format is news.

├── blog_index.html.erb
├── index.html.erb
├── news_index.html.erb
└── show.html.erb

0 directories, 4 files

This will have a very little delay and a very quick change in the route, everytime you have to pass from posts#show to the next route.

I've made a repo, in order you can check how this works.


问:
where to find source code link
i want to dowmload android source  as repo init -u git://android.git.kernel.org/platform/manifest.git -b android-2.2_r1,i know the method of downloads ,but i donot know  where to find "android-2.2_r1" ,if i want to find 2.1, how to modify the  parameter after -b,could you give a link that tell me which versions may be download. thanks </p>

答:
Here   is the complete guide and

 Here  is the complete tutorial

Title: where to find source code link


问:
various div contained in parent div and responsive to parent size
I would like to have all the div(1..7) inside the parent div next to each other and that when the size of the screen changes (portrait,landscape, scale) the organization of the div1..7 is done automatically so that they are always contained in the parent div.

So far I succeeded in:

have a centered parent which is responsive to any screen situation

all the div1..7 inside the parent div (but they are on top of each other)

What I miss:

div1..7 next to each other

div1..7 re-organized/resized automatically when the size of parent div change due to screen change.

html {background: #eee;}
* {padding: 0; margin: 0;}
html, body {height: 100%;text-align: center;}
.container{display: inline-block; vertical-align: middle; margin-top: 10vh; background: rgba(200,200,200,0.5);}
@media screen and (orientation:landscape) {.container {width: 60vw; height: 80vh;}}
@media screen and (orientation:portrait) {.container {width: 80vw; height: 80vh;}}

.div1 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div2 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div3 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div4 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}
.div5 {display: block; background: rgba(0,80,0,0.5); width:200px; height:100px;float:left;}
.div6 {display: block; background: rgba(0,0,80,0.5); width:100px; height:200px;float:left;}
.div7 {display: block; background: rgba(80,0,0,0.5); width:100px; height:100px;float:left;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="div1"></div>
 <div class="div2"></div>
 <div class="div3"></div>
 <div class="div4"></div>
 <div class="div5"></div>
 <div class="div6"></div>
 <div class="div7"></div>
</div></code>```

答:
Not too sure of what you really expect at the end .

fixed width and height using the window's size might come too small at one point.

boxes of different heights and widths can wrap onto few lines but won't imbricate

To center x,y the container , you may use the display table or flex properties. and avoid margins.It will allow also scrolling if the window comes too small.

here is a examples , do not hesitate to clarify :)

table display

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
}

.container>div {
  float: left;
  /*see me */
  box-shadow: 0 0 0 2px;
}

html {
  height: 100%;
  width: 100%;
  display: table;
  text-align: center;
  background: #eee;
}

body {
  display: table-cell;
  vertical-align: middle;
}
.container {
  display:inline-block;
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    max-width: 60vw;
  }
}

@media screen and (orientation:portrait) {
  .container {
    max-width: 80vw;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div></code>```

flex display

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
}

.container>div {
  float: left;
}

html {
  height: 100%;
  display: flex;
  background: #eee;
}

body {
  margin:auto;
  display:flex;/* .container will wrap float elements and will show bg */
}
.container {
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    max-width: 60vw;
  }
}

@media screen and (orientation:portrait) {
  .container {
    max-width: 80vw;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div></code>```

display:grid will alow divs to imbricate / span through columns or rows.

it also centers easily x,y a single element:

example with static sizes:

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
  grid-row: span 2;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
  grid-column: span 2;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
}

.container>div {
  margin: auto;
}

html {
  height: 100%;
  display: grid;
  background: #eee;
}

body {
  margin: auto;
  /* to center x,y */
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill,100px);
  grid-gap: 1vh;
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    width: 60vw;
    height: 80vh;
  }
}

@media screen and (orientation:portrait) {
  .container {
    width: 80vw;
    height: 80vh;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div></code>```

unlucky example resizing

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
  max-height:36vh;
  max-width:18vh;
  grid-row: span 2;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
  max-height:18vh;
  max-width:36vh;
  grid-column: span 2;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
  max-height:18vh;
  max-width:18vh;
}

.container>div {
  margin: auto;
}

html {
  height: 100%;
  display: grid;
  background: #eee;
}

body {
  margin: auto;
  /* to center x,y */
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill,minmax(10vh, 20vh));
  grid-gap: 1vh;
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    width: 60vw;
    height: 80vh;
  }
}

@media screen and (orientation:portrait) {
  .container {
    width: 80vw;
    height: 80vh;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div></code>```

Body:
Not too sure of what you really expect at the end .

fixed width and height using the window's size might come too small at one point.

boxes of different heights and widths can wrap onto few lines but won't imbricate

To center x,y the container , you may use the display table or flex properties. and avoid margins.It will allow also scrolling if the window comes too small.

here is a examples , do not hesitate to clarify :)

table display

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
}

.container>div {
  float: left;
  /*see me */
  box-shadow: 0 0 0 2px;
}

html {
  height: 100%;
  width: 100%;
  display: table;
  text-align: center;
  background: #eee;
}

body {
  display: table-cell;
  vertical-align: middle;
}
.container {
  display:inline-block;
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    max-width: 60vw;
  }
}

@media screen and (orientation:portrait) {
  .container {
    max-width: 80vw;
  }
}

<div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div>

flex display

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
}

.container>div {
  float: left;
}

html {
  height: 100%;
  display: flex;
  background: #eee;
}

body {
  margin:auto;
  display:flex;/* .container will wrap float elements and will show bg */
}
.container {
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    max-width: 60vw;
  }
}

@media screen and (orientation:portrait) {
  .container {
    max-width: 80vw;
  }
}

<div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div>

display:grid will alow divs to imbricate / span through columns or rows.

it also centers easily x,y a single element:

example with static sizes:

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
  grid-row: span 2;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
  grid-column: span 2;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
}

.container>div {
  margin: auto;
}

html {
  height: 100%;
  display: grid;
  background: #eee;
}

body {
  margin: auto;
  /* to center x,y */
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill,100px);
  grid-gap: 1vh;
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    width: 60vw;
    height: 80vh;
  }
}

@media screen and (orientation:portrait) {
  .container {
    width: 80vw;
    height: 80vh;
  }
}

<div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div>

unlucky example resizing

.div6,
.div3 {
  background: rgba(0, 0, 80, 0.5);
  width: 100px;
  height: 200px;
  max-height:36vh;
  max-width:18vh;
  grid-row: span 2;
}

.div2,
.div5 {
  background: rgba(0, 80, 0, 0.5);
  width: 200px;
  height: 100px;
  max-height:18vh;
  max-width:36vh;
  grid-column: span 2;
}

.div7,
.div1,
.div4 {
  background: rgba(80, 0, 0, 0.5);
  width: 100px;
  height: 100px;
  max-height:18vh;
  max-width:18vh;
}

.container>div {
  margin: auto;
}

html {
  height: 100%;
  display: grid;
  background: #eee;
}

body {
  margin: auto;
  /* to center x,y */
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill,minmax(10vh, 20vh));
  grid-gap: 1vh;
  background: rgba(200, 200, 200, 0.5);
}

@media screen and (orientation:landscape) {
  .container {
    width: 60vw;
    height: 80vh;
  }
}

@media screen and (orientation:portrait) {
  .container {
    width: 80vw;
    height: 80vh;
  }
}

<div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
  <div class="div3"></div>
  <div class="div4"></div>
  <div class="div5"></div>
  <div class="div6"></div>
  <div class="div7"></div>
</div>


问:
swift UIImage blue square
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

```<code>sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)
</code>```

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction

答:
A couple things.  I've never seen setImage used with an empty array of states.  Even though the docs say "if the state isn't specified, Normal will be used", try explicitly stating the states where you want your image to be applied:

Try doing this:

```<code>// let's make sure sender is really a button
if let aButton = sender as? UIButton
{
    if let nonBlueImage = UIImage(named: "o.png")
    {
        aButton.setImage(nonBlueImage, for: [.normal, .selected, .highlighted])
    } else {
        print("couldn't find o.png")
    }
} else {
    print("suprise, sender wasn't really a button")
}
</code>```

Title: swift UIImage blue square

Body:
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction

Body:
A couple things.  I've never seen setImage used with an empty array of states.  Even though the docs say "if the state isn't specified, Normal will be used", try explicitly stating the states where you want your image to be applied:

Try doing this:

// let's make sure sender is really a button
if let aButton = sender as? UIButton
{
    if let nonBlueImage = UIImage(named: "o.png")
    {
        aButton.setImage(nonBlueImage, for: [.normal, .selected, .highlighted])
    } else {
        print("couldn't find o.png")
    }
} else {
    print("suprise, sender wasn't really a button")
}


问:
how to search for tags in elasticsearch
I am creating search for photo gallery project where photos could have upto 50 tags (just like in shutterstock and fotolia). I am creating my search in elasticsearch. I have a field with datatype keyword in elasticsearch. When query comes like "Abstract Background", I want to search for abstract and background in all the keywords of the images and sort them by their relevancy. It should not match abstr backgrou. I wrote a query like this

```<code> "query": {
    "bool": {
      "should": [
        {
          "match": {
            "keyword": {
              "query": "abstract, background"
            }
          }
        }
      ]
    }
  }
</code>```

It only works for matching single keywords. I want to match for multiple keywords and also sort them by their relevancy. Thanks

-----EDIT------

These are my mappings.
Title field works fine. Category is just used for aggregations and keyword is the main field to match.

```<code>PUT /freevects
{
  "mappings": {
    "photos": {
      "properties": {
        "title": {
          "type": "text",
          "boost": 1.9,
          "analyzer": "standard"
        },
        "keyword": {
          "type": "keyword",
          "boost": 1.4
        },
        "category": {
          "type": "keyword",
          "index": false
        },
        "quality": {
          "type": "short",
          "index": false,
          "boost": 1.1
        },
        "downloads": {
          "type": "integer",
          "index": false,
          "boost": 1.1
        },
        "likes": {
          "type": "integer",
          "index": false,
          "boost": 1
        },
        "filename": {
          "type": "keyword",
          "index": false
        },
        "type": {
          "type": "keyword",
          "index": false
        },
        "free": {
          "type": "short",
          "index": false
        },
        "created": {
          "type": "date",
          "index": false
        }
      }
    }
  }
}
</code>```

答:
The problem is with the mapping of keyword field. It is of type: keyword in your mapping.
This doesn't tokenize your search query and the indexed values. So when you search, the terms are searched as is.

Example:

Searching for: "abstract, background" (as you did in your question), will actually search only exact occurrences of "abstract, background" in the keyword field.

Change the mapping of keyword field to type: text

```<code>"keyword": {
  "type": "text",
  "boost": 1.4
}
</code>```

And index your values as:

```<code>{
  "keyword": ["abstract", "background"]
}
</code>```

Reference:
https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-keyword-analyzer.html

Query for searching tags:

```<code>{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "keyword": "abstract"
          }
        },
        {
          "match": {
            "keyword": "background"
          }
        }
      ]
    }
  }
}
</code>```

Title: how to search for tags in elasticsearch

Body:
I am creating search for photo gallery project where photos could have upto 50 tags (just like in shutterstock and fotolia). I am creating my search in elasticsearch. I have a field with datatype keyword in elasticsearch. When query comes like "Abstract Background", I want to search for abstract and background in all the keywords of the images and sort them by their relevancy. It should not match abstr backgrou. I wrote a query like this

 "query": {
    "bool": {
      "should": [
        {
          "match": {
            "keyword": {
              "query": "abstract, background"
            }
          }
        }
      ]
    }
  }

It only works for matching single keywords. I want to match for multiple keywords and also sort them by their relevancy. Thanks

-----EDIT------

These are my mappings.
Title field works fine. Category is just used for aggregations and keyword is the main field to match.

PUT /freevects
{
  "mappings": {
    "photos": {
      "properties": {
        "title": {
          "type": "text",
          "boost": 1.9,
          "analyzer": "standard"
        },
        "keyword": {
          "type": "keyword",
          "boost": 1.4
        },
        "category": {
          "type": "keyword",
          "index": false
        },
        "quality": {
          "type": "short",
          "index": false,
          "boost": 1.1
        },
        "downloads": {
          "type": "integer",
          "index": false,
          "boost": 1.1
        },
        "likes": {
          "type": "integer",
          "index": false,
          "boost": 1
        },
        "filename": {
          "type": "keyword",
          "index": false
        },
        "type": {
          "type": "keyword",
          "index": false
        },
        "free": {
          "type": "short",
          "index": false
        },
        "created": {
          "type": "date",
          "index": false
        }
      }
    }
  }
}

Body:
The problem is with the mapping of keyword field. It is of type: keyword in your mapping.
This doesn't tokenize your search query and the indexed values. So when you search, the terms are searched as is.

Example:

Searching for: "abstract, background" (as you did in your question), will actually search only exact occurrences of "abstract, background" in the keyword field.

Change the mapping of keyword field to type: text

"keyword": {
  "type": "text",
  "boost": 1.4
}

And index your values as:

{
  "keyword": ["abstract", "background"]
}

Reference:
https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-keyword-analyzer.html

Query for searching tags:

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "keyword": "abstract"
          }
        },
        {
          "match": {
            "keyword": "background"
          }
        }
      ]
    }
  }
}


问:
Dropbox SDK for iOS works on simulator, not on actual device
I am working on a project involving an iOS app communicating with another device by way of syncing data through Dropbox.

It works perfectly fine when I run the software on the iPhone Simulator (it syncs, uploads, downloads without issues), but when I load it onto my actual device, I get load/save errors.

The app on both the simulator and iPhone was successfully linked to my Dropbox account.

Some errors when I try do load requests:

```<code>2015-05-18 23:27:19.385 [2218:923269] [ERROR] DBRequest#connectionDidFinishLoading: error moving temp file to desired location: The operation couldn’t be completed. (Cocoa error 516.)

2015-05-18 23:27:19.387 [2218:923269] [WARNING] DropboxSDK: error making request to /1/files/dropbox/Projekt 2 (1)/Program/Units.txt - (516) Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x174077700 {path=/Projekt 2 (1)/Program/Units.txt, destinationPath=/...}
</code>```

Samples of the dropbox related code in my app:

In AppDelegate.swift:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let session = DBSession(appKey: "myAppKey", appSecret: "myAppSecret", root: kDBRootDropbox)
    DBSession.setSharedSession(session)
    ...
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    if DBSession.sharedSession().handleOpenURL(url) {
        if DBSession.sharedSession().isLinked() {
            // Linking was successfull.
        }
        return true
    }
    return false
}
</code>```

In ViewControllerCausingErrors.swift:

```<code>class ViewControllerCausingErrors: DBRestClientDelegate {

    var dbClient = DBRestClient()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.dbClient = DBRestClient(session: DBSession.sharedSession())
        self.dbClient.delegate = self
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated: animated)
        if !DBSession.sharedSession().isLinked() {
            DBSession.sharedSession().linkFromController(self)
        }
    }
}
</code>```

Chunk of code i use to download a file, elsewhere in the VC

```<code>if let localPath = NSBundle.mainBundle().pathForResource("Units", ofType: "txt") {
    // Download file from Dropbox to local path.
    let dropboxPath = Constants.Dropbox.Download.UnitFilePath
    self.dbClient.loadFile(dropboxPath, intoPath: localPath)
}
</code>```

Any help is greatly appreciated.

答:
I think problem is in the NSBundle.mainBundle().pathForResource("Units", ofType: "txt"). NSBundle is used in simulator but not in actual device. You just place Units.txt in your loadFile function

self.dbClient.loadFile(dropboxPath, intoPath: "Units.txt")

Body:
I am working on a project involving an iOS app communicating with another device by way of syncing data through Dropbox.

It works perfectly fine when I run the software on the iPhone Simulator (it syncs, uploads, downloads without issues), but when I load it onto my actual device, I get load/save errors.

The app on both the simulator and iPhone was successfully linked to my Dropbox account.

Some errors when I try do load requests:

2015-05-18 23:27:19.385 [2218:923269] [ERROR] DBRequest#connectionDidFinishLoading: error moving temp file to desired location: The operation couldn’t be completed. (Cocoa error 516.)

2015-05-18 23:27:19.387 [2218:923269] [WARNING] DropboxSDK: error making request to /1/files/dropbox/Projekt 2 (1)/Program/Units.txt - (516) Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x174077700 {path=/Projekt 2 (1)/Program/Units.txt, destinationPath=/...}

Samples of the dropbox related code in my app:

In AppDelegate.swift:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let session = DBSession(appKey: "myAppKey", appSecret: "myAppSecret", root: kDBRootDropbox)
    DBSession.setSharedSession(session)
    ...
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    if DBSession.sharedSession().handleOpenURL(url) {
        if DBSession.sharedSession().isLinked() {
            // Linking was successfull.
        }
        return true
    }
    return false
}

In ViewControllerCausingErrors.swift:

class ViewControllerCausingErrors: DBRestClientDelegate {

    var dbClient = DBRestClient()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.dbClient = DBRestClient(session: DBSession.sharedSession())
        self.dbClient.delegate = self
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated: animated)
        if !DBSession.sharedSession().isLinked() {
            DBSession.sharedSession().linkFromController(self)
        }
    }
}

Chunk of code i use to download a file, elsewhere in the VC

if let localPath = NSBundle.mainBundle().pathForResource("Units", ofType: "txt") {
    // Download file from Dropbox to local path.
    let dropboxPath = Constants.Dropbox.Download.UnitFilePath
    self.dbClient.loadFile(dropboxPath, intoPath: localPath)
}

Any help is greatly appreciated.


问:
Windows batch allow numbers and blank only input for variable
I have the following line of code:

```<code>for /f "tokens=1* delims=0123456789" %%a in ("A0%att:"=%") do if not "%%b"=="" echo Only numbers, no spaces or letters! && goto next
</code>```

It works great, however, if there is no input, the batch crashes. Is there any adjustment to incl. or excl. a 'non entry'?

Thanks!

答:
Sorry for the super late reply, but I think I found a workaround to exclude empty input:

```<code>@echo off
set /p "att="

if "%att%"=="" goto :invalid

for /f "tokens=1* delims=0123456789" %%a in ("A0%att:"=%") do (
    if not "%%b"=="" goto :invalid
)

echo It is a number
pause
    goto :next

:invalid
echo Only numbers, no spaces or letters!
pause
    goto :next
</code>```

The script above does:

Get input

Check if input is empty, if true, goto :invalid

Use the for loop you provided to check if %att% is a number

Body:
I have the following line of code:

for /f "tokens=1* delims=0123456789" %%a in ("A0%att:"=%") do if not "%%b"=="" echo Only numbers, no spaces or letters! && goto next

It works great, however, if there is no input, the batch crashes. Is there any adjustment to incl. or excl. a 'non entry'?

Thanks!

Body:
Sorry for the super late reply, but I think I found a workaround to exclude empty input:

@echo off
set /p "att="

if "%att%"=="" goto :invalid

for /f "tokens=1* delims=0123456789" %%a in ("A0%att:"=%") do (
    if not "%%b"=="" goto :invalid
)

echo It is a number
pause
    goto :next

:invalid
echo Only numbers, no spaces or letters!
pause
    goto :next

The script above does:

Get input

Check if input is empty, if true, goto :invalid

Use the for loop you provided to check if %att% is a number


问:
iTunes software service authentication error domain error 434
I am uploading iPhone application using latest xCode 8. I have good internet connection and all the relevant settings set up at iTunes connect. My distribution profiles are also set up correctly.

I am facing below error:-

iTunes software service authentication error domain error 434

答:
To resolve this error follow these methods.

If you have not added app icons add them and try archiving.

Remove developer account and add account again. Press CMD + , to bring up preferences in Xcode and from accounts remove and add back account. Try archiving this.

Clean project (CMD + Shift + K), close Xcode, restart Xcode and
build project (CMD + B). Check for warnings. ( if you are using
cocapods some times Xcode asks you to change project settings in
warning. Click on warning and fix it. Xcode fixes it automatically)

Simply retry archiving.

ToDo. Add More solutions


问:
Swift - Cannot invoke initialiser for type dispatch_time_t
I've taken over some Swift 2 code and trying to bring it up to Swift 3 (Xcode 8.3), but I'm stuck on one line.

The code is checking to see if a host is connected:

```<code>func isHostConnected(hostAddress : String) -> Bool {
    let request = NSMutableURLRequest(url: NSURL(string: hostAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)! as URL)
    request.timeoutInterval = 3
    request.httpMethod = "HEAD"

    let session = URLSession(configuration: URLSessionConfiguration.default)
    var responseCode = -1

    let group = DispatchGroup.init()
    group.enter()

    session.dataTask(with: request as URLRequest, completionHandler: {(_, response, _) in
        if let httpResponse = response as? HTTPURLResponse {
            responseCode = httpResponse.statusCode
        }
        group.leave()
    }).resume()

    group.wait(timeout: dispatch_time_t(DispatchTime.distantFuture)) //ERROR LINE
    return (responseCode == 401)
}
</code>```

I am getting an error on the line:

group.wait(timeout: dispatch_time_t(DispatchTime.distantFuture))

which reads:

Cannot invoke initializer for type 'dispatch_time_t' with an argument list of type '(DispatchTime)'

So it seems to be looking for an object of type DispatchTime as the parameter but I can't seem to find an answer on Google to match .distantFuture

Also, if I try:

group.wait(timeout: dispatch_time_t(.distantFuture))

I get an error saying:

Type of expression is ambiguous without more context

Thanks.

答:
It's way simpler actually :)

group.wait(timeout: .distantFuture)

Or if you'd like to wait say 5 seconds:

group.wait(timeout: .now() + .seconds(5))

Beautiful right

See also this way better answer

Apart from that...you should consider what @vadian says in his comment :)

Hope that helps.

Body:
I've taken over some Swift 2 code and trying to bring it up to Swift 3 (Xcode 8.3), but I'm stuck on one line.

The code is checking to see if a host is connected:

func isHostConnected(hostAddress : String) -> Bool {
    let request = NSMutableURLRequest(url: NSURL(string: hostAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)! as URL)
    request.timeoutInterval = 3
    request.httpMethod = "HEAD"

    let session = URLSession(configuration: URLSessionConfiguration.default)
    var responseCode = -1

    let group = DispatchGroup.init()
    group.enter()

    session.dataTask(with: request as URLRequest, completionHandler: {(_, response, _) in
        if let httpResponse = response as? HTTPURLResponse {
            responseCode = httpResponse.statusCode
        }
        group.leave()
    }).resume()

    group.wait(timeout: dispatch_time_t(DispatchTime.distantFuture)) //ERROR LINE
    return (responseCode == 401)
}

I am getting an error on the line:

group.wait(timeout: dispatch_time_t(DispatchTime.distantFuture))

which reads:

Cannot invoke initializer for type 'dispatch_time_t' with an argument list of type '(DispatchTime)'

So it seems to be looking for an object of type DispatchTime as the parameter but I can't seem to find an answer on Google to match .distantFuture

Also, if I try:

group.wait(timeout: dispatch_time_t(.distantFuture))

I get an error saying:

Type of expression is ambiguous without more context

Thanks.


问:
asp.net core IHtmlLocalizer not work
I write @inject IHtmlLocalizer Localizer in _Layout.cshtml, but it isResourceNotFound = true? why?

答: The structure of the Resources folder might not follow the structure of the Views folder. By convention, _Layout.cshtml is located in the Views/Shared folder. Therefore, your Resources folder should reflect that: resource files for the layout should be in Resources/Views/Shared folder.</p>

Title: asp.net core IHtmlLocalizer not work


问:
Making an Asp.Net treeview draggable: how to set a css class for Leaf Nodes only?
I have an Asp.net treeview and am building the nodes programmatorically in my codebehind.

Now, this treeview is 3 levels deep, being ROOT -> CATEGORY -> Tasks belonging to this category.  I would now like to allow the user to drag these leaf tasks to another table, but only the leafs should be draggable (I'm using the Jquery draggable plugin for this, so I just need to set the css class).

Any idea how I can set the CSS class for the leaf node only (codebehind or js)? I've tried something like:

```<code><asp:treeview id="treeviewTasks" runat="server"  leafnodestyle="draggable"  />
</code>```

but that doesn't seem to do the trick :(

thanks

Sam

答:
Turned out I was almost there, but not quite.  The correct syntax is:

```<code><asp:treeview id="treeviewTasks" runat="server" leafnodestyle-cssclass="draggable hand"/>
</code>```

RTM I guess :)

Body:
I have an Asp.net treeview and am building the nodes programmatorically in my codebehind.

Now, this treeview is 3 levels deep, being ROOT -> CATEGORY -> Tasks belonging to this category.  I would now like to allow the user to drag these leaf tasks to another table, but only the leafs should be draggable (I'm using the Jquery draggable plugin for this, so I just need to set the css class).

Any idea how I can set the CSS class for the leaf node only (codebehind or js)? I've tried something like:

<asp:treeview id="treeviewTasks" runat="server"  leafnodestyle="draggable"  />

but that doesn't seem to do the trick :(

thanks

Sam

Body:
Turned out I was almost there, but not quite.  The correct syntax is:

<asp:treeview id="treeviewTasks" runat="server" leafnodestyle-cssclass="draggable hand"/>

RTM I guess :)


问:
XQuery Count all Nodes
Is there a way to select the sum of all nodes within 1 XML nocument

```<code>for $c in doc("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial.xml")
return count($c//country)
</code>```

That is what i currently have but this only returns the count of all top level nodes.
I would like to count all existing nodes.(recursively?)

答:
To count all nodes in this XML document, the following XPath expression suffices:</p>

```<code>count(doc("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial.xml")//node())
</code>```

Title: XQuery Count all Nodes

Body:
Is there a way to select the sum of all nodes within 1 XML nocument

for $c in doc("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial.xml")
return count($c//country)

That is what i currently have but this only returns the count of all top level nodes.
I would like to count all existing nodes.(recursively?)

Body:
To count all nodes in this XML document, the following XPath expression suffices:

count(doc("http://www.dbis.informatik.uni-goettingen.de/Mondial/mondial.xml")//node())


问:
Join two integers into one double
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

```<code>double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);
</code>```

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

答:
A much better idea would be to send the double directly as 8 bytes in network byte order.

You can use a union

```<code>typedef union
{
   double a;
   uint8_t bytes[8];
} DoubleUnionType;

DoubleUnionType DoubleUnion;
//Assign the double by
DoubleUnion.a = -47.848945;
</code>```

Then you can make a network byte order conversion function

```<code>void htonfl(uint8_t *out, uint8_t *in)
{
    #if LITTLE_ENDIAN   // Use macro name as per architecture
        out[0] = in[7];
        out[1] = in[6];
        out[2] = in[5];
        out[3] = in[4];
        out[4] = in[3];
        out[5] = in[2];
        out[6] = in[1];
        out[7] = in[0];
   #else
        memcpy (out, in, 8);
   #endif
}
</code>```

And call this function before transmission and after reception.

Title: Join two integers into one double

Body:
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

Body:
A much better idea would be to send the double directly as 8 bytes in network byte order.

You can use a union

typedef union
{
   double a;
   uint8_t bytes[8];
} DoubleUnionType;

DoubleUnionType DoubleUnion;
//Assign the double by
DoubleUnion.a = -47.848945;

Then you can make a network byte order conversion function

void htonfl(uint8_t *out, uint8_t *in)
{
    #if LITTLE_ENDIAN   // Use macro name as per architecture
        out[0] = in[7];
        out[1] = in[6];
        out[2] = in[5];
        out[3] = in[4];
        out[4] = in[3];
        out[5] = in[2];
        out[6] = in[1];
        out[7] = in[0];
   #else
        memcpy (out, in, 8);
   #endif
}

And call this function before transmission and after reception.


问:
Finding the solutions of a complicated equation
I have a function (x^x)*((1-x)^(1-x))*(k^(x/2)) = 1 which has a unique solution in 0 < x < 1 for a given natural number k.

Can I use Python to find these solutions, or is my equation too complicated?

答:
Yes, you can use Python to solve this equation.

I suggest you fix k=2 to simplify. Wolfram Alpha can verify your results: https://www.wolframalpha.com/input/?i=(x%5Ex)((1-x)%5E(1-x))(2%5E(x%2F2))+%3D+1

Depending on how you do your root search, you may have to take a first derivative with respect to x and place that into Python, as well.


问:
.hasClass() seem to always return true when used inside a .click() function, why?
```<code><ul id="list">
    <li>item 1</li>
    <li>item 2</li>
</ul>

$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});
</code>```

Why does "$(this).hasClass('active')" always return true?

答:
What is wrong with your code? For the first time it will false as per given HTML. But next time if you're clicking on same item then only it return true else it returns false only.

Demo

Body:
item 1

item 2

$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});

Why does "$(this).hasClass('active')" always return true?


问:
C++ Rehashing Algorithm Vectors
I have been asked to create a rehashing algorithm with instructions:

 Backup the old vector Table to a temporary vector oldTable

 Delete the elements in the old Table

 Obtain the new table size

 Expand Table to the new size

 Reinsert elements from oldTable into the expanded new Table

 Delete the elements in the oldTable

Hash Table.h Class:

```<code>#ifndef HASHTABLE_H
#define HASHTABLE_H
#include "Math.h"

// hash table storing class X objects using linear probing
template <class X>
class HashTable {
public:
    // constructor sets the hash table size & load threshold
    HashTable(int table_size, double load_threshold = 0.75);
    // destructor
    ~HashTable() { for (int i = 0; i < Table.size(); i++) if (Table[i]) delete Table[i]; }

    // search for object a in the table
    size_t find(X& a);  // size_t = unsigned int

    // insert new object a in the table, return true if done
    bool insert(X& a);

    //function to return a new prime table size
    size_t newTableSize();

    //rehash func
    void reHash();

private:
    // the hash table & number of objects stored
    vector<X*> Table;
    size_t num_x;

    // maximum load threshold
    double LOAD_TH;
};

template <class X>
HashTable<X>::HashTable(int table_size, double load_threshold)
{
    for (int i = 0; i < table_size; i++) Table.push_back(NULL);
    num_x = 0;
    LOAD_TH = load_threshold;
}

template <class X>
size_t HashTable<X>::newTableSize() {

    bool found = true;

    int newSize = 2 * Table.size() + 1; // = now odd because oldSize is a prime

    do {
        int x = sqrt(newSize);
        for (int i = 3; i <= x; i += 2) {
            if (newSize % i == 0) {
                newSize = newSize + 2;
                x = sqrt(newSize);
                break;
            }
            else
            {
                found = true;
            }

        }
    } while (!found);

    return newSize;
}

template<class X>

void HashTable<X>::reHash() {

        //Backup the old vector<X*> Table to a temporary vector<X*> oldTable
        vector<X*> tempTable;
        tempTable = Table;

        //Delete the elements in the old Table
        Table.clear();

        //Obtain the new table size
        int newPrimeSize = newTableSize();

        //Expand Table to the new size
        Table.resize(newPrimeSize);

        //Reinsert elements from oldTable into the expanded new Table

        //Table = tempTable;
        //or method below??
        for (int i = 0; i < tempTable.size; i++) {
            if (tempTable[i] != NULL){
                Table.insert(tempTable[i]);
            }
        }

        //Delete the elements in the oldTable
        tempTable.clear();
}

template <class X>
size_t HashTable<X>::find(X& a)
{
    // calculate the hash index
    size_t index = a.hash_index() % Table.size();
    // search - find index of matching key or the 1st empty slot
    while (Table[index] != NULL && Table[index]->get_key() != a.get_key())
        index = (index + 1) % Table.size();
    // retrieve matching value to a if found
    if (Table[index] != NULL) a.set_value(Table[index]->get_value());

    return index;
}

template <class X>
bool HashTable<X>::insert(X& a)
{
    // calculate the load factor of the table
    double load_factor = (double)num_x / (double)Table.size();
    if (load_factor > LOAD_TH) {
        // replace the following return by rehashing - practical work
        return 0;

    }

    // search a in the able
    size_t index = find(a);
    // not found, create a new entry in the table
    if (Table[index] == NULL) {
        Table[index] = new X(a);
        num_x++;
        return 1;
    }

    // object already in table, do nothing
    return 0;
}
#endif
</code>```

Test Class:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <time.h>
#include "Math.h"
using namespace std;

#include "HashTable.h"

// a class of phone records
class PhoneDir {
public:
    PhoneDir(string name, int number = -1)
        : name(name), number(number) {};

    string get_key() { return name; }
    int get_value() { return number; }
    void set_value(int num) { number = num; }

    size_t hash_index(); // return hash index of key: name

private:
    string name;    // key
    int number;     // value
};

size_t PhoneDir::hash_index()
{
    size_t hash_index = 0;
    for (int i = 0; i < name.size(); i++) {
        char c = name[i];
        hash_index = 37 * hash_index + c;
    }
    return hash_index;
}

int main()
{
    int oldSize = 5;
    // store phone records in hash table with size 11
    HashTable<PhoneDir> HTable(7);
    HTable.insert(PhoneDir("Tom", 123456));
    HTable.insert(PhoneDir("Sam", 346834));
    HTable.insert(PhoneDir("Pete", 347980));
    HTable.insert(PhoneDir("Jack", 328709));
    HTable.insert(PhoneDir("David", 335566));

    // serach using name for phone number over the hash table
    char yn = 'y';
    do {
            //test function part 1
    cout << " Test " << endl;
    cout << HTable.newTableSize();

        cout << "Whose number are you looking for? ";
        string name; cin >> name;

        // form enquiry and search
        PhoneDir enquiry(name);
        clock_t t0 = clock();
        size_t index = HTable.find(enquiry);
        clock_t t1 = clock();

        cout << "index = " << index;
        cout << ", name = " << enquiry.get_key();
        cout << ", number = " << enquiry.get_value() << endl;
        cout << "time taken = " << t1 - t0 << endl << endl;

        cout << "Another (y/n)? "; cin >> yn;
    } while (yn == 'y');

    return 0;

}
</code>```

I successfully created & tested the newTableSize function & now I am on the rehash algorithm function.
The use of vectors is confusing me and I am new to this.
Am i on the right track? Will the parts of my re-hash algorithm work?
Thanks

答:
It is better to directly build a tempTable vector with the new size, and when done move it to the Table vector because it involve less copy operation:

save Table, clean, copy:

save is a copy of a vector: involves copying all elements (ok they are only pointers)

clear the original vector

resize the original vector

copy all elements

clear the temp vector

create temp and move:

create a temp vector with the new size

copy all elements

move the temp vector to the original one: you directly steal the internal array of the temp vector which is about to be destroyed instead of copying all of its elements.

Less and simpler operations...

Title: C++ Rehashing Algorithm Vectors

Body:
I have been asked to create a rehashing algorithm with instructions:

 Backup the old vector Table to a temporary vector oldTable

 Delete the elements in the old Table

 Obtain the new table size

 Expand Table to the new size

 Reinsert elements from oldTable into the expanded new Table

 Delete the elements in the oldTable

Hash Table.h Class:

#ifndef HASHTABLE_H
#define HASHTABLE_H
#include "Math.h"

// hash table storing class X objects using linear probing
template <class X>
class HashTable {
public:
    // constructor sets the hash table size & load threshold
    HashTable(int table_size, double load_threshold = 0.75);
    // destructor
    ~HashTable() { for (int i = 0; i < Table.size(); i++) if (Table[i]) delete Table[i]; }

    // search for object a in the table
    size_t find(X& a);  // size_t = unsigned int

    // insert new object a in the table, return true if done
    bool insert(X& a);

    //function to return a new prime table size
    size_t newTableSize();

    //rehash func
    void reHash();

private:
    // the hash table & number of objects stored
    vector<X*> Table;
    size_t num_x;

    // maximum load threshold
    double LOAD_TH;
};

template <class X>
HashTable<X>::HashTable(int table_size, double load_threshold)
{
    for (int i = 0; i < table_size; i++) Table.push_back(NULL);
    num_x = 0;
    LOAD_TH = load_threshold;
}

template <class X>
size_t HashTable<X>::newTableSize() {

    bool found = true;

    int newSize = 2 * Table.size() + 1; // = now odd because oldSize is a prime

    do {
        int x = sqrt(newSize);
        for (int i = 3; i <= x; i += 2) {
            if (newSize % i == 0) {
                newSize = newSize + 2;
                x = sqrt(newSize);
                break;
            }
            else
            {
                found = true;
            }

        }
    } while (!found);

    return newSize;
}

template<class X>

void HashTable<X>::reHash() {

        //Backup the old vector<X*> Table to a temporary vector<X*> oldTable
        vector<X*> tempTable;
        tempTable = Table;

        //Delete the elements in the old Table
        Table.clear();

        //Obtain the new table size
        int newPrimeSize = newTableSize();

        //Expand Table to the new size
        Table.resize(newPrimeSize);

        //Reinsert elements from oldTable into the expanded new Table

        //Table = tempTable;
        //or method below??
        for (int i = 0; i < tempTable.size; i++) {
            if (tempTable[i] != NULL){
                Table.insert(tempTable[i]);
            }
        }

        //Delete the elements in the oldTable
        tempTable.clear();
}

template <class X>
size_t HashTable<X>::find(X& a)
{
    // calculate the hash index
    size_t index = a.hash_index() % Table.size();
    // search - find index of matching key or the 1st empty slot
    while (Table[index] != NULL && Table[index]->get_key() != a.get_key())
        index = (index + 1) % Table.size();
    // retrieve matching value to a if found
    if (Table[index] != NULL) a.set_value(Table[index]->get_value());

    return index;
}

template <class X>
bool HashTable<X>::insert(X& a)
{
    // calculate the load factor of the table
    double load_factor = (double)num_x / (double)Table.size();
    if (load_factor > LOAD_TH) {
        // replace the following return by rehashing - practical work
        return 0;

    }

    // search a in the able
    size_t index = find(a);
    // not found, create a new entry in the table
    if (Table[index] == NULL) {
        Table[index] = new X(a);
        num_x++;
        return 1;
    }

    // object already in table, do nothing
    return 0;
}
#endif

Test Class:

#include <iostream>
#include <vector>
#include <string>
#include <time.h>
#include "Math.h"
using namespace std;

#include "HashTable.h"

// a class of phone records
class PhoneDir {
public:
    PhoneDir(string name, int number = -1)
        : name(name), number(number) {};

    string get_key() { return name; }
    int get_value() { return number; }
    void set_value(int num) { number = num; }

    size_t hash_index(); // return hash index of key: name

private:
    string name;    // key
    int number;     // value
};

size_t PhoneDir::hash_index()
{
    size_t hash_index = 0;
    for (int i = 0; i < name.size(); i++) {
        char c = name[i];
        hash_index = 37 * hash_index + c;
    }
    return hash_index;
}

int main()
{
    int oldSize = 5;
    // store phone records in hash table with size 11
    HashTable<PhoneDir> HTable(7);
    HTable.insert(PhoneDir("Tom", 123456));
    HTable.insert(PhoneDir("Sam", 346834));
    HTable.insert(PhoneDir("Pete", 347980));
    HTable.insert(PhoneDir("Jack", 328709));
    HTable.insert(PhoneDir("David", 335566));

    // serach using name for phone number over the hash table
    char yn = 'y';
    do {
            //test function part 1
    cout << " Test " << endl;
    cout << HTable.newTableSize();

        cout << "Whose number are you looking for? ";
        string name; cin >> name;

        // form enquiry and search
        PhoneDir enquiry(name);
        clock_t t0 = clock();
        size_t index = HTable.find(enquiry);
        clock_t t1 = clock();

        cout << "index = " << index;
        cout << ", name = " << enquiry.get_key();
        cout << ", number = " << enquiry.get_value() << endl;
        cout << "time taken = " << t1 - t0 << endl << endl;

        cout << "Another (y/n)? "; cin >> yn;
    } while (yn == 'y');

    return 0;

}

I successfully created & tested the newTableSize function & now I am on the rehash algorithm function.
The use of vectors is confusing me and I am new to this.
Am i on the right track? Will the parts of my re-hash algorithm work?
Thanks


问:
Using both Python 2.x and Python 3.x in IPython Notebook
I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.

I initially had Anaconda.  With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started.  This is not what I was looking for so I uninstalled Anaconda and now have set up my own installation using MacPorts and PiP.  It seems that I still have to use

```<code>port select --set python <python version>
</code>```

to toggle between python 2.x and 3.x. which is no better than the anaconda solution.

Is there a way to select what version of python you want to use after you start an IPython notebook, preferably with my current MacPorts build?

答: Use sudo pip3 install jupyter for installing jupyter for python3 and sudo pip install jupyter for installing jupyter notebook for python2. Then, you can call ipython kernel install command to enable both types of notebook to choose from in jupyter notebook.

Body:
I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.

I initially had Anaconda.  With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started.  This is not what I was looking for so I uninstalled Anaconda and now have set up my own installation using MacPorts and PiP.  It seems that I still have to use

port select --set python <python version>

to toggle between python 2.x and 3.x. which is no better than the anaconda solution.

Is there a way to select what version of python you want to use after you start an IPython notebook, preferably with my current MacPorts build?


问:
Redirect to login-page when user is not logged in (asp)
I have a login-page where users can log in.
When they logging in with correctly details they are sent to an main admin-page.
If they cant log in they are staying on the login-page.
What I want to do is, if a random user, type in the URL for an admin-page when they are not logged in they are redirecting to the login-page.

I have understood that I have to do it in the masterpage or webconfig!?! I have a main admin-page and some other admin-pages.

Any tips?

答:
I tried to insert this into my webconfig:

```<code><authentication mode="Forms">
    <forms loginUrl="InnUtlogging.aspx" timeout="2880"/>
  </authentication>
</code>```

here is my code for the "login"-button (on the login-page);

```<code>protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * FROM Ansatt WHERE epost='" + brukernavn.Text + "' and passord='" + passord.Text + "'");
        cmd.Connection = con;
        int OBJ = Convert.ToInt32(cmd.ExecuteScalar());

        if (OBJ > 0)

            {
            Session["name"] = brukernavn.Text;
            Response.Redirect("KunstnerAdmin.aspx");
        }
        else
            {
                melding.Text = "Feil brukernavn/passord";
            }
        if (brukernavn.Text == "")
        {
            melding.Text = "Du må fylle inn brukernavn";

        }
        if (passord.Text == "")
        {
            melding.Text = "Du må fylle inn passord";
        }
        }
</code>```

But actually I want to check if user is logged in in the master-page.
Is there something I can do in the masterpage to activate the forms authentication?

Body:
I tried to insert this into my webconfig:

<authentication mode="Forms">
    <forms loginUrl="InnUtlogging.aspx" timeout="2880"/>
  </authentication>

here is my code for the "login"-button (on the login-page);

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * FROM Ansatt WHERE epost='" + brukernavn.Text + "' and passord='" + passord.Text + "'");
        cmd.Connection = con;
        int OBJ = Convert.ToInt32(cmd.ExecuteScalar());

        if (OBJ > 0)

            {
            Session["name"] = brukernavn.Text;
            Response.Redirect("KunstnerAdmin.aspx");
        }
        else
            {
                melding.Text = "Feil brukernavn/passord";
            }
        if (brukernavn.Text == "")
        {
            melding.Text = "Du må fylle inn brukernavn";

        }
        if (passord.Text == "")
        {
            melding.Text = "Du må fylle inn passord";
        }
        }

But actually I want to check if user is logged in in the master-page.
Is there something I can do in the masterpage to activate the forms authentication?


问:
Difference in RabbitMq and RabbitMq with JMS plugin
I am new to JMS.
I am little aware of RabbitMq and now trying to find the difference in rabbitMQ with JMS. How it is used and why it should be used?

Thanks in advance.

答:
JMS is a Java API (part of JEE).

JMS Vendors use a proprietary protocol to talk to the broker; they are not wire-compatible.

You can generally talk to any JMS broker by just changing vendor-specific configuration (connection factory etc).

Vendors provide a JMS client library to talk to their brokers.

AMQP is a wire protocol, not an API.

Vendors provide a Java client API.

You can use Spring AMQP, which sits on top of RabbitMQ's amqp-client library and its API.

You can use Spring JMS, which talks to any JMS broker (including RabbitMQ with the plugin) using the JMS API.

If you need to be compatible with any JMS vendor, use spring-jms; if you only intend to use RabbitMQ, I would recommend using Spring AMQP.

Or, use Spring Integration on top of either one, and you can switch between AMQP and JMS by just changing configuration.


问:
Rename a file using Java
Can we rename a file say test.txt to test1.txt ?

If test1.txt exists will it rename ?

How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for later use?

答:
```<code>Files.move(file.toPath(), fileNew.toPath());
</code>```

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with  file.renameTo or FileUtils.moveFile.

OwnerDisplayName: Shekhar

Title: Rename a file using Java

Body:
Files.move(file.toPath(), fileNew.toPath());

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with  file.renameTo or FileUtils.moveFile.


问:
How to Update to version 1.2 of pgAdmin 4,
I have downloaded and installed the latest version 1.2 for PGAdmin but I keep getting the message "You are currently running version 1.1 of PGAdmin 4, however the current version is 1.2"

What am I missing? (I'm on Windows 10 64-bit).

答: I have Windows 7, but did you try something like: navigate to Control Panel\All Control Panel Items\Programs and Features, find pgAdmin 4 version [?], click it once, right-click, uninstall?</p>


问:
Customised Infowindow not working?
Im trying to customize my Infowindow, but I cant bind the TextViews with the strings. The InfoWindow sometimes shows the raw xml, sometimes just not working. I feel myself a little bit lost.

The loading function seems to be working fine. In my opinion the problem begins at the mMap.addMarker function.

```<code>private void placeAllMarkers() {

    mContext = getActivity();
    mPrefManager = new PrefManager(mContext);
    List <MapMarker> allMapMarker;

    allMapMarker = mPrefManager.loadAllMapMarker();

    if (allMapMarker.size() > 0) {

        for (int counter = 0; counter < allMapMarker.size(); counter++) {

            price = allMapMarker.get(counter).getSum();
            shop = allMapMarker.get(counter).getShop();
            date = allMapMarker.get(counter).getDate();
            Float GPS_X = allMapMarker.get(counter).getGPS_X();
            Float GPS_Y = allMapMarker.get(counter).getGPS_Y();

            LatLng Position = new LatLng(GPS_X, GPS_Y);

            mMap.addMarker(new MarkerOptions()
                    .position(Position)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

            mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                @Override
                public View getInfoWindow(Marker marker) {
                    InfoView = getActivity().getLayoutInflater().inflate(R.layout.custom_infowindow, null);

                    setShop = (TextView) InfoView.findViewById(R.id.setShop);
                    setSum = (TextView) InfoView.findViewById(R.id.setSum);
                    setDate = (TextView) InfoView.findViewById(R.id.setDate);

                    setShop.setText(shop);
                    setSum.setText(price);
                    setDate.setText(date);

                    return InfoView;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }
            });

        }
    }
}
</code>```

Thanks for your time.

EDIT

It is something with the strings:

FATAL EXCEPTION: main
                                                                            Process: hu.mosomaci.flagsproject, PID: 4983
                                                                            android.content.res.Resources$NotFoundException: String resource ID #0xd98
                                                                                at android.content.res.Resources.getText(Resources.java:252)
                                                                                at android.content.res.MiuiResources.getText(MiuiResources.java:108)
                                                                                at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
                                                                                at android.widget.TextView.setText(TextView.java:3895)
                                                                                at hu.mosomaci.flagsproject.fragments.MapForFlags$1.getInfoContents(MapForFlags.java:136)
                                                                                at com.google.android.gms.maps.GoogleMap$7.zzi(Unknown Source)
                                                                                at com.google.android.gms.maps.internal.zzd$zza.onTransact(Unknown Source)
                                                                                at android.os.Binder.transact(Binder.java:361)

答:
First of all set your marker like below. Set snippet for both price and date and add % sign between them.

```<code>mMap.addMarker(new MarkerOptions()
.position(Position)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
.title(shop)
.snippet(price + "%"+date));
</code>```

Try to set the text and other work inside getInfoContents(Marker marker) methode ( as getInfoContents(Marker marker) is used to define the content.) instead of getInfoWindow(Marker marker) of setInfoWindowAdapter.

And when setting text to TextView split the snippet and get price and date by index

```<code>mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                @Override
                public View getInfoWindow(Marker marker) {
               return null;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    InfoView = getActivity().getLayoutInflater().inflate(R.layout.custom_infowindow, null);

                    TextView setShop = (TextView) InfoView.findViewById(R.id.setShop);
                    TextView setSum = (TextView) InfoView.findViewById(R.id.setSum);
                    TextView setDate = (TextView) InfoView.findViewById(R.id.setDate);

                    String snippet = marker.getSnippet();
                    String[] splited_text = snippet.split("%");
                    String price = splited_text[0];
                    String date = splited_text[1];

                    setShop.setText(marker.getTitle());
                    setSum.setText(price);
                    setDate.setText(date);

                    return InfoView;
                }
            });
</code>```

Title: Customised Infowindow not working?

Body:
Im trying to customize my Infowindow, but I cant bind the TextViews with the strings. The InfoWindow sometimes shows the raw xml, sometimes just not working. I feel myself a little bit lost.

The loading function seems to be working fine. In my opinion the problem begins at the mMap.addMarker function.

private void placeAllMarkers() {

    mContext = getActivity();
    mPrefManager = new PrefManager(mContext);
    List <MapMarker> allMapMarker;

    allMapMarker = mPrefManager.loadAllMapMarker();

    if (allMapMarker.size() > 0) {

        for (int counter = 0; counter < allMapMarker.size(); counter++) {

            price = allMapMarker.get(counter).getSum();
            shop = allMapMarker.get(counter).getShop();
            date = allMapMarker.get(counter).getDate();
            Float GPS_X = allMapMarker.get(counter).getGPS_X();
            Float GPS_Y = allMapMarker.get(counter).getGPS_Y();

            LatLng Position = new LatLng(GPS_X, GPS_Y);

            mMap.addMarker(new MarkerOptions()
                    .position(Position)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

            mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                @Override
                public View getInfoWindow(Marker marker) {
                    InfoView = getActivity().getLayoutInflater().inflate(R.layout.custom_infowindow, null);

                    setShop = (TextView) InfoView.findViewById(R.id.setShop);
                    setSum = (TextView) InfoView.findViewById(R.id.setSum);
                    setDate = (TextView) InfoView.findViewById(R.id.setDate);

                    setShop.setText(shop);
                    setSum.setText(price);
                    setDate.setText(date);

                    return InfoView;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }
            });

        }
    }
}

Thanks for your time.

EDIT

It is something with the strings:

FATAL EXCEPTION: main
                                                                            Process: hu.mosomaci.flagsproject, PID: 4983
                                                                            android.content.res.Resources$NotFoundException: String resource ID #0xd98
                                                                                at android.content.res.Resources.getText(Resources.java:252)
                                                                                at android.content.res.MiuiResources.getText(MiuiResources.java:108)
                                                                                at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
                                                                                at android.widget.TextView.setText(TextView.java:3895)
                                                                                at hu.mosomaci.flagsproject.fragments.MapForFlags$1.getInfoContents(MapForFlags.java:136)
                                                                                at com.google.android.gms.maps.GoogleMap$7.zzi(Unknown Source)
                                                                                at com.google.android.gms.maps.internal.zzd$zza.onTransact(Unknown Source)
                                                                                at android.os.Binder.transact(Binder.java:361)

Body:
First of all set your marker like below. Set snippet for both price and date and add % sign between them.

mMap.addMarker(new MarkerOptions()
.position(Position)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
.title(shop)
.snippet(price + "%"+date));

Try to set the text and other work inside getInfoContents(Marker marker) methode ( as getInfoContents(Marker marker) is used to define the content.) instead of getInfoWindow(Marker marker) of setInfoWindowAdapter.

And when setting text to TextView split the snippet and get price and date by index

mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                @Override
                public View getInfoWindow(Marker marker) {
               return null;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    InfoView = getActivity().getLayoutInflater().inflate(R.layout.custom_infowindow, null);

                    TextView setShop = (TextView) InfoView.findViewById(R.id.setShop);
                    TextView setSum = (TextView) InfoView.findViewById(R.id.setSum);
                    TextView setDate = (TextView) InfoView.findViewById(R.id.setDate);

                    String snippet = marker.getSnippet();
                    String[] splited_text = snippet.split("%");
                    String price = splited_text[0];
                    String date = splited_text[1];

                    setShop.setText(marker.getTitle());
                    setSum.setText(price);
                    setDate.setText(date);

                    return InfoView;
                }
            });


问:
Calling particular child method from abstract class using custom annotation
I have a abstract class containing run() method and few children classes overriding run method with different implementation. There a custom annotation class also, each child class has this annotation with different value to distinguish each child class. I was to call this run method for each child class from abstract class object using these annotations without using child class name. Is it possible or there some other way to do this?

CODE IS HERE-------

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomAnno {
    public String name();
}

public abstract class AbstractClass {

    abstract void run();

}

@CustomAnno(name="one")
public class ExtendingClassOne extends AbstractClass {

    @Override
    void run() {
        System.out.println("class one extending");

    }

}

@CustomAnno(name="two")
public class ExtendingClassTwo extends AbstractClass {

    @Override
    void run() {
        System.out.println("class two extending");

    }

}
</code>```

So having abstract class and annotation values "one" and "two", can I call run method for each child class without using child class name.

答: We can use ClassPathScanningCandidateComponentProvider spring library to list all the classes that use a particular kind of annotation. Here annotations can be custom or default one. So putting annotations on all child classes that extend that abstract class can give list of only those child classes only. This solved my problem.

Body:
I have a abstract class containing run() method and few children classes overriding run method with different implementation. There a custom annotation class also, each child class has this annotation with different value to distinguish each child class. I was to call this run method for each child class from abstract class object using these annotations without using child class name. Is it possible or there some other way to do this?

CODE IS HERE-------

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomAnno {
    public String name();
}

public abstract class AbstractClass {

    abstract void run();

}

@CustomAnno(name="one")
public class ExtendingClassOne extends AbstractClass {

    @Override
    void run() {
        System.out.println("class one extending");

    }

}

@CustomAnno(name="two")
public class ExtendingClassTwo extends AbstractClass {

    @Override
    void run() {
        System.out.println("class two extending");

    }

}

So having abstract class and annotation values "one" and "two", can I call run method for each child class without using child class name.