问:
Fill li with content depending on database results
I'm working with fat free framework and am currently working on a bracket generation for competitions.

What I do is passing multiple competitors (from different "layers") to the view to display them in a tree. The basic styling comes from this codepen.

Now the problem is, that I don't know every field from beginning on, as the result of the first two competitions decide how the next level looks (quarter finals in that case). The problem is though, that if I don't put the fields there, then the complete layout is destroyed, thats why I put empty
 elements for the layer, where the competitors are not clear so far, just like so:

```<code><li class="team-item"> </li>
<li class="team-item"> </li>
<li class="team-item"> </li>
<li class="team-item"> </li>
</code>```

Same for semi finals and finals then, just with 2 and 1
s then.

Now in some of the cells of quarter/seminfinals I already have something in my database. So for example, if there's 8 competitions in "layer1", then I would have 4 empty fields in "layer2", respectively in the quarter finals. These 4 fields have to be predefined in order to keep the layout. Now maybe I only have 1 or 2 of these fields filled already, because the other competitions are not over yet.

So I have to always predefine the fields like in the code above. Now the question is: How do I either replace one empty
 with the filled one or alternatively, how do I fill the empty
 with information, if provided.

```<code><ul class="bracket bracket-2">
      <repeat group="{{ @bracket }}" value="{{ @item }}">
        <check if="{{@item.layer == 2}}">
        <!-- li should be filled with this content, if the condition is true, so if in here -->
        <li class="team-item">{{ @item.Vorname1  }} {{ @item.Name1  }} <a href="/getFighterInformation/{{@item.fighter1ID}}"<i class="fa fa-pencil-alt"></i></a> <i class="fa fa-trophy"></i></li>
      <li class="team-item">{{ @item.Vorname2  }} {{ @item.Name2  }} <a href="/getFighterInformation/{{@item.fighter2ID}}"<i class="fa fa-pencil-alt"></i></a> <i class="fa fa-trophy"></i></li>
  </check>
    </repeat>
  <!-- This should be predefined -->
  <li class="team-item"> </li>
  <li class="team-item"> </li>
  <li class="team-item"> </li>
  <li class="team-item"> </li>
  <!-------------------------------->
    </ul>
</code>```

That's an example for layer 2 with 8 competitions in layer 1.

I hope you get what I mean, but its pretty hard to explain...

So summarized, the question is: Is it possible to predefine list elements and then fill or replace them, if an if-condition matches?

EDIT:

This is what I get from database, filled into the bracket variable:

```<code>array(4){
   [
      0
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "1"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "21"      [
         "Vorname1"
      ]      => string(5) "one"      [
         "Name1"
      ]      => string(4) "one"      [
         "Geburtsdatum1"
      ]      => string(10) "1999-04-04"      [
         "fighter1Pos"
      ]      => string(1) "0"      [
         "fighter2ID"
      ]      => string(2) "19"      [
         "Vorname2"
      ]      => string(8) "two"      [
         "Name2"
      ]      => string(4) "two"      [
         "Geburtsdatum2"
      ]      => string(10) "1988-12-11"      [
         "fighter2Pos"
      ]      => string(1) "1"      [
         "result"
      ]      => string(1) "0"
   }   [
      1
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "2"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "25"      [
         "Vorname1"
      ]      => string(5) "three"      [
         "Name1"
      ]      => string(4) "three"      [
         "Geburtsdatum1"
      ]      => string(10) "1988-08-18"      [
         "fighter1Pos"
      ]      => string(1) "2"      [
         "fighter2ID"
      ]      => string(2) "24"      [
         "Vorname2"
      ]      => string(5) "four"      [
         "Name2"
      ]      => string(4) "four"      [
         "Geburtsdatum2"
      ]      => string(10) "1985-08-17"      [
         "fighter2Pos"
      ]      => string(1) "3"      [
         "result"
      ]      => string(1) "0"
   }   [
      2
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "3"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "23"      [
         "Vorname1"
      ]      => string(5) "five"      [
         "Name1"
      ]      => string(4) "five"      [
         "Geburtsdatum1"
      ]      => string(10) "1966-06-16"      [
         "fighter1Pos"
      ]      => string(1) "4"      [
         "fighter2ID"
      ]      => string(2) "20"      [
         "Vorname2"
      ]      => string(8) "six"      [
         "Name2"
      ]      => string(4) "six"      [
         "Geburtsdatum2"
      ]      => string(10) "1966-03-03"      [
         "fighter2Pos"
      ]      => string(1) "5"      [
         "result"
      ]      => string(1) "0"
   }   [
      3
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "4"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "18"      [
         "Vorname1"
      ]      => string(6) "seven"      [
         "Name1"
      ]      => string(4) "seven"      [
         "Geburtsdatum1"
      ]      => string(10) "1985-08-17"      [
         "fighter1Pos"
      ]      => string(1) "6"      [
         "fighter2ID"
      ]      => string(2) "22"      [
         "Vorname2"
      ]      => string(9) "eight"      [
         "Name2"
      ]      => string(4) "eight"      [
         "Geburtsdatum2"
      ]      => string(10) "1995-09-15"      [
         "fighter2Pos"
      ]      => string(1) "7"      [
         "result"
      ]      => string(1) "0"
   }
}
</code>```

One box should contain one fighter only, not two fighters. So each array element represents one fight, containing two fighters (referencable by fighter1ID/fighter2ID, respectively Name1, Name2, etc.). fighter1Pos and fighter2Pos then, together with the value "ebene", which is the layer (3, 2, 1 or 0), determine the position in the bracket, so layer 3 with fighter1Pos 7 would be the last "box" in the layer 3 (counting from 0 - 7).

答:
Yes, you can select a list item using javascript and then add text to it.

Take this list:

```<code><ul>
<li class="team-item">Result 1</li>
<li class="team-item">Result 2</li>
<li class="team-item">Waiting for Result...</li>
<li class="team-item">Waiting for Result...</li>
</ul>
</code>```

and then add a script, as in the example below:

const resultsList = document.getElementsByTagName('ul')[0];
const resultsListItems = resultsList.getElementsByTagName('li');

resultsListItems[2].textContent = 'Result 3'; ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li class="team-item">Result 1</li>
<li class="team-item">Result 2</li>
<li class="team-item">Waiting for Result...</li>
<li class="team-item">Waiting for Result...</li>
</ul></code>```

Body:
I'm working with fat free framework and am currently working on a bracket generation for competitions.

What I do is passing multiple competitors (from different "layers") to the view to display them in a tree. The basic styling comes from this codepen.

Now the problem is, that I don't know every field from beginning on, as the result of the first two competitions decide how the next level looks (quarter finals in that case). The problem is though, that if I don't put the fields there, then the complete layout is destroyed, thats why I put empty
 elements for the layer, where the competitors are not clear so far, just like so:

Same for semi finals and finals then, just with 2 and 1
s then.

Now in some of the cells of quarter/seminfinals I already have something in my database. So for example, if there's 8 competitions in "layer1", then I would have 4 empty fields in "layer2", respectively in the quarter finals. These 4 fields have to be predefined in order to keep the layout. Now maybe I only have 1 or 2 of these fields filled already, because the other competitions are not over yet.

So I have to always predefine the fields like in the code above. Now the question is: How do I either replace one empty
 with the filled one or alternatively, how do I fill the empty
 with information, if provided.

      <repeat group="{{ @bracket }}" value="{{ @item }}">
        <check if="{{@item.layer == 2}}">

{{ @item.Vorname1  }} {{ @item.Name1  }} <a href="/getFighterInformation/{{@item.fighter1ID}}"

{{ @item.Vorname2  }} {{ @item.Name2  }} <a href="/getFighterInformation/{{@item.fighter2ID}}"

  </check>
    </repeat>

That's an example for layer 2 with 8 competitions in layer 1.

I hope you get what I mean, but its pretty hard to explain...

So summarized, the question is: Is it possible to predefine list elements and then fill or replace them, if an if-condition matches?

EDIT:

This is what I get from database, filled into the bracket variable:

array(4){
   [
      0
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "1"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "21"      [
         "Vorname1"
      ]      => string(5) "one"      [
         "Name1"
      ]      => string(4) "one"      [
         "Geburtsdatum1"
      ]      => string(10) "1999-04-04"      [
         "fighter1Pos"
      ]      => string(1) "0"      [
         "fighter2ID"
      ]      => string(2) "19"      [
         "Vorname2"
      ]      => string(8) "two"      [
         "Name2"
      ]      => string(4) "two"      [
         "Geburtsdatum2"
      ]      => string(10) "1988-12-11"      [
         "fighter2Pos"
      ]      => string(1) "1"      [
         "result"
      ]      => string(1) "0"
   }   [
      1
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "2"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "25"      [
         "Vorname1"
      ]      => string(5) "three"      [
         "Name1"
      ]      => string(4) "three"      [
         "Geburtsdatum1"
      ]      => string(10) "1988-08-18"      [
         "fighter1Pos"
      ]      => string(1) "2"      [
         "fighter2ID"
      ]      => string(2) "24"      [
         "Vorname2"
      ]      => string(5) "four"      [
         "Name2"
      ]      => string(4) "four"      [
         "Geburtsdatum2"
      ]      => string(10) "1985-08-17"      [
         "fighter2Pos"
      ]      => string(1) "3"      [
         "result"
      ]      => string(1) "0"
   }   [
      2
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "3"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "23"      [
         "Vorname1"
      ]      => string(5) "five"      [
         "Name1"
      ]      => string(4) "five"      [
         "Geburtsdatum1"
      ]      => string(10) "1966-06-16"      [
         "fighter1Pos"
      ]      => string(1) "4"      [
         "fighter2ID"
      ]      => string(2) "20"      [
         "Vorname2"
      ]      => string(8) "six"      [
         "Name2"
      ]      => string(4) "six"      [
         "Geburtsdatum2"
      ]      => string(10) "1966-03-03"      [
         "fighter2Pos"
      ]      => string(1) "5"      [
         "result"
      ]      => string(1) "0"
   }   [
      3
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "4"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "18"      [
         "Vorname1"
      ]      => string(6) "seven"      [
         "Name1"
      ]      => string(4) "seven"      [
         "Geburtsdatum1"
      ]      => string(10) "1985-08-17"      [
         "fighter1Pos"
      ]      => string(1) "6"      [
         "fighter2ID"
      ]      => string(2) "22"      [
         "Vorname2"
      ]      => string(9) "eight"      [
         "Name2"
      ]      => string(4) "eight"      [
         "Geburtsdatum2"
      ]      => string(10) "1995-09-15"      [
         "fighter2Pos"
      ]      => string(1) "7"      [
         "result"
      ]      => string(1) "0"
   }
}

One box should contain one fighter only, not two fighters. So each array element represents one fight, containing two fighters (referencable by fighter1ID/fighter2ID, respectively Name1, Name2, etc.). fighter1Pos and fighter2Pos then, together with the value "ebene", which is the layer (3, 2, 1 or 0), determine the position in the bracket, so layer 3 with fighter1Pos 7 would be the last "box" in the layer 3 (counting from 0 - 7).

Body:
Yes, you can select a list item using javascript and then add text to it.

Take this list:

<ul>
<li class="team-item">Result 1</li>
<li class="team-item">Result 2</li>
<li class="team-item">Waiting for Result...</li>
<li class="team-item">Waiting for Result...</li>
</ul>

and then add a script, as in the example below:

const resultsList = document.getElementsByTagName('ul')[0];
const resultsListItems = resultsList.getElementsByTagName('li');

resultsListItems[2].textContent = 'Result 3';

<ul>
<li class="team-item">Result 1</li>
<li class="team-item">Result 2</li>
<li class="team-item">Waiting for Result...</li>
<li class="team-item">Waiting for Result...</li>
</ul>


来源: stackexchange

问:
Copy files from folders and sub-folders to another folder and saving the structure of the folders
I have created a list of files by some conditions and I want to copy only the files from that list to a new folder and subfolders like in the origin folder.
The structure of the folders is year/month/day.

This is the code I tried:

```<code>from.dir <- "J:/Radar_data/Beit_Dagan/RAW/2018"
## I want only the files from the night
to.dir   <- "J:/Radar_data/Beit_Dagan/night"
files    <- list.files(path = from.dir, full.names = TRUE, recursive =
TRUE)
## night_files is a vector I created with the files I need - only during the night
for (f in night_files) file.copy(from = f, to = to.dir)
</code>```

But I get all the files in one folder

part of my list look like this:

```<code>[1] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142554.h5"
[2] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142749.h5"
[3] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310143054.h5"
</code>```

Is there a way to keep the structure of the folder and the subfolders when copying?

I want to get the same structure of year/month/day in the new "night" folder

答:
You need to use the flag recursive = T inside the copy call, so you don't really need to loop inside the dir.

from = paste0(getwd(),"/output/","output_1")
 to = paste0(getwd(),"/output/","output_1_copy")
 file.copy(from, to, recursive = T)

Note that you need to create the /output_1_copy directory previously to the call. Yo can do it manually or using dir.create(...).

ContentLicense: CC BY-SA 4.0

Body:
I have created a list of files by some conditions and I want to copy only the files from that list to a new folder and subfolders like in the origin folder.
The structure of the folders is year/month/day.

This is the code I tried:

from.dir <- "J:/Radar_data/Beit_Dagan/RAW/2018"
## I want only the files from the night
to.dir   <- "J:/Radar_data/Beit_Dagan/night"
files    <- list.files(path = from.dir, full.names = TRUE, recursive =
TRUE)
## night_files is a vector I created with the files I need - only during the night
for (f in night_files) file.copy(from = f, to = to.dir)

But I get all the files in one folder

part of my list look like this:

[1] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142554.h5"
[2] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142749.h5"
[3] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310143054.h5"

Is there a way to keep the structure of the folder and the subfolders when copying?

I want to get the same structure of year/month/day in the new "night" folder


问:
Data is getting pasted twice (base64image and text) from excel to CKEditor
When I am trying to copy and paste the data from excel to ckeditor it is getting pasted twice as plain text and base64image. I need to paste it as base64image only. Screen shot is attached for reference.

答:
I have resolved the problem using following solution</p>

```<code>var editor = CKEDITOR.replace( 'editor1', {
    extraPlugins : 'pastebase64'
});
editor.on( 'pluginsLoaded', function( event ){
    var excelRegex = RegExp( '(schemas-microsoft-com\:office\:excel)', 'ig' );

    // How to change image, dropped from local folder into CKEditor, from image file to base64 string with the help of CKEditor objects.
    editor.on( 'paste', function( evt ) {
        var testHtml = evt.data.dataTransfer.getData( 'text/html' , true);

        if ( testHtml.search( excelRegex ) >= 0 )
      evt.cancel();
    });
});
</code>```

Body:
I have resolved the problem using following solution

var editor = CKEDITOR.replace( 'editor1', {
    extraPlugins : 'pastebase64'
});
editor.on( 'pluginsLoaded', function( event ){
    var excelRegex = RegExp( '(schemas-microsoft-com\:office\:excel)', 'ig' );

    // How to change image, dropped from local folder into CKEditor, from image file to base64 string with the help of CKEditor objects.
    editor.on( 'paste', function( evt ) {
        var testHtml = evt.data.dataTransfer.getData( 'text/html' , true);

        if ( testHtml.search( excelRegex ) >= 0 )
      evt.cancel();
    });
});


问:
KVO for scroll start & end in UIScrollView
Is there a way to use KVO (key value observing) to detect scrollViewWillBeginDragging and scrollViewDidEndDecelerating in swift?

Edit: I tried

```<code>scrollView.addObserver(self, forKeyPath: "dragging", options: NSKeyValueObservingOptions.New, context: nil)
</code>```

But it's never called. If I observe for instance "contentOffset" in the same way, it's called. Is it KVC compliant?

答:
Answer based on @Philip De Vries

Swift 5

add observer

```<code>scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
</code>```

observe

```<code>// MARK: - Observation

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
    if let obj = object as? UIScrollView {
      if obj == self.scrollView && keyPath == "contentOffset" {

        scrollViewDidScroll(scrollView)

        if !draggingInitiated && scrollView.isDragging {
          draggingInitiated = true
          onStartDraggin()
        } else if draggingInitiated && !scrollView.isDragging {
          draggingInitiated = false
          onReleaseDragging()
        }
      }
    }
  }
</code>```

cleanUp

```<code>private func removeObsrvers() {
   scrollView.removeObserver(self, forKeyPath: "contentOffset")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to use KVO (key value observing) to detect scrollViewWillBeginDragging and scrollViewDidEndDecelerating in swift?

Edit: I tried

scrollView.addObserver(self, forKeyPath: "dragging", options: NSKeyValueObservingOptions.New, context: nil)

But it's never called. If I observe for instance "contentOffset" in the same way, it's called. Is it KVC compliant?

Body:
Answer based on @Philip De Vries

Swift 5

add observer

scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)

observe

// MARK: - Observation

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
    if let obj = object as? UIScrollView {
      if obj == self.scrollView && keyPath == "contentOffset" {

        scrollViewDidScroll(scrollView)

        if !draggingInitiated && scrollView.isDragging {
          draggingInitiated = true
          onStartDraggin()
        } else if draggingInitiated && !scrollView.isDragging {
          draggingInitiated = false
          onReleaseDragging()
        }
      }
    }
  }

cleanUp

private func removeObsrvers() {
   scrollView.removeObserver(self, forKeyPath: "contentOffset")
}


问:
How to ensure the query use the index?
My query is slow.

```<code>SELECT
    posts.*
FROM
    posts
    INNER JOIN categories ON posts.category_id = categories.id
        AND categories.main = 1
        AND(categories.private_category = 0
            OR categories.private_category IS NULL)
WHERE
    posts.id NOT IN('')
    AND posts.deleted = 0
    AND posts.hidden = 0
    AND posts.total_points >= - 5
ORDER BY
    posts.id DESC
LIMIT 10;
</code>```

So after I explain it:

```<code>| id | select_type | table       | partitions | type | possible_keys                                                                                | key                         | key_len | ref                           | rows  | filtered | Extra                                        |
|----|-------------|-------------|------------|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------|---------|-------------------------------|-------|----------|----------------------------------------------|
|  1 | SIMPLE      | categories  |            | ALL  | PRIMARY,index_categories_on_private_category                                                                                |                             |         |                               |    12 |    10.00 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | posts       |            | ref  | PRIMARY,index_posts_on_category_id,index_posts_on_deleted_and_hidden_and_user_id_and_created_at,index_posts_deleted,index_posts_hidden,index_posts_total_points  | index_posts_on_category_id  | 5       | mydb.categories.id            | 37516 |    12.50 | Using index condition; Using where           |
</code>```

I added an index on categories.main:

```<code>| id | select_type | table       | type   | possible_keys                                                                                | key     | key_len | ref                               | rows  | Extra       |
|----|-------------|-------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|---------|-----------------------------------|-------|-------------|
|  1 | SIMPLE      | posts       | range  | PRIMARY,index_posts_on_category_id,index_posts_on_deleted_and_hidden_and_user_id_and_created_at,index_posts_deleted,index_posts_hidden,index_posts_total_points  | PRIMARY | 4       |                                   | 37516 | Using where |
|  1 | SIMPLE      | categories  | eq_ref | PRIMARY,index_categories_on_private_category,index_categories_on_main                                                                                | PRIMARY | 4       | mydb.posts.category_id            |    12 | Using where |
</code>```

it shows that it does not use the indexing(?). the query is still slow and I want to optimize it. What is the wrong with the query?

Edit

This how the posts table created:

```<code>CREATE TABLE `posts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `category_id` int(11) DEFAULT NULL,
  `title` varchar(1000) NOT NULL,
  `content` text,
  `total_points` int(11) DEFAULT '0',
  `deleted` tinyint(1) DEFAULT '0',
  `hidden` tinyint(1) DEFAULT '0',
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index_posts_on_category_id` (`category_id`),
  KEY `index_posts_created_at` (`created_at`),
  KEY `index_posts_on_deleted_and_hidden_and_user_id_and_created_at` (`deleted`,`hidden`,`user_id`,`created_at`),
  KEY `index_posts_deleted` (`deleted`),
  KEY `index_posts_hidden` (`hidden`),
  KEY `index_posts_total_points` (`total_points`),
  KEY `index_posts_user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=304063 DEFAULT CHARSET=utf8
</code>```

This how the categories table created:

```<code>CREATE TABLE `categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `main` tinyint(1) DEFAULT '0',
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `hidden` tinyint(1) DEFAULT '0',
  `private_category` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `index_categories_on_private_category` (`private_category`),
  KEY `index_categories_on_main` (`main`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8
</code>```

答:
The query is slow because you use OR condition:

```<code>categories.private_category = 0 OR categories.private_category IS NULL
</code>```

MySQL have to scan all records in categories table

Title: How to ensure the query use the index?

Body:
My query is slow.

SELECT
    posts.*
FROM
    posts
    INNER JOIN categories ON posts.category_id = categories.id
        AND categories.main = 1
        AND(categories.private_category = 0
            OR categories.private_category IS NULL)
WHERE
    posts.id NOT IN('')
    AND posts.deleted = 0
    AND posts.hidden = 0
    AND posts.total_points >= - 5
ORDER BY
    posts.id DESC
LIMIT 10;

So after I explain it:

| id | select_type | table       | partitions | type | possible_keys                                                                                | key                         | key_len | ref                           | rows  | filtered | Extra                                        |
|----|-------------|-------------|------------|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------|---------|-------------------------------|-------|----------|----------------------------------------------|
|  1 | SIMPLE      | categories  |            | ALL  | PRIMARY,index_categories_on_private_category                                                                                |                             |         |                               |    12 |    10.00 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | posts       |            | ref  | PRIMARY,index_posts_on_category_id,index_posts_on_deleted_and_hidden_and_user_id_and_created_at,index_posts_deleted,index_posts_hidden,index_posts_total_points  | index_posts_on_category_id  | 5       | mydb.categories.id            | 37516 |    12.50 | Using index condition; Using where           |

I added an index on categories.main:

| id | select_type | table       | type   | possible_keys                                                                                | key     | key_len | ref                               | rows  | Extra       |
|----|-------------|-------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|---------|-----------------------------------|-------|-------------|
|  1 | SIMPLE      | posts       | range  | PRIMARY,index_posts_on_category_id,index_posts_on_deleted_and_hidden_and_user_id_and_created_at,index_posts_deleted,index_posts_hidden,index_posts_total_points  | PRIMARY | 4       |                                   | 37516 | Using where |
|  1 | SIMPLE      | categories  | eq_ref | PRIMARY,index_categories_on_private_category,index_categories_on_main                                                                                | PRIMARY | 4       | mydb.posts.category_id            |    12 | Using where |

it shows that it does not use the indexing(?). the query is still slow and I want to optimize it. What is the wrong with the query?

Edit

This how the posts table created:

CREATE TABLE `posts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `category_id` int(11) DEFAULT NULL,
  `title` varchar(1000) NOT NULL,
  `content` text,
  `total_points` int(11) DEFAULT '0',
  `deleted` tinyint(1) DEFAULT '0',
  `hidden` tinyint(1) DEFAULT '0',
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index_posts_on_category_id` (`category_id`),
  KEY `index_posts_created_at` (`created_at`),
  KEY `index_posts_on_deleted_and_hidden_and_user_id_and_created_at` (`deleted`,`hidden`,`user_id`,`created_at`),
  KEY `index_posts_deleted` (`deleted`),
  KEY `index_posts_hidden` (`hidden`),
  KEY `index_posts_total_points` (`total_points`),
  KEY `index_posts_user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=304063 DEFAULT CHARSET=utf8

This how the categories table created:

CREATE TABLE `categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `main` tinyint(1) DEFAULT '0',
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `hidden` tinyint(1) DEFAULT '0',
  `private_category` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `index_categories_on_private_category` (`private_category`),
  KEY `index_categories_on_main` (`main`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8

Body:
The query is slow because you use OR condition:

categories.private_category = 0 OR categories.private_category IS NULL

MySQL have to scan all records in categories table


问:
How to extract duplicate values in each column separately?
I want to extract only values with two or more occurrence in each column separately and write them in separate file with column header.

Example file: (actual csv file is 1.5 Gb, here including summary of it)
First row is the header row of each column

```<code>AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3
</code>```

I have tried to write code in R and even Python panda but failed to get the result.

Expected outcome:

```<code>AO1 BO1 CO1 DO1 EO1 FO1
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4        typ3        rtf5
            wer3        rtf5
            wer3        rtf5
</code>```

答:
```<code>import pandas as pd
from StringIO import StringIO

df = pd.read_csv(StringIO("""AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3"""))

d = {}

for col in df.columns:
    repeated_values =  df[col].value_counts()[df[col].value_counts() >= 2].index.tolist()
    cond = df[col].isin(repeated_values)
    d[col] = df[cond][col]

final = pd.concat(d, axis=1)
</code>```

Body:
I want to extract only values with two or more occurrence in each column separately and write them in separate file with column header.

Example file: (actual csv file is 1.5 Gb, here including summary of it)
First row is the header row of each column

AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3

I have tried to write code in R and even Python panda but failed to get the result.

Expected outcome:

AO1 BO1 CO1 DO1 EO1 FO1
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4        typ3        rtf5
            wer3        rtf5
            wer3        rtf5


问:
Overriding protected methods in Java
Test.java

```<code>package a;
import b.B;
public class Test {
    public static void main(String[] v) {
        new A().test();
        new B().test();
    }
}
</code>```

A.java:

```<code>package a;
public class A {
    protected void test() { }
}
</code>```

B.java:

```<code>package b;
public class B extends a.A {
    protected void test() { }
}
</code>```

Why does new B().test() give an error? Doesn't that break visibility rules?

B.test() is invisible in Test because they're in different packages, and yet it refuses to call the test() in B's superclass which is visible.

Links to the appropriate part of the JLS would be appreciated.

答:
The problem is that at compile time you are telling Java that you want to access a protected member of a class when you do not have such access.

If you did this instead;

```<code>  A a = new B();
  a.test();
</code>```

Then it would work and the overridden method will run because at compile time Java checks that you have access to A. At run time the object provided has the appropriate method so the B test() method executes. Dynamic binding or late binding is the key.

Title: Overriding protected methods in Java

Body:
Test.java

package a;
import b.B;
public class Test {
    public static void main(String[] v) {
        new A().test();
        new B().test();
    }
}

A.java:

package a;
public class A {
    protected void test() { }
}

B.java:

package b;
public class B extends a.A {
    protected void test() { }
}

Why does new B().test() give an error? Doesn't that break visibility rules?

B.test() is invisible in Test because they're in different packages, and yet it refuses to call the test() in B's superclass which is visible.

Links to the appropriate part of the JLS would be appreciated.

Body:
The problem is that at compile time you are telling Java that you want to access a protected member of a class when you do not have such access.

If you did this instead;

  A a = new B();
  a.test();

Then it would work and the overridden method will run because at compile time Java checks that you have access to A. At run time the object provided has the appropriate method so the B test() method executes. Dynamic binding or late binding is the key.


问:
Dispose invoked in run time when image is added through Import process
I have an application where I use a custom button. For this I use separate drawing class for the drawing. The drawing class was derived from IDisposable and I have invoked GC.SuppressFinalize(this) in its interface. Everything works fine, but when I import an image for button, the dispose is invoked which disposes my image which is leading to an Invalid exception.

We are using GC.SuppressFinalize(this) for disposing the managed resources used in our application and I found this is causing the issue.

This is a simple code for replication.

```<code>public class Custom : Control
{
    private DrawingClass drawingClass;
    public Custom()
    {
        this.drawingClass = new DrawingClass();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if(Image != null)
        e.Graphics.DrawImage(Image, this.ClientRectangle.Location);
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        if (disposing)
        {
            Image.Dispose();
        }
    }

    public Image Image { get; set; }
}

public class DrawingClass : IDisposable
{
    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}
</code>```

When I drag and drop this Custom control and try to assign an image using Import process, the dispose was invoked which disposes the Image which leading exception when drawing.

The Dispose was invoked from " System.Windows.Forms.UnsafeNativeMethod ".

Can someone suggest what is wrong or using GC.SuppressFinalize() does really cause problems ?

答:
From https://learn.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize:

GC.SuppressFinalize()

This method sets a bit in the object header of obj, which the runtime checks when calling finalizers. A finalizer, which is represented by the Object.Finalize method, is used to release unmanaged resources before an object is garbage-collected. If obj does not have a finalizer, the call to the SuppressFinalize method has no effect.

Also, check out this stackoverflow topic on implementing Disposable: Finalizer and IDisposable

Body:
I have an application where I use a custom button. For this I use separate drawing class for the drawing. The drawing class was derived from IDisposable and I have invoked GC.SuppressFinalize(this) in its interface. Everything works fine, but when I import an image for button, the dispose is invoked which disposes my image which is leading to an Invalid exception.

We are using GC.SuppressFinalize(this) for disposing the managed resources used in our application and I found this is causing the issue.

This is a simple code for replication.

public class Custom : Control
{
    private DrawingClass drawingClass;
    public Custom()
    {
        this.drawingClass = new DrawingClass();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if(Image != null)
        e.Graphics.DrawImage(Image, this.ClientRectangle.Location);
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        if (disposing)
        {
            Image.Dispose();
        }
    }

    public Image Image { get; set; }
}

public class DrawingClass : IDisposable
{
    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}

When I drag and drop this Custom control and try to assign an image using Import process, the dispose was invoked which disposes the Image which leading exception when drawing.

The Dispose was invoked from " System.Windows.Forms.UnsafeNativeMethod ".

Can someone suggest what is wrong or using GC.SuppressFinalize() does really cause problems ?


问:
Service Fabric Restart Application
I have a service fabric app that reads from KeyVault on startup. When we change the KeyVault value we have to restart the nodes for it to read the new value. This causes the other applications on the same node to go down.

I am trying to write a PowerShell script to restart the service fabric application I have got the following script working on a 1 node cluster however it does not work on multiple node cluster.

```<code>Restart-ServiceFabricDeployedCodePackage -ApplicationName $appName -CommandCompletionMode Verify -ServiceName $ServiceName -TimeoutSec 8000
</code>```

When I have a multiple node cluster this does not work. I can't figure out why it will not work.

Am I doing something wrong?

答:
The minimum amount of parameters that I made this powershell command work are:

-ApplicationName
-NodeName
-ServiceManifestName
-CodePackageName
-ServicePackageActivationId

Like this:
Restart-ServiceFabricDeployedCodePackage -ApplicationName fabric:/App -NodeName "Node01" -ServiceManifestName "ServicePkg" -CodePackageName "Code" -ServicePackageActivationId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Using this command I sometimes get weird error Did not find deployed code package for fabric:/App:Code on node Node01 but at least every time service gets restarted. I've played with other parameters combinations but with no luck. It seems above parameters are must.

Writing generic powershell script which restart specific service (and only this service) on all nodes, I would've firstly take all node names running Get-ServiceFabricNode and then iterating on these names run Get-ServiceFabricDeployedCodePackage -NodeName Node01 -ApplicationName fabric:/App -ServiceManifestName ServicePkg in order to take ServicePackageActivationId which is the only parameter that is dynamic. And finally with ServicePackageActivationId run Restart-ServiceFabricDeployedCodePackage

Title: Service Fabric Restart Application

Body:
I have a service fabric app that reads from KeyVault on startup. When we change the KeyVault value we have to restart the nodes for it to read the new value. This causes the other applications on the same node to go down.

I am trying to write a PowerShell script to restart the service fabric application I have got the following script working on a 1 node cluster however it does not work on multiple node cluster.

Restart-ServiceFabricDeployedCodePackage -ApplicationName $appName -CommandCompletionMode Verify -ServiceName $ServiceName -TimeoutSec 8000

When I have a multiple node cluster this does not work. I can't figure out why it will not work.

Am I doing something wrong?


问:
How to open a particular file on git bash vim editor itself to edit contents upon error msg “e325-attention-swap-file-already-present-error-in-vi”
Prob Scenario  : I encountered an error msg  “e325-attention-swap-file-already-present-error-in-vi” when I tried to perform a git commit.

Qn: “How do I open that particular file on git bash vim editor itself to peer inside the contents where exactly did the clash occur? I’m not asking how to remove the file form the staging area, I’m asking in particular to open that file on the git bash’s vim editor itself? And if so able, once done, how do I save that file ON the vim editor itself in git bash & exit the irritating modes in vim. PS: can any kind soul give me a useful “f1/-help”-type command that I can use to check to move forward whenever I am stuck in the vim editor mode and not exit the editor altogether each time I encounter sucha prob? Thanks!

答:
More than likely, the swapfile was from the .git/COMMIT_MESSAGE file (I believe I have the name right). It exists when vim crashes or exits abnormally to aid data recovery. In your case, I recommend deleting it (rm .git/.COMMIT_MESSAGE.sw?—find it with ls -a .git or tab-complete). Then commit.

See this question for exiting vim. Long story short, I hit Esc after finishing my commit message and then hit Z Z to save and quit.

The QA also mentions :help—this is the best place to read about vim. :help can usually be tab-complete (you may need Ctrl-d). I highly recommend running through vimtutor and some of the help pages if you plan to use vim at all. Or, set your EDITOR and VISUAL environment variables to something else (I’ve seen nano a lot for folks who don’t want to learn a command-line editor à la vim or emacs). Also note that vi.stackexchange exists.

Note: normal advice is not to delete the swap file. Often you want to recover information from them, or see if there is recoverable information. The internet and the help pages have details on doing this. For the case of a commit message, however, and for the OP, the simplest thing to do is to start from scratch (as the swap file was likely created by destroying the vim instance once OP couldn’t figure out what to do).


问:
Retrieving one value from JSON works, but identical approach on the other value fails
The source .json file is as simple as this:

```<code>{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}
</code>```

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

```<code>Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub
</code>```

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

```<code>MsgBox oJSON.rates.EURUSD.rate
</code>```

auto-transforms into

```<code>MsgBox oJSON.rates.EURUSD.Rate
</code>```

How can I return the "rate" value?

答:
A great solution for smaller projects is employing CallByName function. Not a pretty one, but can do the job in a single line, and it's not requiring to import external files to the project or add references.

```<code>Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox VBA.CallByName(VBA.CallByName(VBA.CallByName(oJSON, "rates", VbGet), "EURUSD", VbGet), "rate", VbGet)

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub
</code>```

Body:
The source .json file is as simple as this:

{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

MsgBox oJSON.rates.EURUSD.rate

auto-transforms into

MsgBox oJSON.rates.EURUSD.Rate

How can I return the "rate" value?

Body:
A great solution for smaller projects is employing CallByName function. Not a pretty one, but can do the job in a single line, and it's not requiring to import external files to the project or add references.

Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox VBA.CallByName(VBA.CallByName(VBA.CallByName(oJSON, "rates", VbGet), "EURUSD", VbGet), "rate", VbGet)

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub


问:
How to configure https VM on Proxmox to avoid cURL error 7 port 443: Connection refused?
I have a website running on a VM on Proxmox.

Public IP -> Host Proxmox -> Private IP of the VM

https     -> Certificate SSL given by the Host Proxmox -> http on the private IP of the VM

On the client side (from outside) all is ok.

On the server side (admin of Wordpress), I get some cURL error 7 :

Failed to connect to mysitename.com port 443 : Connection refused

I think on the server side, wordpress admin tries to reach https://mysitename.com from the VM .... which run under http

My etc/host files (on the VM) is :

```<code>127.0.0.1       localhost mysitename.com
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
# --- BEGIN PVE ---
10.10.2.30 mysitename.com mysitename
# --- END PVE ---
</code>```

What should I change in my configuration to autorize https connection from and to the local VM (which did not have the https certificate) ?

Thanks a lot !

答:
The Connection Refused error indicates https (port 443) can't be reached. Double-check your firewall / port forwarding rules to make sure both 80 and 443 are forwarded to your private IP. It's best practice to only use 443 but this depends on other factors.

If you haven't setup an SSL certificate for your WordPress install yet, you may get started by using free certificates from the https://letsencrypt.org/ project.

Body:
I have a website running on a VM on Proxmox.

Public IP -> Host Proxmox -> Private IP of the VM

https     -> Certificate SSL given by the Host Proxmox -> http on the private IP of the VM

On the client side (from outside) all is ok.

On the server side (admin of Wordpress), I get some cURL error 7 :

Failed to connect to mysitename.com port 443 : Connection refused

I think on the server side, wordpress admin tries to reach https://mysitename.com from the VM .... which run under http

My etc/host files (on the VM) is :

127.0.0.1       localhost mysitename.com
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
# --- BEGIN PVE ---
10.10.2.30 mysitename.com mysitename
# --- END PVE ---

What should I change in my configuration to autorize https connection from and to the local VM (which did not have the https certificate) ?

Thanks a lot !


问:
How to handle JS serialized item in PHP?
Hey guys!
I am having a bit of trouble handling the data from a submitted form that is serialized with JS.
In the form there a textarea fields which users can input any text they want but when they enter & like "apples & oranges", I have trouble handling that.  As we know that JS serializes & to %26 and spaces with a "+" sign.

So now back in PHP, I am trying to put this data into the database and call it back out elsewhere but for the life of me don't know how to handle the special characters properly.

Note that I am also php exploding the data at the "&" sign to make it into an array, then is put into the database as an array.  I tried several methods like urldecode, htmlentities but those don't help because remember I need to explode at "&".

I am serializing in JS because its an AJAX submitting form.


问:
Use Glide to load images from URL but without extensions
I could use Glide to load images from my local web server via the following code:

```<code>Glide.with(this)
     .load(SERVER_HOST_ADDRESS + userID + ".jpg")
     .into((ImageView) mBinding.getRoot().findViewById(R.id.userImage));
</code>```

The problem is that with this method, I am limited to having access only to.jpg extensions, when sometimes the user may have chosen to upload a different type of image.
Is there a way for Glide to handle loading an image from a URL, but without the extensions?
Building an iterator would be fine, but may be unnecessary.

答:
Is there a way for Glide to handle loading an image from a URL, but without the extensions?

Yes, though your Web server may not support it.

My interpretation is that you want:

```<code>.load(SERVER_HOST_ADDRESS + userID)
</code>```

If your Web server serves an image at that URL, with a valid image MIME type, Glide will handle it. Glide itself does not care about file extensions — it wants a valid URL that supplies a valid image MIME type.

However, my guess it that your server will return a 404 error for that URL, because the server is expecting the file extension, to match up with the file on the server.

Options to deal with this include:

Teach the server how to handle the no-extension URL

Use a consistent image type (e.g., have the server convert everything to JPEG)

Have some metadata tell you what URL to load (e.g., a Web service call to get details of the user has a JSON property that provides the image URL)

Do what you suggested and just iterate over the various possibilities and see if one of them works

Body:
I could use Glide to load images from my local web server via the following code:

Glide.with(this)
     .load(SERVER_HOST_ADDRESS + userID + ".jpg")
     .into((ImageView) mBinding.getRoot().findViewById(R.id.userImage));

The problem is that with this method, I am limited to having access only to.jpg extensions, when sometimes the user may have chosen to upload a different type of image.
Is there a way for Glide to handle loading an image from a URL, but without the extensions?
Building an iterator would be fine, but may be unnecessary.

Body:
Is there a way for Glide to handle loading an image from a URL, but without the extensions?

Yes, though your Web server may not support it.

My interpretation is that you want:

.load(SERVER_HOST_ADDRESS + userID)

If your Web server serves an image at that URL, with a valid image MIME type, Glide will handle it. Glide itself does not care about file extensions — it wants a valid URL that supplies a valid image MIME type.

However, my guess it that your server will return a 404 error for that URL, because the server is expecting the file extension, to match up with the file on the server.

Options to deal with this include:

Teach the server how to handle the no-extension URL

Use a consistent image type (e.g., have the server convert everything to JPEG)

Have some metadata tell you what URL to load (e.g., a Web service call to get details of the user has a JSON property that provides the image URL)

Do what you suggested and just iterate over the various possibilities and see if one of them works


问:
PHP urldecode() function wont work for email validation
Im trying to decode the email, since its been encoded in the url, but the urldecode() function wont decode it.

I'v also tried rawurldecode(), then tried first encoding it myself and then decoding it, but its still encoded like %40 instead of an @ sign.

Here is the code:

```<code>$isValid = ! User::emailExists(urldecode($_GET['email']));
</code>```

Im getting something like this:

http://localhost/account/validate-email?email=some_email%40gmail.com

答:
$_GET gets automatically decoded, are sure you're correctly encoding the url in the first place?

Also remember that you should pay attention also to the encoding of the url for the HTML attribute you put it into:

It might be you're double encoding and/or wrongly encoding!

Body:
Im trying to decode the email, since its been encoded in the url, but the urldecode() function wont decode it.

I'v also tried rawurldecode(), then tried first encoding it myself and then decoding it, but its still encoded like %40 instead of an @ sign.

Here is the code:

$isValid = ! User::emailExists(urldecode($_GET['email']));

Im getting something like this:

http://localhost/account/validate-email?email=some_email%40gmail.com


问:
Neo4j Cypher Client Create Dynamic Objects
At the moment I have to specify what class is needed during the return, is there a way to get all properties and and create a dynamic/anonymous object.</p>

```<code>public IEnumerable<Node> GetNodes()
    {
        Console.WriteLine($"Retrieving All Nodes from DB...");
        try
        {
            return graphClient.Cypher
               .Match($"(n:Node)")
               .Return(t => new Node
               {
                   Latitude = Return.As<double>("n.lat"),
                   Longitude = Return.As<double>("n.lon"),
                   Id = Return.As<string>("n.id"),
                   ValA = Return.As<long>("n.valA")
               }).Results;
        }
        catch (Exception ex)
        {
            string error = $"ERROR (Get Node): {ex.ToString()}";
            Console.WriteLine(error);
        }

        return null;
    }
</code>```

答:
You can use the solution I wrote for this question: Neo4jClient How can I return all nodes, relationships and parameters for a dynamic graph

I would argue - if this is what you really want to do - you might be better off using the official driver (Neo4j-Driver) or indeed just using a standard REST client and connecting directly - however - the above answer should get you going where you want to be!

Body:
At the moment I have to specify what class is needed during the return, is there a way to get all properties and and create a dynamic/anonymous object.

public IEnumerable<Node> GetNodes()
    {
        Console.WriteLine($"Retrieving All Nodes from DB...");
        try
        {
            return graphClient.Cypher
               .Match($"(n:Node)")
               .Return(t => new Node
               {
                   Latitude = Return.As<double>("n.lat"),
                   Longitude = Return.As<double>("n.lon"),
                   Id = Return.As<string>("n.id"),
                   ValA = Return.As<long>("n.valA")
               }).Results;
        }
        catch (Exception ex)
        {
            string error = $"ERROR (Get Node): {ex.ToString()}";
            Console.WriteLine(error);
        }

        return null;
    }


问:
Removing the duplicates from an array of objects
Duplicate values are being storing into an array of object

Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array

But with the below piece of code duplicate values are being stored into an array teamSocketsList

```<code>var  TeamUser = {
    userId : userID,
    socketId : socket.id
}

var i = $.inArray( userID, teamSocketsList );
if(i == -1){
    teamSocketsList.push(TeamUser);
}else{
        teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
        return value != userID;
    });
}
</code>```

Actual Result:

```<code>[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
</code>```

Expected Result:

```<code>[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]
</code>```

Edit:

Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value

The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.

Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.

答:
You can store your data in the object (key-value pair) and avoid adding duplicate data.
For example:

```<code>var teamSocketsList = {};

var TeamUser = {
    userId : userID,
    socketId : socket.id
}

teamSocketsList[TeamUser.userId] = TeamUser;
</code>```

Then if you are adding new user to teamSocketsList, you can easily (without iterating through all elements in the array) check if there are teamUser with that id.

```<code>if(teamSocketsList[TeamUser.userId]) // team user exists in the list
</code>```

Body:
Duplicate values are being storing into an array of object

Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array

But with the below piece of code duplicate values are being stored into an array teamSocketsList

var  TeamUser = {
    userId : userID,
    socketId : socket.id
}

var i = $.inArray( userID, teamSocketsList );
if(i == -1){
    teamSocketsList.push(TeamUser);
}else{
        teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
        return value != userID;
    });
}

Actual Result:

[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]

Expected Result:

[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]

Edit:

Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value

The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.

Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.

Body:
You can store your data in the object (key-value pair) and avoid adding duplicate data.
For example:

var teamSocketsList = {};

var TeamUser = {
    userId : userID,
    socketId : socket.id
}

teamSocketsList[TeamUser.userId] = TeamUser;

Then if you are adding new user to teamSocketsList, you can easily (without iterating through all elements in the array) check if there are teamUser with that id.

if(teamSocketsList[TeamUser.userId]) // team user exists in the list


问:
How to get downloadURL from this function?
I want to get downloadURL from this function. But, It doesn't wait to get it. So this function does not return downloadURL.
How can I get it??</p>

```<code>uploadProfileImage = async (uid, file) => {
        let userRef = this.str.ref(`${uid}`).child(`images/avatar.png`);

        const uploadTask = userRef.put(file);

        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {

            let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
                case firebase.storage.TaskState.PAUSED:
                    console.log('Upload is paused');
                    break;
                case firebase.storage.TaskState.RUNNING:
                    console.log('Upload is running');
                    break;

                default:
            }

        }, error => {
            console.log('[Error] ', error);
        }, async () => {
            const downloadUrl = await uploadTask.snapshot.ref.getDownloadURL()
            // update firebase database
            this.updateUserInfo(uid, { profileImage: downloadUrl });

        });

}
</code>```

答:
One way of doing it is to simply follow up documentation provided by google here

```<code>uploadProfileImage = (uid, file) => {
    let userRef = this.str.ref(`${uid}`).child(`images/avatar.png`);

    const uploadTask = userRef.put(file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {

        let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        switch (snapshot.state) {
            case firebase.storage.TaskState.PAUSED:
                console.log('Upload is paused');
                break;
            case firebase.storage.TaskState.RUNNING:
                console.log('Upload is running');
                break;

            default:
        }

    }, error => {
        console.log('[Error] ', error);
    }, () => {
        uploadTask.snapshot.ref.getDownloadURL().then((downloadUrl)=>{
        // update firebase database
        this.updateUserInfo(uid, { profileImage: downloadUrl });
        }
    });
}
</code>```

I assume your variables are correct

Body:
I want to get downloadURL from this function. But, It doesn't wait to get it. So this function does not return downloadURL.
How can I get it??

uploadProfileImage = async (uid, file) => {
        let userRef = this.str.ref(`${uid}`).child(`images/avatar.png`);

        const uploadTask = userRef.put(file);

        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {

            let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
                case firebase.storage.TaskState.PAUSED:
                    console.log('Upload is paused');
                    break;
                case firebase.storage.TaskState.RUNNING:
                    console.log('Upload is running');
                    break;

                default:
            }

        }, error => {
            console.log('[Error] ', error);
        }, async () => {
            const downloadUrl = await uploadTask.snapshot.ref.getDownloadURL()
            // update firebase database
            this.updateUserInfo(uid, { profileImage: downloadUrl });

        });

}

Body:
One way of doing it is to simply follow up documentation provided by google here

uploadProfileImage = (uid, file) => {
    let userRef = this.str.ref(`${uid}`).child(`images/avatar.png`);

    const uploadTask = userRef.put(file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {

        let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        switch (snapshot.state) {
            case firebase.storage.TaskState.PAUSED:
                console.log('Upload is paused');
                break;
            case firebase.storage.TaskState.RUNNING:
                console.log('Upload is running');
                break;

            default:
        }

    }, error => {
        console.log('[Error] ', error);
    }, () => {
        uploadTask.snapshot.ref.getDownloadURL().then((downloadUrl)=>{
        // update firebase database
        this.updateUserInfo(uid, { profileImage: downloadUrl });
        }
    });
}

I assume your variables are correct


问:
I need delete two " " with sed command
I need to delete "" in file

```<code>"CITFFUSKD-E0"
</code>```

I have tried sed 's/\"//.

Result is:

```<code>CITFFUSKD-E0"
</code>```

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

```<code>"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"
</code>```

Result I want it:

```<code>CITFFUSKD
</code>```

答:
When you have 1 line, you can use

```<code>grep -Eo "(\w)*" file | head -1
</code>```

For normal files (starting with a double quote on each line)
, try this

```<code>tr -c [^[:alnum:]] '"' < file | cut -d'"' -f2
</code>```

Title: I need delete two " " with sed command

Body:
I need to delete "" in file

"CITFFUSKD-E0"

I have tried sed 's/\"//.

Result is:

CITFFUSKD-E0"

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"

Result I want it:

CITFFUSKD

Body:
When you have 1 line, you can use

grep -Eo "(\w)*" file | head -1

For normal files (starting with a double quote on each line)
, try this

tr -c [^[:alnum:]] '"' < file | cut -d'"' -f2


问:
using getFragmentSupport Manager inside PreferenceFragment
I found this library that I want to use inside my PreferenceFragment extended class, my problem is that the getSupportFragmentManager can not be resolved.
My question is how do I show the fragment when it extends a PreferenceFragment

I tried changing to getFragmentManager but won't work

```<code>public class PreferencesFragment extends PreferenceFragment {

 final Preference currencyPreference = findPreference(getResources().getString(R.string.setting_category_currency_key));
        currencyPreference.setOnPreferenceClickListener(preference -> {
            //selectCurrencyDialog = new SelectCurrencyFragment();
            //selectCurrencyDialog.show(((SettingsActivity) getActivity()).getSupportFragmentManager(), "SelectCurrency");

            CurrencyPicker picker = CurrencyPicker.newInstance("Select Currency");  // dialog title
            picker.setListener((name, code, symbol, flagDrawableResID) -> {
                // Implement your code here
            });
            picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");

            return false;
        });

}
</code>```

The error is on this Line

getSupportFragmentManager()

```<code>picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");
</code>```

答:
In Fragment use -

```<code>picker.show(getChildFragmentManager(), "CURRENCY_PICKER");
</code>```

In Activity use -

```<code>picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");
</code>```

Body:
I found this library that I want to use inside my PreferenceFragment extended class, my problem is that the getSupportFragmentManager can not be resolved.
My question is how do I show the fragment when it extends a PreferenceFragment

I tried changing to getFragmentManager but won't work

public class PreferencesFragment extends PreferenceFragment {

 final Preference currencyPreference = findPreference(getResources().getString(R.string.setting_category_currency_key));
        currencyPreference.setOnPreferenceClickListener(preference -> {
            //selectCurrencyDialog = new SelectCurrencyFragment();
            //selectCurrencyDialog.show(((SettingsActivity) getActivity()).getSupportFragmentManager(), "SelectCurrency");

            CurrencyPicker picker = CurrencyPicker.newInstance("Select Currency");  // dialog title
            picker.setListener((name, code, symbol, flagDrawableResID) -> {
                // Implement your code here
            });
            picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");

            return false;
        });

}

The error is on this Line

getSupportFragmentManager()

picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");

Body:
In Fragment use -

picker.show(getChildFragmentManager(), "CURRENCY_PICKER");

In Activity use -

picker.show(getSupportFragmentManager(), "CURRENCY_PICKER");


问:
Best approach to bind to events occurring inside a component
Angular4 app:
I am using a videogular2 library(or let say just  elem) in a component call it CompA, where CompA then used inside CompB.

I need to subscribe to the events of videogular(or video elem) inside CompA such that if play/pause occurs it will emit or could listen in the ServiceX.

First of all I am not getting solution exact to my problem, second I want to what will be best approach to achieve this?

答:
According to the docs for videogular2 here, you need to bind to the onPlayerReady event on the vg-player component. Something like this:

```<code><vg-player (onPlayerReady)="onPlayerReady($event)">
    <video [vgMedia]="media" #media id="singleVideo" preload="auto" controls>
        <source src="https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm">
    </video>
</vg-player>
</code>```

You will then get an event in the onPlayerReady event handler. This event basically is an API that exposes getDefaultMedia().subscriptions. On that, you can subscribe to Observables like play and pause listed here. Something like this:

```<code>import { Component } from '@angular/core';
import { VgAPI } from 'videogular2/core';

import { PlayerStateService } from './player-state.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  api: VgAPI;

  constructor(private playerState: PlayerStateService) { }

  onPlayerReady(api: VgAPI) {
    console.log('playerReady');
    this.api = api;
    this.api.getDefaultMedia().subscriptions.play.subscribe(
        (event) => {
          this.playerState.updatePlayerState('play');
        }
    );

    this.api.getDefaultMedia().subscriptions.pause.subscribe(
        (event) => {
          this.playerState.updatePlayerState('pause');
        }
    );

  }
}
</code>```

Now that you get to know that the player has paused or resumed, you can easily create a Shared Service, with a BehaviorSubject on it. And every time there's a change in the status of the player, you can set a new value on that BehaviorSubject by calling the next method on it.

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class PlayerStateService {

  private state: BehaviorSubject<string> = new BehaviorSubject<string>('');
  public state$: Observable<string> = this.state.asObservable();

  constructor() { }

  updatePlayerState(playerState: string) {
    this.state.next(playerState);
  }

}
</code>```

And you can then subscribe to it in some other component where you want to listen to these state changes in the player.

```<code>import { Component, Input } from '@angular/core';
import { Observable } from 'rxjs';

import { PlayerStateService } from './player-state.service';

@Component({
  selector: 'hello',
  template: `<h1>Current state of the player is {{ playerState$ | async }}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {

  playerState$: Observable<string>;

  constructor(private playerState: PlayerStateService) { }

  ngOnInit() {
    this.playerState$ = this.playerState.state$;
  }

}
</code>```

Here's a Working Sample StackBlitz for your ref.

Body:
According to the docs for videogular2 here, you need to bind to the onPlayerReady event on the vg-player component. Something like this:

<vg-player (onPlayerReady)="onPlayerReady($event)">
    <video [vgMedia]="media" #media id="singleVideo" preload="auto" controls>
        <source src="https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm">
    </video>
</vg-player>

You will then get an event in the onPlayerReady event handler. This event basically is an API that exposes getDefaultMedia().subscriptions. On that, you can subscribe to Observables like play and pause listed here. Something like this:

import { Component } from '@angular/core';
import { VgAPI } from 'videogular2/core';

import { PlayerStateService } from './player-state.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  api: VgAPI;

  constructor(private playerState: PlayerStateService) { }

  onPlayerReady(api: VgAPI) {
    console.log('playerReady');
    this.api = api;
    this.api.getDefaultMedia().subscriptions.play.subscribe(
        (event) => {
          this.playerState.updatePlayerState('play');
        }
    );

    this.api.getDefaultMedia().subscriptions.pause.subscribe(
        (event) => {
          this.playerState.updatePlayerState('pause');
        }
    );

  }
}

Now that you get to know that the player has paused or resumed, you can easily create a Shared Service, with a BehaviorSubject on it. And every time there's a change in the status of the player, you can set a new value on that BehaviorSubject by calling the next method on it.

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class PlayerStateService {

  private state: BehaviorSubject<string> = new BehaviorSubject<string>('');
  public state$: Observable<string> = this.state.asObservable();

  constructor() { }

  updatePlayerState(playerState: string) {
    this.state.next(playerState);
  }

}

And you can then subscribe to it in some other component where you want to listen to these state changes in the player.

import { Component, Input } from '@angular/core';
import { Observable } from 'rxjs';

import { PlayerStateService } from './player-state.service';

@Component({
  selector: 'hello',
  template: `<h1>Current state of the player is {{ playerState$ | async }}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {

  playerState$: Observable<string>;

  constructor(private playerState: PlayerStateService) { }

  ngOnInit() {
    this.playerState$ = this.playerState.state$;
  }

}

Here's a Working Sample StackBlitz for your ref.


问:
replace spaces with null value using regexp_replace if i have multiple
How to replace spaces with Null if i have spaces in multiple column.

```<code>Input Dataset which i have
+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  |     |
|  1|     |     |
+---+-----+-----+
</code>```

```<code>import org.apache.spark.sql.functions._

val test = df.withColumn("col_1","col_2", regexp_replace(df("col_1","col_1"), "^\\s*", lit(Null)))
test.filter("col_1,col_2 is null").show()
</code>```

Output Dataset:

```<code>+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  | Null|
|  1|Null | Null|
+---+-----+-----+
</code>```

答:
Hi You can do like this:

```<code>scala> val someDFWithName = Seq((1, "anurag", ""), (5, "", "")).toDF("id", "name", "age")
someDFWithName: org.apache.spark.sql.DataFrame = [id: int, name: string ... 1 more field]

scala> someDFWithName.show
+---+------+---+
| id|  name|age|
+---+------+---+
|  1|anurag|   |
|  5|      |   |
+---+------+---+
scala> someDFWithName.na.replace(Seq("name","age"),Map(""-> null)).show
+---+------+----+
| id|  name| age|
+---+------+----+
|  1|anurag|null|
|  5|  null|null|
+---+------+----+
</code>```

Or try out this also:

```<code>scala> someDFWithName.withColumn("Name", when(col("Name") === "", null).otherwise(col("Name"))).withColumn("Age", when(col("Age") === "", null).otherwise(col("Age"))).show
+---+------+----+
| id|  name| age|
+---+------+----+
|  1|anurag|null|
|  5|  null|null|
+---+------+----+
</code>```

Or For more than one space try out this:

```<code>scala> val someDFWithName = Seq(("n", "a"), ( "", "n"), ("         ", ""), ("  ", "a"), ("   ",""), ("        ","   "), ("c"," ")).toDF("name", "place")
someDFWithName: org.apache.spark.sql.DataFrame = [name: string, place: string]

scala> someDFWithName.withColumn("Name", when(regexp_replace(col("name"),"\\s+","") === "", null).otherwise(col("Name"))).withColumn("Place", when(regexp_replace(col("place"),"\\s+","") === "", null).otherwise(col("place"))).show
+----+-----+
|Name|Place|
+----+-----+
|   n|    a|
|null|    n|
|null| null|
|null|    a|
|null| null|
|null| null|
|   c| null|
+----+-----+
</code>```

I hope this will help you. Thanks

Body:
How to replace spaces with Null if i have spaces in multiple column.

Input Dataset which i have
+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  |     |
|  1|     |     |
+---+-----+-----+

import org.apache.spark.sql.functions._

val test = df.withColumn("col_1","col_2", regexp_replace(df("col_1","col_1"), "^\\s*", lit(Null)))
test.filter("col_1,col_2 is null").show()

Output Dataset:

+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  | Null|
|  1|Null | Null|
+---+-----+-----+

Body:
Hi You can do like this:

scala> val someDFWithName = Seq((1, "anurag", ""), (5, "", "")).toDF("id", "name", "age")
someDFWithName: org.apache.spark.sql.DataFrame = [id: int, name: string ... 1 more field]

scala> someDFWithName.show
+---+------+---+
| id|  name|age|
+---+------+---+
|  1|anurag|   |
|  5|      |   |
+---+------+---+
scala> someDFWithName.na.replace(Seq("name","age"),Map(""-> null)).show
+---+------+----+
| id|  name| age|
+---+------+----+
|  1|anurag|null|
|  5|  null|null|
+---+------+----+

Or try out this also:

scala> someDFWithName.withColumn("Name", when(col("Name") === "", null).otherwise(col("Name"))).withColumn("Age", when(col("Age") === "", null).otherwise(col("Age"))).show
+---+------+----+
| id|  name| age|
+---+------+----+
|  1|anurag|null|
|  5|  null|null|
+---+------+----+

Or For more than one space try out this:

scala> val someDFWithName = Seq(("n", "a"), ( "", "n"), ("         ", ""), ("  ", "a"), ("   ",""), ("        ","   "), ("c"," ")).toDF("name", "place")
someDFWithName: org.apache.spark.sql.DataFrame = [name: string, place: string]

scala> someDFWithName.withColumn("Name", when(regexp_replace(col("name"),"\\s+","") === "", null).otherwise(col("Name"))).withColumn("Place", when(regexp_replace(col("place"),"\\s+","") === "", null).otherwise(col("place"))).show
+----+-----+
|Name|Place|
+----+-----+
|   n|    a|
|null|    n|
|null| null|
|null|    a|
|null| null|
|null| null|
|   c| null|
+----+-----+

I hope this will help you. Thanks


问:
Passing data to Fragment before destroying Activity
I've

Activity A -> Fragment A

[from Fragment A I decide to create Activity B]

Fragment A ->  Activity B.

When I press back button, I go back to Fragment A which contains data list. I'd like to update this list when back button is pressed. No, I don't store data locally and making another request is too expensive. Is there a simple way to pass modified object X on back button press [From Activity B to Fragment A]? How?

答:
In fragment A you can call a method from Activity A to start an activity with result to Activity B.

When you go back you can send that data with it.
In activity A you can have the method onActivityResult to catch this result and refresh Fragment A.

Android documentation