问:
Append/Prepend space on outer tag
I would like to append/prepend a space on the outer tags.

I tried the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append(" ")
$elem.prepend(" ");

console.log($elem[0]);
console.log($elem[0].innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

As you can see only the inner tag has the spaces.

However, I would like to have it on the outer tag. Like the following:

```<code> <span data-function="addSynonym" data-options="[ test1, test2, test3]"><span style="background-color: yellow;">test4</span></span>

</code>```

Any suggestions how to do this?

I appreciate your replies!

答:
Method 1: Wrap your node to another node with a no break space at start/end

You can use another span element to wrap your text. That won't affect anything in your text neither in the way you may want to use $elem afterwards. Then create a text node using NO-BREAK SPACE' (U+00A0) which is equivalent to   and use it to compile your final text node.

var colors = ['yellow', 'red', 'lightgreen', 'cyan'];
var currentColor = 0;

// Create a text node using Unicode Character 'NO-BREAK SPACE' (U+00A0)
var $spaceNode = $(document.createTextNode('\u00A0'));

// Wrap the text node to a span with a begin and end sibling of the space text node clone
var $elem = $('').append(
  $spaceNode.clone(),
  $('', {
    'data-function': "addSynonym",
    'data-options': '[test1, test2, test3]',
    'html': $('', {
      'text': 'test4',
      'css': {
        backgroundColor: 'yellow'
      }
    })
  }),
  $spaceNode.clone()
);

function appendText() {
  // Output $elem node outer HTML to a preview element
  $('#elem_html').text($elem[0].outerHTML);

  // Clone the $elem so we can use it multiple times
  var $elemClone = $elem.clone();

  // Append the cloned $elem to the DOM
  $('#editor').append($elemClone);

  // Apply manipulation demo timer
  hookElemChange($elemClone);
}

// Handle add text button click
$('#add_text').on('click', function() {
  appendText();
});

// Handle change $elem color button click
$('#change_text_color').on('click', function() {
  var newColor;

  // Generate a random color
  do {
    newColor = Math.floor(Math.random() * Math.floor(colors.length));
  } while(newColor === currentColor);

  currentColor = newColor;

  // Change the $elem inner span background color to a random color
  $elem.find('span > span').css('background-color', colors[currentColor]);
  // We can also use specific element selector using data-function with "addSynonym" value
  // $elem.find('span[data-function="addSynonym"] > span').css('background-color', colors[currentColor]);

  // Append the text to the DOM
  appendText();
});

// A timer for each element that parses and increases the text prepending number
// This is for to demontrate that each node can be manipulated with no restrictions after creating/cloning
function hookElemChange($element) {
  setInterval(function() {
    var $currentElem = $element.find('span[data-function="addSynonym"] > span');

    var text = $currentElem.text();
    var textParts = text.match(/([a-z]+)(\d+)/);

    if (textParts) {
      var num = parseInt(textParts[2]);
      var newText = textParts[1] + ++num;

      $currentElem.text(newText);
    }
  }, 1000);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editor {
  border: 1px solid grey;
  height: 100px;
  margin-bottom: 10px;
  overflow-wrap: break-word;
  overflow: auto;
}

#elem_html {
  white-space: normal;
  margin-top: 20px;
}</code>```

  <button id="add_text">Add text</button>
  <button id="change_text_color">Change color</button>

```
</div></code>```

As you can see, you can save and access each cloned $elem afterwards with both span selector ($elem.find('span')) or even more specific using data-function name span[data-function="addSynonym"] ($elem.find('span[data-function="addSynonym"]')) and for the inner element span > span or span[data-function="addSynonym"] > span.

Method 2: Append everything directly to the target node (space/$elem/space)

Another way is to directly append everything to the target node if you want to keep that specific $elem structure:

var colors = ['yellow', 'red', 'lightgreen', 'cyan'];
var currentColor = 0;

// Create a text node using Unicode Character 'NO-BREAK SPACE' (U+00A0)
var $spaceNode = $(document.createTextNode('\u00A0'));

// Create the node with initial structure
var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

function appendText() {
  // Clone the $elem so we can use it multiple times
  var $elemClone = $elem.clone();

  // Append the cloned $elem to the DOM
  $('#editor').append($spaceNode.clone(), $elemClone, $spaceNode.clone());

  // Output #editor node inner HTML to a preview element
  $('#elem_html').text($('#editor')[0].innerHTML);

  // Apply manipulation demo timer
  hookElemChange($elemClone);
}

// Handle add text button click
$('#add_text').on('click', function() {
  appendText();
});

// Handle change $elem color button click
$('#change_text_color').on('click', function() {
  var newColor;

  // Generate a random color
  do {
    newColor = Math.floor(Math.random() * Math.floor(colors.length));
  } while(newColor === currentColor);

  currentColor = newColor;

  // Change the $elem inner span background color to a random color
  $elem.find('span').css('background-color', colors[currentColor]);
  // We can also use specific element selector using data-function with "addSynonym" value
  // $elem.find('span[data-function="addSynonym"] > span').css('background-color', colors[currentColor]);

  // Append the text to the DOM
  appendText();
});

// A timer for each element that parses and increases the text prepending number
// This is for to demontrate that each node can be manipulated with no restrictions after creating/cloning

function hookElemChange($element) {
  setInterval(function() {
    var $currentElem = $element.find('span');

    var text = $currentElem.text();
    var textParts = text.match(/([a-z]+)(\d+)/);

    if (textParts) {
      var num = parseInt(textParts[2]);
      var newText = textParts[1] + ++num;
      $currentElem.text(newText);
    }
  }, 1000);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editor {
  border: 1px solid grey;
  height: 100px;
  margin-bottom: 10px;
  overflow-wrap: break-word;
  overflow: auto;
}

#elem_html {
  white-space: normal;
  margin-top: 20px;
}</code>```

  <button id="add_text">Add text</button>
  <button id="change_text_color">Change color</button>

```</div></code>```

Using this way, you'll have to access inner span using just span ($elem.find('span')) selector.

Title: Append/Prepend space on outer tag

Body:
I would like to append/prepend a space on the outer tags.

I tried the following:

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[ test1, test2, test3]',
  'html': $('', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

$elem.append(" ")
$elem.prepend(" ");

console.log($elem[0]);
console.log($elem[0].innerHTML);

As you can see only the inner tag has the spaces.

However, I would like to have it on the outer tag. Like the following:

 test4

Any suggestions how to do this?

I appreciate your replies!

Body:
Method 1: Wrap your node to another node with a no break space at start/end

You can use another span element to wrap your text. That won't affect anything in your text neither in the way you may want to use $elem afterwards. Then create a text node using NO-BREAK SPACE' (U+00A0) which is equivalent to &nbsp; and use it to compile your final text node.

var colors = ['yellow', 'red', 'lightgreen', 'cyan'];
var currentColor = 0;

// Create a text node using Unicode Character 'NO-BREAK SPACE' (U+00A0)
var $spaceNode = $(document.createTextNode('\u00A0'));

// Wrap the text node to a span with a begin and end sibling of the space text node clone
var $elem = $('<span>').append(
  $spaceNode.clone(),
  $('<span>', {
    'data-function': "addSynonym",
    'data-options': '[test1, test2, test3]',
    'html': $('<span>', {
      'text': 'test4',
      'css': {
        backgroundColor: 'yellow'
      }
    })
  }),
  $spaceNode.clone()
);

function appendText() {
  // Output $elem node outer HTML to a preview element
  $('#elem_html').text($elem[0].outerHTML);

  // Clone the $elem so we can use it multiple times
  var $elemClone = $elem.clone();

  // Append the cloned $elem to the DOM
  $('#editor').append($elemClone);

  // Apply manipulation demo timer
  hookElemChange($elemClone);
}

// Handle add text button click
$('#add_text').on('click', function() {
  appendText();
});

// Handle change $elem color button click
$('#change_text_color').on('click', function() {
  var newColor;

  // Generate a random color
  do {
    newColor = Math.floor(Math.random() * Math.floor(colors.length));
  } while(newColor === currentColor);

  currentColor = newColor;

  // Change the $elem inner span background color to a random color
  $elem.find('span > span').css('background-color', colors[currentColor]);
  // We can also use specific element selector using data-function with "addSynonym" value
  // $elem.find('span[data-function="addSynonym"] > span').css('background-color', colors[currentColor]);

  // Append the text to the DOM
  appendText();
});

// A timer for each element that parses and increases the text prepending number
// This is for to demontrate that each node can be manipulated with no restrictions after creating/cloning
function hookElemChange($element) {
  setInterval(function() {
    var $currentElem = $element.find('span[data-function="addSynonym"] > span');

    var text = $currentElem.text();
    var textParts = text.match(/([a-z]+)(\d+)/);

    if (textParts) {
      var num = parseInt(textParts[2]);
      var newText = textParts[1] + ++num;

      $currentElem.text(newText);
    }
  }, 1000);
}

#editor {
  border: 1px solid grey;
  height: 100px;
  margin-bottom: 10px;
  overflow-wrap: break-word;
  overflow: auto;
}

#elem_html {
  white-space: normal;
  margin-top: 20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="editor"></div>

<div>
  <button id="add_text">Add text</button>
  <button id="change_text_color">Change color</button>
</div>

<div>
  <pre id="elem_html"></pre>
</div>

As you can see, you can save and access each cloned $elem afterwards with both span selector ($elem.find('span')) or even more specific using data-function name span[data-function="addSynonym"] ($elem.find('span[data-function="addSynonym"]')) and for the inner element span > span or span[data-function="addSynonym"] > span.

Method 2: Append everything directly to the target node (space/$elem/space)

Another way is to directly append everything to the target node if you want to keep that specific $elem structure:

var colors = ['yellow', 'red', 'lightgreen', 'cyan'];
var currentColor = 0;

// Create a text node using Unicode Character 'NO-BREAK SPACE' (U+00A0)
var $spaceNode = $(document.createTextNode('\u00A0'));

// Create the node with initial structure
var $elem = $('<span>', {
  'data-function': "addSynonym",
  'data-options': '[test1, test2, test3]',
  'html': $('<span>', {
    'text': 'test4',
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

function appendText() {
  // Clone the $elem so we can use it multiple times
  var $elemClone = $elem.clone();

  // Append the cloned $elem to the DOM
  $('#editor').append($spaceNode.clone(), $elemClone, $spaceNode.clone());

  // Output #editor node inner HTML to a preview element
  $('#elem_html').text($('#editor')[0].innerHTML);

  // Apply manipulation demo timer
  hookElemChange($elemClone);
}

// Handle add text button click
$('#add_text').on('click', function() {
  appendText();
});

// Handle change $elem color button click
$('#change_text_color').on('click', function() {
  var newColor;

  // Generate a random color
  do {
    newColor = Math.floor(Math.random() * Math.floor(colors.length));
  } while(newColor === currentColor);

  currentColor = newColor;

  // Change the $elem inner span background color to a random color
  $elem.find('span').css('background-color', colors[currentColor]);
  // We can also use specific element selector using data-function with "addSynonym" value
  // $elem.find('span[data-function="addSynonym"] > span').css('background-color', colors[currentColor]);

  // Append the text to the DOM
  appendText();
});

// A timer for each element that parses and increases the text prepending number
// This is for to demontrate that each node can be manipulated with no restrictions after creating/cloning

function hookElemChange($element) {
  setInterval(function() {
    var $currentElem = $element.find('span');

    var text = $currentElem.text();
    var textParts = text.match(/([a-z]+)(\d+)/);

    if (textParts) {
      var num = parseInt(textParts[2]);
      var newText = textParts[1] + ++num;
      $currentElem.text(newText);
    }
  }, 1000);
}

#editor {
  border: 1px solid grey;
  height: 100px;
  margin-bottom: 10px;
  overflow-wrap: break-word;
  overflow: auto;
}

#elem_html {
  white-space: normal;
  margin-top: 20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="editor"></div>

<div>
  <button id="add_text">Add text</button>
  <button id="change_text_color">Change color</button>
</div>

<div><pre id="elem_html"></pre></div>

Using this way, you'll have to access inner span using just span ($elem.find('span')) selector.


来源: stackexchange

问:
Get the access token
I need to get the token and it returns a lot of information

```<code>getTokenSilently$(options?): Observable<string> {
        return this.auth0Client$.pipe(
          concatMap((client: Auth0Client) => from(client.getTokenSilently(options)))
        );
      }

    const token =  auth.getTokenSilently$()
</code>```

https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api

答:
You have to subscribe to the observable in order to get the token because getTokenSilenty$ method is an observable.

Use

AuthService.ts

    getTokenSilently$(options?): Observable<string> {
        return this.auth0Client$.pipe(
          concatMap((client: Auth0Client) => from(client.getTokenSilently(options)))
      );
    }
```

<p>RoleGuardService.ts</p>

<pre class="lang-js prettyprint-override"><code>    canActivate(): Observable<boolean> {
      return this.auth.getTokenSilently$().pipe(
        first(),
        map((token) => {
          console.info(token);
          // apply here your code to get the permission
          return true;
         })
       )
     }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get the access token

Body:
I need to get the token and it returns a lot of information

getTokenSilently$(options?): Observable<string> {
        return this.auth0Client$.pipe(
          concatMap((client: Auth0Client) => from(client.getTokenSilently(options)))
        );
      }

    const token =  auth.getTokenSilently$()

https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api

Body:
You have to subscribe to the observable in order to get the token because getTokenSilenty$ method is an observable.

Use

AuthService.ts

    getTokenSilently$(options?): Observable<string> {
        return this.auth0Client$.pipe(
          concatMap((client: Auth0Client) => from(client.getTokenSilently(options)))
      );
    }

RoleGuardService.ts

    canActivate(): Observable<boolean> {
      return this.auth.getTokenSilently$().pipe(
        first(),
        map((token) => {
          console.info(token);
          // apply here your code to get the permission
          return true;
         })
       )
     }


问:
GKE cluster - can I direct traffic from global http load balancer to nginx ingress controller
I'm using GKE and I installed nginx ingress controller on the cluster. GCP created automatically a TCP load balancer to redirect the request from the external ephemeral IP to my cluster nodes (nginx).

I have another a web application deployed on a VM, and I'd like to balance the incoming requests by subdomain between VM and gke cluster. In order to do that I created a global load balancer with 2 backends and the host and path rules.

I configured DNS record A to point the Global load balancer.

I can reach the VM from my domain but I cannot reach the ingresses installed on GKE.

I tried to configure the gke-backend as instance group (node pool) and as Internet network endpoint group pointing to TCP load balancer. But without success :-(

How can I balance between a VM and GKE cluster in GCP?

答:
I suggest you to check logs on your global LB to see what happened to the packets whose destination was your GKE cluster, for more information see this. If possible, share any errors or warnings.

This way we could have a better picture of what's happening.


问:
How i can count the instance of ckeditor exist on webpage in javascript?
How i can count the instance of ckeditor exist on webpage in javascript ? can anyone show me sample code for that ?</p>

答:
```<code>function getNumberOfInstances(){
    var x = 0; // x is the number of instances
    for(var instances in CKEDITOR.instances){
        x ++;
    }
    return x;
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Proper JSON serialization in MVC 4
I'd like to have JSON 'properly' serialized (camelCase), and the ability to change date formats if necessary.

For Web API it is very easy - in the Global.asax I execute the following code

```<code>var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
</code>```

This code, at the pipeline level, handles serialization the way I'd like.

I would like to accomplish the same thing in MVC 4 - have any JSON returned from controller action methods to be serialized properly.  With a little searching I found the following code to throw in the Global.asax application startup:

```<code>HttpConfiguration config = GlobalConfiguration.Configuration;
Int32 index = config.Formatters.IndexOf(config.Formatters.JsonFormatter);
config.Formatters[index] = new JsonMediaTypeFormatter
{
     SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
};
</code>```

It seems to execute fine but when I return JSON from a controller it is all PascalCased.  A simple example of my action method:

```<code>private JsonResult GetJsonTest()
{
    var returnData = dataLayer.GetSomeObject();
    return Json(returnData, JsonRequestBehavior.AllowGet);
}
</code>```

Am I going about this wrong? Any idea how to accomplish this at the pipeline level?

答:
You can create a static method to return a ContentResult that utilizes the NewtonSoft.Json library to do the serialization similar to this:

public static ContentResult CamelJson<TData>(TData response)
{
    DefaultContractResolver resolver = new CamelCasePropertyNamesContractResolver();
    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        ContractResolver = resolver,
        DateFormatHandling = DateFormatHandling.IsoDateFormat
    };
    return new ContentResult
    {
        Content = JsonConvert.SerializeObject(response, settings),
        ContentType = "application/json"
    };
}
```

<p>Example usage:</p>

<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public ContentResult GetCamelCaseJsonData()
{
  return ContentUtils.CamelJson(result);
}
</code>```

The output will be camel-case.

Title: Proper JSON serialization in MVC 4

Body:
I'd like to have JSON 'properly' serialized (camelCase), and the ability to change date formats if necessary.

For Web API it is very easy - in the Global.asax I execute the following code

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

This code, at the pipeline level, handles serialization the way I'd like.

I would like to accomplish the same thing in MVC 4 - have any JSON returned from controller action methods to be serialized properly.  With a little searching I found the following code to throw in the Global.asax application startup:

HttpConfiguration config = GlobalConfiguration.Configuration;
Int32 index = config.Formatters.IndexOf(config.Formatters.JsonFormatter);
config.Formatters[index] = new JsonMediaTypeFormatter
{
     SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
};

It seems to execute fine but when I return JSON from a controller it is all PascalCased.  A simple example of my action method:

private JsonResult GetJsonTest()
{
    var returnData = dataLayer.GetSomeObject();
    return Json(returnData, JsonRequestBehavior.AllowGet);
}

Am I going about this wrong? Any idea how to accomplish this at the pipeline level?

Body:
You can create a static method to return a ContentResult that utilizes the NewtonSoft.Json library to do the serialization similar to this:

public static ContentResult CamelJson<TData>(TData response)
{
    DefaultContractResolver resolver = new CamelCasePropertyNamesContractResolver();
    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        ContractResolver = resolver,
        DateFormatHandling = DateFormatHandling.IsoDateFormat
    };
    return new ContentResult
    {
        Content = JsonConvert.SerializeObject(response, settings),
        ContentType = "application/json"
    };
}

Example usage:

[HttpGet]
public ContentResult GetCamelCaseJsonData()
{
  return ContentUtils.CamelJson(result);
}

The output will be camel-case.


问:
Python, how to import datasets with vertically stacked columns headers, @relation,@attribute,@data?
I'm trying to load a dataset from timeseriesclassification.com, but the datasets are formatted in a way that I've never seen before.

The .csv file looks as follows,

```<code>@relation Wine
@attribute att0 numeric
@attribute att1 numeric
@attribute target {1    2}
@data
0,1,1
0,0,0
1,0,0
</code>```

This is how the data should be formatted.

```<code>att0,att1,target
0,1,1
0,0,0
1,0,0
</code>```

This is my current strategy:

read the file with file('filename.csv)

count the number of rows until @data appears

remove all the headers, and import the data with pandas

add new column names

Does anyone know what type of formatting this dataset is in? Also could anyone point me to a resource where I can reference different dataset formats.

答: That format is a .arff (Attribute-Relation File format) file. You can read it with the scipy.io.arff python module.</p>

Body:
I'm trying to load a dataset from timeseriesclassification.com, but the datasets are formatted in a way that I've never seen before.

The .csv file looks as follows,

@relation Wine
@attribute att0 numeric
@attribute att1 numeric
@attribute target {1    2}
@data
0,1,1
0,0,0
1,0,0

This is how the data should be formatted.

att0,att1,target
0,1,1
0,0,0
1,0,0

This is my current strategy:

read the file with file('filename.csv)

count the number of rows until @data appears

remove all the headers, and import the data with pandas

add new column names

Does anyone know what type of formatting this dataset is in? Also could anyone point me to a resource where I can reference different dataset formats.


问:
Extract residuals from models fit in purrr
I grouped my data and fit a model to each group and I would like to have the residuals for each group. I can see the residuals for each model with RStudio's viewer, but I cannot figure out how to extract them. Extracting one set of residuals can be done like diamond_mods[[3]][[1]][["residuals"]], but how do I use purrr to extract the set from every group (along with broom to end up with a nice tibble)?

Below is how far I've gotten:

```<code>library(tidyverse)
library(purrr)
library(broom)

fit_mod <- function(df) {
  lm(price ~ poly(carat, 2, raw = TRUE), data = df)
}

diamond_mods <- diamonds %>%
  group_by(cut) %>%
  nest() %>%
  mutate(
    model = map(data, fit_mod),
    tidied = map(model, tidy)
    #resid = map_dbl(model, "residuals") #this was my best try, it doesn't work
  ) %>%
  unnest(tidied)
</code>```

答:
You were close - but you should use map() instead of map_dbl() as you need to return a list not a vector.

```<code>diamond_mods <- diamonds %>%
  group_by(cut) %>%
  nest() %>%
  mutate(
    model = map(data, fit_mod),
    tidied = map(model, tidy),
    resid = map(model, residuals)
  )
</code>```

Body:
I grouped my data and fit a model to each group and I would like to have the residuals for each group. I can see the residuals for each model with RStudio's viewer, but I cannot figure out how to extract them. Extracting one set of residuals can be done like diamond_mods[[3]][[1]][["residuals"]], but how do I use purrr to extract the set from every group (along with broom to end up with a nice tibble)?

Below is how far I've gotten:

library(tidyverse)
library(purrr)
library(broom)

fit_mod <- function(df) {
  lm(price ~ poly(carat, 2, raw = TRUE), data = df)
}

diamond_mods <- diamonds %>%
  group_by(cut) %>%
  nest() %>%
  mutate(
    model = map(data, fit_mod),
    tidied = map(model, tidy)
    #resid = map_dbl(model, "residuals") #this was my best try, it doesn't work
  ) %>%
  unnest(tidied)

Body:
You were close - but you should use map() instead of map_dbl() as you need to return a list not a vector.

diamond_mods <- diamonds %>%
  group_by(cut) %>%
  nest() %>%
  mutate(
    model = map(data, fit_mod),
    tidied = map(model, tidy),
    resid = map(model, residuals)
  )


问:
How to connect single.c/.h files to cmake project?
So, I'm new to cmake and have some troubles. I have simple cmake project that contains a few .h and .c files. I've searched C code at github which consists of only one .h and one .c files. And i want to use some functions from this pack, but i don't want to put this file in my project directory. I want to keep them somewhere outside the project directory. So, how to connect them to project, how to make header visible for project and use #include "name.h" for watching and
and using available C functions .c/.h pack in my project.</p>

答: Create some other directory in your project, such as misc/ and put the files there. Then use it in your code via "/misc/name.h"</p>


问:
How can I create a string from just the first line of my UITextView?
I am making a UITextView which is similar to notes.app, where the first line of the textView is used as the title. I need to create a new string which contains only the first line of text. So far I've come up with this:

```<code>NSRange startRange = NSMakeRange(0, 1);
NSRange titleRange = [noteTextView.text lineRangeForRange:startRange];
NSString *titleString = [noteTextView.text substringToIndex:titleRange.length];
NSLog(@"The title is: %@", titleString);
</code>```

The only problem with this is that it relies on the user pressing Return. I've also tried using a loop to find the number of characters in the first line:

```<code>CGSize lineSize = [noteTextView.text sizeWithFont:noteTextView.font
                                constrainedToSize:noteTextView.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];
int textLength =1;

while ((lineSize.width < noteTextView.frame.size.width) &&
       ([[noteTextView.text substringToIndex:textLength] length] < [noteTextView.text length]))
{
    lineSize = [[noteTextView.text substringToIndex:textLength] sizeWithFont:noteTextView.font
                                                           constrainedToSize:noteTextView.frame.size
                                                               lineBreakMode:UILineBreakModeWordWrap];
    textLength = textLength+1;
}

NSLog(@"Length is %i", textLength);
</code>```

But I've got this wrong somewhere - it returns the total number of characters, instead of the number on the first line.

Does anyone know an easier/better way of doing this?

答:
I do not understand the code you're having above. Wouldn't it be simpler do just find the first line of text in the string, e.g. until a CR or LF terminates the first line?
And if there is no CR or LF, then you take the entire text as you have only one line then.

Of course, this will give you not what is visible in the first line in case the line is longer and gets wrapped, but I think that using lineRangeForRange doesn't do this, either, or does it?

And if your only concern is that "the user has to press enter" to make it work, then why not simply append a newline char to the text before testing for the first line's length?

Body:
I am making a UITextView which is similar to notes.app, where the first line of the textView is used as the title. I need to create a new string which contains only the first line of text. So far I've come up with this:

NSRange startRange = NSMakeRange(0, 1);
NSRange titleRange = [noteTextView.text lineRangeForRange:startRange];
NSString *titleString = [noteTextView.text substringToIndex:titleRange.length];
NSLog(@"The title is: %@", titleString);

The only problem with this is that it relies on the user pressing Return. I've also tried using a loop to find the number of characters in the first line:

CGSize lineSize = [noteTextView.text sizeWithFont:noteTextView.font
                                constrainedToSize:noteTextView.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];
int textLength =1;

while ((lineSize.width < noteTextView.frame.size.width) &&
       ([[noteTextView.text substringToIndex:textLength] length] < [noteTextView.text length]))
{
    lineSize = [[noteTextView.text substringToIndex:textLength] sizeWithFont:noteTextView.font
                                                           constrainedToSize:noteTextView.frame.size
                                                               lineBreakMode:UILineBreakModeWordWrap];
    textLength = textLength+1;
}

NSLog(@"Length is %i", textLength);

But I've got this wrong somewhere - it returns the total number of characters, instead of the number on the first line.

Does anyone know an easier/better way of doing this?


问:
Replace pattern with value
How can I replace the $SV### value in this string example if I don't know what the numbers following will be?  Or even just get the 1234544 into another string variable.

I tried this but it doesn't replace anything:

```<code>      declare @string varchar(100) = 'F4 Obstructed reach beyond.  [$SV1234544" provided.]'
      SELECT REPLACE(@string,PATINDEX('%$SV[0-9+]%',@string),'test')
</code>```

Thank you!

答:
The below code will work with the expectation that the number will always be prefixed with "$SV". It goes through a series of iterations to locate the numeric value after "$SV" and then replaces the "$SV" and the numeric number with whatever text you want it replaced with. This code uses the substring, patindex, concat, and replace functions.</p>

```<code>DECLARE @string varchar(100) = 'F4 Obstructed reach beyond.  [$SV1234544" provided.]'
DECLARE @SubString Varchar(100) = SUBSTRING(@string, PATINDEX('%$SV[0-9]%', @string), LEN(@string))
SELECT REPLACE(@string,CONCAT('$SV',LEFT(SUBSTRING(@SubString, PATINDEX('%[0-9.-]%', @SubString), 8000),PATINDEX('%[^0-9.-]%', SUBSTRING(@SubString, PATINDEX('%[0-9.-]%', @SubString), 8000) + 'X') -1)),'test')
</code>```

Title: Replace pattern with value

Body:
How can I replace the $SV### value in this string example if I don't know what the numbers following will be?  Or even just get the 1234544 into another string variable.

I tried this but it doesn't replace anything:

      declare @string varchar(100) = 'F4 Obstructed reach beyond.  [$SV1234544" provided.]'
      SELECT REPLACE(@string,PATINDEX('%$SV[0-9+]%',@string),'test')

Thank you!

Body:
The below code will work with the expectation that the number will always be prefixed with "$SV". It goes through a series of iterations to locate the numeric value after "$SV" and then replaces the "$SV" and the numeric number with whatever text you want it replaced with. This code uses the substring, patindex, concat, and replace functions.

DECLARE @string varchar(100) = 'F4 Obstructed reach beyond.  [$SV1234544" provided.]'
DECLARE @SubString Varchar(100) = SUBSTRING(@string, PATINDEX('%$SV[0-9]%', @string), LEN(@string))
SELECT REPLACE(@string,CONCAT('$SV',LEFT(SUBSTRING(@SubString, PATINDEX('%[0-9.-]%', @SubString), 8000),PATINDEX('%[^0-9.-]%', SUBSTRING(@SubString, PATINDEX('%[0-9.-]%', @SubString), 8000) + 'X') -1)),'test')


问:
CSS: How to center the snackbar horizontally?
I am using a simple snackbar code from w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar). It works OK but for long message it starts to move off the horizontal center, for example.

```<code><div id="snackbar">Some very very very very very very long text some message..</div>
</code>```

I try to fix it by removing "margin-left" and also "left", and only setting "margin: 0 auto" but it doesn't work.

答:
In that example, the snackbar is positioned fixed at 50% and re-positioned with a negative margin of 125px - and that's the problem. Those 125px are a so called 'magical number', i.e. a number that only works in special circumstances. In this case, it only works for a special width of the snackbar. It fails in any other width. Bad! ;)

It would be better to position (as it is done in the example) at 50%, but then (other than in the example) re-position it by half of its own width. You can do so with

```<code>transform: translateX(-50%);
</code>```

Those 50% refer to the width of the snackbox itself.

EDIT: Wooops, Lazar Delic was way faster! :)

Body:
I am using a simple snackbar code from w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar). It works OK but for long message it starts to move off the horizontal center, for example.

Some very very very very very very long text some message..

I try to fix it by removing "margin-left" and also "left", and only setting "margin: 0 auto" but it doesn't work.

Body:
In that example, the snackbar is positioned fixed at 50% and re-positioned with a negative margin of 125px - and that's the problem. Those 125px are a so called 'magical number', i.e. a number that only works in special circumstances. In this case, it only works for a special width of the snackbar. It fails in any other width. Bad! ;)

It would be better to position (as it is done in the example) at 50%, but then (other than in the example) re-position it by half of its own width. You can do so with

transform: translateX(-50%);

Those 50% refer to the width of the snackbox itself.

EDIT: Wooops, Lazar Delic was way faster! :)


问:
How can I export my tests results from docker container to a directory on the host machine
I run some tests inside a docker container, at the end, test reports get generated in a directory called 'allure_test_results' and I would like those report to be available on the host machine.

1.Command in a bash file that I run as an entrypoint in a docker file:

behave -f allure_behave.formatter:AllureFormatter -o allure_test_results service/features/

2.The docker image will also be ran in Jenkins CI and I would like the same thing to happen.

3.Solutions I tried (container is not running):

docker cp <container ID>:/allure_test_results/ allure_test_results/

docker run <image id> cp /allure_test_results/:/<repo root>/allure_test_results/

PS. It would be great if the copy can be done inside dockerfile or docker-compose

I would really appreciate any help.
Thank you guys so much

答:
Check this docker container:

https://github.com/fescobar/allure-docker-service

https://github.com/fescobar/allure-docker-service/tree/master/allure-docker-python-behave-example


问:
Use Azure data sync with localdb
B"H

How can I use Azure Data Sync with localdb?

Please note: I am not asking about using it with a "Local Database" as in an on-prem database. I am speaking specifically about the technology (particular Sql Server Edition) known as localdb. As in (localdb)\MSSQLLocalDB.

The issue is adding the localdb instance to SQL Data Sync Agent. The agent must be run under an entity (windows login) that has permission to run as a service. It can not be run using a windows live identity which is what the users are usually logged in as. Yet it also needs to have permissions to the database in localdb.

Use Case:

I have a central database running in Azure. With multiple users with laptops and limited internet connection, running local apps (some built in Access). Connecting directly from the apps to Azure is too slow or otherwise impractical. Therefore I install the lightweight localdb as a cache for the users data. Which will be merged using Azure Data Sync.

I am currently using a solution built directly on Microsoft Sync Framework. However there is a maintenance overhead on that solution. So I would like to migrate to the Microsoft maintained Azure Data Sync.

Thank you

答:
B"H

Ok, it was actually a silly mistake.

You actually can run the SQL Data Sync Agent using a windows live identity. You just need to use the local user name. Which is the name of the folder for that user in the Users folder. You must also use the name of the computer in the format MyComputer\localUserName.
Once I was running the SQL Data Sync Agent under the currently logged in user - who also has access to the DB - everything else ran smoothly.

Title: Use Azure data sync with localdb


问:
SwiftUI: Remove 'Focus Ring' Highlight Border from macOS TextField
I used the below code to create a custom search bar in SwiftUI. It works great on iOS / Catalyst:

...but when running natively on macOS, the 'focus ring' highlighted border styling (when the user selects the text field) rather ruins the effect:

Using .textFieldStyle(PlainTextFieldStyle()) has removed most of the default styling from the underlying field (which I believe is an NSTextField), but not the focus ring.

Is there a way to remove this too? I tried creating a custom TextFieldStyle and applying that, but couldn't find any modifier to style that border.

```<code>public struct SearchTextView: View {

    @Binding var searchText: String

    #if !os(macOS)
    private let backgroundColor = Color(UIColor.secondarySystemBackground)
    #else
    private let backgroundColor = Color(NSColor.controlBackgroundColor)
    #endif

    public var body: some View {

        HStack {

            Spacer()

            #if !os(macOS)
            Image(systemName: "magnifyingglass")
            #else
            Image("icons.general.magnifyingGlass")
            #endif

            TextField("Search", text: self.$searchText)
                .textFieldStyle(PlainTextFieldStyle())
                .foregroundColor(.primary)
                .padding(8)

            Spacer()
        }
        .foregroundColor(.secondary)
        .background(backgroundColor)
        .cornerRadius(12)
        .padding()
    }

    public init(searchText: Binding<String>) {
        self._searchText = searchText
    }
}
</code>```

答:
As stated in an answer by Asperi to a similar question here, it's not (yet) possible to turn off the focus ring for a specific field using SwiftUI; however, the following workaround will disable the focus ring for all NSTextField instances in the app:

```<code>extension NSTextField {
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}
</code>```

If you want to replace this with your own custom focus ring within the view, the onEditingChanged parameter can help you achieve this (see below example); however, it's unfortunately called on macOS when the user types the first letter, not when they first click on the field (which isn't ideal).

In theory, you could use the onFocusChange closure in the focusable modifier instead, but that doesn't appear to get called for these macOS text fields currently (as of macOS 10.15.3).

```<code>public struct SearchTextView: View {

    @Binding var searchText: String

    @State private var hasFocus = false

    #if !os(macOS)
    private var backgroundColor = Color(UIColor.secondarySystemBackground)
    #else
    private var backgroundColor = Color(NSColor.controlBackgroundColor)
    #endif

    public var body: some View {

        HStack {

            Spacer()

            #if !os(macOS)
            Image(systemName: "magnifyingglass")
            #else
            Image("icons.general.magnifyingGlass")
            #endif

            TextField("Search", text: self.$searchText, onEditingChanged: { currentlyEditing in
                self.hasFocus = currentlyEditing // If the editing state has changed to be currently edited, update the view's state
            })
                .textFieldStyle(PlainTextFieldStyle())
                .foregroundColor(.primary)
                .padding(8)

            Spacer()
        }
        .foregroundColor(.secondary)
        .background(backgroundColor)
        .cornerRadius(12)
        .border(self.hasFocus ? Color.accentColor : Color.clear, width: self.hasFocus ? 3 : 0)
        .padding()
    }

    public init(searchText: Binding<String>) {
        self._searchText = searchText
    }
}
</code>```

Body:
I used the below code to create a custom search bar in SwiftUI. It works great on iOS / Catalyst:

...but when running natively on macOS, the 'focus ring' highlighted border styling (when the user selects the text field) rather ruins the effect:

Using .textFieldStyle(PlainTextFieldStyle()) has removed most of the default styling from the underlying field (which I believe is an NSTextField), but not the focus ring.

Is there a way to remove this too? I tried creating a custom TextFieldStyle and applying that, but couldn't find any modifier to style that border.

public struct SearchTextView: View {

    @Binding var searchText: String

    #if !os(macOS)
    private let backgroundColor = Color(UIColor.secondarySystemBackground)
    #else
    private let backgroundColor = Color(NSColor.controlBackgroundColor)
    #endif

    public var body: some View {

        HStack {

            Spacer()

            #if !os(macOS)
            Image(systemName: "magnifyingglass")
            #else
            Image("icons.general.magnifyingGlass")
            #endif

            TextField("Search", text: self.$searchText)
                .textFieldStyle(PlainTextFieldStyle())
                .foregroundColor(.primary)
                .padding(8)

            Spacer()
        }
        .foregroundColor(.secondary)
        .background(backgroundColor)
        .cornerRadius(12)
        .padding()
    }

    public init(searchText: Binding<String>) {
        self._searchText = searchText
    }
}

Body:
As stated in an answer by Asperi to a similar question here, it's not (yet) possible to turn off the focus ring for a specific field using SwiftUI; however, the following workaround will disable the focus ring for all NSTextField instances in the app:

extension NSTextField {
    open override var focusRingType: NSFocusRingType {
        get { .none }
        set { }
    }
}

If you want to replace this with your own custom focus ring within the view, the onEditingChanged parameter can help you achieve this (see below example); however, it's unfortunately called on macOS when the user types the first letter, not when they first click on the field (which isn't ideal).

In theory, you could use the onFocusChange closure in the focusable modifier instead, but that doesn't appear to get called for these macOS text fields currently (as of macOS 10.15.3).

public struct SearchTextView: View {

    @Binding var searchText: String

    @State private var hasFocus = false

    #if !os(macOS)
    private var backgroundColor = Color(UIColor.secondarySystemBackground)
    #else
    private var backgroundColor = Color(NSColor.controlBackgroundColor)
    #endif

    public var body: some View {

        HStack {

            Spacer()

            #if !os(macOS)
            Image(systemName: "magnifyingglass")
            #else
            Image("icons.general.magnifyingGlass")
            #endif

            TextField("Search", text: self.$searchText, onEditingChanged: { currentlyEditing in
                self.hasFocus = currentlyEditing // If the editing state has changed to be currently edited, update the view's state
            })
                .textFieldStyle(PlainTextFieldStyle())
                .foregroundColor(.primary)
                .padding(8)

            Spacer()
        }
        .foregroundColor(.secondary)
        .background(backgroundColor)
        .cornerRadius(12)
        .border(self.hasFocus ? Color.accentColor : Color.clear, width: self.hasFocus ? 3 : 0)
        .padding()
    }

    public init(searchText: Binding<String>) {
        self._searchText = searchText
    }
}


问:
JFileChooser select directory but show files
I feel like there should be a simple way to do this but I can't figure it out. I have a JFileChooser that allows the user to select directories. I want to show all the files in the directories to give the user some context, but only directories should be accepted as selections (maybe the Open button would be disabled when a file is selected). Is there an easy way of doing this?</p>

答:
The JFileChooser supports three selection modes: files only, directories only, and files and directories. In your case what you need is :

```<code>JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
</code>```

source : http://www.java2s.com/Tutorial/Java/0240__Swing/TheJFileChoosersupportsthreeselectionmodesfilesonlydirectoriesonlyandfilesanddirectories.htm

ContentLicense: CC BY-SA 2.5

Body:
The JFileChooser supports three selection modes: files only, directories only, and files and directories. In your case what you need is :

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

source : http://www.java2s.com/Tutorial/Java/0240__Swing/TheJFileChoosersupportsthreeselectionmodesfilesonlydirectoriesonlyandfilesanddirectories.htm


问:
How to make horizontal scrollview in kivy
i've been trying to make a horizontal scrollview but it won't work for two or more widget...instead it will automatically convert them( the widget) to a kind of an ASCII characters

main.py

```<code>#...neccessary modules imported

class Root( BoxLayout ):
    pass

class MainApp( MDApp ):
    pass

if __name__ == "__main__":
    MainApp().run()
</code>```

then inside the main.kv file, i got

```<code>Root
<Root>:
    orientation:"vertical"

    ScrollView:
       do_scroll_x: True
       do_scroll_y: False

       BoxLayout:
          size_hint:None, None
          width:self.minimum_width
          spacing:dp(20)

          # Then follows repetition of the below widget 20 times
          MDCard:
            MDLabel:
              text:"some text"
</code>```

it wont show the widget but some random Ascii characters

答:
You have to give some size to the contents of the BoxLayout:

            # Then follows repetition of the below widget 20 times
            MDCard:
                size_hint:None, None
                size: dp(100), dp(50)
                MDLabel:
                    text:"some text"
```

Body:
i've been trying to make a horizontal scrollview but it won't work for two or more widget...instead it will automatically convert them( the widget) to a kind of an ASCII characters

main.py

#...neccessary modules imported

class Root( BoxLayout ):
    pass

class MainApp( MDApp ):
    pass

if __name__ == "__main__":
    MainApp().run()

then inside the main.kv file, i got

Root
<Root>:
    orientation:"vertical"

    ScrollView:
       do_scroll_x: True
       do_scroll_y: False

       BoxLayout:
          size_hint:None, None
          width:self.minimum_width
          spacing:dp(20)

          # Then follows repetition of the below widget 20 times
          MDCard:
            MDLabel:
              text:"some text"

it wont show the widget but some random Ascii characters


问:
Subprocess with a variable that contains a whitespace (path)
Just started Python again and now I'm already stuck on the following...

I'm trying to use subprocess.Popen with a variable with a whitespace in it (a Windows path).

Doing a print on the variable the variable seems to work fine. But when using the variable in subprocess.Popen, the variable is cut off by the first whitespace.

Below a part of the script (the variable 'image_file' contains the Windows Path(s) with spaces)

```<code>def start_phone(image_file):
    cmd = tar_exe + " -tf "+ image_file
    print (cmd)
    subprocess.Popen(cmd, shell=True)
</code>```

How can I use subprocess with a variable with whitespaces (path) in it?

答:
If you take a look at the subprocess documentation you'll see that arguments must be provided to subprocess commands in the form of a list, so your code sample should look like</p>

```<code>def start_phone(image_file):
    subprocess.Popen([tar_exe, "-tf", image_file])
</code>```

Body:
Just started Python again and now I'm already stuck on the following...

I'm trying to use subprocess.Popen with a variable with a whitespace in it (a Windows path).

Doing a print on the variable the variable seems to work fine. But when using the variable in subprocess.Popen, the variable is cut off by the first whitespace.

Below a part of the script (the variable 'image_file' contains the Windows Path(s) with spaces)

def start_phone(image_file):
    cmd = tar_exe + " -tf "+ image_file
    print (cmd)
    subprocess.Popen(cmd, shell=True)

How can I use subprocess with a variable with whitespaces (path) in it?

Body:
If you take a look at the subprocess documentation you'll see that arguments must be provided to subprocess commands in the form of a list, so your code sample should look like

def start_phone(image_file):
    subprocess.Popen([tar_exe, "-tf", image_file])


问:
Efficiently removing duplicates from a list
Good evening. I have an excel file with zip codes and associated information. Those zip codes have a lot of duplicates. I'd like to figure out which zip codes I have by putting them all in a list without duplicates. This code works, but runs very slowly (took over 100 seconds), and was wondering what I could do to improve the efficiency of it.

I know that having to check the whole list for duplicates each time is contributing a lot to the inefficiency, but I'm not sure how to fix that. I also know that going through every row is probably not the best answer, but again I am pretty new and am now stuck.

Thanks in advance.

```<code>import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    for i in range(sheet.nrows):
        if str(sheet.cell(i,0).value) in zipsInSheet:
            pass
        else:
            zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()
</code>```

答:
If you're looking to avoid duplicates then you should definitely consider using Sets in python. See here

What I would do is to create a set and simply add all your elements to a set; note that, a set is an unordered, unique collection of items. Once all data has been added you can then just add all elements in the set  it to your sheet. This, therefore, avoids redundant data.

```<code>

import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    data = set()

    for i in range(sheet.nrows):
      data.add(str(sheet.cell(i,0).value)

    #now add all elements in the set to your sheet
    for i in range(len(data)):
      zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()
</code>```

Body:
Good evening. I have an excel file with zip codes and associated information. Those zip codes have a lot of duplicates. I'd like to figure out which zip codes I have by putting them all in a list without duplicates. This code works, but runs very slowly (took over 100 seconds), and was wondering what I could do to improve the efficiency of it.

I know that having to check the whole list for duplicates each time is contributing a lot to the inefficiency, but I'm not sure how to fix that. I also know that going through every row is probably not the best answer, but again I am pretty new and am now stuck.

Thanks in advance.

import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    for i in range(sheet.nrows):
        if str(sheet.cell(i,0).value) in zipsInSheet:
            pass
        else:
            zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()

Body:
If you're looking to avoid duplicates then you should definitely consider using Sets in python. See here

What I would do is to create a set and simply add all your elements to a set; note that, a set is an unordered, unique collection of items. Once all data has been added you can then just add all elements in the set  it to your sheet. This, therefore, avoids redundant data.

import sys
import xlrd

loc = ("locationOfFile")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

def findUniqueZips():
    zipsInSheet = []
    data = set()

    for i in range(sheet.nrows):
      data.add(str(sheet.cell(i,0).value)

    #now add all elements in the set to your sheet
    for i in range(len(data)):
      zipsInSheet.append(str(sheet.cell(i,0).value))
    print(zipsInSheet)

findUniqueZips()


答:
You can either put double quotes around each argument with potential white spaces in it:

```<code>cmd = f'"{tar_exe}" -tf "{image_file}"'
subprocess.Popen(cmd, shell=True)
</code>```

or don't use shell=True and instead put arguments in a list:

```<code>subprocess.Popen([tar_exe, '-tf', image_file])
</code>```

Title: Subprocess with a variable that contains a whitespace (path)

Body:
You can either put double quotes around each argument with potential white spaces in it:

cmd = f'"{tar_exe}" -tf "{image_file}"'
subprocess.Popen(cmd, shell=True)

or don't use shell=True and instead put arguments in a list:

subprocess.Popen([tar_exe, '-tf', image_file])


问:
TXT file can be downloaded using stream on Heroku but fails for PDF files - NodeJS, Heroku
I am unable to download pdf file and view it on Heroku using "heroku run bash". but same code does work for txt file on heroku. Whereas, this same code works for txt and pdf files in local machine.

I have git clone Heroku Nodejs git repository (git clone https://github.com/heroku/node-js-getting-started.git) found here (https://devcenter.heroku.com/articles/getting-started-with-nodejs) and pushed the app to the Heroku.

added fs and https libraries to nodejs project.

```<code>const express = require('express')
const path = require('path')
var fs = require('fs');
const https = require('https');

const AWS = require('aws-sdk');

AWS.config.loadFromPath('./config.json');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const URL = "<YOUR_URL>";

const PORT = process.env.PORT || 5000

express()
  .use(express.static(path.join(__dirname, 'public')))
  .set('views', path.join(__dirname, 'views'))
  .set('view engine', 'ejs')
  .get('/', (req, res) => res.render('pages/index'))
  .get('/test', function(req,res) {

    const file = fs.createWriteStream("XXXXXX-pdf.pdf");
    https.get("XXXXX-pdf.pdf", response => {
      var stream = response.pipe(file);

      stream.on("finish", function() {
        console.log("done");

        try{

            // Create params for putObject call
            const objectParams = {
                Bucket: "<YOUR_BUCKET>",
                Key: "<YOUR_KEY>",
                ContentLength: headers['content-length'],
                Body: stream
            };
            // Create object upload promise
            await s3.putObject(objectParams).promise();
        } catch(err){
            console.log("ERROR --->" + err)
        }
      });
    });
  })
  .listen(PORT, () => console.log(`Listening on ${ PORT }`))
</code>```

答:
"heroku run bash" does not reliably see the file that was just uploaded because there is no guarantee it is running on the same heroku dyno.

Files on heroku are temporary, they only last as long as the dyno is active and you get a limited amount of space for them too. However, you can count on them to exist in the dyno that created them long enough to finish handling a web request.

So the correct solution is to download the file, then upload it directly to a durable storage service like Amazon S3. Although the official AWS SDK for Node.js does not provide a streaming API for uploads, this is fine because you can ask the API to upload the file you just downloaded, all before you respond to the original web request, which you must do in order to terminate it properly and avoid potential socket exhaustion in your Node.js application.

Body:
I am unable to download pdf file and view it on Heroku using "heroku run bash". but same code does work for txt file on heroku. Whereas, this same code works for txt and pdf files in local machine.

I have git clone Heroku Nodejs git repository (git clone https://github.com/heroku/node-js-getting-started.git) found here (https://devcenter.heroku.com/articles/getting-started-with-nodejs) and pushed the app to the Heroku.

added fs and https libraries to nodejs project.

const express = require('express')
const path = require('path')
var fs = require('fs');
const https = require('https');

const AWS = require('aws-sdk');

AWS.config.loadFromPath('./config.json');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const URL = "<YOUR_URL>";

const PORT = process.env.PORT || 5000

express()
  .use(express.static(path.join(__dirname, 'public')))
  .set('views', path.join(__dirname, 'views'))
  .set('view engine', 'ejs')
  .get('/', (req, res) => res.render('pages/index'))
  .get('/test', function(req,res) {

    const file = fs.createWriteStream("XXXXXX-pdf.pdf");
    https.get("XXXXX-pdf.pdf", response => {
      var stream = response.pipe(file);

      stream.on("finish", function() {
        console.log("done");

        try{

            // Create params for putObject call
            const objectParams = {
                Bucket: "<YOUR_BUCKET>",
                Key: "<YOUR_KEY>",
                ContentLength: headers['content-length'],
                Body: stream
            };
            // Create object upload promise
            await s3.putObject(objectParams).promise();
        } catch(err){
            console.log("ERROR --->" + err)
        }
      });
    });
  })
  .listen(PORT, () => console.log(`Listening on ${ PORT }`))


问:
Expected results of Assertion Errors are not showing up when using Pytest and conftest.py file
I am using Pytest to test my website content.  I have a fixure in my conftest.py that creates a webdriver for other tests to reference.  When an error occurs during a test run, only AssertionError is displayed, as opposed to the actual and expected values being tested in the assert statement.

Here is my conftest.py file:

```<code>import os

import pytest
from selenium import webdriver

@pytest.fixture(scope="session")
def setup(request):
    driver_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'drivers')
    driver = webdriver.Chrome()
    session = request.node
    for item in session.items:
        cls = item.getparent(pytest.Class)
        setattr(cls.obj, "driver", driver)

    yield driver
    driver.close()
</code>```

Here is my high-level test file:

```<code>import pytest

from validations import *

@pytest.mark.usefixtures("setup")
class TestOurServices:
    def test_our_services_direct_navigation(self):
        go_to_our_services(self.driver)
        validate_our_services_content(self.driver)
</code>```

Then here is an example of the output:

答:
This post helped solve the issue:

pytest assert introspection in helper function

I had assertions in helper functions such as validate_our_services_content from above.  They were in a file called validations.py

Referencing the above issue I created an __init__.py file to declare those validations:

__init__.py

```<code>import pytest

pytest.register_assert_rewrite('validations')
</code>```

Body:
I am using Pytest to test my website content.  I have a fixure in my conftest.py that creates a webdriver for other tests to reference.  When an error occurs during a test run, only AssertionError is displayed, as opposed to the actual and expected values being tested in the assert statement.

Here is my conftest.py file:

import os

import pytest
from selenium import webdriver

@pytest.fixture(scope="session")
def setup(request):
    driver_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'drivers')
    driver = webdriver.Chrome()
    session = request.node
    for item in session.items:
        cls = item.getparent(pytest.Class)
        setattr(cls.obj, "driver", driver)

    yield driver
    driver.close()

Here is my high-level test file:

import pytest

from validations import *

@pytest.mark.usefixtures("setup")
class TestOurServices:
    def test_our_services_direct_navigation(self):
        go_to_our_services(self.driver)
        validate_our_services_content(self.driver)

Then here is an example of the output:

Body:
This post helped solve the issue:

pytest assert introspection in helper function

I had assertions in helper functions such as validate_our_services_content from above.  They were in a file called validations.py

Referencing the above issue I created an __init__.py file to declare those validations:

__init__.py

import pytest

pytest.register_assert_rewrite('validations')


问:
how to execute shell command files in python
I am having trouble executing the following shell command.  I'm in windows 10.  I had to delete the user authorization here and left it as 'tktk' as i dind't want my authorization out here like that.

```<code>curl 'https://pegasus-test.etflogic.io/portfolio/analyze' -H 'authority: pegasus-test.etflogic.io' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: application/json' -H 'authorization: tktk' -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' -H 'content-type: application/json' -H 'origin: https://akita.etflogic.com' -H 'sec-fetch-site: cross-site' -H 'sec-fetch-mode: cors' -H 'referer: https://akita.etflogic.com/portfolio-analysis' -H 'accept-encoding: gzip, deflate, br' -H 'accept-language: en-US,en;q=0.9' --data-binary '{"portfolio":{"currency":"usd","id":"8576e266-c6f4-44fe-a6a6-9c64869b55dd","name":"test1","records":[{"locale":"US","id":"df92931e-3063-4889-8e4b-100c66f14d22","name":"SSGA SPDR S&P 500 - SSgA Active Trust","secid":549535,"size":100,"ticker":"SPY US"}],"size_type":"notional","type":"primary"}}' --compressed > /tmp/jsonpayload
</code>```

I stored the above command in a test.sh file
I'm having trouble executing the above shell command.  It works on the linux terminal.  But it doesn't work on my windows cmd.  I need to read the above url, get the json object and do some analysis with it.

What i tried:

```<code>import subprocess
ans = subprocess.Popen(["bash",os.path.join(os.getcwd(), 'test.sh')])
</code>```

This fails.  ok...

I tried then...

```<code>subprocess.call(['test.sh'])
</code>```

I'm getting error '%1 is not a valid Win32 application'

答:
I copied your test.sh code into my own test.sh file, and tested a few different things.

Try using os.system for calling your command instead of methods from subprocess.

This worked for me:

```<code>import os
os.system(os.getcwd() + '/test.sh')
</code>```

If you prefer os.path.join(os.getcwd(), 'test.sh') instead of what I have here, you can use that too, there's no major difference.

I hope this solves your problem :)

Body:
I am having trouble executing the following shell command.  I'm in windows 10.  I had to delete the user authorization here and left it as 'tktk' as i dind't want my authorization out here like that.

curl 'https://pegasus-test.etflogic.io/portfolio/analyze' -H 'authority: pegasus-test.etflogic.io' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: application/json' -H 'authorization: tktk' -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' -H 'content-type: application/json' -H 'origin: https://akita.etflogic.com' -H 'sec-fetch-site: cross-site' -H 'sec-fetch-mode: cors' -H 'referer: https://akita.etflogic.com/portfolio-analysis' -H 'accept-encoding: gzip, deflate, br' -H 'accept-language: en-US,en;q=0.9' --data-binary '{"portfolio":{"currency":"usd","id":"8576e266-c6f4-44fe-a6a6-9c64869b55dd","name":"test1","records":[{"locale":"US","id":"df92931e-3063-4889-8e4b-100c66f14d22","name":"SSGA SPDR S&P 500 - SSgA Active Trust","secid":549535,"size":100,"ticker":"SPY US"}],"size_type":"notional","type":"primary"}}' --compressed > /tmp/jsonpayload

I stored the above command in a test.sh file
I'm having trouble executing the above shell command.  It works on the linux terminal.  But it doesn't work on my windows cmd.  I need to read the above url, get the json object and do some analysis with it.

What i tried:

import subprocess
ans = subprocess.Popen(["bash",os.path.join(os.getcwd(), 'test.sh')])

This fails.  ok...

I tried then...

subprocess.call(['test.sh'])

I'm getting error '%1 is not a valid Win32 application'

Body:
I copied your test.sh code into my own test.sh file, and tested a few different things.

Try using os.system for calling your command instead of methods from subprocess.

This worked for me:

import os
os.system(os.getcwd() + '/test.sh')

If you prefer os.path.join(os.getcwd(), 'test.sh') instead of what I have here, you can use that too, there's no major difference.

I hope this solves your problem :)


问:
AWS CLI - is there a way to extract tar.gz from S3 to home without storing the tar.gz?
To elaborate,

There is a tar.gz file on my AWS S3, let's call it example.tar.gz.

So, what I want to do is download the extracted contents of example.tar.gz to /var/home/.

One way to do it is to simply download the tar.gz, extract it, then delete the tar.gz.

However, I don't want to use space downloading the tar.gz file, I just want to download the extracted version or only store the extracted version.

Is this possible?

Thanks!

答: Today I tested with Python Boto 3 and aws cli and I noticed that tar.gz is extracted automatically when the file is downloaded</p>


问:
Can't upload folder to Sftp using pysftp
Not sure why this is not working, I am attempting to upload an entire directory from my local drive to the sftp but instead of uploading the folder it creates a file that looks like this ".\20200131\doc1.txt"? I have been at this for hours I think I am missing something</p>

```<code>def upload_files_to_sftp():
    localpath = r"c:\test\"
    remotepath = "/uploads/test_Unzipped"
    for root,dirs,_ in os.walk(r"c:\test"):
        for d in dirs:
            folders_to_upload = (os.path.join(root,d))
            print(folders_to_upload)
            with pysftp.Connection('mysftp', username='username', password='mypassword') as sftp:
                sftp.put_r(localpath , remotepath)
</code>```

答:
Usually an sftp server will also grant ssh access.

If you have ssh access, you could:

```<code>(cd /source/dir && tar --create --sparse --one-file-system .) | ssh example.com 'cd /target/dir && tar xfp -'
</code>```

...using cygwin tar and ssh, for example.  IOW, this can easily be reduced to a one-liner in shell.

Body:
Not sure why this is not working, I am attempting to upload an entire directory from my local drive to the sftp but instead of uploading the folder it creates a file that looks like this ".\20200131\doc1.txt"? I have been at this for hours I think I am missing something

def upload_files_to_sftp():
    localpath = r"c:\test\"
    remotepath = "/uploads/test_Unzipped"
    for root,dirs,_ in os.walk(r"c:\test"):
        for d in dirs:
            folders_to_upload = (os.path.join(root,d))
            print(folders_to_upload)
            with pysftp.Connection('mysftp', username='username', password='mypassword') as sftp:
                sftp.put_r(localpath , remotepath)

Body:
Usually an sftp server will also grant ssh access.

If you have ssh access, you could:

(cd /source/dir && tar --create --sparse --one-file-system .) | ssh example.com 'cd /target/dir && tar xfp -'

...using cygwin tar and ssh, for example.  IOW, this can easily be reduced to a one-liner in shell.


问:
Multiple streams to firebase documents without disposing
I am trying to add chatting to my app.
When my user starts a chat with a new user, I create a chatroom with a unique id in my Firebase database. I want my user to be notified with any updates of the chatroom document( eg: new messages) so when I create a chatroom, I also create a new stream to that chatroom document. Is there a problem with constantly listening to many documents with different streams without disposing the streams (because I want to get the latest results of any chatroom that user is a member of.)

This is my chatroom_screen code:

```<code>import 'package:flutter/material.dart';
import '../models/databse_management.dart';

class ChatroomScreen extends StatefulWidget {
  static const String routeName = "/chatroom_screen";
  @override
  _ChatroomScreenState createState() => _ChatroomScreenState();
}

class _ChatroomScreenState extends State<ChatroomScreen> {
  TextEditingController _messageTextEditingController = TextEditingController();
  bool isChatroomExists;
  Stream chatroomDocStream; //my initial stream variable which is null
  @override
  Widget build(BuildContext context) {
    final Map<String, dynamic> passedArguments =
        ModalRoute.of(context).settings.arguments;
    //sedner details can be retrieved from currentUserDetails
    final String senderId = passedArguments["senderId"];
    final List<String> receiversIds = passedArguments["receiverIds"];
    final String senderUsername = passedArguments["senderUsername"];
    final List<String> receiverUsernames = passedArguments["receiverUsernames"];
    final String chatroomId = passedArguments["chatroomId"];
    if(chatroomDocStream == null){
      chatroomDocStream = Firestore.instance.collection("chatrooms").document(chatroomId).snapshots(); //if no stream was created before (first time we build the widget), we connect a stream to this chatroom documentspecified with chatroomId
    }
    isChatroomExists = isChatroomExists == null

        ? passedArguments["isChatroomExists"]
        : isChatroomExists;

    final Image senderProfilePictureUrl =
        passedArguments["senderProfilePicture"];
    final List<Image> receiverProfilePictures =
        passedArguments["receiverProfilePictures"];
    final mediaQuery = MediaQuery.of(context).size;
    final ThemeData theme = Theme.of(context);

    //we get the values from the passed argument map
    if (isChatroomExists) {
      //load the previous chats
    }
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            CircleAvatar(
              backgroundImage: receiverProfilePictures[0]
                  .image, //right now only for 1 receiver but change it for multi members later
            ),
            Container(
              child: Text(receiverUsernames[0]),
              margin: const EdgeInsets.only(left: 10),
            ),
          ],
        ),
      ),
      body: //to do=> create a stream that is listening to the chatroom document for any changes
          Stack(
        children: <Widget>[
         StreamBuilder(
            //updates the chats whenever data of the chatroom document changes
            stream: chatroomDocStream,
            builder: (context, snapShot) {
              return Column(
                children: <Widget>[
                  Center(child: const Text("My chats"))
                  //message widgets go here
                ],
              );
            },
          ),
          Positioned(
            //positioned is used for positioning the widgets inside a stack. bottom: 10 means 10 pixel from bottom
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              width: mediaQuery.width, //takes the total width of the screen
              decoration: BoxDecoration(
                color: theme.primaryColor.withOpacity(0.3),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    //always takes the remaining space (textField widget use this as its size https://stackoverflow.com/questions/45986093/textfield-inside-of-row-causes-layout-exception-unable-to-calculate-size)
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal:
                              10), //horizontal padding for the textfield widget
                      decoration: BoxDecoration(
                        color: theme.accentColor,
                        borderRadius: BorderRadius.circular(25),
                        border: Border.all(width: 2, color: theme.primaryColor),
                      ),
                      child: TextField(
                        minLines: 1,
                        maxLines: 5,
                        controller: _messageTextEditingController,
                        decoration: const InputDecoration(
                            hintText: "Type something here...",
                            border: InputBorder
                                .none //removes all the border for textfield widget
                            ),
                      ),
                    ),
                  ),
                  Container(
                    child: Row(
                      //another row for buttons to be treated all toghether as a container in the parent row
                      children: <Widget>[
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () {
                            //add media like image or pictures
                          },
                        ),
                        IconButton(
                          icon: const Icon(Icons.camera_alt),
                          onPressed: () {
                            //take picture or video
                          },
                        ),
                        IconButton(
                          icon: const Icon(Icons.send),
                          onPressed: () async {
                            if (_messageTextEditingController.text
                                .trim()
                                .isEmpty) {
                              return;
                            }
                            try {
                              await DatabaseManagement().sendMessage(
                                membersIds: [
                                  senderId,
                                  ...receiversIds
                                ], //extracts all the members of the list as seperate String items
                                //to do=>later on we have to get a list of the members as well
                                isChatroomExists: isChatroomExists,
                                chatroomId: chatroomId,
                                messageContent:
                                    _messageTextEditingController.text,
                                senderId: senderId,
                                timestamp: Timestamp
                                    .now(), //it's from firebase and records the time stamp of the sending message
                              );
                              if (isChatroomExists != true) {
                                isChatroomExists =
                                    true; //after we sent a messsage, we 100% created the chatroom so it becomes true
                              }
                            } catch (e) {
                              print(
                                e.toString(),
                              );
                              return;
                            }
                          },
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

The idea is to have something like WhatsApp which you receive a notification of any updates in any chatroom you are a member of.

答:
You can create a lot of snapshot listeners, but Google recommends a limit of 100 snapshot listeners per client:

Source: https://cloud.google.com/firestore/docs/best-practices?hl=en#realtime_updates

Body:
I am trying to add chatting to my app.
When my user starts a chat with a new user, I create a chatroom with a unique id in my Firebase database. I want my user to be notified with any updates of the chatroom document( eg: new messages) so when I create a chatroom, I also create a new stream to that chatroom document. Is there a problem with constantly listening to many documents with different streams without disposing the streams (because I want to get the latest results of any chatroom that user is a member of.)

This is my chatroom_screen code:

import 'package:flutter/material.dart';
import '../models/databse_management.dart';

class ChatroomScreen extends StatefulWidget {
  static const String routeName = "/chatroom_screen";
  @override
  _ChatroomScreenState createState() => _ChatroomScreenState();
}

class _ChatroomScreenState extends State<ChatroomScreen> {
  TextEditingController _messageTextEditingController = TextEditingController();
  bool isChatroomExists;
  Stream chatroomDocStream; //my initial stream variable which is null
  @override
  Widget build(BuildContext context) {
    final Map<String, dynamic> passedArguments =
        ModalRoute.of(context).settings.arguments;
    //sedner details can be retrieved from currentUserDetails
    final String senderId = passedArguments["senderId"];
    final List<String> receiversIds = passedArguments["receiverIds"];
    final String senderUsername = passedArguments["senderUsername"];
    final List<String> receiverUsernames = passedArguments["receiverUsernames"];
    final String chatroomId = passedArguments["chatroomId"];
    if(chatroomDocStream == null){
      chatroomDocStream = Firestore.instance.collection("chatrooms").document(chatroomId).snapshots(); //if no stream was created before (first time we build the widget), we connect a stream to this chatroom documentspecified with chatroomId
    }
    isChatroomExists = isChatroomExists == null

        ? passedArguments["isChatroomExists"]
        : isChatroomExists;

    final Image senderProfilePictureUrl =
        passedArguments["senderProfilePicture"];
    final List<Image> receiverProfilePictures =
        passedArguments["receiverProfilePictures"];
    final mediaQuery = MediaQuery.of(context).size;
    final ThemeData theme = Theme.of(context);

    //we get the values from the passed argument map
    if (isChatroomExists) {
      //load the previous chats
    }
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            CircleAvatar(
              backgroundImage: receiverProfilePictures[0]
                  .image, //right now only for 1 receiver but change it for multi members later
            ),
            Container(
              child: Text(receiverUsernames[0]),
              margin: const EdgeInsets.only(left: 10),
            ),
          ],
        ),
      ),
      body: //to do=> create a stream that is listening to the chatroom document for any changes
          Stack(
        children: <Widget>[
         StreamBuilder(
            //updates the chats whenever data of the chatroom document changes
            stream: chatroomDocStream,
            builder: (context, snapShot) {
              return Column(
                children: <Widget>[
                  Center(child: const Text("My chats"))
                  //message widgets go here
                ],
              );
            },
          ),
          Positioned(
            //positioned is used for positioning the widgets inside a stack. bottom: 10 means 10 pixel from bottom
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              width: mediaQuery.width, //takes the total width of the screen
              decoration: BoxDecoration(
                color: theme.primaryColor.withOpacity(0.3),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    //always takes the remaining space (textField widget use this as its size https://stackoverflow.com/questions/45986093/textfield-inside-of-row-causes-layout-exception-unable-to-calculate-size)
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal:
                              10), //horizontal padding for the textfield widget
                      decoration: BoxDecoration(
                        color: theme.accentColor,
                        borderRadius: BorderRadius.circular(25),
                        border: Border.all(width: 2, color: theme.primaryColor),
                      ),
                      child: TextField(
                        minLines: 1,
                        maxLines: 5,
                        controller: _messageTextEditingController,
                        decoration: const InputDecoration(
                            hintText: "Type something here...",
                            border: InputBorder
                                .none //removes all the border for textfield widget
                            ),
                      ),
                    ),
                  ),
                  Container(
                    child: Row(
                      //another row for buttons to be treated all toghether as a container in the parent row
                      children: <Widget>[
                        IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () {
                            //add media like image or pictures
                          },
                        ),
                        IconButton(
                          icon: const Icon(Icons.camera_alt),
                          onPressed: () {
                            //take picture or video
                          },
                        ),
                        IconButton(
                          icon: const Icon(Icons.send),
                          onPressed: () async {
                            if (_messageTextEditingController.text
                                .trim()
                                .isEmpty) {
                              return;
                            }
                            try {
                              await DatabaseManagement().sendMessage(
                                membersIds: [
                                  senderId,
                                  ...receiversIds
                                ], //extracts all the members of the list as seperate String items
                                //to do=>later on we have to get a list of the members as well
                                isChatroomExists: isChatroomExists,
                                chatroomId: chatroomId,
                                messageContent:
                                    _messageTextEditingController.text,
                                senderId: senderId,
                                timestamp: Timestamp
                                    .now(), //it's from firebase and records the time stamp of the sending message
                              );
                              if (isChatroomExists != true) {
                                isChatroomExists =
                                    true; //after we sent a messsage, we 100% created the chatroom so it becomes true
                              }
                            } catch (e) {
                              print(
                                e.toString(),
                              );
                              return;
                            }
                          },
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

The idea is to have something like WhatsApp which you receive a notification of any updates in any chatroom you are a member of.


问:
Filter Intent based on custom data
I want to broadcast intent with custom-data and only the receiver that have this custom data should receive this intent, how this could be done ?

this how i broadcast the intent :

```<code>Intent intent = new Intent();
 intent.setAction("com.example");
 context.sendBroadcast(intent);
</code>```

and i define the broadcast receiver as following :

```<code> <receiver android:name="com.test.myReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="com.example"></action>
        </intent-filter>
    </receiver>
</code>```

答:
If you already define your broadcast receiver class, then the next step is to register it on the Activity/Service which you'd like to receive the broadcast intent. An example to register:

```<code>    IntentFilter iFilter = new IntentFilter();
    iFilter.addAction("com.example"); //add your custom intent to register
    //below is your class which extends BroadcastReceiver, contains action
    //which will be triggered when current class received the broadcast intent
    MyReceiver myReceiver = new MyReceiver();
    registerReceiver(myReceiver, iFilter); //register intent & receiver
</code>```

If you destroy the activity/service, for best practice don't forget to unregister the broadcast receiver on the same activity/service:

```<code>@Override
protected void onDestroy() {
    if(myReceiver!=null)
        unregisterReceiver(myReceiver)
    super.onDestroy();
}
</code>```

MyReceiver class:

```<code>public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context arg0, Intent intent) {
        if(intent.getAction().equals("com.example")){
            //DO SOMETHING HERE
        }
    }
}
</code>```

Title: Filter Intent based on custom data

Body:
I want to broadcast intent with custom-data and only the receiver that have this custom data should receive this intent, how this could be done ?

this how i broadcast the intent :

Intent intent = new Intent();
 intent.setAction("com.example");
 context.sendBroadcast(intent);

and i define the broadcast receiver as following :

 <receiver android:name="com.test.myReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="com.example"></action>
        </intent-filter>
    </receiver>

Body:
If you already define your broadcast receiver class, then the next step is to register it on the Activity/Service which you'd like to receive the broadcast intent. An example to register:

    IntentFilter iFilter = new IntentFilter();
    iFilter.addAction("com.example"); //add your custom intent to register
    //below is your class which extends BroadcastReceiver, contains action
    //which will be triggered when current class received the broadcast intent
    MyReceiver myReceiver = new MyReceiver();
    registerReceiver(myReceiver, iFilter); //register intent & receiver

If you destroy the activity/service, for best practice don't forget to unregister the broadcast receiver on the same activity/service:

@Override
protected void onDestroy() {
    if(myReceiver!=null)
        unregisterReceiver(myReceiver)
    super.onDestroy();
}

MyReceiver class:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context arg0, Intent intent) {
        if(intent.getAction().equals("com.example")){
            //DO SOMETHING HERE
        }
    }
}


问:
Google Cloud Storage 429 PATCH Too many requests
I'm sorry if this isn't the place to ask, desperately looking for advice.

We have a Django 2.2 project using django-storages and GCS for a long time, about an hour ago we started to receive this error constantly, apparently, there is a rate of 1 per second, per file, however only one upload is being made, also we haven't deployed new code related to this, every section of our site where user uploads file we get this error.

We don't consume directly the API, we only execute "save" on our models.

Any ideas on how can we debug this?
This is an example of a complete error:
429 PATCH https://www.googleapis.com/storage/v1/b/at_private_storage/o/dany8%2Fdocumentos%2Faaa16962-fe3e-4242-b479-12d4d4d84ea7.xml?projection=full&predefinedAcl=publicRead: The rate of change requests to the object at_private_storage/dany8/documentos/aaa16962-fe3e-4242-b479-12d4d4d84ea7.xml exceeds the rate limit. Please reduce the rate of create, update, and delete requests.

答: We updated django-storages from 1.7.1 1.9.1 and apparently problem is solved. </p>