问:
Can't JSON parse message received from Azure Service Bus in Node.js app
This is my JS code to receive a message from Azure Service Bus

```<code>function receiveMessage(serviceBusTopic, serviceBusSubscriber, callback) {
  serviceBus.receiveSubscriptionMessage(serviceBusTopic, serviceBusSubscriber,
{ isPeekLock: true }, function (error, lockedMessage) {

if (!error) {
  try {
    const receivedMessage = JSON.parse(lockedMessage.body);
    console.log('receivedMessage', receivedMessage);
    if (!_.isEqual(receivedMessage.Type, messageType.USERPROFILES_USER_UPDATED)) {
      return;
    }
    //Message received and locked
    callback(receivedMessage);
    serviceBus.deleteMessage(lockedMessage, function (deleteError) {
      if (!deleteError) {
        // Message deleted
        console.log('message has been deleted.');
      }
    });
  }
  catch (error) {
    console.log('Start debugging');
    console.log(lockedMessage.body);
  }
</code>```

When I receive a message it has strange encoding and JSON.parse throws an exception.

The lockedMessage output is:

```<code>{ body: '@\fbase64Binary\b3http://schemas.microsoft.com/2003/10/Serialization/�s\u0002{"Type":"SomeEvent"�\u0001}',
   brokerProperties:
{ DeliveryCount: 9,
  EnqueuedSequenceNumber: 0,
  EnqueuedTimeUtc: 'Thu, 16 Nov 2017 23:50:16 GMT',
  LockToken: '6e3e311f-0fe9-4366-844d-18046fd000db',
  LockedUntilUtc: 'Fri, 17 Nov 2017 00:10:46 GMT',
  MessageId: 'nil',
  PartitionKey: '1d84084f-65af-4a33-bb30-62d97d85557d',
  SequenceNumber: 61643019899633670,
  SessionId: '1d84084f-65af-4a33-bb30-62d97d85557d',
  State: 'Active',
  TimeToLive: 1566804.069 },
   location: '',
   contentType: 'application/xml; charset=utf-8',
   customProperties: { 'strict-transport-security': NaN, connection: NaN } }
</code>```

The message is coming from a .NET Core service and that service sends with this code:

```<code>            var payload = JsonConvert.SerializeObject(SomeEvent);
            var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload));
            serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
            topicClient.SendAsync(serviceBusMessage).Wait();
</code>```

Why is Node.js not able to parse the message? Another .NET app can receive the same message without any issues.

答:
To avoid this, you need to set ContentType to text/plain when sending a message from .NET Core service. So it should be something like this:

```<code>var payload = JsonConvert.SerializeObject(SomeEvent);
var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload))
{
    ContentType = "text/plain"
};
serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
topicClient.SendAsync(serviceBusMessage).Wait();
</code>```

In this article, they explained the problem and the solution for .NET.

Update:

After some diving, this would not happen to me when I either use .NET Core or .NET to send a message with the standard library Microsoft.Azure.ServiceBus whether ContentType is specified or not.

This is my C# code to send a message:

```<code>class Program
{
    static void Main(string[] args)
    {
        string connectionString = "Endpoint=sb://...";
        var client = new TopicClient(connectionString, "MyTopic");
        var payload = JsonConvert.SerializeObject(new DemoMessage() { Title = $"hello core!!! {DateTime.Now}" });
        var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload));
        serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");

        client.SendAsync(serviceBusMessage).Wait();

    }

    private class DemoMessage
    {
        public DemoMessage()
        {
        }

        public string Title { get; set; }
    }
}
</code>```

This is my Node.js code to receive a message:

```<code>var azure = require('azure');

var serviceBusService = azure.createServiceBusService("Endpoint=sb://...");

serviceBusService.receiveSubscriptionMessage('MyTopic', 'sub1', { isPeekLock: true }, function(error, lockedMessage) {
    if(!error) {

        console.log(lockedMessage);

        serviceBusService.deleteMessage(lockedMessage, function (deleteError){
            if(!deleteError){
                // Message deleted
                console.log('message has been deleted.');
            }
        })
    }
});
</code>```

The lockedMessage output is:

This only happens when I use .NET and the SDK WindowsAzure.ServiceBus with this code:

```<code>class Program
{
    static void Main(string[] args)
    {
        string connectionString = "Endpoint=sb://...";
        var client = TopicClient.CreateFromConnectionString(connectionString, "MyTopic");
        var payload = JsonConvert.SerializeObject(new DemoMessage() { Title = $"hello core!!! {DateTime.Now}" });
        var serviceBusMessage = new BrokeredMessage(Encoding.UTF8.GetBytes(payload));
        serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");

        client.Send(serviceBusMessage);

    }

    private class DemoMessage
    {
        public DemoMessage()
        {
        }

        public string Title { get; set; }
    }
}
</code>```

Now, the lockedMessage output is:

So, I think the message you received is sent from another .NET client and I suggest you clear all messages from the topic before you test it in Node.js.

Body:
This is my JS code to receive a message from Azure Service Bus

function receiveMessage(serviceBusTopic, serviceBusSubscriber, callback) {
  serviceBus.receiveSubscriptionMessage(serviceBusTopic, serviceBusSubscriber,
{ isPeekLock: true }, function (error, lockedMessage) {

if (!error) {
  try {
    const receivedMessage = JSON.parse(lockedMessage.body);
    console.log('receivedMessage', receivedMessage);
    if (!_.isEqual(receivedMessage.Type, messageType.USERPROFILES_USER_UPDATED)) {
      return;
    }
    //Message received and locked
    callback(receivedMessage);
    serviceBus.deleteMessage(lockedMessage, function (deleteError) {
      if (!deleteError) {
        // Message deleted
        console.log('message has been deleted.');
      }
    });
  }
  catch (error) {
    console.log('Start debugging');
    console.log(lockedMessage.body);
  }

When I receive a message it has strange encoding and JSON.parse throws an exception.

The lockedMessage output is:

{ body: '@\fbase64Binary\b3http://schemas.microsoft.com/2003/10/Serialization/�s\u0002{"Type":"SomeEvent"�\u0001}',
   brokerProperties:
{ DeliveryCount: 9,
  EnqueuedSequenceNumber: 0,
  EnqueuedTimeUtc: 'Thu, 16 Nov 2017 23:50:16 GMT',
  LockToken: '6e3e311f-0fe9-4366-844d-18046fd000db',
  LockedUntilUtc: 'Fri, 17 Nov 2017 00:10:46 GMT',
  MessageId: 'nil',
  PartitionKey: '1d84084f-65af-4a33-bb30-62d97d85557d',
  SequenceNumber: 61643019899633670,
  SessionId: '1d84084f-65af-4a33-bb30-62d97d85557d',
  State: 'Active',
  TimeToLive: 1566804.069 },
   location: '',
   contentType: 'application/xml; charset=utf-8',
   customProperties: { 'strict-transport-security': NaN, connection: NaN } }

The message is coming from a .NET Core service and that service sends with this code:

            var payload = JsonConvert.SerializeObject(SomeEvent);
            var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload));
            serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
            topicClient.SendAsync(serviceBusMessage).Wait();

Why is Node.js not able to parse the message? Another .NET app can receive the same message without any issues.

Body:
To avoid this, you need to set ContentType to text/plain when sending a message from .NET Core service. So it should be something like this:

var payload = JsonConvert.SerializeObject(SomeEvent);
var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload))
{
    ContentType = "text/plain"
};
serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");
topicClient.SendAsync(serviceBusMessage).Wait();

In this article, they explained the problem and the solution for .NET.

Update:

After some diving, this would not happen to me when I either use .NET Core or .NET to send a message with the standard library Microsoft.Azure.ServiceBus whether ContentType is specified or not.

This is my C# code to send a message:

class Program
{
    static void Main(string[] args)
    {
        string connectionString = "Endpoint=sb://...";
        var client = new TopicClient(connectionString, "MyTopic");
        var payload = JsonConvert.SerializeObject(new DemoMessage() { Title = $"hello core!!! {DateTime.Now}" });
        var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(payload));
        serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");

        client.SendAsync(serviceBusMessage).Wait();

    }

    private class DemoMessage
    {
        public DemoMessage()
        {
        }

        public string Title { get; set; }
    }
}

This is my Node.js code to receive a message:

var azure = require('azure');

var serviceBusService = azure.createServiceBusService("Endpoint=sb://...");

serviceBusService.receiveSubscriptionMessage('MyTopic', 'sub1', { isPeekLock: true }, function(error, lockedMessage) {
    if(!error) {

        console.log(lockedMessage);

        serviceBusService.deleteMessage(lockedMessage, function (deleteError){
            if(!deleteError){
                // Message deleted
                console.log('message has been deleted.');
            }
        })
    }
});

The lockedMessage output is:

This only happens when I use .NET and the SDK WindowsAzure.ServiceBus with this code:

class Program
{
    static void Main(string[] args)
    {
        string connectionString = "Endpoint=sb://...";
        var client = TopicClient.CreateFromConnectionString(connectionString, "MyTopic");
        var payload = JsonConvert.SerializeObject(new DemoMessage() { Title = $"hello core!!! {DateTime.Now}" });
        var serviceBusMessage = new BrokeredMessage(Encoding.UTF8.GetBytes(payload));
        serviceBusMessage.SessionId = Guid.NewGuid().ToString("D");

        client.Send(serviceBusMessage);

    }

    private class DemoMessage
    {
        public DemoMessage()
        {
        }

        public string Title { get; set; }
    }
}

Now, the lockedMessage output is:

So, I think the message you received is sent from another .NET client and I suggest you clear all messages from the topic before you test it in Node.js.


来源: stackexchange

问:
s3 bucket delete missing credentials error
Hi guys I am trying to delete objects from my s3 bucket using node js here is my server side script that will execute

```<code>var aws = require('aws-sdk');
var s33 = new aws.S3();
aws.config.update({
    accessKeyId: "xxxxxxxxxxxxxxxxxxxxxx",
    secretAccessKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    bucket : "xxxxxxxxxxxx",
    region: "us-east-1"
});

app.post('/deleteObj',function(req, res) {
        var params = {
          Bucket: 'xxxxxxxxxxxxx',
          Delete: { // required
            Objects: [ // required
              {
                Key: 'some-key' // required
              },
              /*{
                Key: 'sample-image--10.jpg'
              }*/
            ],
          },
        };

        s33.deleteObjects(params, function(err, data) {
          if (err) console.log(err, err.stack); // an error occurred
          else     console.log(data);           // successful response
        });

    });
</code>```

It is showing an error of missing credentials that should not happen as I am able to do a browser-based POST upload using these credentials only.

here is the error log:

```<code>CredentialsError: Missing credentials in config
    at IncomingMessage.<anonymous> (/home/ubuntu/xxxxxx/node_modules/aws-sdk/lib/util.js:864:34)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
  message: 'Missing credentials in config',
  retryable: false,
  time: 2017-11-17T06:43:51.657Z,
  code: 'CredentialsError',
  originalError:
   { message: 'Could not load credentials from any providers',
     retryable: false,
     time: 2017-11-17T06:43:51.657Z,
</code>```

here is the cors config of the bucket take a look into this if it helps:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>http://xxxxxxxxxxxxxxxxxxxxxxxxxxxx</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

Let me know your thoughts on this.

-Thanks

答:
When you are using the AWS API, CORS is not involved.

Your problem is that you are assigning your credentials after you create the S3 client.

Change your code to look like this:

```<code>var aws = require('aws-sdk');

aws.config.update({
    accessKeyId: "xxxxxxxxxxxxxxxxxxxxxx",
    secretAccessKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    bucket : "xxxxxxxxxxxx",
    region: "us-east-1"
});

var s33 = new aws.S3();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi guys I am trying to delete objects from my s3 bucket using node js here is my server side script that will execute

var aws = require('aws-sdk');
var s33 = new aws.S3();
aws.config.update({
    accessKeyId: "xxxxxxxxxxxxxxxxxxxxxx",
    secretAccessKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    bucket : "xxxxxxxxxxxx",
    region: "us-east-1"
});

app.post('/deleteObj',function(req, res) {
        var params = {
          Bucket: 'xxxxxxxxxxxxx',
          Delete: { // required
            Objects: [ // required
              {
                Key: 'some-key' // required
              },
              /*{
                Key: 'sample-image--10.jpg'
              }*/
            ],
          },
        };

        s33.deleteObjects(params, function(err, data) {
          if (err) console.log(err, err.stack); // an error occurred
          else     console.log(data);           // successful response
        });

    });

It is showing an error of missing credentials that should not happen as I am able to do a browser-based POST upload using these credentials only.

here is the error log:

CredentialsError: Missing credentials in config
    at IncomingMessage.<anonymous> (/home/ubuntu/xxxxxx/node_modules/aws-sdk/lib/util.js:864:34)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
  message: 'Missing credentials in config',
  retryable: false,
  time: 2017-11-17T06:43:51.657Z,
  code: 'CredentialsError',
  originalError:
   { message: 'Could not load credentials from any providers',
     retryable: false,
     time: 2017-11-17T06:43:51.657Z,

here is the cors config of the bucket take a look into this if it helps:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>http://xxxxxxxxxxxxxxxxxxxxxxxxxxxx</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Let me know your thoughts on this.

-Thanks

Body:
When you are using the AWS API, CORS is not involved.

Your problem is that you are assigning your credentials after you create the S3 client.

Change your code to look like this:

var aws = require('aws-sdk');

aws.config.update({
    accessKeyId: "xxxxxxxxxxxxxxxxxxxxxx",
    secretAccessKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    bucket : "xxxxxxxxxxxx",
    region: "us-east-1"
});

var s33 = new aws.S3();


问:
Webview in Swift
I want to integrate webpage into an Ios application.
I have created a webpage using D3 js and SVG elements.
I am trying to display the webpage on Ipad Pro 12.9" 2nd generation.
But somehow it is showing only a 1/4 portion of my webpage in webView.

Here is the webpage URL -
http://ec2-54-198-148-171.compute-1.amazonaws.com/webapp/question

I got iPad pro-resolution from apple website which is 1366X1024 so I have created a webpage for the same resolution.

I have verified webpage on browsers like safari, chrome, firefox and it's looking perfect on it with 1366X1024 resolution.

Attached screenshot BrowserScreenCap taken with 1366 X 1024 on browser and IpadAppScreenCap took on iPad application.
I am using WKwebView on IOS side. I have verified webpage layout on simulator only.
How we make that webpage fullscreen?

答:
Content from the link mentioned in comment.</p>

```<code>NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];

    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
</code>```

Title: Webview in Swift

Body:
Content from the link mentioned in comment.

NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];

    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;


问:
Regular expression to exclude a string/character in nodejs
Currently I have a variable that has turnallplugsoffR1, turnallplugsonR1.
I wanted to exclude R1 from the string and get only turnallplugsoff in my variable in nodejs.
Could you please help me in achieving the same?
dataval="turnallplugsoffR1"</p>

```<code>var room_value=dataval.match(/R[0-9]+/i); //matched R1/R2 any other string
    console.log(excl); // i want only turnallplugsoff. I dont want R1/R2
    console.log(room_value[0]);
</code>```

答:
You may remove R followed with any 1+ digits at the end of the string:

```<code>var room_value=dataval.replace(/R\d+$/, '')
</code>```

Details

R - a R letter

\d+ - 1 or more digits

$ - end of string.

var dataval="turnallplugsoffR1";
var room_value=dataval.replace(/R\d+$/, '');
console.log(room_value);```
</div>
</div>
</p>

<p>You may also get both the values with one matching operation using</p>

```dataval.match(/^(.*)(R\d+)$/)
```

<p>Here, <code>^</code> matches the start of the string, <code>(.*)</code> captures into Group 1 any 0+
 chars other than line break chars up to the last <code>R</code> followed with digits at the end of the string <code>(R\d+)$</code> capturing the <code>R</code>+digits into Group 2.</p>

<p>See the JS demo:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var dataval="turnallplugsoffR1";
var res = dataval.match(/^(.*)(R\d+)$/);
if (res) {
  console.log(res[1]); // turnallplugsoff
  console.log(res[2]); // R1
}</code>```

Body:
Currently I have a variable that has turnallplugsoffR1, turnallplugsonR1.
I wanted to exclude R1 from the string and get only turnallplugsoff in my variable in nodejs.
Could you please help me in achieving the same?
dataval="turnallplugsoffR1"

var room_value=dataval.match(/R[0-9]+/i); //matched R1/R2 any other string
    console.log(excl); // i want only turnallplugsoff. I dont want R1/R2
    console.log(room_value[0]);

Body:
You may remove R followed with any 1+ digits at the end of the string:

var room_value=dataval.replace(/R\d+$/, '')

Details

R - a R letter

\d+ - 1 or more digits

$ - end of string.

var dataval="turnallplugsoffR1";
var room_value=dataval.replace(/R\d+$/, '');
console.log(room_value);

You may also get both the values with one matching operation using

dataval.match(/^(.*)(R\d+)$/)

Here, ^ matches the start of the string, (.*) captures into Group 1 any 0+
 chars other than line break chars up to the last R followed with digits at the end of the string (R\d+)$ capturing the R+digits into Group 2.

See the JS demo:

var dataval="turnallplugsoffR1";
var res = dataval.match(/^(.*)(R\d+)$/);
if (res) {
  console.log(res[1]); // turnallplugsoff
  console.log(res[2]); // R1
}


问:
JS & CSS - How to Randomly generate a colour and have it apply to an element on an event?
I know this question has been asked before, but I can never seem to find it in the right context.

For my website, I want, upon loading the page, a random colour to be generated (1 of the rainbow). Then, whenever I hover over a div, (it is one that is repeated), that div(s) will become the specified colour.

```<code>.shape:hover {
        background-color: green;
        transition-duration: 0.1s;
    }
</code>```

That's the CSS. The current background colour is green, but that's the property I want to be randomly selected upon the page loading. Thanks.

答:
The current background colour is green but that's the property I want
  to be randomly selected upon the page loading

You need to generate a random color at page-load and assigns the same as background-color to element.

Here is an approach using the getRandomColor given in this SO post

```<code>document.addEventListener( "DOMContentLoaded", function(){
   document.querySelectorAll( ".shape" ).forEach( function(el){
      var randomColor = getRandomColor();
      el.addEventListener("mouseover", function() {
         el.style.backgroundColor = randomColor;
      });
      el.addEventListener( "mouseleave", function(){
        el.style.backgroundColor = defaultBGColor;
      });
   })
});

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
</code>```

Demo

document.addEventListener("DOMContentLoaded", function() {
  document.querySelectorAll(".shape").forEach(function(el) {
    var defaultBGColor = el.style.backgroundColor;
    var randomColor = getRandomColor();
    el.addEventListener("mouseover", function() {
      el.style.backgroundColor = randomColor;
    });
    el.addEventListener("mouseleave", function() {
      el.style.backgroundColor = defaultBGColor;
    });
  })
});

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.shape {
  width:100px;
  height:100px;
  background-color: black;
}
.shape:hover {
  background-color: green;
  transition-duration: 0.1s;
}</code>```

```

Body:
I know this question has been asked before, but I can never seem to find it in the right context.

For my website, I want, upon loading the page, a random colour to be generated (1 of the rainbow). Then, whenever I hover over a div, (it is one that is repeated), that div(s) will become the specified colour.

.shape:hover {
        background-color: green;
        transition-duration: 0.1s;
    }

That's the CSS. The current background colour is green, but that's the property I want to be randomly selected upon the page loading. Thanks.

Body:
The current background colour is green but that's the property I want
  to be randomly selected upon the page loading

You need to generate a random color at page-load and assigns the same as background-color to element.

Here is an approach using the getRandomColor given in this SO post

document.addEventListener( "DOMContentLoaded", function(){
   document.querySelectorAll( ".shape" ).forEach( function(el){
      var randomColor = getRandomColor();
      el.addEventListener("mouseover", function() {
         el.style.backgroundColor = randomColor;
      });
      el.addEventListener( "mouseleave", function(){
        el.style.backgroundColor = defaultBGColor;
      });
   })
});

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

Demo

document.addEventListener("DOMContentLoaded", function() {
  document.querySelectorAll(".shape").forEach(function(el) {
    var defaultBGColor = el.style.backgroundColor;
    var randomColor = getRandomColor();
    el.addEventListener("mouseover", function() {
      el.style.backgroundColor = randomColor;
    });
    el.addEventListener("mouseleave", function() {
      el.style.backgroundColor = defaultBGColor;
    });
  })
});

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

.shape {
  width:100px;
  height:100px;
  background-color: black;
}
.shape:hover {
  background-color: green;
  transition-duration: 0.1s;
}

<div class="shape">
</div>


问:
Motorola 68000 Storage in Assembly
This program is written to take space delimited user input with four tokens, add the tokens together if they are all numbers, and print the result to the terminal. Right now it works for numbers such as "1 1 1 1" and "123 123 123 123," but when I attempt to add 4 numbers that are seven digits long (7 digits, because that is the extreme case), it only adds up to 23068. This sounds like it would be a sizing issue with one of my labels or something, but I am not certain.

Here is the code:

```<code>*
        ORG     $0
        DC.L    $3000           * Stack pointer value after a reset
        DC.L    start           * Program counter value after a reset
        ORG     $3000           * Start at location 3000 Hex
*
*----------------------------------------------------------------------
*
#minclude /home/cs/faculty/cs237/bsvc/macros/iomacs.s
#minclude /home/cs/faculty/cs237/bsvc/macros/evtmacs.s
*
*----------------------------------------------------------------------
*
* Register use
*
*----------------------------------------------------------------------
*
start:  initIO                  * Initialize (required for I/O)
    setEVT          * Error handling routines
*   initF           * For floating point macros only

                * Your code goes HERE
*Output info:
    lineout header      *Display header info
    lineout prompt      *Display prompt
    linein  buffer      *Read input to buffer

    lea buffer,A1       *
    adda.l  D0,A1       *Add null terminator
    clr.b   (A1)        *

    lea buffer,A1       *Reload the beginning of buffer address

    move.l  #1,D1       *D1 is input counter and starts at 1

    clr.l   D2          *
    clr.l   D3          *Prepping registers for calculations
    move.l  #0,result   *

    move.l  A1,A2       *Duplicating address to use for strlen

top:
    tst.b   (A1)        *Check for end of string
    BEQ rest            *If end, go to rest

    cmpi.b  #47,(A1)    *Check current byte against low end of ascii numbers
    BGT toprange        *This means byte *might* be an ascii number

    cmpi.b  #32,(A1)    *Byte is below range for numbers. Is it a space?
    BNE notno           *If this triggers, it's not a space and not a number. Exit.

    cmpi.b  #32,1(A1)   *Is the character after this a space? If yes, loop to top.
    BNE addit           *If not, it's either another valid byte or null terminator.

    adda.l  #1,A1       *Increment token counter and loop to top.
    BRA     top

toprange:
    cmpi.b  #57,(A1)    *Is byte value higher than ascii numbers range?
    BGT notno           *If yes, it's not an ascii number. Exit.

    cmpi.b  #32,1(A1)   *Is the byte after this a space?
    BEQ endoftoken      *If yes, that means this is the end of the token.

    tst.b   1(A1)       *If not, is this byte a null terminator?
    BEQ endoftoken      *If yes, this is the last token. Add it.

    adda.l  #1,A1       *Else increment the address pointer and loop.
    BRA top

endoftoken:
    adda.l  #1,A1       *Increment pointer
    move.l  A1,D2       *
    sub.l   A2,D2       *Find length of token

    cvta2   (A2),D2     *Convert current token segment to number
    add.l   D0,result   *Add converted number to result address.
    BRA     top         *Loop to top.

addit:
    tst.b   1(A1)       *Test for null
    BEQ endoftoken      *If null, go endof token to add it to running total

    addi.l  #1,D1       *If next byte isn't null, there might be more tokens. Incr & cont.
    adda.l  #1,A1

    move.l  A1,A2       *Shift token starting point pointer forward
    BRA top

rest:
    cmpi.l  #4,D1       *Check to make sure we have 4 tokens
    BNE incnums         *If not, exit on error

    move.l  result,D0   *Convert numbers back to text representations
    ext.l   D0
    cvt2a   result,#8
    stripp  result,#8
    lea result,A0
    adda.l  D0,A0
    clr.b   (A0)

    lea sum,A1          *Point to first bit of text for strcat
    lea output,A2       *Point to destination during copying
strcat1:
    tst.b   (A1)        *Null?
    BEQ strcat2         *Go to next segment of code
    move.b  (A1)+,(A2)+ *If not null, copy from A1 to A2. Post increment
    BRA strcat1

strcat2:
    move.b  #32,(A2)+   *Append space. Post increment
    lea result,A1       *Point to calculated result

strcat3:
    tst.b   (A1)        *Is this byte null?
    BEQ printr          *If yes, go to print response.
    move.b  (A1)+,(A2)+ *If not, copy byte to output string.
    BRA strcat3

printr:
    move.b  #46,(A2)+   *Append period to output string.
    clr.b   (A2)        *Null terminate the string.
    lineout output      *Print built string to terminal.
    BRA end

incnums:
    lineout incno       *If here, there were not the correct number of tokens.
    BRA end

notno:
    cmpi.b  #1,D1       *This checks the token counter to determine which token was not a #
    BNE ch2
    lineout bn1
    BRA end

ch2:
    cmpi.b  #2,D1
    BNE ch3
    lineout bn2
    BRA     end

ch3:
    cmpi.b  #3,D1
    BNE ch4
    lineout bn3
    BRA end

ch4:
    lineout bn4

end:

*Output result

        break                   * Terminate execution
*
*----------------------------------------------------------------------
*       Storage declarations

prompt: dc.b    'Enter the four space separated numbers:',0
sum:    dc.b    'The sum is',0
incno:  dc.b    'There are not four inputs.',0
buffer: ds.b    80
result: ds.l    3
output: ds.l    3
bn1:    dc.b    'The #1 input is not a number',0
bn2:    dc.b    'The #2 input is not a number',0
bn3:    dc.b    'The #3 input is not a number',0
bn4:    dc.b    'The #4 input is not a number',0
        end
</code>```

Edit 1

It looks like it has to do with when I convert the ascii representation to an actual number. I add.l to the result label. The label is big enough to store the characters, but I am not moving a large enough chunk to it.

When I enter "9999999 9999999 9999999 9999999" and set a break point to watch it, the memory will correctly display the hex value of 26259FC, so it's a problem when I convert it back using the provided macro.

I don't expect anyone to have a solution for that, but maybe someone does.

Edit2:
This code has been revised under the guidance of Sep Rowland (many thanks). I think I got everything he covered, and the revised code has been submitted as an answer.

答:
The initial problem:
The ext.l instruction. This is explained by Sep Rowland in one of the other answers provided.

Other revisions:
Under the guidance of Sep, I have optimized the code in several areas.

+1 for memory viewer and break points.

```<code>* Problem statement: Read input and determine if 4 numbers are provided. Add numbers.
* Input: ### ### ### ###
* Output: "The sum is ###"
* Error conditions tested: Correct number of data provided. Number vs Char
*  Also handles leading white spaces/multiple spaces between tokens
* Included files: None
* Method and/or pseudocode:
* References:
*----------------------------------------------------------------------
*
        ORG     $0
        DC.L    $3000           * Stack pointer value after a reset
        DC.L    start           * Program counter value after a reset
        ORG     $3000           * Start at location 3000 Hex
*
*----------------------------------------------------------------------
*
#minclude /home/cs/faculty/cs237/bsvc/macros/iomacs.s
#minclude /home/cs/faculty/cs237/bsvc/macros/evtmacs.s
*
*----------------------------------------------------------------------
*
* Register use
*
*----------------------------------------------------------------------
*
start:  initIO                  * Initialize (required for I/O)
    setEVT          * Error handling routines
*   initF           * For floating point macros only

    lineout header      *Display header info
    lineout prompt      *Display prompt
    linein  buffer      *Read input to buffer
    lea buffer,A1       *
    adda.l  D0,A1       *Add null terminator
    clr.b   (A1)        *
    lea buffer,A1       *Reload the beginning of buffer address
    clr.l   D1          *D1 is input counter and starts at 0
    clr.l   D2          *D2 used as workspace
    move.l  #0,result   *Clearing garbage out of memory address
    move.l  A1,A2       *A2 used for strlen

top:
    tst.b   (A1)        *Check for end of string
    BEQ rest            *If end, go to rest

    cmpi.b  #47,(A1)    *Check current byte against low end of ascii numbers
    BGT checktoprange   *This means byte *might* be an ascii number

    cmpi.b  #32,(A1)
    BNE notnumber

whitespace:             *This will eat whitespace anywhere in buffer
    addq.l  #1,A1       *If we are here, we know current location is space
    cmpi.b  #32,(A1)    *So increment pointer and check for additional spaces
    BEQ whitespace
    move.l  A1,A2       *If we are here, we encountered a token
    BRA top             *Shift our pointer for token start location

checktoprange:
    cmpi.b  #57,(A1)    *Is byte value higher than ascii numbers range?
    BGT notnumber       *If yes, it's not an ascii number. Exit.

    cmpi.b  #32,1(A1)   *Is the byte after this a space?
    BEQ endoftoken      *If yes, that means this is the end of the token.

    tst.b   1(A1)       *If not, is this byte a null terminator?
    BEQ endoftoken      *If yes, this is the last token. Add it.

    addq.l  #1,A1       *Else increment the address pointer and loop.
    BRA top

endoftoken:
    addq.l  #1,A1       *Increment pointer
    move.l  A1,D2       *
    sub.l   A2,D2       *Find length of token

    cvta2   (A2),D2     *Convert current token segment to number

    add.l   D0,result   *Add converted number to result address.
    addq.l  #1,D1       *Increment token counter
    BRA     top

rest:
    cmpi.l  #4,D1       *Check to make sure we have 4 tokens
    BNE incnums         *If not, exit on error

    move.l  result,D0   *Convert numbers back to text representations
    cvt2a   result,#8
    stripp  result,#8
    lea result,A0
    adda.l  D0,A0
    move.b  #46,(A0)+
    clr.b   (A0)
    lineout sum
    BRA end

incnums:
    lineout incno       *If here, there were not the correct number of tokens.
    BRA end

notnumber:
    lea bn,A1
    addi.b  #49,D1       *From number to character
    move.b  D1,5(A1)     *Replaces the dot in the error message
    lineout bn

end:

        break                   * Terminate execution
*
*----------------------------------------------------------------------
*       Storage declarations

header: dc.b    'This is a header',0
prompt: dc.b    'Enter the four space separated numbers:',0
incno:  dc.b    'There are not four inputs.',0
buffer: ds.b    80
bn:     dc.b    'The #. input is not a number',0
sum:    dc.b    'The sum is '
result: ds.l    1

        end
</code>```

Title: Motorola 68000 Storage in Assembly

Body:
This program is written to take space delimited user input with four tokens, add the tokens together if they are all numbers, and print the result to the terminal. Right now it works for numbers such as "1 1 1 1" and "123 123 123 123," but when I attempt to add 4 numbers that are seven digits long (7 digits, because that is the extreme case), it only adds up to 23068. This sounds like it would be a sizing issue with one of my labels or something, but I am not certain.

Here is the code:

*
        ORG     $0
        DC.L    $3000           * Stack pointer value after a reset
        DC.L    start           * Program counter value after a reset
        ORG     $3000           * Start at location 3000 Hex
*
*----------------------------------------------------------------------
*
#minclude /home/cs/faculty/cs237/bsvc/macros/iomacs.s
#minclude /home/cs/faculty/cs237/bsvc/macros/evtmacs.s
*
*----------------------------------------------------------------------
*
* Register use
*
*----------------------------------------------------------------------
*
start:  initIO                  * Initialize (required for I/O)
    setEVT          * Error handling routines
*   initF           * For floating point macros only

                * Your code goes HERE
*Output info:
    lineout header      *Display header info
    lineout prompt      *Display prompt
    linein  buffer      *Read input to buffer

    lea buffer,A1       *
    adda.l  D0,A1       *Add null terminator
    clr.b   (A1)        *

    lea buffer,A1       *Reload the beginning of buffer address

    move.l  #1,D1       *D1 is input counter and starts at 1

    clr.l   D2          *
    clr.l   D3          *Prepping registers for calculations
    move.l  #0,result   *

    move.l  A1,A2       *Duplicating address to use for strlen

top:
    tst.b   (A1)        *Check for end of string
    BEQ rest            *If end, go to rest

    cmpi.b  #47,(A1)    *Check current byte against low end of ascii numbers
    BGT toprange        *This means byte *might* be an ascii number

    cmpi.b  #32,(A1)    *Byte is below range for numbers. Is it a space?
    BNE notno           *If this triggers, it's not a space and not a number. Exit.

    cmpi.b  #32,1(A1)   *Is the character after this a space? If yes, loop to top.
    BNE addit           *If not, it's either another valid byte or null terminator.

    adda.l  #1,A1       *Increment token counter and loop to top.
    BRA     top

toprange:
    cmpi.b  #57,(A1)    *Is byte value higher than ascii numbers range?
    BGT notno           *If yes, it's not an ascii number. Exit.

    cmpi.b  #32,1(A1)   *Is the byte after this a space?
    BEQ endoftoken      *If yes, that means this is the end of the token.

    tst.b   1(A1)       *If not, is this byte a null terminator?
    BEQ endoftoken      *If yes, this is the last token. Add it.

    adda.l  #1,A1       *Else increment the address pointer and loop.
    BRA top

endoftoken:
    adda.l  #1,A1       *Increment pointer
    move.l  A1,D2       *
    sub.l   A2,D2       *Find length of token

    cvta2   (A2),D2     *Convert current token segment to number
    add.l   D0,result   *Add converted number to result address.
    BRA     top         *Loop to top.

addit:
    tst.b   1(A1)       *Test for null
    BEQ endoftoken      *If null, go endof token to add it to running total

    addi.l  #1,D1       *If next byte isn't null, there might be more tokens. Incr & cont.
    adda.l  #1,A1

    move.l  A1,A2       *Shift token starting point pointer forward
    BRA top

rest:
    cmpi.l  #4,D1       *Check to make sure we have 4 tokens
    BNE incnums         *If not, exit on error

    move.l  result,D0   *Convert numbers back to text representations
    ext.l   D0
    cvt2a   result,#8
    stripp  result,#8
    lea result,A0
    adda.l  D0,A0
    clr.b   (A0)

    lea sum,A1          *Point to first bit of text for strcat
    lea output,A2       *Point to destination during copying
strcat1:
    tst.b   (A1)        *Null?
    BEQ strcat2         *Go to next segment of code
    move.b  (A1)+,(A2)+ *If not null, copy from A1 to A2. Post increment
    BRA strcat1

strcat2:
    move.b  #32,(A2)+   *Append space. Post increment
    lea result,A1       *Point to calculated result

strcat3:
    tst.b   (A1)        *Is this byte null?
    BEQ printr          *If yes, go to print response.
    move.b  (A1)+,(A2)+ *If not, copy byte to output string.
    BRA strcat3

printr:
    move.b  #46,(A2)+   *Append period to output string.
    clr.b   (A2)        *Null terminate the string.
    lineout output      *Print built string to terminal.
    BRA end

incnums:
    lineout incno       *If here, there were not the correct number of tokens.
    BRA end

notno:
    cmpi.b  #1,D1       *This checks the token counter to determine which token was not a #
    BNE ch2
    lineout bn1
    BRA end

ch2:
    cmpi.b  #2,D1
    BNE ch3
    lineout bn2
    BRA     end

ch3:
    cmpi.b  #3,D1
    BNE ch4
    lineout bn3
    BRA end

ch4:
    lineout bn4

end:

*Output result

        break                   * Terminate execution
*
*----------------------------------------------------------------------
*       Storage declarations

prompt: dc.b    'Enter the four space separated numbers:',0
sum:    dc.b    'The sum is',0
incno:  dc.b    'There are not four inputs.',0
buffer: ds.b    80
result: ds.l    3
output: ds.l    3
bn1:    dc.b    'The #1 input is not a number',0
bn2:    dc.b    'The #2 input is not a number',0
bn3:    dc.b    'The #3 input is not a number',0
bn4:    dc.b    'The #4 input is not a number',0
        end

Edit 1

It looks like it has to do with when I convert the ascii representation to an actual number. I add.l to the result label. The label is big enough to store the characters, but I am not moving a large enough chunk to it.

When I enter "9999999 9999999 9999999 9999999" and set a break point to watch it, the memory will correctly display the hex value of 26259FC, so it's a problem when I convert it back using the provided macro.

I don't expect anyone to have a solution for that, but maybe someone does.

Edit2:
This code has been revised under the guidance of Sep Rowland (many thanks). I think I got everything he covered, and the revised code has been submitted as an answer.

Body:
The initial problem:
The ext.l instruction. This is explained by Sep Rowland in one of the other answers provided.

Other revisions:
Under the guidance of Sep, I have optimized the code in several areas.

+1 for memory viewer and break points.

* Problem statement: Read input and determine if 4 numbers are provided. Add numbers.
* Input: ### ### ### ###
* Output: "The sum is ###"
* Error conditions tested: Correct number of data provided. Number vs Char
*  Also handles leading white spaces/multiple spaces between tokens
* Included files: None
* Method and/or pseudocode:
* References:
*----------------------------------------------------------------------
*
        ORG     $0
        DC.L    $3000           * Stack pointer value after a reset
        DC.L    start           * Program counter value after a reset
        ORG     $3000           * Start at location 3000 Hex
*
*----------------------------------------------------------------------
*
#minclude /home/cs/faculty/cs237/bsvc/macros/iomacs.s
#minclude /home/cs/faculty/cs237/bsvc/macros/evtmacs.s
*
*----------------------------------------------------------------------
*
* Register use
*
*----------------------------------------------------------------------
*
start:  initIO                  * Initialize (required for I/O)
    setEVT          * Error handling routines
*   initF           * For floating point macros only

    lineout header      *Display header info
    lineout prompt      *Display prompt
    linein  buffer      *Read input to buffer
    lea buffer,A1       *
    adda.l  D0,A1       *Add null terminator
    clr.b   (A1)        *
    lea buffer,A1       *Reload the beginning of buffer address
    clr.l   D1          *D1 is input counter and starts at 0
    clr.l   D2          *D2 used as workspace
    move.l  #0,result   *Clearing garbage out of memory address
    move.l  A1,A2       *A2 used for strlen

top:
    tst.b   (A1)        *Check for end of string
    BEQ rest            *If end, go to rest

    cmpi.b  #47,(A1)    *Check current byte against low end of ascii numbers
    BGT checktoprange   *This means byte *might* be an ascii number

    cmpi.b  #32,(A1)
    BNE notnumber

whitespace:             *This will eat whitespace anywhere in buffer
    addq.l  #1,A1       *If we are here, we know current location is space
    cmpi.b  #32,(A1)    *So increment pointer and check for additional spaces
    BEQ whitespace
    move.l  A1,A2       *If we are here, we encountered a token
    BRA top             *Shift our pointer for token start location

checktoprange:
    cmpi.b  #57,(A1)    *Is byte value higher than ascii numbers range?
    BGT notnumber       *If yes, it's not an ascii number. Exit.

    cmpi.b  #32,1(A1)   *Is the byte after this a space?
    BEQ endoftoken      *If yes, that means this is the end of the token.

    tst.b   1(A1)       *If not, is this byte a null terminator?
    BEQ endoftoken      *If yes, this is the last token. Add it.

    addq.l  #1,A1       *Else increment the address pointer and loop.
    BRA top

endoftoken:
    addq.l  #1,A1       *Increment pointer
    move.l  A1,D2       *
    sub.l   A2,D2       *Find length of token

    cvta2   (A2),D2     *Convert current token segment to number

    add.l   D0,result   *Add converted number to result address.
    addq.l  #1,D1       *Increment token counter
    BRA     top

rest:
    cmpi.l  #4,D1       *Check to make sure we have 4 tokens
    BNE incnums         *If not, exit on error

    move.l  result,D0   *Convert numbers back to text representations
    cvt2a   result,#8
    stripp  result,#8
    lea result,A0
    adda.l  D0,A0
    move.b  #46,(A0)+
    clr.b   (A0)
    lineout sum
    BRA end

incnums:
    lineout incno       *If here, there were not the correct number of tokens.
    BRA end

notnumber:
    lea bn,A1
    addi.b  #49,D1       *From number to character
    move.b  D1,5(A1)     *Replaces the dot in the error message
    lineout bn

end:

        break                   * Terminate execution
*
*----------------------------------------------------------------------
*       Storage declarations

header: dc.b    'This is a header',0
prompt: dc.b    'Enter the four space separated numbers:',0
incno:  dc.b    'There are not four inputs.',0
buffer: ds.b    80
bn:     dc.b    'The #. input is not a number',0
sum:    dc.b    'The sum is '
result: ds.l    1

        end


问:
Alternate name for one-to-one vs one-to-many
Are there generally accepted computer science terms for one-to-one  and one-to-many relationships? Something similar to the terms "aggregation", "generalization", and "association," but strictly pertaining to the cardinality of the relationship?</p>

答: From everything I've ever read, one-to-one, one-to-many, etc. are the accepted ways of referring to these relationships. They are very self descriptive of what they're about.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Paolo Bergantino


问:
Changing the format of date after picking from datepicker after SAPUI5
I have a datepicker from which I want to extract the date and display in a label. Currently the date is getting displayed in the format MM/DD/YYYY but I want it in the format MMM dd, yyyy (Nov 17, 2017). Below is the code : </p>

```<code>screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
date.setText(screenDate);
</code>```

<p>XML : </p>

```<code>    <HBox alignItems="Center" renderType="Bare">
                    <Label text="Date of Screening" width="50%"/>
                    <DatePicker class="sapUiLargeMarginBegin" width="50%" id="screeningDate"/>
                </HBox>
</code>```

答:
In addition to Naveen's answer here's the solution with your existing code:</p>

```<code>screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
// Make date object out of screenDate
var dateObject = new Date(screenDate);
// SAPUI5 date formatter
var dateFormat = sap.ui.core.format.DateFormat.getDateInstance({pattern : "MMM dd,YYYY" });
// Format the date
var dateFormatted = dateFormat.format(dateObject);
date.setText(dateFormatted);
</code>```

Body:
I have a datepicker from which I want to extract the date and display in a label. Currently the date is getting displayed in the format MM/DD/YYYY but I want it in the format MMM dd, yyyy (Nov 17, 2017). Below is the code :

screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
date.setText(screenDate);

XML :

    <HBox alignItems="Center" renderType="Bare">

                    <DatePicker class="sapUiLargeMarginBegin" width="50%" id="screeningDate"/>
                </HBox>

Body:
In addition to Naveen's answer here's the solution with your existing code:

screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
// Make date object out of screenDate
var dateObject = new Date(screenDate);
// SAPUI5 date formatter
var dateFormat = sap.ui.core.format.DateFormat.getDateInstance({pattern : "MMM dd,YYYY" });
// Format the date
var dateFormatted = dateFormat.format(dateObject);
date.setText(dateFormatted);


问:
Getting null while reading image through URL using Angular JS
I have an URL, for eg: w3schools image. When I try to read image and calculate its width and height, I'm getting null at img.src=imgData.
This is the code I'm trying.Why I'm not able to read image from this URL.

```<code>var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
  $rootScope.width = this.width;
  $rootScope.height = this.height;
}
</code>```

答:
You can use naturalHeight and naturalWidth on the image element. Like this:

```<code>var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
   $rootScope.width = this.naturalWidth;
   $rootScope.height = this.naturalHeight;
}
</code>```

Body:
I have an URL, for eg: w3schools image. When I try to read image and calculate its width and height, I'm getting null at img.src=imgData.
This is the code I'm trying.Why I'm not able to read image from this URL.

var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
  $rootScope.width = this.width;
  $rootScope.height = this.height;
}

Body:
You can use naturalHeight and naturalWidth on the image element. Like this:

var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
   $rootScope.width = this.naturalWidth;
   $rootScope.height = this.naturalHeight;
}


问:
Getting error message: AttributeError: 'list' object has no attribute 'lower' in Python
I have the problem, that I am trying to run a function which has as input an array of strings and before making some if-statement I am lowering the strings. somehow i am receiving the error message

AttributeError: 'list' object has no attribute 'lower'

It is not clear for me why do I receive it. The funny part is, If I have both in one script it works. If I source the function out and load it into another script it does not work. The code looks like the following:

```<code>def Calc(String_Array1, String_Array2):
    String_Array1 = String_Array1.lower()
    String_Array2 = String_Array2.lower()

    if String_Array1 == "a":
        print(String_Array1)
    elif String_Array2 == "b":
        print(String_Array2)
    else:
        raise Exception("Something went wrong")

    return 0
</code>```

I am running then my own module like the following

```<code>import helper_module as hm

String_Array1 = ["A"]
String_Array2 = ["B"]

test = hm.CalcFXFwdCurve(String_Array1,String_Array2)

print(test)
</code>```

答: So the solution works with an numpy array using char.lower(). The the if-statement can be performed using any() or all()  </p>

Body:
I have the problem, that I am trying to run a function which has as input an array of strings and before making some if-statement I am lowering the strings. somehow i am receiving the error message

AttributeError: 'list' object has no attribute 'lower'

It is not clear for me why do I receive it. The funny part is, If I have both in one script it works. If I source the function out and load it into another script it does not work. The code looks like the following:

def Calc(String_Array1, String_Array2):
    String_Array1 = String_Array1.lower()
    String_Array2 = String_Array2.lower()

    if String_Array1 == "a":
        print(String_Array1)
    elif String_Array2 == "b":
        print(String_Array2)
    else:
        raise Exception("Something went wrong")

    return 0

I am running then my own module like the following

import helper_module as hm

String_Array1 = ["A"]
String_Array2 = ["B"]

test = hm.CalcFXFwdCurve(String_Array1,String_Array2)

print(test)


问:
Make text bold in SQLite
I'm new to Android I want to make some text bold or italic or insert a new paragraph in Android sqlite database.db
I know that I can do it using HTML tags but it doesn't show in the app it displays tags instead of bold or italic text. Can anyone help here is my code
https://drive.google.com/file/d/0B7KpqDyiTdk5cVc0X2t3N3F1WjA/view
I could have pasted it here but stack overflow doesn't let me paste that much code.

Also it would be a huge help if any one can tell me how can I mark some words as favorite and display them in new activity.

Thanks

答:
have you tried to set data using HTML context </p>

```<code>textView.setText(Html.fromHtml("htmlcontect u want to show "), TextView.BufferType.SPANNABLE)
</code>```

Title: Make text bold in SQLite

Body:
have you tried to set data using HTML context

textView.setText(Html.fromHtml("htmlcontect u want to show "), TextView.BufferType.SPANNABLE)


问:
Why is data transfer speed slower for multiple smaller files than a huge file?
I have always noticed that when for example a react project or a whole website for an instance whose size sums up to say 350-450 MB takes a longer time to transfer than a 2-3 GB video file or for the matter of fact any number of files that are bundled into one file like a .zip/.rar/.iso.

Some SCs :-

Transferring some react projects:-

Transferring a movie:-

I scoured the web but unfortunately found no relevant posts/answers.

Maybe I didn't use the necessary keywords...idk

If possible, a detailed explanation would be really helpful :)

Even if the explanation dives into OS concepts it's cool.
I just wanna know why

答: As per https://serverfault.com/a/9743 suggested, plus writing multiple file will also need to be indexed in the indexing table. Also It will check if same file name exist. That takes time!</p>


问:
How to speedup bulk record deletion in postgres sql
I am having a function which delete more than 1000000 record it takes around 1 min.

```<code>CREATE OR REPLACE FUNCTION DeleteRecord (cmpId integer)
RETURNS boolean AS
$BODY$
DECLARE cmpId INTEGER DEFAULT 0;
DECLARE counter INTEGER := 1 ;
DECLARE batch    INTEGER := 0 ;
DECLARE batchSize    INTEGER :=50000 ;
BEGIN

     SELECT count(*)/batchSize INTO batch FROM department WHERE cmpId= cmpId;
     WHILE counter <= batch + 1 LOOP
          DELETE FROM department WHERE deptId IN ( SELECT deptId FROM
           department WHERE cmpId = cmpId limit batchSize);
          RAISE NOTICE 'Counter: %', counter;
          counter := counter + 1 ;
       END LOOP ;

     counter := 1 ;
     SELECT count(*)/batchSize INTO batch FROM employee WHERE cmpId = cmpId;
     WHILE counter <= batch + 1 LOOP
          DELETE FROM empoyee WHERE empId IN ( SELECT empId FROM
           employee  WHERE cmpId = cmpId limit batchSize);
          RAISE NOTICE 'Counter: %', counter;
          counter := counter + 1 ;
       END LOOP ;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION DeleteRecord(integer)
  OWNER TO postgres;
</code>```

Department table holds 500000 record for cmpId

Employee table hold more 500000 records for cmpId

I tried to delete with simple delete also but it took more than 1 min.

I found one link
How do I speed up deletes from a large database table?

which tells to do delete operation in batch.

But it does helps more time reduced to by just 2 to 3 sec.

答:
There is not really much you can do to speed up large deletes.

Increase max_wal_size if checkpoint are occurring to frequently and get faster storage.

If you face that kind of problem regularly, consider partitioning your table. Dropping a partition is much faster than a mass delete.

Body:
I am having a function which delete more than 1000000 record it takes around 1 min.

CREATE OR REPLACE FUNCTION DeleteRecord (cmpId integer)
RETURNS boolean AS
$BODY$
DECLARE cmpId INTEGER DEFAULT 0;
DECLARE counter INTEGER := 1 ;
DECLARE batch    INTEGER := 0 ;
DECLARE batchSize    INTEGER :=50000 ;
BEGIN

     SELECT count(*)/batchSize INTO batch FROM department WHERE cmpId= cmpId;
     WHILE counter <= batch + 1 LOOP
          DELETE FROM department WHERE deptId IN ( SELECT deptId FROM
           department WHERE cmpId = cmpId limit batchSize);
          RAISE NOTICE 'Counter: %', counter;
          counter := counter + 1 ;
       END LOOP ;

     counter := 1 ;
     SELECT count(*)/batchSize INTO batch FROM employee WHERE cmpId = cmpId;
     WHILE counter <= batch + 1 LOOP
          DELETE FROM empoyee WHERE empId IN ( SELECT empId FROM
           employee  WHERE cmpId = cmpId limit batchSize);
          RAISE NOTICE 'Counter: %', counter;
          counter := counter + 1 ;
       END LOOP ;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION DeleteRecord(integer)
  OWNER TO postgres;

Department table holds 500000 record for cmpId

Employee table hold more 500000 records for cmpId

I tried to delete with simple delete also but it took more than 1 min.

I found one link
How do I speed up deletes from a large database table?

which tells to do delete operation in batch.

But it does helps more time reduced to by just 2 to 3 sec.


问:
Check if an input form is filled in, in a Adaptive Card
You can use input forms in an Adaptive card.
But how can i check if the fields are filled in without going further to the next dialog. So after i clicked a submit button, it should check if the fields are filled in.

Code: nodejs

Example: http://adaptivecards.io/samples/InputForm.html

答:
You can validate the inputs and control the dialog water fulls in bot application.
E.G.

```<code>var bot = new builder.UniversalBot(connector, [(session,args,next) => {

    if (session.message && session.message.value) {
        // A Card's Submit Action obj was received
        if (processSubmitAction(session, session.message.value)) {
            next(session.message.value)
        }
        return;

    }
        // Display Welcome card with Hotels and Flights search options
        var card = {
            'contentType': 'application/vnd.microsoft.card.adaptive',
            'content': {
                "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
                "type": "AdaptiveCard",
                "version": "1.0",
                "body": [{
                    "type": "ColumnSet",
                    "columns": [{
                            "type": "Column",
                            "width": 2,
                            "items": [{
                                    "type": "TextBlock",
                                    "text": "Tell us about yourself",
                                    "weight": "bolder",
                                    "size": "medium"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "We just need a few more details to get you booked for the trip of a lifetime!",
                                    "isSubtle": true,
                                    "wrap": true
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Don't worry, we'll never share or sell your information.",
                                    "isSubtle": true,
                                    "wrap": true,
                                    "size": "small"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Your name",
                                    "wrap": true
                                },
                                {
                                    "type": "Input.Text",
                                    "id": "myName",
                                    "placeholder": "Last, First"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Your email",
                                    "value": "somevalue",
                                    "wrap": true
                                },
                                {
                                    "type": "Input.Text",
                                    "id": "myEmail",
                                    "placeholder": "youremail@example.com",
                                    "style": "email"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Phone Number"
                                },
                                {
                                    "type": "Input.Text",
                                    "id": "myTel",
                                    "placeholder": "xxx.xxx.xxxx",
                                    "style": "tel"
                                }
                            ]
                        },
                        {
                            "type": "Column",
                            "width": 1,
                            "items": [{
                                "type": "Image",
                                "url": "https://upload.wikimedia.org/wikipedia/commons/b/b2/Diver_Silhouette%2C_Great_Barrier_Reef.jpg",
                                "size": "auto"
                            }]
                        }
                    ]
                }],
                "actions": [{
                    "type": "Action.Submit",
                    "title": "Submit"
                }]
            }
        };

        var msg = new builder.Message(session)
            .addAttachment(card);
        session.send(msg);

}, (session, results) => {
    session.send(JSON.stringify(results))
}]);

function processSubmitAction(session, value) {
    var defaultErrorMessage = 'Please complete all the search parameters';
    if (!value.myName) {
        session.send(defaultErrorMessage);
        return false;
    } else {
        return true;
    }
}
</code>```

Hope ut helps.

Body:
You can validate the inputs and control the dialog water fulls in bot application.
E.G.

var bot = new builder.UniversalBot(connector, [(session,args,next) => {

    if (session.message && session.message.value) {
        // A Card's Submit Action obj was received
        if (processSubmitAction(session, session.message.value)) {
            next(session.message.value)
        }
        return;

    }
        // Display Welcome card with Hotels and Flights search options
        var card = {
            'contentType': 'application/vnd.microsoft.card.adaptive',
            'content': {
                "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
                "type": "AdaptiveCard",
                "version": "1.0",
                "body": [{
                    "type": "ColumnSet",
                    "columns": [{
                            "type": "Column",
                            "width": 2,
                            "items": [{
                                    "type": "TextBlock",
                                    "text": "Tell us about yourself",
                                    "weight": "bolder",
                                    "size": "medium"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "We just need a few more details to get you booked for the trip of a lifetime!",
                                    "isSubtle": true,
                                    "wrap": true
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Don't worry, we'll never share or sell your information.",
                                    "isSubtle": true,
                                    "wrap": true,
                                    "size": "small"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Your name",
                                    "wrap": true
                                },
                                {
                                    "type": "Input.Text",
                                    "id": "myName",
                                    "placeholder": "Last, First"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Your email",
                                    "value": "somevalue",
                                    "wrap": true
                                },
                                {
                                    "type": "Input.Text",
                                    "id": "myEmail",
                                    "placeholder": "youremail@example.com",
                                    "style": "email"
                                },
                                {
                                    "type": "TextBlock",
                                    "text": "Phone Number"
                                },
                                {
                                    "type": "Input.Text",
                                    "id": "myTel",
                                    "placeholder": "xxx.xxx.xxxx",
                                    "style": "tel"
                                }
                            ]
                        },
                        {
                            "type": "Column",
                            "width": 1,
                            "items": [{
                                "type": "Image",
                                "url": "https://upload.wikimedia.org/wikipedia/commons/b/b2/Diver_Silhouette%2C_Great_Barrier_Reef.jpg",
                                "size": "auto"
                            }]
                        }
                    ]
                }],
                "actions": [{
                    "type": "Action.Submit",
                    "title": "Submit"
                }]
            }
        };

        var msg = new builder.Message(session)
            .addAttachment(card);
        session.send(msg);

}, (session, results) => {
    session.send(JSON.stringify(results))
}]);

function processSubmitAction(session, value) {
    var defaultErrorMessage = 'Please complete all the search parameters';
    if (!value.myName) {
        session.send(defaultErrorMessage);
        return false;
    } else {
        return true;
    }
}

Hope ut helps.


问:
Is there an open source tool based on perl or python to generate the summary of mindmap of documents
I am really looking for a toolkit or readymade tool which will parse a given document and then generate a brief summary of better still a mindmap of the document. I know Python has ntlk and perl has quite a few  modules which will help in natural language parsing etc.
It is even feasible to write a tool to do so, with using ntlk like tool kit, but for the lack of time. Would appreciate if you know of some such tool or has some pointer to such a tool, if you could post it here, with thanks in advance. </p>

答: Someone (here on SO) has already written it for you (discussion). Another option would be TexLexAn (Text Analyzer Classifier Summarizer).</p>


问:
Linq query to Join tables if value not in first table fetch from second
I have 2 lists with below structure.

```<code>public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D2" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D1"} }
};

var allTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D1" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D2"}, Codriver = new Driver { DriverId = "C2"} }
};
</code>```

I want to get all the Id's of driver and codriver from modifiedTeams but if driver/codriver is not there in modifiedTeams then fetch it from allTeams based on Team ids(T1,T2) Eg: Id of codriver from Team T2

Final Output:

```<code>{D2,C1,D1,C2}
</code>```

Can some one help me how I could achieve this via LINQ(Lambda expressions) in C#.

Simple C# code:-

```<code>List<string> allDriverCodriverIds = new List<string>();
foreach (var team in modifiedTeams)
{
    if (team.Driver != null && !string.IsNullOrEmpty(team.Driver.DriverId))
    {
        allDriverCodriverIds.Add(team.Driver.DriverId);
    }
    else {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Driver != null && !string.IsNullOrEmpty(existingTeam.Driver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Driver.DriverId);
        }
    }
    if (team.Codriver != null && !string.IsNullOrEmpty(team.Codriver.DriverId))
    {
        allDriverCodriverIds.Add(team.Codriver.DriverId);
    }
    else
    {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Codriver != null && !string.IsNullOrEmpty(existingTeam.Codriver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Codriver.DriverId);
        }
    }
}
</code>```

答:
I'm editing my answer as per your comment. Please find the code below.

```<code>public static void KvYQ()
            {
                List<Team> modifiedTeams = new List<Team>() {
                    new Team() {
                        Id="T1"
                        ,Driver=new Driver() {
                            DriverId="D2"
                        }
                        ,Codriver=new Driver() {
                            DriverId="C1"
                        }
                    }
                    ,new Team() {
                        Id="T2"
                        ,Driver=new Driver() {
                            DriverId="D1"
                        }
                    }
                };

                List<Team> allTeams = new List<Team>() {
                    new Team() {
                        Id="T1"
                        ,Driver=new Driver() {
                            DriverId="D1"
                        }
                        ,Codriver=new Driver() {
                            DriverId="C1"
                        }
                    }
                    ,new Team() {
                        Id="T2"
                        ,Driver=new Driver() {
                            DriverId="D2"
                        }
                        ,Codriver=new Driver() {
                            DriverId="C2"
                        }
                    }
                };

                var driverdetails = modifiedTeams.Select(x => new Team()
                {
                    Driver = x.Driver,
                    Codriver = x.Codriver

                });

                foreach (var item in driverdetails)
                {
                    Driver d = (item.Driver == null) ? allTeams.Select(x => x.Driver).FirstOrDefault() : item.Driver;
                    Driver c = (item.Codriver == null) ? allTeams.Select(x => x.Codriver).FirstOrDefault() : item.Codriver;
                    Console.WriteLine(d.DriverId + " " + c.DriverId);
                    //{D2,C1}
                    //{D1,C1}
                }

            }
</code>```

You can Write the logic in one query itself. But to make it clear, i've written it in foreach.

Hope this helps

Body:
I have 2 lists with below structure.

public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D2" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D1"} }
};

var allTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D1" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D2"}, Codriver = new Driver { DriverId = "C2"} }
};

I want to get all the Id's of driver and codriver from modifiedTeams but if driver/codriver is not there in modifiedTeams then fetch it from allTeams based on Team ids(T1,T2) Eg: Id of codriver from Team T2

Final Output:

{D2,C1,D1,C2}

Can some one help me how I could achieve this via LINQ(Lambda expressions) in C#.

Simple C# code:-

List<string> allDriverCodriverIds = new List<string>();
foreach (var team in modifiedTeams)
{
    if (team.Driver != null && !string.IsNullOrEmpty(team.Driver.DriverId))
    {
        allDriverCodriverIds.Add(team.Driver.DriverId);
    }
    else {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Driver != null && !string.IsNullOrEmpty(existingTeam.Driver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Driver.DriverId);
        }
    }
    if (team.Codriver != null && !string.IsNullOrEmpty(team.Codriver.DriverId))
    {
        allDriverCodriverIds.Add(team.Codriver.DriverId);
    }
    else
    {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Codriver != null && !string.IsNullOrEmpty(existingTeam.Codriver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Codriver.DriverId);
        }
    }
}

Body:
I'm editing my answer as per your comment. Please find the code below.

public static void KvYQ()
            {
                List<Team> modifiedTeams = new List<Team>() {
                    new Team() {
                        Id="T1"
                        ,Driver=new Driver() {
                            DriverId="D2"
                        }
                        ,Codriver=new Driver() {
                            DriverId="C1"
                        }
                    }
                    ,new Team() {
                        Id="T2"
                        ,Driver=new Driver() {
                            DriverId="D1"
                        }
                    }
                };

                List<Team> allTeams = new List<Team>() {
                    new Team() {
                        Id="T1"
                        ,Driver=new Driver() {
                            DriverId="D1"
                        }
                        ,Codriver=new Driver() {
                            DriverId="C1"
                        }
                    }
                    ,new Team() {
                        Id="T2"
                        ,Driver=new Driver() {
                            DriverId="D2"
                        }
                        ,Codriver=new Driver() {
                            DriverId="C2"
                        }
                    }
                };

                var driverdetails = modifiedTeams.Select(x => new Team()
                {
                    Driver = x.Driver,
                    Codriver = x.Codriver

                });

                foreach (var item in driverdetails)
                {
                    Driver d = (item.Driver == null) ? allTeams.Select(x => x.Driver).FirstOrDefault() : item.Driver;
                    Driver c = (item.Codriver == null) ? allTeams.Select(x => x.Codriver).FirstOrDefault() : item.Codriver;
                    Console.WriteLine(d.DriverId + " " + c.DriverId);
                    //{D2,C1}
                    //{D1,C1}
                }

            }

You can Write the logic in one query itself. But to make it clear, i've written it in foreach.

Hope this helps


答:
If you include jquery library in your html page then you can do it with jquery easily.</p>

```<code>$(function() {
var color_arr = ['red','green','blue']; //add more color in this array
    $(".shape").hover(
    function() {
        $(this).css('background-color', jQuery.rand(color_arr));
    }, function() {
        $(this).css('background-color', '');
    });
});
(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 1;  // chosen by fair dice roll
        }
    };
})(jQuery);
</code>```

Title: JS & CSS - How to Randomly generate a colour and have it apply to an element on an event?

Body:
If you include jquery library in your html page then you can do it with jquery easily.

$(function() {
var color_arr = ['red','green','blue']; //add more color in this array
    $(".shape").hover(
    function() {
        $(this).css('background-color', jQuery.rand(color_arr));
    }, function() {
        $(this).css('background-color', '');
    });
});
(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 1;  // chosen by fair dice roll
        }
    };
})(jQuery);


问:
Kibana reports a field is conflicting, how can I resolve it?
In Kibana I've noticed after I did an Index Pattern refresh that my one field shows up as conflicted.

Example:

So I understand that this is because Elastic Search found values in that field that are of different types, how can I determine that? It is causing my Visuals to break as they can't work with conflicting fields.
How can I get around this problem for the existing data?

答:
After many hours of playing around and going through the Elastic documentation I have finally found an answer to my problem.

In Elastic Search 5.1 (the version I used) you can re-index those specific Indexes that are "problematic".

You can find this in Kibana by clicking on Management > Index Patterns and looking for the field that shows up as conflicted. Then click on the corresponding pencil icon to look at the field's details. In there is will show the Indexes under the different field types.

I wrote a script in Power-Shell that automated this for me by specifying the "problematic indexes" and then it does the following (let's assume your problematic index is called: log-20170101):

Create a mapping for log-20170101-1

Re-index log-20170101 to log-20170101-1

Delete log-20170101

Create a mapping for log-20170101

Re-index log-20170101-1 to log-20170101

Delete log-20170101-1

Now when you Refresh your Index Patter in Kibana you will notice that the field is no longer conflicted.

You can read up on: Mappings and Re-Indexing

Make sure that when you specify your new mapping below, that you use the appropriate mapping data-types that you are looking for.

You can get an existing mapping by querying the Elastic API with:

```<code>GET /_mapping/<your mapping name>
</code>```

Here is a skeleton (sample) script I did in Power-Shell, it is very basic but I think it can help.

$index_list = @(
    "log-20170101"
)

$index_list  | % {
    $index_name = $_

    $mapping_body = "
    {
        ""mappings"": {
            ""logevent"": {
                ""properties"": {
                    ""@timestamp"": {
                        ""type"": ""date""
                    },
                    ""correlationId"": {
                        ""type"": ""text"",
                        ""fields"": {
                            ""keyword"": {
                                ""type"": ""keyword"",
                                ""ignore_above"": 256
                            }
                        }
                    },
                    ""duration"": {
                        ""properties"": {
                            ""TotalMilliseconds"": {
                                ""type"": ""float""
                            }
                        }
                    }
                }
            }
        }
    }"

    $reindex_body = "{
        ""source"": {
            ""index"": ""$index_name""
        },
        ""dest"": {
            ""index"": ""$index_name-1""
        }
    }"

    $reindex_body_reverse = "{
        ""source"": {
            ""index"": ""$index_name-1""
        },
        ""dest"": {
            ""index"": ""$index_name""
        }
    }"

    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Put -Body $mapping_body
    Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body
    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Delete
    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Put -Body $mapping_body
    Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body_reverse
    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Delete
}
```

EDIT

See this post for how to setup default mappings going forward to try and prevent this problem from happening again.

Body:
After many hours of playing around and going through the Elastic documentation I have finally found an answer to my problem.

In Elastic Search 5.1 (the version I used) you can re-index those specific Indexes that are "problematic".

You can find this in Kibana by clicking on Management > Index Patterns and looking for the field that shows up as conflicted. Then click on the corresponding pencil icon to look at the field's details. In there is will show the Indexes under the different field types.

I wrote a script in Power-Shell that automated this for me by specifying the "problematic indexes" and then it does the following (let's assume your problematic index is called: log-20170101):

Create a mapping for log-20170101-1

Re-index log-20170101 to log-20170101-1

Delete log-20170101

Create a mapping for log-20170101

Re-index log-20170101-1 to log-20170101

Delete log-20170101-1

Now when you Refresh your Index Patter in Kibana you will notice that the field is no longer conflicted.

You can read up on: Mappings and Re-Indexing

Make sure that when you specify your new mapping below, that you use the appropriate mapping data-types that you are looking for.

You can get an existing mapping by querying the Elastic API with:

GET /_mapping/<your mapping name>

Here is a skeleton (sample) script I did in Power-Shell, it is very basic but I think it can help.

$index_list = @(
    "log-20170101"
)

$index_list  | % {
    $index_name = $_

    $mapping_body = "
    {
        ""mappings"": {
            ""logevent"": {
                ""properties"": {
                    ""@timestamp"": {
                        ""type"": ""date""
                    },
                    ""correlationId"": {
                        ""type"": ""text"",
                        ""fields"": {
                            ""keyword"": {
                                ""type"": ""keyword"",
                                ""ignore_above"": 256
                            }
                        }
                    },
                    ""duration"": {
                        ""properties"": {
                            ""TotalMilliseconds"": {
                                ""type"": ""float""
                            }
                        }
                    }
                }
            }
        }
    }"

    $reindex_body = "{
        ""source"": {
            ""index"": ""$index_name""
        },
        ""dest"": {
            ""index"": ""$index_name-1""
        }
    }"

    $reindex_body_reverse = "{
        ""source"": {
            ""index"": ""$index_name-1""
        },
        ""dest"": {
            ""index"": ""$index_name""
        }
    }"

    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Put -Body $mapping_body
    Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body
    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Delete
    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name -Method Put -Body $mapping_body
    Invoke-WebRequest -Uri http://elasticserver:9200/_reindex -Method Post -Body $reindex_body_reverse
    Invoke-WebRequest -Uri http://elasticserver:9200/$index_name-1 -Method Delete
}

EDIT

See this post for how to setup default mappings going forward to try and prevent this problem from happening again.

ContentLicense: CC BY-SA 4.0


问:
Write to existing json file in specific place
I have a json file in which must be added some values which I am getting from another json file. the problem is that I could add anything at the end of the json, but not in the exact place.
My actual json file is:

```<code>{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}
</code>```

I am getting service3 and another-id from another json file Need to add them into destination json file in this way:

```<code>       {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    },
</code>```

after this part:

```<code>"config" : {
    "pipelineConfigs" : [
</code>```

and add the "service3" to "applications" : [ "service1", "service2" ],

The desired final result:

```<code>{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    }, {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    } ],
    "applications" : [ "service1", "service2", "service3" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}
</code>```

Which direction I should dig?

答:
a.py:

```<code>import json
from pprint import pprint as pp

def add_app(obj_dict, app_name, pipeline_config_id):
    new_cfg = {
        "application": app_name,
        "pipelineConfigId": pipeline_config_id,
    }
    obj_dict["config"]["pipelineConfigs"].append(new_cfg)
    obj_dict["config"]["applications"].append(app_name)

def main():
    with open("initial.json") as fin:
        obj = json.load(fin)
    print("INITIAL:\n")
    pp(obj)
    add_app(obj, "service3", "another_id")
    print("\nFINAL:\n")
    pp(obj)
    # EDIT: writing the modified json to file
    with open("final.json", "w") as fout:
        json.dump(obj, fout, indent="  ")

if __name__ == "__main__":
    main()
</code>```

Notes:

I saved your initial json in a file called initial.json which I'm loading using the [Python]: json — JSON encoder and decoder module

2 things needed to do (after loading the file):

Add the application name to the existing applications list

Ad the application config to the existing  pipeline configs list

I'm not doing any error checking

Output:

```<code>c:\Work\Dev\StackOverflow\q47345368>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py
INITIAL:

{'config': {'applications': ['service1', 'service2'],
            'clusters': [{'account': 'some-account',
                          'applications': None,
                          'detail': '*',
                          'stack': '*'}],
            'pipelineConfigs': [{'application': 'service1',
                                 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'},
                                {'application': 'service2',
                                 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'}]},
 'createTs': 1510743534340,
 'email': 'some@email.com',
 'id': 'some-id',
 'lastModifiedBy': 'admin',
 'name': 'some-name',
 'updateTs': 1510750871252}

FINAL:

{'config': {'applications': ['service1', 'service2', 'service3'],
            'clusters': [{'account': 'some-account',
                          'applications': None,
                          'detail': '*',
                          'stack': '*'}],
            'pipelineConfigs': [{'application': 'service1',
                                 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'},
                                {'application': 'service2',
                                 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'},
                                {'application': 'service3',
                                 'pipelineConfigId': 'another_id'}]},
 'createTs': 1510743534340,
 'email': 'some@email.com',
 'id': 'some-id',
 'lastModifiedBy': 'admin',
 'name': 'some-name',
 'updateTs': 1510750871252}
</code>```

Body:
I have a json file in which must be added some values which I am getting from another json file. the problem is that I could add anything at the end of the json, but not in the exact place.
My actual json file is:

{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}

I am getting service3 and another-id from another json file Need to add them into destination json file in this way:

       {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    },

after this part:

"config" : {
    "pipelineConfigs" : [

and add the "service3" to "applications" : [ "service1", "service2" ],

The desired final result:

{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    }, {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    } ],
    "applications" : [ "service1", "service2", "service3" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}

Which direction I should dig?

Body:
a.py:

import json
from pprint import pprint as pp

def add_app(obj_dict, app_name, pipeline_config_id):
    new_cfg = {
        "application": app_name,
        "pipelineConfigId": pipeline_config_id,
    }
    obj_dict["config"]["pipelineConfigs"].append(new_cfg)
    obj_dict["config"]["applications"].append(app_name)

def main():
    with open("initial.json") as fin:
        obj = json.load(fin)
    print("INITIAL:\n")
    pp(obj)
    add_app(obj, "service3", "another_id")
    print("\nFINAL:\n")
    pp(obj)
    # EDIT: writing the modified json to file
    with open("final.json", "w") as fout:
        json.dump(obj, fout, indent="  ")

if __name__ == "__main__":
    main()

Notes:

I saved your initial json in a file called initial.json which I'm loading using the [Python]: json — JSON encoder and decoder module

2 things needed to do (after loading the file):

Add the application name to the existing applications list

Ad the application config to the existing  pipeline configs list

I'm not doing any error checking

Output:

c:\Work\Dev\StackOverflow\q47345368>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py
INITIAL:

{'config': {'applications': ['service1', 'service2'],
            'clusters': [{'account': 'some-account',
                          'applications': None,
                          'detail': '*',
                          'stack': '*'}],
            'pipelineConfigs': [{'application': 'service1',
                                 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'},
                                {'application': 'service2',
                                 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'}]},
 'createTs': 1510743534340,
 'email': 'some@email.com',
 'id': 'some-id',
 'lastModifiedBy': 'admin',
 'name': 'some-name',
 'updateTs': 1510750871252}

FINAL:

{'config': {'applications': ['service1', 'service2', 'service3'],
            'clusters': [{'account': 'some-account',
                          'applications': None,
                          'detail': '*',
                          'stack': '*'}],
            'pipelineConfigs': [{'application': 'service1',
                                 'pipelineConfigId': 'd2eb526c-839b-41b3-b59c-f86db6eebb4e'},
                                {'application': 'service2',
                                 'pipelineConfigId': 'f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7'},
                                {'application': 'service3',
                                 'pipelineConfigId': 'another_id'}]},
 'createTs': 1510743534340,
 'email': 'some@email.com',
 'id': 'some-id',
 'lastModifiedBy': 'admin',
 'name': 'some-name',
 'updateTs': 1510750871252}