问:
Replace some words in string, but keep another
I'm trying to replace some words in string, so we have an encoded string:

%3Cscript%20async%20src%3D%22%2F%2Fpagead2.googlesyndication.com%2F%25dontreplace%25%2Fjs%2Fadsbygoogle.js%22%3E%3C%2Fscript%3E%0A%3Cins%20class%3D%E2%80%9C%25dontreplace%25%22%0Astyle%3D%22display%3Ainline-block%3Bwidth%3A300px%3Bheight%3A250px%22%0Adata-ad-client%3D%22ca-pub-xxxxxxxxxxxxxxxxxxxx%22%0Adata-ad-slot%3D%22yyyyyyyyyyyy%E2%80%9D%3E%0Aparams%20%3D%20%7B%0Apuid1%3A%E2%80%99%25replace1%25%E2%80%99%2C%0Apuid2%3A%E2%80%99%25replace2%25%27%2C%0Apuid3%3A%27%25replace3%25%27%0A%0A%7D

And there are a few words in it:

%25dontreplace%25

%25dontreplace%25

%25replace1%25

%25replace2%25

%25replace3%25

I need to replace all %25replaceX%25 with %replaceX%, but do not touch all %25dontreplace%25 (there can be different quantity of each)

I'm trying to split it into array and do some ifelse statements, but it doesn't seem to work and I don't think it's the most elegant:

var x = "%3Cscript%20async%20src%3D%22%2F%2Fpagead2.googlesyndication.com%2F%25dontreplace%25%2Fjs%2Fadsbygoogle.js%22%3E%3C%2Fscript%3E%0A%3Cins%20class%3D%E2%80%9C%25dontreplace%25%22%0Astyle%3D%22display%3Ainline-block%3Bwidth%3A300px%3Bheight%3A250px%22%0Adata-ad-client%3D%22ca-pub-xxxxxxxxxxxxxxxxxxxx%22%0Adata-ad-slot%3D%22yyyyyyyyyyyy%E2%80%9D%3E%0Aparams%20%3D%20%7B%0Apuid1%3A%E2%80%99%25replace1%25%E2%80%99%2C%0Apuid2%3A%E2%80%99%25replace2%25%27%2C%0Apuid3%3A%27%25replace3%25%27%0A%0A%7D";
    console.log(x);
    var y = x.split(/(%25)/);
    console.log(y);
    var n = [];
    for (var i = 0; i <= y.length; i++) {
    if (y[i].indexOf('%25') >= 0) {
            if (y[i + 1].indexOf('request.puid') >= 0) {
            n.push('%'+y[i]+'%');
            console.log(n);
        }
    } else {
          if (y[i - 1] === undefined && y[i + 1] === '%25') {
             n.push(y[i]);
             console.log(n);
          } else if (y[i - 1] === '%25' && y[i + 1] === undefined) {
             n.push(y[i]);
             console.log(n);
          } else if (y[i - 1] === '%25' && y[i + 1] === '%25') {
             n.push('%25'+y[i]+'%25');
             console.log(n);
          }
        }
    }```

Is there an elegant way to solve this problem?

答:
You can use .replace with a RegExp using capture groups.

The RegExp we'll use is RegExp(/%25replace([0-9]*)%25/, 'g') which finds strings matching %25replaceX%25 and the g finds all matches. The () captures the number so we can use it in the replacement text.

Something like this:

var str = "%3Cscript%20async%20src%3D%22%2F%2Fpagead2.googlesyndication.com%2F%25dontreplace%25%2Fjs%2Fadsbygoogle.js%22%3E%3C%2Fscript%3E%0A%3Cins%20class%3D%E2%80%9C%25dontreplace%25%22%0Astyle%3D%22display%3Ainline-block%3Bwidth%3A300px%3Bheight%3A250px%22%0Adata-ad-client%3D%22ca-pub-xxxxxxxxxxxxxxxxxxxx%22%0Adata-ad-slot%3D%22yyyyyyyyyyyy%E2%80%9D%3E%0Aparams%20%3D%20%7B%0Apuid1%3A%E2%80%99%25replace1%25%E2%80%99%2C%0Apuid2%3A%E2%80%99%25replace2%25%27%2C%0Apuid3%3A%27%25replace3%25%27%0A%0A%7D";

var newStr = str.replace(new RegExp(/%25replace([0-9]*)%25/, 'g'), "%replace$1%");

document.write(newStr)```

Body:
I'm trying to replace some words in string, so we have an encoded string:

%3Cscript%20async%20src%3D%22%2F%2Fpagead2.googlesyndication.com%2F%25dontreplace%25%2Fjs%2Fadsbygoogle.js%22%3E%3C%2Fscript%3E%0A%3Cins%20class%3D%E2%80%9C%25dontreplace%25%22%0Astyle%3D%22display%3Ainline-block%3Bwidth%3A300px%3Bheight%3A250px%22%0Adata-ad-client%3D%22ca-pub-xxxxxxxxxxxxxxxxxxxx%22%0Adata-ad-slot%3D%22yyyyyyyyyyyy%E2%80%9D%3E%0Aparams%20%3D%20%7B%0Apuid1%3A%E2%80%99%25replace1%25%E2%80%99%2C%0Apuid2%3A%E2%80%99%25replace2%25%27%2C%0Apuid3%3A%27%25replace3%25%27%0A%0A%7D

And there are a few words in it:

%25dontreplace%25

%25dontreplace%25

%25replace1%25

%25replace2%25

%25replace3%25

I need to replace all %25replaceX%25 with %replaceX%, but do not touch all %25dontreplace%25 (there can be different quantity of each)

I'm trying to split it into array and do some ifelse statements, but it doesn't seem to work and I don't think it's the most elegant:

var x = "%3Cscript%20async%20src%3D%22%2F%2Fpagead2.googlesyndication.com%2F%25dontreplace%25%2Fjs%2Fadsbygoogle.js%22%3E%3C%2Fscript%3E%0A%3Cins%20class%3D%E2%80%9C%25dontreplace%25%22%0Astyle%3D%22display%3Ainline-block%3Bwidth%3A300px%3Bheight%3A250px%22%0Adata-ad-client%3D%22ca-pub-xxxxxxxxxxxxxxxxxxxx%22%0Adata-ad-slot%3D%22yyyyyyyyyyyy%E2%80%9D%3E%0Aparams%20%3D%20%7B%0Apuid1%3A%E2%80%99%25replace1%25%E2%80%99%2C%0Apuid2%3A%E2%80%99%25replace2%25%27%2C%0Apuid3%3A%27%25replace3%25%27%0A%0A%7D";
    console.log(x);
    var y = x.split(/(%25)/);
    console.log(y);
    var n = [];
    for (var i = 0; i <= y.length; i++) {
    if (y[i].indexOf('%25') >= 0) {
            if (y[i + 1].indexOf('request.puid') >= 0) {
            n.push('%'+y[i]+'%');
            console.log(n);
        }
    } else {
          if (y[i - 1] === undefined && y[i + 1] === '%25') {
             n.push(y[i]);
             console.log(n);
          } else if (y[i - 1] === '%25' && y[i + 1] === undefined) {
             n.push(y[i]);
             console.log(n);
          } else if (y[i - 1] === '%25' && y[i + 1] === '%25') {
             n.push('%25'+y[i]+'%25');
             console.log(n);
          }
        }
    }

Is there an elegant way to solve this problem?


来源: stackexchange

问:
Why doesn't this "is not" if statement work?
This is my code,

```<code>if diff != "1" or diff != "2" or diff != "3":
            print("You need to pick either 1, 2 or 3\n")
</code>```

For some reason, the outcome is,

```<code>Pick a difficulty:
1) Easy
2) Medium
3) Hard
>> 2
You need to pick either 1, 2 or 3
</code>```

I want the if statement to check if the variable diff is not equal to strings 1, 2 and 3. But when I put either 1, 2 or 3, the error message for when diff doesn't equal the numbers prints instead. Why does this happen?

答:
You need to use and instead of or.  If you input 1, then diff != "1" returns True.

Your code should look like this:

```<code>if diff != "1" and diff != "2" and diff != "3":
            print("You need to pick either 1, 2 or 3\n")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my code,

if diff != "1" or diff != "2" or diff != "3":
            print("You need to pick either 1, 2 or 3\n")

For some reason, the outcome is,

Pick a difficulty:
1) Easy
2) Medium
3) Hard
>> 2
You need to pick either 1, 2 or 3

I want the if statement to check if the variable diff is not equal to strings 1, 2 and 3. But when I put either 1, 2 or 3, the error message for when diff doesn't equal the numbers prints instead. Why does this happen?

Body:
You need to use and instead of or.  If you input 1, then diff != "1" returns True.

Your code should look like this:

if diff != "1" and diff != "2" and diff != "3":
            print("You need to pick either 1, 2 or 3\n")


问:
aws-sdk-php v3.44 fails to sendMessage to SQS FIFO Queue: MessageGroupId missing?
I am using the Amazon SDK for PHP version 3.44 (released 2017-11-30). I can connect to my Amazon SQS account and execute the listQueues(), getQueueUrl(), getQueueAttributes(), and receiveMessage() commands just fine. However, the sendMessage() command consistently fails with the following message:

The request must contain the parameter MessageGroupId.

I am most definitely including this parameter. It doesn't seem to matter which version of the aws-sdk-php API I use, this message keeps coming back. Here is my code:

```<code>$queue = SqsClient::factory([
    'profile'     => $profile,
    'region'      => $region,
    'version'     => '2012-11-05',
    'credentials' => $credentials,
]);
$queue_list = $queue->listQueues(); // ok
$url        = $queue->getQueueUrl(['QueueName'=>$queue_name]); // ok
$received   = $queue->receiveMessage(['QueueUrl'=>$url->get('QueueUrl')]); // ok
$response   = $queue->sendMessage([
    'MessageBody'    => $message,
    'MessageGroupId' => $message_group_id,
    'QueueUrl'       => $url->get('QueueUrl'),
]); // fails with message indicating MessageGroupId is missing
</code>```

I have spent several hours searching for a working example of sending a message up to an Amazon SQS FIFO queue through the PHP SDK, and am beginning to believe this is not possible. Has anybody out there been able to get the aws-sdk-php library to work with an SQS FIFO queue?

答:
The first line is creating an instance of SqsClient, not creating a SQS queue.  You still still need to call $queue->createQueue.  See the documentation.  For fifo queues, you will need to enable "FifoQueue" to "true", and set up the "ContentBasedDeduplication" when creating the queue.  When you send your message, depending on the ContentBasedDeduplication setting of the queue you created, you may or may not also need to send a "MessageDeduplicationId" along with the "MessageGroupId".

From your code, I can't see how you created the Queue.

Did you enable fifo queues with the property "FifoQueue" => "true"

Did you set "ContentBasedDeduplication" to "true" or "false" ?

Did you name your queue with the extension ".fifo" ?

I did all of these things, and configured my queue with ContentBasedDeduplication set to "false".  When I send a message, the only other property that I'm sending that you aren't (along with the MessageGroupId) is MessageDeduplicationId.  I'm able to send messages to the fifo queue just fine using sdk 3.44.

Body:
I am using the Amazon SDK for PHP version 3.44 (released 2017-11-30). I can connect to my Amazon SQS account and execute the listQueues(), getQueueUrl(), getQueueAttributes(), and receiveMessage() commands just fine. However, the sendMessage() command consistently fails with the following message:

The request must contain the parameter MessageGroupId.

I am most definitely including this parameter. It doesn't seem to matter which version of the aws-sdk-php API I use, this message keeps coming back. Here is my code:

$queue = SqsClient::factory([
    'profile'     => $profile,
    'region'      => $region,
    'version'     => '2012-11-05',
    'credentials' => $credentials,
]);
$queue_list = $queue->listQueues(); // ok
$url        = $queue->getQueueUrl(['QueueName'=>$queue_name]); // ok
$received   = $queue->receiveMessage(['QueueUrl'=>$url->get('QueueUrl')]); // ok
$response   = $queue->sendMessage([
    'MessageBody'    => $message,
    'MessageGroupId' => $message_group_id,
    'QueueUrl'       => $url->get('QueueUrl'),
]); // fails with message indicating MessageGroupId is missing

I have spent several hours searching for a working example of sending a message up to an Amazon SQS FIFO queue through the PHP SDK, and am beginning to believe this is not possible. Has anybody out there been able to get the aws-sdk-php library to work with an SQS FIFO queue?


问:
Installing SSL Module for Python (2.5.4) on Windows
since AppEngine requires to upload your apps via SSL I tried to install the module on my working laptop.

It is a x64 Win 7 System with Python 2.5.4 x86 installed.

I followed guides such as this one: How to install Python ssl module on Windows?
and also all related links.

But the major problem is, that neither MinGw nor GnuWin seems to really work.

GnuWin is perfectly installed, up to date and has all dependencies it needs to build the SSL module.

But typing in

```<code>> "C:\Python25\python.py" setup.py install -c mingw32
</code>```

just badly fails.
So does "-cmingw32" and "-gnuwin32".
(-cmingw32 obviously fails, because even though MinGW is fully installed MinGw is not regcognized)

"build" instead of install seems to "output" something:
MinGw complains about "ggc no such file or directory", and with GnuWin "it doesn't know how to compile C/C++ on a nt with gnuwin"

This sounds like total garbage to me, because I did everything as described in the tutorials.

I fixed one part of my problem: gcc is now getting recognized by easy_install but AE still complains about the missing SSL module though both, easy_install and python say Pycrypto incl. SSL is successfully installed

easy_install ssl

```<code>C:\Users\faits>easy_install ssl
Searching for ssl
Best match: ssl 1.15
Adding ssl 1.15 to easy-install.pth file

Using c:\python25\lib\site-packages
Processing dependencies for ssl
Finished processing dependencies for ssl
</code>```

easy_install pycrypto

```<code>C:\Users\faits>easy_install ssl
Searching for ssl
Best match: ssl 1.15
Adding ssl 1.15 to easy-install.pth file

Using c:\python25\lib\site-packages
Processing dependencies for ssl
Finished processing dependencies for ssl
</code>```

python

```<code>IDLE 1.2.4
>>> import ssl

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import ssl
  File "C:\Python25\lib\site-packages\ssl\__init__.py", line 61, in <module>
    import _ssl2             # if we can't import it, let the error propagate
ImportError: No module named _ssl2
</code>```

python

```<code>>>> import pycrypto

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import pycrypto
ImportError: No module named pycrypto
</code>```

答:
Use -c with the build command.

Compare:

$ python setup.py install -c

```<code>--compile (-c)     compile .py to .pyc [default]
</code>```

with:

$ python setup.py build -c

```<code>--compiler (-c)    specify the compiler type
</code>```

To find out other options , run:

$ python setup.py build --help

ContentLicense: CC BY-SA 2.5

Body:
since AppEngine requires to upload your apps via SSL I tried to install the module on my working laptop.

It is a x64 Win 7 System with Python 2.5.4 x86 installed.

I followed guides such as this one: How to install Python ssl module on Windows?
and also all related links.

But the major problem is, that neither MinGw nor GnuWin seems to really work.

GnuWin is perfectly installed, up to date and has all dependencies it needs to build the SSL module.

But typing in

> "C:\Python25\python.py" setup.py install -c mingw32

just badly fails.
So does "-cmingw32" and "-gnuwin32".
(-cmingw32 obviously fails, because even though MinGW is fully installed MinGw is not regcognized)

"build" instead of install seems to "output" something:
MinGw complains about "ggc no such file or directory", and with GnuWin "it doesn't know how to compile C/C++ on a nt with gnuwin"

This sounds like total garbage to me, because I did everything as described in the tutorials.

I fixed one part of my problem: gcc is now getting recognized by easy_install but AE still complains about the missing SSL module though both, easy_install and python say Pycrypto incl. SSL is successfully installed

easy_install ssl

C:\Users\faits>easy_install ssl
Searching for ssl
Best match: ssl 1.15
Adding ssl 1.15 to easy-install.pth file

Using c:\python25\lib\site-packages
Processing dependencies for ssl
Finished processing dependencies for ssl

easy_install pycrypto

C:\Users\faits>easy_install ssl
Searching for ssl
Best match: ssl 1.15
Adding ssl 1.15 to easy-install.pth file

Using c:\python25\lib\site-packages
Processing dependencies for ssl
Finished processing dependencies for ssl

python

IDLE 1.2.4
>>> import ssl

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import ssl
  File "C:\Python25\lib\site-packages\ssl\__init__.py", line 61, in <module>
    import _ssl2             # if we can't import it, let the error propagate
ImportError: No module named _ssl2

python

>>> import pycrypto

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import pycrypto
ImportError: No module named pycrypto

Body:
Use -c with the build command.

Compare:

$ python setup.py install -c

--compile (-c)     compile .py to .pyc [default]

with:

$ python setup.py build -c

--compiler (-c)    specify the compiler type

To find out other options , run:

$ python setup.py build --help


问:
Display json data from a javascript file to html list
I have the following javascript/json array and would like to display it as an html list but im stuck:

```<code>    var myFunction = function() {
        var myList = [
            {
                'name': 'Emely',
            },
            {
                'name': 'John',
            },
            {
                'name': 'Stewart',
            }
        ];
    var dataObject = JSON.parse(myList);
    var listItemString = $('#listItem').html();
    dataObject.forEach(buildNewList);
    function buildNewList(item, index) {
        var listItem = $('<li>' + listItemString + '</li>');
        var listItemTitle = $('.title', listItem);
        listItemTitle.html(item.name);
        $('#mydatalist').append(listItem);
    }
  };
</code>```

i am not sure what im doing wrong.Ive been trying for three hours now.

my html is as follows:

```<code><div id="listItem">
  <div class="row1">
    <div class="title"></div>
  </div>
</div>
</code>```

but my list is still not displaying

答:
try this</p>

```<code>function buildNewList(item, index) {
    var listItem = $('<li><div class="row1"><div class="title">' + item+ '</div></div></li>');
    $('#mydatalist').append(listItem);
}

var myFunction = function() {
    var myList = '[
        {
            "name": "Emely"
        },
        {
            "name": "John"
        },
        {
            "name": "Stewart"
        }
    ]';
    var dataObject = JSON.parse(myList);
    var listItemString = $('#listItem').html();

    dataObject.forEach(buildNewList);

};
</code>```

Body:
I have the following javascript/json array and would like to display it as an html list but im stuck:

    var myFunction = function() {
        var myList = [
            {
                'name': 'Emely',
            },
            {
                'name': 'John',
            },
            {
                'name': 'Stewart',
            }
        ];
    var dataObject = JSON.parse(myList);
    var listItemString = $('#listItem').html();
    dataObject.forEach(buildNewList);
    function buildNewList(item, index) {
        var listItem = $('
' + listItemString + '
');
        var listItemTitle = $('.title', listItem);
        listItemTitle.html(item.name);
        $('#mydatalist').append(listItem);
    }
  };

i am not sure what im doing wrong.Ive been trying for three hours now.

my html is as follows:

but my list is still not displaying

Body:
try this

function buildNewList(item, index) {
    var listItem = $('<li><div class="row1"><div class="title">' + item+ '</div></div></li>');
    $('#mydatalist').append(listItem);
}

var myFunction = function() {
    var myList = '[
        {
            "name": "Emely"
        },
        {
            "name": "John"
        },
        {
            "name": "Stewart"
        }
    ]';
    var dataObject = JSON.parse(myList);
    var listItemString = $('#listItem').html();

    dataObject.forEach(buildNewList);

};


问:
Using Gsub to get matched strings in R - regular expression
I am trying to extract words after the first space using

species<-gsub(".* ([A-Za-z]+)", "\1", x=genus)

This works fine for the other rows that have two words, however row [9] "Eulamprus tympanum marnieae" has 3 words and my code is only returning the last word in the string "marnieae". How can I extract the words after the first space so I can retrieve "tympanum marnieae" instead of "marnieae" but have the answers stored in one variable called >species.

genus

[9] "Eulamprus tympanum marnieae"

答:
Your original pattern didn't work because the subpattern [A-Za-z]+ doesn't match spaces, and therefore will only match a single word.

You can use the following pattern to match any number of words (other than 0) after the first, within double quotes:

"[A-Za-z]+ ([A-Za-z ]+)" https://regex101.com/r/p6ET3I/1

https://regex101.com/r/p6ET3I/2

This is a relatively simple, but imperfect, solution. It will also match trailing spaces, or just one or more spaces after the first word even if a second word doesn't exist. "Eulamprus      " for example will successfully match the pattern, and return 5 spaces. You should only use this pattern if you trust your data to be properly formatted.

A more reliable approach would be the following:

"[A-Za-z]+ ([A-Za-z]+(?: [A-Za-z]+)*)"

https://regex101.com/r/p6ET3I/3

This pattern will capture one word (following the first), followed by any number of addition words (including 0), separated by spaces.

However, from what I remember from biology class, species are only ever comprised of one or two names, and never capitalized. The following pattern will reflect this format:

"[A-Za-z]+ ([a-z]+(?: [a-z]+)?)"

https://regex101.com/r/p6ET3I/4


问:
Android Studio all gms/firebase libaries must use the exact same version
This is my Gradle:app file

Error I get when I try to rebuild:
"All gms/firebase libaries must use the exact same version specification. Found versions 11.6.0, 10.2.0. Examples include com.google.android.gms:play-services-auth:11.6.0 and com.google.android.gms:play-services-location:10.2.0"

Anyone know how to get rid of the error?

答:
I also had same error for the dependency version:

```<code>compile com.google.firebase:firebase-core:11.6.2'
</code>```

I resolved it by adding this missing dependency:

```<code>compile 'com.google.android.gms:play-services:11.6.2'
</code>```

Body:
I also had same error for the dependency version:

compile com.google.firebase:firebase-core:11.6.2'

I resolved it by adding this missing dependency:

compile 'com.google.android.gms:play-services:11.6.2'


问:
How to "Decompile" a Bookmarklet?
We all know that bookmarklets are nothing but some
executable javascript code that do some things for us
when we click on them depending on the function that they
are intended to do... My Question is:

For example, I have a Bookmarklet, don't know, something like this one:

```<code>javascript:void(window.open('http://www.pdfdownload.org/web2pdf/Default.aspx?left=0&right=0&top=0&bottom=0&page=0&cURL='+document.location.href));
</code>```

As far as I understand, the bookmarklet code (with the "&cURL=" thing) takes the URL that is in the adress bar of the browser and then do something with it in order to get a result. Something similar can be done with a selection, by changing some parameters in the bookmarklet (Like with the "Search selection in Google Maps" one) and some others.

How can I "decompile" a bookmarklet in order to make it take the desired data (in this case an URL) from a form?

For example, let's say I want to use the above bookmarklet in a webpage to provide a form that let's the user input a URL and then click a button to get the result.

I've seen other bookmarklets that get the URL from a "?input=" and others from a "?url="

How can I pass bookmarklet's functions to a form?

答:
Try something like this:</p>

```<code><form method="get" action="http://www.pdfdownload.org/web2pdf/Default.aspx">
<input type="hidden" name="left" value="0">
<input type="hidden" name="right" value="0">
<input type="hidden" name="top" value="0">
<input type="hidden" name="bottom" value="0">
<input type="hidden" name="page" value="0">
<input type="text" name="cURL">
<input type="submit">
</form>
</code>```

Title: How to "Decompile" a Bookmarklet?

Body:
We all know that bookmarklets are nothing but some
executable javascript code that do some things for us
when we click on them depending on the function that they
are intended to do... My Question is:

For example, I have a Bookmarklet, don't know, something like this one:

javascript:void(window.open('http://www.pdfdownload.org/web2pdf/Default.aspx?left=0&right=0&top=0&bottom=0&page=0&cURL='+document.location.href));

As far as I understand, the bookmarklet code (with the "&cURL=" thing) takes the URL that is in the adress bar of the browser and then do something with it in order to get a result. Something similar can be done with a selection, by changing some parameters in the bookmarklet (Like with the "Search selection in Google Maps" one) and some others.

How can I "decompile" a bookmarklet in order to make it take the desired data (in this case an URL) from a form?

For example, let's say I want to use the above bookmarklet in a webpage to provide a form that let's the user input a URL and then click a button to get the result.

I've seen other bookmarklets that get the URL from a "?input=" and others from a "?url="

How can I pass bookmarklet's functions to a form?

Body:
Try something like this:

<form method="get" action="http://www.pdfdownload.org/web2pdf/Default.aspx">
<input type="hidden" name="left" value="0">
<input type="hidden" name="right" value="0">
<input type="hidden" name="top" value="0">
<input type="hidden" name="bottom" value="0">
<input type="hidden" name="page" value="0">
<input type="text" name="cURL">
<input type="submit">
</form>


问:
Convert integer to equivalent number of blank spaces
I was wondering what the easiest way is to convert an integer to the equivalent number of blank spaces. I need it for the spaces between nodes when printing a binary search tree. I tried this

```<code>  int position = printNode.getPosition();
  String formatter = "%1"+position+"s%2$s\n";
  System.out.format(formatter, "", node.element);
</code>```

But I am getting almost 3 times as many spaces compared to the int value of position. I'm not really sure if I am formatting the string right either.
Any suggestions would be great!
If it makes it clearer, say position = 6; I want 6 blank spaces printed before my node element.

答:
If one were going to use an iterative solution anyway, one might want to do it a more "Groovy" way, like:

```<code>def spaces=6
print ((1..spaces).collect(" ").join())
</code>```

Note that this doesn't work for zero spaces.  for that you might want something more like:

```<code>print (spaces?(1..spaces).collect(" ").join():"")
</code>```

Body:
I was wondering what the easiest way is to convert an integer to the equivalent number of blank spaces. I need it for the spaces between nodes when printing a binary search tree. I tried this

  int position = printNode.getPosition();
  String formatter = "%1"+position+"s%2$s\n";
  System.out.format(formatter, "", node.element);

But I am getting almost 3 times as many spaces compared to the int value of position. I'm not really sure if I am formatting the string right either.
Any suggestions would be great!
If it makes it clearer, say position = 6; I want 6 blank spaces printed before my node element.

Body:
If one were going to use an iterative solution anyway, one might want to do it a more "Groovy" way, like:

def spaces=6
print ((1..spaces).collect(" ").join())

Note that this doesn't work for zero spaces.  for that you might want something more like:

print (spaces?(1..spaces).collect(" ").join():"")


问:
Angular 5 webpack 3 aot builds
we recently upgraded to angular 5 from angular 4. We also upgraded to webpack 3. Managed to get our aot builds to work by getting rid of main.aot.ts and pointing the to main.ts directly but we are unable to load the build. We see 'AppService is not defined' error. Can someone please help?

main.ts

```<code>import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

webpack.config.js

```<code>module.exports = {
bail: true,
resolve: {
    extensions: ['.js', '.ts'],
    alias: {
        jquery: "jquery/src/jquery"
    }
},

entry: {
    'app': './app/main.ts',
},
output: {
    path: './compiled',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
},

plugins: [
    new ngToolsWebpack.AngularCompilerPlugin({
        tsConfigPath: './tsaotconfig.json',
        entryModule: __dirname + '/../app/app.module#AppModule'
    }),
  ]
}
</code>```

error

```<code>Uncaught ReferenceError: AppService is not defined
at e.ctorParameters (http://localhost:4200/bundle/app.js:1:915567)
at e._ownParameters (http://localhost:4200/bundle/app.js:1:60309)
at e.parameters (http://localhost:4200/bundle/app.js:1:60727)
at e.parameters (http://localhost:4200/bundle/app.js:1:1250184)
at e._getDependenciesMetadata (http://localhost:4200/bundle/app.js:1:1439376)
at e._getTypeMetadata (http://localhost:4200/bundle/app.js:1:1438259)
at e.getNonNormalizedDirectiveMetadata (http://localhost:4200/bundle/app.js:1:1431328)
at e._getEntryComponentMetadata (http://localhost:4200/bundle/app.js:1:1442081)
at http://localhost:4200/bundle/app.js:1:1441836
at Array.forEach (native)
</code>```

答:
I was able to make a sample angular5 app build in AOT

https://github.com/tomalex0/angularx-aot-jit

I created a sample angular5 app which generates AOT and JIT, might not be in same structure as yours but works

https://github.com/tomalex0/angularx-aot-jit

This commit difference will give better picture of what all i changed while updating to angular5
https://github.com/tomalex0/angularx-aot-jit/commit/1435fddf1a6336f05e63f30062cb4cd2d0ba771f

tsconfig-aot.json for angular5

```<code>{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "noImplicitAny": false,
    "sourceMap": true,
    "mapRoot": "",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "outDir": "aot",
    "skipLibCheck": true,
    "rootDir": "."
  }
}
</code>```

No longer needs "angularCompilerOptions": {"genDir": "aot" }|

in webpack config make entry as entry: './js/ng2/app/main.jit.ts'

in webpack  const { AngularCompilerPlugin } = require('@ngtools/webpack'); and in plugins as new AngularCompilerPlugin({tsConfigPath: './tsconfig-aot.json', entryModule: ...})

Title: Angular 5 webpack 3 aot builds

Body:
we recently upgraded to angular 5 from angular 4. We also upgraded to webpack 3. Managed to get our aot builds to work by getting rid of main.aot.ts and pointing the to main.ts directly but we are unable to load the build. We see 'AppService is not defined' error. Can someone please help?

main.ts

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

webpack.config.js

module.exports = {
bail: true,
resolve: {
    extensions: ['.js', '.ts'],
    alias: {
        jquery: "jquery/src/jquery"
    }
},

entry: {
    'app': './app/main.ts',
},
output: {
    path: './compiled',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
},

plugins: [
    new ngToolsWebpack.AngularCompilerPlugin({
        tsConfigPath: './tsaotconfig.json',
        entryModule: __dirname + '/../app/app.module#AppModule'
    }),
  ]
}

error

Uncaught ReferenceError: AppService is not defined
at e.ctorParameters (http://localhost:4200/bundle/app.js:1:915567)
at e._ownParameters (http://localhost:4200/bundle/app.js:1:60309)
at e.parameters (http://localhost:4200/bundle/app.js:1:60727)
at e.parameters (http://localhost:4200/bundle/app.js:1:1250184)
at e._getDependenciesMetadata (http://localhost:4200/bundle/app.js:1:1439376)
at e._getTypeMetadata (http://localhost:4200/bundle/app.js:1:1438259)
at e.getNonNormalizedDirectiveMetadata (http://localhost:4200/bundle/app.js:1:1431328)
at e._getEntryComponentMetadata (http://localhost:4200/bundle/app.js:1:1442081)
at http://localhost:4200/bundle/app.js:1:1441836
at Array.forEach (native)

Body:
I was able to make a sample angular5 app build in AOT

https://github.com/tomalex0/angularx-aot-jit

I created a sample angular5 app which generates AOT and JIT, might not be in same structure as yours but works

https://github.com/tomalex0/angularx-aot-jit

This commit difference will give better picture of what all i changed while updating to angular5
https://github.com/tomalex0/angularx-aot-jit/commit/1435fddf1a6336f05e63f30062cb4cd2d0ba771f

tsconfig-aot.json for angular5

{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "noImplicitAny": false,
    "sourceMap": true,
    "mapRoot": "",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "outDir": "aot",
    "skipLibCheck": true,
    "rootDir": "."
  }
}

No longer needs "angularCompilerOptions": {"genDir": "aot" }|

in webpack config make entry as entry: './js/ng2/app/main.jit.ts'

in webpack  const { AngularCompilerPlugin } = require('@ngtools/webpack'); and in plugins as new AngularCompilerPlugin({tsConfigPath: './tsconfig-aot.json', entryModule: ...})


问:
Array indexOf() vs includes() perfomance depending on browser and needle position
Is there any advantage to Array.prototype.includes() over Array.prototype.indexOf() depending on browsers (Chrome, Firefox) and needle item position (at the begging, middle, ending of the array)?

Array.prototype.includes vs. Array.prototype.indexOf
There is no browser specific information, there is no position in the array specific information, and I don't ask about NaN value.

答:
I made a test using array with 10 000 numeric values, here is results:

Chrome:

beginning

includes (22,043,904 ops/sec)

indexOf (136,512,737 ops/sec)

middle

includes (8,361 ops/sec)

indexOf (31,296 ops/sec)

ending

includes (4,018 ops/sec)

indexOf (95,221 ops/sec)

Firefox:

beginning

includes (34,087,623 ops/sec)

indexOf (33,196,839 ops/sec)

middle

includes (84,880 ops/sec)

indexOf (86,612 ops/sec)

ending

includes (25,253 ops/sec)

indexOf (14,994 ops/sec)

So, indexOf() in Chrome works much faster than includes() in all positions.

In Firefox both indexOf() and includes() works almost similar.

ContentLicense: CC BY-SA 4.0


问:
PHP fopen does not working with directory variable
I have a php code that it creates a random name, then creates the directory, and then I need to create and write a text file inside the directory.
It creates the directory, but nothing when it need to create the text file.
This is what I have:

This create the random name

```<code>$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));
</code>```

This join all the characters:

```<code>$letras = $letra1 . $letra2 . $letra3 . $letra4;
</code>```

This creates de directory:

```<code>mkdir("a/$letras", 777);
</code>```

And here, where i think I have the problem, the fopen:

```<code>$archt = fopen("a/$letras/text.txt", "w") or die("");
$txt = "";
fclose($archt);
</code>```

I think it isn't a perms problem, I have given 777 to all directories...

I have tried a lot of stuf that I have been searched from stackoverflow but nothing is working for me and don't know what it will be?

答:
As I stated in my comment to the questions: you are passing a decimal to the mkdir function as apposed to passing an octal which is what is required. The permissions are not being set correctly as a result.

With the interpreter (php) setup correctly for a development environment your code produced the following error:

PHP Warning:  fopen(a/DeOq/text.txt): failed to open stream:
  Permission denied in /home/dave/Desktop/test/test.php on line 11

To avoid having to dig through comments for details:

The mkdir() documentation here: http://php.net/manual/en/function.mkdir.php refers to the chmod() directory for explanation of mode. Mode is required to be an octal

Note that mode is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix mode with a zero (0). Strings such as "g+w" will not work properly.

http://php.net/manual/en/function.chmod.php

In addition to changing 777 to 0777 in the mkdir() function, ensure that the "a" directory actually exists as the mkdir() function will not make a directory "tree". "a" is required to already exist in order to make a directory under it.

This code is tested and works:

```<code><?php
$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));

$letras = $letra1 . $letra2 . $letra3 . $letra4;

mkdir("a/$letras", 0777);

$archt = fopen("a/$letras/text.txt", "w") or die("Death");
$txt = "";
fclose($archt);
</code>```

Body:
I have a php code that it creates a random name, then creates the directory, and then I need to create and write a text file inside the directory.
It creates the directory, but nothing when it need to create the text file.
This is what I have:

This create the random name

$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));

This join all the characters:

$letras = $letra1 . $letra2 . $letra3 . $letra4;

This creates de directory:

mkdir("a/$letras", 777);

And here, where i think I have the problem, the fopen:

$archt = fopen("a/$letras/text.txt", "w") or die("");
$txt = "";
fclose($archt);

I think it isn't a perms problem, I have given 777 to all directories...

I have tried a lot of stuf that I have been searched from stackoverflow but nothing is working for me and don't know what it will be?

Body:
As I stated in my comment to the questions: you are passing a decimal to the mkdir function as apposed to passing an octal which is what is required. The permissions are not being set correctly as a result.

With the interpreter (php) setup correctly for a development environment your code produced the following error:

PHP Warning:  fopen(a/DeOq/text.txt): failed to open stream:
  Permission denied in /home/dave/Desktop/test/test.php on line 11

To avoid having to dig through comments for details:

The mkdir() documentation here: http://php.net/manual/en/function.mkdir.php refers to the chmod() directory for explanation of mode. Mode is required to be an octal

Note that mode is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix mode with a zero (0). Strings such as "g+w" will not work properly.

http://php.net/manual/en/function.chmod.php

In addition to changing 777 to 0777 in the mkdir() function, ensure that the "a" directory actually exists as the mkdir() function will not make a directory "tree". "a" is required to already exist in order to make a directory under it.

This code is tested and works:

<?php
$letra1 = chr(rand(65,90));
$letra2 = chr(rand(97,122));
$letra3 = chr(rand(65,90));
$letra4 = chr(rand(97,122));

$letras = $letra1 . $letra2 . $letra3 . $letra4;

mkdir("a/$letras", 0777);

$archt = fopen("a/$letras/text.txt", "w") or die("Death");
$txt = "";
fclose($archt);


问:
I want to get only count from the control file
I want to get only count from a control file. The control file's name is AA.dat (for example) and the data in the file will be as follows.

```<code>AA.dat  200
</code>```

From the above file I want to pick only the value 200. When I try to use the cut command I am not able to get the result.

答:
Solution using cut

```<code>$ cut -d' ' -f2 < AA.dat
200
</code>```

using awk,

```<code>$ awk '{print $2}' AA.dat
200
</code>```

Body:
I want to get only count from a control file. The control file's name is AA.dat (for example) and the data in the file will be as follows.

AA.dat  200

From the above file I want to pick only the value 200. When I try to use the cut command I am not able to get the result.

Body:
Solution using cut

$ cut -d' ' -f2 < AA.dat
200

using awk,

$ awk '{print $2}' AA.dat
200


问:
How to see Sqlite database of an app installed on Bluestack emulator?
So I have installed this SQLite app on Bluestack emulator but when I go into the Android Device Monitor I don't see any process with the name of my project in the emulator.
When I click on Data folder in the file explorer nothing actually happens even though it has this ">" greater than sign means there is data inside this folder but when I click the sign goes away for a few seconds but comes back without any other change.

答:
You can find your database in /data/data/yourpackage/databases/yourdatabase.db
Copy it to your pc and inspect it with SQLiteStudio.
You can copy it with the adb pull command.</p>


问:
Fonts not displayed on HTML email and underline comes for hyperlinks
I have an HTML email code as given in the below link:

https://privatebin.net/?1ca92ace7be6c777#LLNgtdGPXCC4Si0Ui7jsEt7P/g+PsZ1gRq08qBTOljo=

The issue is the fonts linked by link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700" rel="stylesheet" type="text/css" is not displayed correctly even though I have added inline styles to all tags.
Also an underline is displayed for the renew button. I tried by adding text-decoration:none style with !important. but was of no use.
Any opinions?

答:
Web fonts do not work in all email clients. Some of the clients where they do not work include Gmail, Yahoo, some fonts do not work in Outlook and in email clients for Android devices.

You need to choose a backup font which will be used when Open Sans is not supported. I suggest Trebuchet or Arial or what meets your clients expectations for a fallback font. Something like this:

```<code>font-family: "Open Sans, Trebuchet, sans-serif;";
</code>```

These links will give you a better understanding of web fonts and how to use them in email.

https://www.campaignmonitor.com/css/text-fonts/font-face/

https://www.cssfontstack.com

https://www.cssfontstack.com/Open-Sans

https://litmus.com/blog/the-ultimate-guide-to-web-fonts

Your Button Issue

Your button only shows an underline in Windows Mail. However, the button shows up as Times New Roman in Outlook because you're using single quotes '' in the font-family description. It sees that as an error and defaults to Times. You should address this.

You are having display problems with iPhone 5 and Android you should address before you send out the email.

Good luck.

Body:
Web fonts do not work in all email clients. Some of the clients where they do not work include Gmail, Yahoo, some fonts do not work in Outlook and in email clients for Android devices.

You need to choose a backup font which will be used when Open Sans is not supported. I suggest Trebuchet or Arial or what meets your clients expectations for a fallback font. Something like this:

font-family: "Open Sans, Trebuchet, sans-serif;";

These links will give you a better understanding of web fonts and how to use them in email.

https://www.campaignmonitor.com/css/text-fonts/font-face/

https://www.cssfontstack.com

https://www.cssfontstack.com/Open-Sans

https://litmus.com/blog/the-ultimate-guide-to-web-fonts

Your Button Issue

Your button only shows an underline in Windows Mail. However, the button shows up as Times New Roman in Outlook because you're using single quotes '' in the font-family description. It sees that as an error and defaults to Times. You should address this.

You are having display problems with iPhone 5 and Android you should address before you send out the email.

Good luck.


问:
SQL Design: need ability to add custom "columns" to a table using a fixed schema
Using: SQL Server 2008, Entity Framework, WCF 4 REST

I have a table for holding the measurement data generated by monitoring system (aka the app).  There are currently about 10 different well-known pieces of data being monitored within the app - and each corresponds to a column in the table.  Each customer can "customize" each of their apps to capture from 1 to 10 pieces of data - they only need to capture those pieces of info they are interested in analyzing. Everything's working great (and performance is good) with this straight-forward fixed schema.  This schema is designed to be multi-tenant, so multiple applications across multiple customers in multiple locations could be pumping data into the same DB - millions and millions of rows of measurement data (I wouldn't be surprised if we go to Azure before too long).

I have now been told that the measurement application will soon be able to monitor additional "things".  This new list (so far I'm told is at around 150 items) could wind up being about 1000 items being measured.  Add on top of that, the user could specify their own criteria for items to monitor/measure (i.e. custom measurements equating to custom columns.)  The good news is that all the measurement data will be integers.

Now the fun - how do I design the schema for this situation?  I would really like to keep the schema fixed.  I would also like to keep it as performant as possible given the high volumes of data.

Any help is appreciated.

Current Schema:

```<code>CREATE TABLE MeasurementData (
    DataId bigint IDENTITY(1,1) NOT NULL PRIMARY KEY,
    ApplicationId int NOT NULL,    -- FK to Application table
    DateCollected datetime NOT NULL,
    Length int NULL,
    Width int NULL,
    Height int NULL,
    Color int NULL,
    Shape int NULL,
    Mass int NULL
)
CREATE TABLE Application (
    ApplicationId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyId int NOT NULL,    -- FK to Company table
    SerialNumber nvarchar(50) NOT NULL
)
CREATE TABLE Company (
    CompanyId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyName nvarchar(50) NOT NULL
)
</code>```

And then we have the user table, the roles table, etc, where there's a 1-n relationship btw company and user.

FYI, the web app will then present the data with tables, graphs, etc (communicating via the REST web service layer)

答:
Can you add two more tables? One with the types of measurements and the other with a mapping from the type to the measurement itself?

Basically A table with {DataId, DataMeasurementTypeId, DataValue} and {DataMeasurementTypeId, DataMeasurementType}

That should allow you to provide stored procedures to retrieve all Datameasurements in a table.

The better optiom might be to solve it with a Name,Value table and have the business object layer take care of constructing the right content.. That would fit (and likely perform) better with BigTable approach of Google than RDBMS though.

Body:
Using: SQL Server 2008, Entity Framework, WCF 4 REST

I have a table for holding the measurement data generated by monitoring system (aka the app).  There are currently about 10 different well-known pieces of data being monitored within the app - and each corresponds to a column in the table.  Each customer can "customize" each of their apps to capture from 1 to 10 pieces of data - they only need to capture those pieces of info they are interested in analyzing. Everything's working great (and performance is good) with this straight-forward fixed schema.  This schema is designed to be multi-tenant, so multiple applications across multiple customers in multiple locations could be pumping data into the same DB - millions and millions of rows of measurement data (I wouldn't be surprised if we go to Azure before too long).

I have now been told that the measurement application will soon be able to monitor additional "things".  This new list (so far I'm told is at around 150 items) could wind up being about 1000 items being measured.  Add on top of that, the user could specify their own criteria for items to monitor/measure (i.e. custom measurements equating to custom columns.)  The good news is that all the measurement data will be integers.

Now the fun - how do I design the schema for this situation?  I would really like to keep the schema fixed.  I would also like to keep it as performant as possible given the high volumes of data.

Any help is appreciated.

Current Schema:

CREATE TABLE MeasurementData (
    DataId bigint IDENTITY(1,1) NOT NULL PRIMARY KEY,
    ApplicationId int NOT NULL,    -- FK to Application table
    DateCollected datetime NOT NULL,
    Length int NULL,
    Width int NULL,
    Height int NULL,
    Color int NULL,
    Shape int NULL,
    Mass int NULL
)
CREATE TABLE Application (
    ApplicationId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyId int NOT NULL,    -- FK to Company table
    SerialNumber nvarchar(50) NOT NULL
)
CREATE TABLE Company (
    CompanyId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyName nvarchar(50) NOT NULL
)

And then we have the user table, the roles table, etc, where there's a 1-n relationship btw company and user.

FYI, the web app will then present the data with tables, graphs, etc (communicating via the REST web service layer)


问:
Changing <select>'s Background Color
I don't understand why the following isn't changing the select's background color.  It's probably something simple, but I can't see it.  I'm using Notepad++ editor with Chrome and Opera browsers.</p>

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Debugging</title>
    <style >
        select {
          background-color: #FF0000;
        }

    </style>
    <script>

      function myFunction() {
        document.getElementById('slct').style.backgroundColor = #FFFFFF;
      }

    </script>
  </head>
  <body>
    <select id="slct">
      <option>Choose</option>
      <option>The First Choice</option>
      <option>The Second Choice</option>
    </select>

    <input type="button" onclick="myFunction()" value="Click Me!">
  </body>
</html>
</code>```

答:
Check your browser's console, you might be getting errors. Background-color value must be in quotes.

```<code>document.getElementById('slct').style.backgroundColor = "#FFFFFF";
</code>```

Title: Changing <select>'s Background Color

Body:
I don't understand why the following isn't changing the select's background color.  It's probably something simple, but I can't see it.  I'm using Notepad++ editor with Chrome and Opera browsers.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Debugging</title>

    <select id="slct">
      <option>Choose</option>
      <option>The First Choice</option>
      <option>The Second Choice</option>
    </select>

    <input type="button" onclick="myFunction()" value="Click Me!">

Body:
Check your browser's console, you might be getting errors. Background-color value must be in quotes.

document.getElementById('slct').style.backgroundColor = "#FFFFFF";


问:
Add current or next year to string depending on month
I am scraping from https://stocktwits.com/SpeedyCalls and need to format the dates the bot uses for expiration such that it has the correct expiration year appended to the end.

And example is below. The December ones would be this current year, the Jan and beyond would be next year.

I could figure out a hack but I'm sure you smarter people would be able to figure out a more accurate and correct way.
Thanks.

```<code>'Jan, 19th'
'Dec, 15th'
'Jan, 19th'
'Jun, 15th'
'Apr, 20th'
'Dec, 15th'
'Jan, 19th'
'Dec, 15th'
'Jan, 19th'
'Feb, 16th'
'May, 18th'
'Dec, 15th'
'Mar, 16th'
'Dec, 15th'
'Feb, 16th'
</code>```

答:
Here's the method I wrote to solve the need. </p>

```<code>def get_exp_date(self, exp):
    exp_datetime_0 = datetime.strptime(exp+str(datetime.now().year), '%b, %d %Y')
    exp_datetime_1 = datetime.strptime(exp+str(datetime.now().year+1), '%b, %d %Y')
    start = datetime.now()
    end = datetime.now() + timedelta(days=182)

    if exp_datetime_1<end and exp_datetime_1>start:
        exp_date = exp_datetime_1
    else:
        exp_date = exp_datetime_0

    return exp_date.strftime('%b, %d %Y')
</code>```

Body:
I am scraping from https://stocktwits.com/SpeedyCalls and need to format the dates the bot uses for expiration such that it has the correct expiration year appended to the end.

And example is below. The December ones would be this current year, the Jan and beyond would be next year.

I could figure out a hack but I'm sure you smarter people would be able to figure out a more accurate and correct way.
Thanks.

'Jan, 19th'
'Dec, 15th'
'Jan, 19th'
'Jun, 15th'
'Apr, 20th'
'Dec, 15th'
'Jan, 19th'
'Dec, 15th'
'Jan, 19th'
'Feb, 16th'
'May, 18th'
'Dec, 15th'
'Mar, 16th'
'Dec, 15th'
'Feb, 16th'

Body:
Here's the method I wrote to solve the need.

def get_exp_date(self, exp):
    exp_datetime_0 = datetime.strptime(exp+str(datetime.now().year), '%b, %d %Y')
    exp_datetime_1 = datetime.strptime(exp+str(datetime.now().year+1), '%b, %d %Y')
    start = datetime.now()
    end = datetime.now() + timedelta(days=182)

    if exp_datetime_1<end and exp_datetime_1>start:
        exp_date = exp_datetime_1
    else:
        exp_date = exp_datetime_0

    return exp_date.strftime('%b, %d %Y')


问:
java Xiaolin Wu’s algorithm
I am trying to programme Xiaolin Wu’s algorithm and I got stuck.

It seems it should works but not, line is completly rasterized witch full opacity, Does anybody has any ide why? thanks a lot. I copared it with pseoudo code and it looks pretty same. I think that the error will be somewhere in selecting colors.

Code:

```<code>public class LineRasterizerXiaolinWu {

private RasterImage img;
private int color;
double gradient;

public LineRasterizerXiaolinWu(RasterImage img) {
    this.img = img;
}

public RasterImage rasterizeLine(int x1, int y1,
                                 int x2, int y2) {

    RasterImage result = img;

    boolean steep = Math.abs(y2-y1)> Math.abs(x2-x1);

    if(steep){
        int c = y1;
        y1 = x1;
        x1 = c;
        c = x2;
        x2 = y2;
        y2 = c;
    }
    if(x2 < x1) {
        int d = x2;
        x2 = x1;
        x1 = d;
        d = y2;
        y2 = y1;
        y1 = d;
    }

    double dx = x2 - x1;
    double dy = y2 - y1;

    if (dx == 0.0){
        gradient =1;
    }else {
        gradient = dy / dx;
    }

    //first end point
    int xEnd = round(x1);
    int yEnd = (int)(y1+gradient*(xEnd-x1));
    int xGap = (int) rfpart(x1+0.5);

    int xPxl1 = xEnd;
    int yPxl1 = (int)ipart(yEnd);

    if (steep) {
        plot(yPxl1, xPxl1, rfpart(yEnd)*xGap);
        plot((yPxl1 + 1), xPxl1, fpart(yEnd)*xGap);
    } else {
        plot(xPxl1, yPxl1, rfpart(yEnd) * xGap);
        plot(xPxl1, yPxl1 + 1, fpart(yEnd) * xGap);
    }

    double intery = yEnd + gradient;

    //second end point
    xEnd = round(x2);
    yEnd = (int)(y2+gradient*(xEnd-x2));
    xGap = (int) rfpart(x2+0.5);

    int xPxl2 = xEnd;
    int yPxl2 = (int)ipart(yEnd);

    if (steep) {
        plot(yPxl2, xPxl2, rfpart(yEnd)*xGap);
        plot((yPxl2 + 1), xPxl2, fpart(yEnd)*xGap);
    } else {
        plot(xPxl2, yPxl2, rfpart(yEnd) * xGap);
        plot(xPxl2, yPxl2 + 1, fpart(yEnd) * xGap);
    }

    if(steep){
        for(int i = xPxl1+1; i<=xPxl2-1; i++){
            plot((int)ipart(intery),i,rfpart(intery));
            plot((int)ipart(intery)+1,i,fpart(intery));
            intery +=gradient;
        }
    }else {
        for(int i = xPxl1+1; i<=xPxl2-1; i++){
            plot(i,(int)ipart(intery),rfpart(intery));
            plot(i,(int)ipart(intery)+1,fpart(intery));
            intery +=gradient;
        }
    }
    return result;
}

private void plot(int x, int y, double intensity){
    double alfaChanel = Math.round(intensity*100.0)/100.0;

    if (alfaChanel >= 0 && alfaChanel <= 0.2) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 1.0f)).getRGB();
    } else if (alfaChanel > 0.2 && alfaChanel <= 0.4) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.8f)).getRGB();
    } else if (alfaChanel > 0.4 && alfaChanel <= 0.6) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.6f)).getRGB();
    } else if (alfaChanel > 0.6 && alfaChanel <= 0.8) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.4f)).getRGB();
    } else if (alfaChanel > 0.8 && alfaChanel <= 1.0) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.2f)).getRGB();
    }

    img.withPixel(x,y,color);
}

//integer part of x
private double ipart (double x){
    return Math.floor(x);
}

private int round (double x){
    return (int) Math.round(x+0.5);
}

//fractional part of x
private double fpart (double x){
    return x-Math.floor(x);
}

private double rfpart (double x){
    return 1-fpart(x);
}
</code>```

Result:

答:
Solved with adding this method:

```<code> private int blend (int a, int b, float ratio) {
    if (ratio > 1f) {
        ratio = 1f;
    } else if (ratio < 0f) {
        ratio = 0f;
    }

    float iRatio = 1.0f - ratio;

    int aA = (a >> 24 & 0xff);
    int aR = ((a & 0xff0000) >> 16);
    int aG = ((a & 0xff00) >> 8);
    int aB = (a & 0xff);

    int bA = (b >> 24 & 0xff);
    int bR = ((b & 0xff0000) >> 16);
    int bG = ((b & 0xff00) >> 8);
    int bB = (b & 0xff);

    int A = (int)((aA * iRatio) + (bA * ratio));
    int R = (int)((aR * iRatio) + (bR * ratio));
    int G = (int)((aG * iRatio) + (bG * ratio));
    int B = (int)((aB * iRatio) + (bB * ratio));

    return A << 24 | R << 16 | G << 8 | B;
}
</code>```

and choosing color like this:

```<code>private void plot(int x, int y, double intensity){
    double alfaChanel = Math.round(intensity*100.0)/100.0;
    backGroundColor = 0xff2f2f2f;
    drawingColor = 0xffff0000;

    if (alfaChanel >= 0 && alfaChanel <= 0.2) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.2 && alfaChanel <= 0.4) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.4 && alfaChanel <= 0.6) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.6 && alfaChanel <= 0.8) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.8 && alfaChanel <= 1.0) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    }

    img.withPixel(x,y,color);
}
</code>```

thank you

Title: java Xiaolin Wu’s algorithm

Body:
I am trying to programme Xiaolin Wu’s algorithm and I got stuck.

It seems it should works but not, line is completly rasterized witch full opacity, Does anybody has any ide why? thanks a lot. I copared it with pseoudo code and it looks pretty same. I think that the error will be somewhere in selecting colors.

Code:

public class LineRasterizerXiaolinWu {

private RasterImage img;
private int color;
double gradient;

public LineRasterizerXiaolinWu(RasterImage img) {
    this.img = img;
}

public RasterImage rasterizeLine(int x1, int y1,
                                 int x2, int y2) {

    RasterImage result = img;

    boolean steep = Math.abs(y2-y1)> Math.abs(x2-x1);

    if(steep){
        int c = y1;
        y1 = x1;
        x1 = c;
        c = x2;
        x2 = y2;
        y2 = c;
    }
    if(x2 < x1) {
        int d = x2;
        x2 = x1;
        x1 = d;
        d = y2;
        y2 = y1;
        y1 = d;
    }

    double dx = x2 - x1;
    double dy = y2 - y1;

    if (dx == 0.0){
        gradient =1;
    }else {
        gradient = dy / dx;
    }

    //first end point
    int xEnd = round(x1);
    int yEnd = (int)(y1+gradient*(xEnd-x1));
    int xGap = (int) rfpart(x1+0.5);

    int xPxl1 = xEnd;
    int yPxl1 = (int)ipart(yEnd);

    if (steep) {
        plot(yPxl1, xPxl1, rfpart(yEnd)*xGap);
        plot((yPxl1 + 1), xPxl1, fpart(yEnd)*xGap);
    } else {
        plot(xPxl1, yPxl1, rfpart(yEnd) * xGap);
        plot(xPxl1, yPxl1 + 1, fpart(yEnd) * xGap);
    }

    double intery = yEnd + gradient;

    //second end point
    xEnd = round(x2);
    yEnd = (int)(y2+gradient*(xEnd-x2));
    xGap = (int) rfpart(x2+0.5);

    int xPxl2 = xEnd;
    int yPxl2 = (int)ipart(yEnd);

    if (steep) {
        plot(yPxl2, xPxl2, rfpart(yEnd)*xGap);
        plot((yPxl2 + 1), xPxl2, fpart(yEnd)*xGap);
    } else {
        plot(xPxl2, yPxl2, rfpart(yEnd) * xGap);
        plot(xPxl2, yPxl2 + 1, fpart(yEnd) * xGap);
    }

    if(steep){
        for(int i = xPxl1+1; i<=xPxl2-1; i++){
            plot((int)ipart(intery),i,rfpart(intery));
            plot((int)ipart(intery)+1,i,fpart(intery));
            intery +=gradient;
        }
    }else {
        for(int i = xPxl1+1; i<=xPxl2-1; i++){
            plot(i,(int)ipart(intery),rfpart(intery));
            plot(i,(int)ipart(intery)+1,fpart(intery));
            intery +=gradient;
        }
    }
    return result;
}

private void plot(int x, int y, double intensity){
    double alfaChanel = Math.round(intensity*100.0)/100.0;

    if (alfaChanel >= 0 && alfaChanel <= 0.2) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 1.0f)).getRGB();
    } else if (alfaChanel > 0.2 && alfaChanel <= 0.4) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.8f)).getRGB();
    } else if (alfaChanel > 0.4 && alfaChanel <= 0.6) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.6f)).getRGB();
    } else if (alfaChanel > 0.6 && alfaChanel <= 0.8) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.4f)).getRGB();
    } else if (alfaChanel > 0.8 && alfaChanel <= 1.0) {
        color =  (new Color(1.0f, 0.0f, 0.0f, 0.2f)).getRGB();
    }

    img.withPixel(x,y,color);
}

//integer part of x
private double ipart (double x){
    return Math.floor(x);
}

private int round (double x){
    return (int) Math.round(x+0.5);
}

//fractional part of x
private double fpart (double x){
    return x-Math.floor(x);
}

private double rfpart (double x){
    return 1-fpart(x);
}

Result:

Body:
Solved with adding this method:

 private int blend (int a, int b, float ratio) {
    if (ratio > 1f) {
        ratio = 1f;
    } else if (ratio < 0f) {
        ratio = 0f;
    }

    float iRatio = 1.0f - ratio;

    int aA = (a >> 24 & 0xff);
    int aR = ((a & 0xff0000) >> 16);
    int aG = ((a & 0xff00) >> 8);
    int aB = (a & 0xff);

    int bA = (b >> 24 & 0xff);
    int bR = ((b & 0xff0000) >> 16);
    int bG = ((b & 0xff00) >> 8);
    int bB = (b & 0xff);

    int A = (int)((aA * iRatio) + (bA * ratio));
    int R = (int)((aR * iRatio) + (bR * ratio));
    int G = (int)((aG * iRatio) + (bG * ratio));
    int B = (int)((aB * iRatio) + (bB * ratio));

    return A << 24 | R << 16 | G << 8 | B;
}

and choosing color like this:

private void plot(int x, int y, double intensity){
    double alfaChanel = Math.round(intensity*100.0)/100.0;
    backGroundColor = 0xff2f2f2f;
    drawingColor = 0xffff0000;

    if (alfaChanel >= 0 && alfaChanel <= 0.2) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.2 && alfaChanel <= 0.4) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.4 && alfaChanel <= 0.6) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.6 && alfaChanel <= 0.8) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    } else if (alfaChanel > 0.8 && alfaChanel <= 1.0) {
        color = blend(backGroundColor,drawingColor,(float)alfaChanel);
    }

    img.withPixel(x,y,color);
}

thank you


问:
Eclipse hangs when installing new software
I am trying to install new software within Eclipse the C++ version. Help -> install new software. When I go to install new software, it hangs or takes hours to move a percentage.

I have read that this is a known bug in JRE7, which I am assuming I am using since I have it installed. I changed to JRE6 by changing the eclipse.ini file with the argument -vm XXXX where XXXX is the path to my javaw.exe.

It does not seem to have changed anything.

Ideas?

Thanks.

答:
None of above methods worked for me in Ubuntu 16.04 LTS and Eclipse Mars. Had to do following

Go to "Preferences"->"Install/Update"->"Available Software Sites" and uncheck all except "Mars".

After this install worked in a jiffy.


问:
Find closest value to determined multiplicated value
I have two values. One is static and equals 24

```<code>int A = 24;
</code>```

and I have entries list :

```<code>[0, 21, 45, 76, 98]
</code>```

All of occurences comes in loop and I want to get closest value which divides on A :

```<code>0 - 24
21 - 24
45 - 48
76 - 72
98 - 96
</code>```

How to calculate this?

答:
Assuming that the arrays are also integers, the correct approach for rounding an integer a to the nearest multiple of integer n is as follows:1

```<code>(a + n/2) / n * n
</code>```

How this works

Hopefully the a / n * n approach should be familiar as an approach to get floor-like behaviour, due to the way integer maths works.  The n/2 is a bias to give you round-like behaviour instead.2

Things to be aware of

Exact ties are rounded upward.

Inputs within n / 2 of the maximum representable value will cause this to fail.

Comparison with other answers

The floating-point approaches aren't guaranteed to give the right answer for all input values, due to the limitations of floating-point arithmetic.
Using double may work if the inputs are ints (although I'm not sure what the proof is).  But it certainly won't be sufficient for longs.

This integer approach may be equivalent to @CodeApprentice's answer, I'm not sure.  But this approach avoids the conditional.

1. The boilerplate stream/loop code to get this to work for multiple input values is left as an exercise for the reader.

2. And for completeness, if you use a bias of n-1, you get ceil-like behaviour!

Body:
I have two values. One is static and equals 24

int A = 24;

and I have entries list :

[0, 21, 45, 76, 98]

All of occurences comes in loop and I want to get closest value which divides on A :

0 - 24
21 - 24
45 - 48
76 - 72
98 - 96

How to calculate this?

Body:
Assuming that the arrays are also integers, the correct approach for rounding an integer a to the nearest multiple of integer n is as follows:1

(a + n/2) / n * n

How this works

Hopefully the a / n * n approach should be familiar as an approach to get floor-like behaviour, due to the way integer maths works.  The n/2 is a bias to give you round-like behaviour instead.2

Things to be aware of

Exact ties are rounded upward.

Inputs within n / 2 of the maximum representable value will cause this to fail.

Comparison with other answers

The floating-point approaches aren't guaranteed to give the right answer for all input values, due to the limitations of floating-point arithmetic.
Using double may work if the inputs are ints (although I'm not sure what the proof is).  But it certainly won't be sufficient for longs.

This integer approach may be equivalent to @CodeApprentice's answer, I'm not sure.  But this approach avoids the conditional.

1. The boilerplate stream/loop code to get this to work for multiple input values is left as an exercise for the reader.

2. And for completeness, if you use a bias of n-1, you get ceil-like behaviour!


问:
Getting a input option to happen in all input statements without repeating if/elif/else statments
Wondering if there is a way to get python to accept "save" or "s" in a input statement  to do something every time you enter that into any if/elif/else in the .py file, so i don't have to repeat if/elif/else several times. I want some thing like this

```<code>a=input("some other question that i want to accept s/save: ")
b=input("Again but i dont want 2 if statments: ")
</code>```

rather than.

```<code>a=input("question: ")
if a == "y":
    print("something")
elif a == "y":
    print("Something")
elif a in ("s", "save")
    print("save")
else:
    print("not option")
print("A bunch of other code for 100 lines")
a=input("question: ")
if a == "y":
    print("something")
elif a == "y":
    print("Something")
elif a in ("s", "save")
    print("save")
else:
    print("not option")
</code>```

and so on through the code

答:
You could use a dictionary.</p>

```<code>a = input("question: ")

a_dict = {'y': 'something', 's': 'save'}

if a in a_dict:
    print(a_dict[a])
else:
    print('not option')
</code>```

Body:
Wondering if there is a way to get python to accept "save" or "s" in a input statement  to do something every time you enter that into any if/elif/else in the .py file, so i don't have to repeat if/elif/else several times. I want some thing like this

a=input("some other question that i want to accept s/save: ")
b=input("Again but i dont want 2 if statments: ")

rather than.

a=input("question: ")
if a == "y":
    print("something")
elif a == "y":
    print("Something")
elif a in ("s", "save")
    print("save")
else:
    print("not option")
print("A bunch of other code for 100 lines")
a=input("question: ")
if a == "y":
    print("something")
elif a == "y":
    print("Something")
elif a in ("s", "save")
    print("save")
else:
    print("not option")

and so on through the code

Body:
You could use a dictionary.

a = input("question: ")

a_dict = {'y': 'something', 's': 'save'}

if a in a_dict:
    print(a_dict[a])
else:
    print('not option')


问:
AbsListView$LayoutParams cannot be cast to LinearLayout$LayoutParams
I'm just not able to set LinearLayout parameters programatically. Everything I try, I get this exact exception.

```<code>LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) outerLayout.getLayoutParams();
params.bottomMargin = 50;
outerLayout.setLayoutParams(params);

java.lang.ClassCastException: android.widget.AbsListView$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
</code>```

I have no idea why, but it seems I just can't get LinearLayout.LayoutParams on a view. outerLayout is my LinearLayout I am instantiating it with findViewById(). I've tried importing different things but no luck.

Here is my xml that represents one item in a list view. outer_item_layout is the layout i am calling getLayoutParams() on.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/outer_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/modeName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_weight="3"
            android:text="Medium Text"
            android:textSize="18dp" />

        <ImageView
            android:id="@+id/dropdown_speed"
            android:layout_width="23dp"
            android:layout_height="23dp"
            android:layout_gravity="center"
            android:layout_marginRight="20dp"
            android:background="?selectableItemBackgroundBorderless"
            android:clickable="true"
            android:src="@drawable/ic_dropdown"
            tools:ignore="InvalidId" />
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:id="@+id/expandable_seekbar"
    android:layout_width="match_parent"
    android:layout_marginBottom="-50dip"
    android:visibility="gone"
    android:layout_height="50dip"
    android:orientation="horizontal">

    <SeekBar
        android:id="@+id/custom_mode_speed_seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp" />

</LinearLayout>
</code>```

答:
The return type of a view's getLayoutParams() call is not dependent on the type of the view, but rather on the type of that view's parent. So, even though outerLayout is a LinearLayout, its layout params could be anything.

It seems that your outerLayout view is being hosted inside some sort of ListView, which is why the result of outerLayout.getLayoutParams() is of type AbsListView.LayoutParams.

Body:
I'm just not able to set LinearLayout parameters programatically. Everything I try, I get this exact exception.

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) outerLayout.getLayoutParams();
params.bottomMargin = 50;
outerLayout.setLayoutParams(params);

java.lang.ClassCastException: android.widget.AbsListView$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

I have no idea why, but it seems I just can't get LinearLayout.LayoutParams on a view. outerLayout is my LinearLayout I am instantiating it with findViewById(). I've tried importing different things but no luck.

Here is my xml that represents one item in a list view. outer_item_layout is the layout i am calling getLayoutParams() on.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/outer_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/modeName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_weight="3"
            android:text="Medium Text"
            android:textSize="18dp" />

        <ImageView
            android:id="@+id/dropdown_speed"
            android:layout_width="23dp"
            android:layout_height="23dp"
            android:layout_gravity="center"
            android:layout_marginRight="20dp"
            android:background="?selectableItemBackgroundBorderless"
            android:clickable="true"
            android:src="@drawable/ic_dropdown"
            tools:ignore="InvalidId" />
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:id="@+id/expandable_seekbar"
    android:layout_width="match_parent"
    android:layout_marginBottom="-50dip"
    android:visibility="gone"
    android:layout_height="50dip"
    android:orientation="horizontal">

    <SeekBar
        android:id="@+id/custom_mode_speed_seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp" />

</LinearLayout>


问:
I want to reorder an array of strings
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

```<code>String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);
</code>```

答:
You can just change the order of the String creation:</p>

```<code>deli = reverse[i] + " " +  deli;
</code>```

Title: I want to reorder an array of strings

Body:
I have an array of String ["a", "b", "c", "d"]. My task is to add them to a listView in order like this:

row ==> d

row ==> c d

row ==> b c d

row ==> a b c d

For now I have created an empty String and through a for loop I added an array of items to it by + but problem is if I use this method, the ListView will look like:

row ==> d

row ==> d c

row ==> d c b

row ==> d c b a

This is what I have done:
...

String arrNaslovi[] = reverse.split(" ");
String deli = "";

for(int i=arrNaslovi.length-1; i>=0; i--) {
    deli += arrNaslovi[i] + " ";
    arrayNaslovi.add(deli);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayNaslovi);
    ListView listView = findViewById(R.id.listView);
    listView.setAdapter(adapter);

Body:
You can just change the order of the String creation:

deli = reverse[i] + " " +  deli;


问:
Best way to translate UTF-8 to ISO8859-1 in Go
I'm trying to map UTF-8 characters to their "similar" ISO8859-1 representation. Removing diacritics, but also replacing characters like Ł with L or ı with i.

Example:
José Kakışır should become Jose Kakisir.

I'm aware that removing diacritics can be done this way:

```<code>// (From https://blog.golang.org/normalization#TOC_10.)
import (
    "unicode"

    "golang.org/x/text/transform"
    "golang.org/x/text/unicode/norm"
)

isMn := func(r rune) bool {
    return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
}
t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
result, _, err := transform.String(t, "José Kakışır")
println(result)
</code>```

Which prints out Jose Karısır - ş replaced with s, but ı not replaced with i.

What's the best way to achieve that in Go?

答:
I believe the charmap package does what you want with a charmap.ISO8859_1.NewEncoder()

Edit: nevermind, that will barf on unsupported runes. Sorry. It may be worth looking into this package some more though.

Ultimately, it feels like you will need to find (or create) a mapping from UTF-8 to ISO8859. I don't think you'll find a "standard" one out there though, the mapping is too arbitrary.

Body:
I'm trying to map UTF-8 characters to their "similar" ISO8859-1 representation. Removing diacritics, but also replacing characters like Ł with L or ı with i.

Example:
José Kakışır should become Jose Kakisir.

I'm aware that removing diacritics can be done this way:

// (From https://blog.golang.org/normalization#TOC_10.)
import (
    "unicode"

    "golang.org/x/text/transform"
    "golang.org/x/text/unicode/norm"
)

isMn := func(r rune) bool {
    return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
}
t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
result, _, err := transform.String(t, "José Kakışır")
println(result)

Which prints out Jose Karısır - ş replaced with s, but ı not replaced with i.

What's the best way to achieve that in Go?


问:
C# discord bot not working
I can't start any bots and I'm just getting this error:

Discord.Net.WebSocketException: 'Received close code 4012: Requested gateway version is no longer supported or invalid'

Is it because I need to update to 1.0+?

How do I know the version is the root cause and is upgrading the only option I have?

答:
Discord.NET v0.9 uses version 5 of Discord API, which was discontinued today. All bots using Discord.NET v0.9 are no longer working.

Only solution is to upgrade to Discord.NET v1.0 wich uses the newest API version.

Title: C# discord bot not working


答:
Following query should work:</p>

```<code>select countriesTable.country, countriesTable.country_id, at_.last_login_date
from countriesTable
inner join accountsTable at_
on countriesTable.country_id = at_.country_id
where (select count(*)
       from accountsTable at2
       where at_.country_id = at2.country_id
       and at2.last_login_date>=at_.last_login_date
      )<=2
order by at_.country_id
</code>```

Title: select the top 2 users by country based on the users last login date

Body:
I would like to get a list of the top 2 accounts that by country. The users with the last two login dates from each country is the criteria that is used to determine the top 2 accounts. That is, the object is to achieve the last 2 last 2 users from each country with the max date.

--------------
 accountsTable
---------------------------------------
id  last_login_date         country_id
1   2016-07-13 13:52:10         3
2   2016-03-30 10:11:18         3
3   2016-03-30 10:11:18         1
4   2017-01-13 22:34:20         2
5   2017-04-22 12:25:04         2
6   2017-04-24 15:12:00         1
7   2017-05-18 10:16:30         4
8   2017-10-04 23:21:12         4
9   2017-10-10 00:54:55         2
10  2017-10-13 14:28:34         2
11  2017-06-18 10:16:30         4
---------------------------------------

---------------
countriesTable
--------------------------
country_id      country
--------------------------
1               UK
2               France
3               Germany
4               Japan
5               Brazil
6               Chile
7               Mexico
--------------------------

--------------
Desired Output
------------------------------------------------
country     country_id      last_login_date
------------------------------------------------
UK          1               2017-04-24 15:12:00
UK          1               2016-03-30 10:11:18
France      2               2017-10-13 14:28:34
France      2               2017-10-10 00:54:55
Germany     3               2016-03-30 10:11:18
Germany     3               2016-07-13 13:52:10
Japan       4               2017-05-18 10:16:30
Japan       4               2017-10-04 23:21:12
------------------------------------------------

select country, countriesTable.country_id, last_login_date
from countriesTable
inner join accountsTable
on countriesTable.country_id = accountsTable.country_id
group by (country)
order by last_login_date
limit 2

Table structure for countriesTable.

create table countriesTable(
    country_id int primary key,
    country varchar(20)
);

Insert for the countriesTable.

insert into countriesTable values (1, 'UK');
insert into countriesTable values (2, 'France');
insert into countriesTable values (3, 'Germany');
insert into countriesTable values (4, 'Japan');
insert into countriesTable values (5, 'Brazil');
insert into countriesTable values (6, 'Chile');
insert into countriesTable values (7, 'Mexico');

Table structure for accountsTable.

create table accountsTable(
    id int primary key,
    last_login_date timestamp,
    country_id int
);

Inserts for accountsTable.

insert into accountsTable values(1, '2016-07-13 13:52:10', 3);
insert into accountsTable values(2, '2016-03-30 10:11:18', 3);
insert into accountsTable values(3, '2016-03-30 10:11:18', 1);
insert into accountsTable values(4, '2017-01-13 22:34:20', 2);
insert into accountsTable values(5, '2017-04-22 12:25:04', 2);
insert into accountsTable values(6, '2017-04-24 15:12:00', 1);
insert into accountsTable values(7, '2017-05-18 10:16:30', 4);
insert into accountsTable values(8, '2017-10-04 23:21:12', 4);
insert into accountsTable values(9, '2017-10-10 00:54:55', 2);
insert into accountsTable values(10, '2017-10-13 14:28:34',2);
insert into accountsTable values(11, '2017-06-18 10:16:30', 4);

Body:
Following query should work:

select countriesTable.country, countriesTable.country_id, at_.last_login_date
from countriesTable
inner join accountsTable at_
on countriesTable.country_id = at_.country_id
where (select count(*)
       from accountsTable at2
       where at_.country_id = at2.country_id
       and at2.last_login_date>=at_.last_login_date
      )<=2
order by at_.country_id


问:
How to update existing rows in Room database?
I have a DAO class for updating a note if a note already exists for a particular date. If note, the DAO creates a new note. Here's the DAO interface:

```<code>@Insert(onConflict = OnConflictStrategy.REPLACE)
public long insertNote(Note note);

@Update
public int updateNote(Note note);
</code>```

Here's how I read all the data from the Database:

```<code>viewModel = ViewModelProviders.of(this).get(NoteListViewModel.class);
viewModel.getNoteList().observe(MainActivity.this, new Observer<List<Note>>() {
      @Override
      public void onChanged(@Nullable List<Note> noteList) {
            Log.d("Note List Items", noteList.toString());
      }
});
</code>```

Now, I don't know to check, compare and update existing rows in the database.

答: Your Note @Entity class has a primary key. updateNote() will update the row based on that primary key.

Body:
I have a DAO class for updating a note if a note already exists for a particular date. If note, the DAO creates a new note. Here's the DAO interface:

@Insert(onConflict = OnConflictStrategy.REPLACE)
public long insertNote(Note note);

@Update
public int updateNote(Note note);

Here's how I read all the data from the Database:

viewModel = ViewModelProviders.of(this).get(NoteListViewModel.class);
viewModel.getNoteList().observe(MainActivity.this, new Observer<List<Note>>() {
      @Override
      public void onChanged(@Nullable List<Note> noteList) {
            Log.d("Note List Items", noteList.toString());
      }
});

Now, I don't know to check, compare and update existing rows in the database.


问:
Form fields are shown before the layout is done in FF
I'm sorry for my bad english but I hope you will understand.

What's my problem....

I wrote a code to simple show the form which contains textfields, htmleditors, comboboxes, etc. Everything goes fine but in Firefox my fields appears before the form layout is done. so it looks quite weird because form fields overlaps other components.

sample code:

```<code>positionsPanel = new Ext.FormPanel({
 margins     : '2 2 2 0',
 frame       : true,
 flex        : 3,
 labelWidth  : 220,
 buttonAlign : 'right',
 labelAlign  : 'top',
 autoScroll  : true,
 height      : oldFormPanelHeight, //this is ok, just a value
 autoShow    : true,
 defaults    : {
  enableKeyEvents : true,
  anchor          : '97%'
 },
 items       : [{...etc.
</code>```

Have you any idea how to fix that? Thanks a lot...

答:
remove flex: 3

Note: this config is only used when this Component is rendered by a Container which has been configured to use a BoxLayout.

By default (in your case also) FormPanel use 'form' layout

Body:
I'm sorry for my bad english but I hope you will understand.

What's my problem....

I wrote a code to simple show the form which contains textfields, htmleditors, comboboxes, etc. Everything goes fine but in Firefox my fields appears before the form layout is done. so it looks quite weird because form fields overlaps other components.

sample code:

positionsPanel = new Ext.FormPanel({
 margins     : '2 2 2 0',
 frame       : true,
 flex        : 3,
 labelWidth  : 220,
 buttonAlign : 'right',
 labelAlign  : 'top',
 autoScroll  : true,
 height      : oldFormPanelHeight, //this is ok, just a value
 autoShow    : true,
 defaults    : {
  enableKeyEvents : true,
  anchor          : '97%'
 },
 items       : [{...etc.

Have you any idea how to fix that? Thanks a lot...


问:
How to specify an endpoint's authorization is optional in openapi v3?
I'm trying to document an existing API that contains various endpoints whose authentication is optional.  That is, more data is returned if the user is authorized than if they were not authorized.

Could not find that explicitly in the OAspec v3.  Is there a coding trick to define this situation?

My present work-around is to code for authorization, yet in a description of the endpoint write that authorization is optional.  This works and seems adequate.  Yet the purist in me wonders if there is another way.

答:
I just learned that security: can have an array of hash maps that cater to multiple authentication protocols.

Two examples:

```<code>security: # protocol A or protocol B
    - A
    - B

security: protocol A and protocol B
    - A
      B
</code>```

Body:
I just learned that security: can have an array of hash maps that cater to multiple authentication protocols.

Two examples:

security: # protocol A or protocol B
    - A
    - B

security: protocol A and protocol B
    - A
      B


问:
How to replace variable name and variable value from string?
I have a Google Forms Prefilled URL

```<code>$input = "https://docs.google.com/forms/d/e/1FAIpQLSe8aZbfXa2IRRzK6hPTDKvAf_Oa8chTMrX8wkkYcuVHGs-vuA/viewform?usp=pp_url&entry.1064398956=NAME&entry.1318807391=TELEPHONE";
$pars = parse_url($input);
$values = $pars["query"];
$values = str_replace("entry.", "", $values);
$values = str_replace("usp=pp_url&", "", $values);
</code>```

With this code I get values as

```<code>1064398956=NAME&1318807391=TELEPHONE
</code>```

Because the numbers (entry id) are always different, I use default values (like NAME, TELEPHONE), and these would be storaged to mySQL database like this:

```<code>Id  ||  NAME       || VALUE
================================
1   || 1064398956  || 1318807391
</code>```

To upload a row to that mysql database I have the query:

```<code>    INSERT INTO TABLE (ID, NAME, VALUE) VALUES (1, $NAME, $VALUE)
</code>```

Based on the following string, how i can find values $NAME and $VALUE?

```<code>1064398956=NAME&1318807391=TELEPHONE
</code>```

答:
This code will switch the var name whit the value ($VALUE variable with 'NAME' value)</p>

```<code>function get_var_name($vars, $var)
{
  foreach ($vars as $name => $value) {
    if ($value === $var) {
      return $name;
    }
  }
  return false;
}

$NAME = "VALUE";
$$NAME = get_var_name(get_defined_vars(), $NAME);

echo $VALUE; // will print 'NAME'
</code>```

Body:
I have a Google Forms Prefilled URL

$input = "https://docs.google.com/forms/d/e/1FAIpQLSe8aZbfXa2IRRzK6hPTDKvAf_Oa8chTMrX8wkkYcuVHGs-vuA/viewform?usp=pp_url&entry.1064398956=NAME&entry.1318807391=TELEPHONE";
$pars = parse_url($input);
$values = $pars["query"];
$values = str_replace("entry.", "", $values);
$values = str_replace("usp=pp_url&", "", $values);

With this code I get values as

1064398956=NAME&1318807391=TELEPHONE

Because the numbers (entry id) are always different, I use default values (like NAME, TELEPHONE), and these would be storaged to mySQL database like this:

Id  ||  NAME       || VALUE
================================
1   || 1064398956  || 1318807391

To upload a row to that mysql database I have the query:

    INSERT INTO TABLE (ID, NAME, VALUE) VALUES (1, $NAME, $VALUE)

Based on the following string, how i can find values $NAME and $VALUE?

1064398956=NAME&1318807391=TELEPHONE

Body:
This code will switch the var name whit the value ($VALUE variable with 'NAME' value)

function get_var_name($vars, $var)
{
  foreach ($vars as $name => $value) {
    if ($value === $var) {
      return $name;
    }
  }
  return false;
}

$NAME = "VALUE";
$$NAME = get_var_name(get_defined_vars(), $NAME);

echo $VALUE; // will print 'NAME'


问:
TF IDF using dictionaries
I calculated tf and idf for all terms in documents, so I have two objects:
1) tf  dictionaries(there are about 10k):

```<code>{'doc_1': {'rain':0.4, 'sun':0.6}}
{'doc_2': {'............
{'doc_3': {'rain':0.1, .......
</code>```

2) idf ONE single dictionary:

```<code>{'rain': 0.18, 'sun': 0.12......
</code>```

3) I have my list index for all terms:

```<code>[{'term1':[[doc_1, 2],[doc_2, 3]]}, {'term2': [[doc_6, 6],[doc3,1]]}
</code>```

....and so on for every term

How can I calculate tf*idf now for example for a list of words? I was trying:

```<code>def tf_idf(list_of words):
    t_id={}
    for i in list_of_words:
        score= {}
        for j in terms:
            score[j[0]]=(idf[i]*tf[j[0]][i])
        t_id[i]=score
    return t_id
</code>```

it give me an error:

```<code>KeyError: 0
</code>```

答:
I agree with the programming advice from ers81239. I analysed your program and I saw the same mistakes. So the real answer to your actual question is that you can't given your data structures.

However, to get you started, I rewrote it from scratch, trying to interpret your intentions from your code.

First, the term frequencies contain al information. I changed that into a nested dict and then calculated idf. This leaves you with less data structures and less places to mis-index.

From that it is not hard to calculate the TF*IDF. I left out as much as possible.

```<code>from collections import Counter
from math import log

tf = {
        'term1': {'doc_1': 2, 'doc_2': 3},
        'term2': {'doc_2': 6, 'doc_3': 1},
}

N = float(len({k for doc_freqs in tf.itervalues()
                   for k in doc_freqs.iterkeys()}))

print N

idf = {term: N/len(doc_freqs)
           for term, doc_freqs in tf.iteritems()}

print idf

tf_idf = {term: tf[term][doc] * idf[term]
             for term, doc_freqs in tf.iteritems()
                for doc in doc_freqs}

print tf_idf
</code>```

Please keep in mind that this is the simplest TF*IDF one can imagine and lots of improvements are generally applied.

Title: TF IDF using dictionaries

Body:
I calculated tf and idf for all terms in documents, so I have two objects:
1) tf  dictionaries(there are about 10k):

{'doc_1': {'rain':0.4, 'sun':0.6}}
{'doc_2': {'............
{'doc_3': {'rain':0.1, .......

2) idf ONE single dictionary:

{'rain': 0.18, 'sun': 0.12......

3) I have my list index for all terms:

[{'term1':[[doc_1, 2],[doc_2, 3]]}, {'term2': [[doc_6, 6],[doc3,1]]}

....and so on for every term

How can I calculate tf*idf now for example for a list of words? I was trying:

def tf_idf(list_of words):
    t_id={}
    for i in list_of_words:
        score= {}
        for j in terms:
            score[j[0]]=(idf[i]*tf[j[0]][i])
        t_id[i]=score
    return t_id

it give me an error:

KeyError: 0

Body:
I agree with the programming advice from ers81239. I analysed your program and I saw the same mistakes. So the real answer to your actual question is that you can't given your data structures.

However, to get you started, I rewrote it from scratch, trying to interpret your intentions from your code.

First, the term frequencies contain al information. I changed that into a nested dict and then calculated idf. This leaves you with less data structures and less places to mis-index.

From that it is not hard to calculate the TF*IDF. I left out as much as possible.

from collections import Counter
from math import log

tf = {
        'term1': {'doc_1': 2, 'doc_2': 3},
        'term2': {'doc_2': 6, 'doc_3': 1},
}

N = float(len({k for doc_freqs in tf.itervalues()
                   for k in doc_freqs.iterkeys()}))

print N

idf = {term: N/len(doc_freqs)
           for term, doc_freqs in tf.iteritems()}

print idf

tf_idf = {term: tf[term][doc] * idf[term]
             for term, doc_freqs in tf.iteritems()
                for doc in doc_freqs}

print tf_idf

Please keep in mind that this is the simplest TF*IDF one can imagine and lots of improvements are generally applied.


问:
HTTPS equivalent of Django's HttpResponse
For some reason I am in need of a views.py that returns only  some text. Normally, i'd use HttpResponse("text") for this. However, In this case I require the text to be send over https, to counter the inevitable mixed content warning.

What is the simplest way of sending pure text via django(1.7.11) over https?

答:
I've run into the mixed content problems as well. From my experience, you simply can't use the HttpResponse objects without running into trouble. I was never totally sure though and eventually found a way "around" it.

My solution for it was to use the JsonResponse object instead, to return JSON strings, kind of a work-around with the views returning something like:

```<code>mytext = 'stuff blablabla'
return JsonResponse({'response_text': mytext})
</code>```

Which is super easy to parse, and OK with HTTPS.
Maybe not what you're looking for, but I hope it helps you find your way.

Body:
I've run into the mixed content problems as well. From my experience, you simply can't use the HttpResponse objects without running into trouble. I was never totally sure though and eventually found a way "around" it.

My solution for it was to use the JsonResponse object instead, to return JSON strings, kind of a work-around with the views returning something like:

mytext = 'stuff blablabla'
return JsonResponse({'response_text': mytext})

Which is super easy to parse, and OK with HTTPS.
Maybe not what you're looking for, but I hope it helps you find your way.


问:
What does the backslash operator do inside RSH conditionals?
I'm interested to know what this snippet of RSH code does, and whether Bash has something similar:</p>

```<code>if [ -z $ALPHA \
     -z $BRAVO \
     -z $CHARLIE \
     -z $DELTA ]; then

   var=$ZULU
fi
</code>```

答:
Those baskslashes are allowing for line continuation. It's as if the code were written like the following:

```<code>if [ -z $ALPHA -z $BRAVO -z $CHARLIE -z $DELTA ]; then

   var=$ZULU
fi
</code>```

From man bash

If  a  \<newline>  pair
         appears, and the backslash is not itself quoted, the \<newline> is
  treated as a line continuation (that
  is, it is removed from the input
  stream and effectively ignored).

Body:
I'm interested to know what this snippet of RSH code does, and whether Bash has something similar:

if [ -z $ALPHA \
     -z $BRAVO \
     -z $CHARLIE \
     -z $DELTA ]; then

   var=$ZULU
fi

Body:
Those baskslashes are allowing for line continuation. It's as if the code were written like the following:

if [ -z $ALPHA -z $BRAVO -z $CHARLIE -z $DELTA ]; then

   var=$ZULU
fi

From man bash

If  a  \<newline>  pair
         appears, and the backslash is not itself quoted, the \<newline> is
  treated as a line continuation (that
  is, it is removed from the input
  stream and effectively ignored).


问:
Xcode 9.0 simulators "disappeared"
I recently installed Xcode 9.0 GM on my machine. I fired it up to play around and the only simulators I see in the scheme are iPhone 8, iPHone 8 Plus, and iPhone X. I clicked "Download Additional Simulators" thinking the solution would lie there.

I'm greeted with this screen, which is everything I previously had installed.

I dug around on the Apple Developer forum and found this post discussing a similar problem with a prior version of iOS. At the suggestion of one of the posters, I powered down my machine and booted it cold. I opened up Xcode 9.0 again and I have the same issue.

Any suggestions what I can get additional hardware to appear in my Xcode scheme? Thank you for reading.

答: In case anyone else gets here and are in my situation, I just upgraded to Xcode 9.2 and the simulators were all missing, but quitting and relaunching Xcode restored them.</p>

Title: Xcode 9.0 simulators "disappeared"