text:
Q: repeating code for each row jquery Hope you can help me, which I think is really easy for you to solve :).
I have the following jquery script:
    $('#addpricebtn').click(function () {

    $('.stidinput').each(function (i) {

        $.ajax({
            type: 'GET',
            url: '/Builder/rateretriever',
            datatype: 'json',
            data: { id: $('.stidinput').val() },
            success: function (result) {
                $('.categoryinput').html(result[i].category + ' - ' + result[i].subcategory + ' - ' + result[i].site);
                $('.formatinput').html(result[i].format);
                $('.exclusiveinput').html(result[i].exclusive);
                $('.cminput').html(result[i].costmethod);
            }
        });
    });
});

this script works, however only looks at the first filled in id and I would like to use the code for every row, that's why I have the code below... (I would like to use the same request with a different id on every line that's getting filled in by the user :))
$('#addpricebtn').click(function () {

    $('.stidinput').each(function (i) {

        var inputer = $('.stidinput').val();

        $.ajax({
            type: 'GET',
            url: '/Builder/rateretriever',
            datatype: 'json',
            data: { id: inputer[i] },
            success: function (result) {
                $('.categoryinput').html(result[i].category + ' - ' + result[i].subcategory + ' - ' + result[i].site);
                $('.formatinput').html(result[i].format);
                $('.exclusiveinput').html(result[i].exclusive);
                $('.cminput').html(result[i].costmethod);
            }
        });
    });
});

Hope you can help :).
EDIT
Sure, I have the following HTML Code:

        ID
        Name:
        Format:
        Exclusive:
        Start:
        End:
        Cost Method:
        Target 1:
        Target 2:
        Frequency Cap:
        RC Price:
        Impressions:
        Gross Budget Discount:
        Net Net Budget
        Net eCPM

        <input class="stidinput" name="stidinput" type="text" />

        01/01/2015
        01/01/2015

<button id="addrowbtn">AddRow</button>
<button id="addpricebtn">AddPrice</button>

The user should be able to add a row and fill in the cell with class: stidinput, after that the user clicks the addpricebtn button which will retrieve the rates from the database in JSON format.  I need to find a way that the jquery script retrieves all the STID and fill's in the corresponding information received from the database and not only the first one...
Thanks,

A: Obviously your mistake is that you fill the 1st TR line within each iteration. I think you have first to catch a parent row of each stidinput and fill it with respective data. it may look like follow (And I think it don't need to use index):
$('#addpricebtn').click(function () {
    $('.stidinput').each(function (i) {

        var inputer = $(this).val();
        var currentRow = $(this).parent();

        $.ajax({
            type: 'GET',
            url: '/Builder/rateretriever',
            datatype: 'json',
            data: { id: inputer },
            success: function (result) {
                currentRow.find('.categoryinput').html(result.category + ' - ' + result.subcategory + ' - ' + result.site);
                currentRow.find('.formatinput').html(result.format);
                currentRow.find('.exclusiveinput').html(result.exclusive);
                currentRow.find('.cminput').html(result.costmethod);
            }
        });
    });
});

Also you can add if... before ajax call to check is that row already filled to prevent both of repeated fill  of row  and excessive call of server script.


text:
Q: Move a module from devDependencies to dependencies in npm package.json Is there any short command to move a module from devDependencies to dependencies in package.json?
I find myself always doing this:
npm uninstall <module_name> --save-dev
npm install <module_name> --save

Is there a shorter approach to this?

A: The issue of using npm install is that you end up with updated versions. What worked for me is:

*

*Moving them to the intended part (dev, or prod)

*Removing them from node_modules folder

*Execute npm install
That kept all versions intact.

A: In yarn:
Move a module from devDependencies to dependencies:
yarn remove <module_name> --dev && yarn add <module_name>

Move a module from dependencies to devDependencies :
yarn remove <module_name> && yarn add <module_name> --dev

As said in the comments, the command actually deletes the module and reinstall it in the new place.

A: Shorthand to move from devDependencies to dependencies (prod):
npm i <module_name> -P

If you want to do the opposite (i.e. move a module from dependencies to devDependencies) just do:
npm install <module_name> --save-dev

or shorthand:
npm i <module_name> -D

A: If your project doesn't have a lockfile or a shrinkwrap file yet, you can simply move the corresponding line in your package.json.
(I'm not recommending not using lockfiles)

A: Yes! to move a module from devDependencies to dependencies:
npm install <module_name> --save-prod

A: The problem with using npm or yarn commands is that there is a chance that the version that is re-added is a different version than the one that is currently used. If this is what you want - both a move and an upgrade - then go ahead and use the accepted answer.
If not, simply manually edit your package.json to move the line from the devDependencies object to the dependencies object (creating it if necessary). You can go the other direction too.
The lock file doesn't hold any information about if things are prod or dev dependencies, so that doesn't need to be updated. You can do a npm/yarn install afterwards to fix up any flags in the lock files.

A: I was trying to find an answer for this question for people that uses Yarn, but it hasn't a command for this matter yet.
Although, I believe it is not essential anyway.
Physically (in the Node modules folder) there are no difference between a dependency listed for production and the ones listed for development in your package.json, they'll go to the same place (node_modules).
So, if you need to switch a dependency from devDependencies to dependecies you can go to your package.json and move manually with no need to run a new install or remove the dependency and then install it again with the dev flag.
For me, it's not so great at all to manage the package.json manually, but Yarn is not as advanced as NPM in all functionalities, thus that's a thing to consider.

A: For Yarn, I moved them manually inside package.json and then ran yarn install. Yarn lock file does not get updated, so I think this is fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculating percentages per product using aggregate functions and group by I have a table with 5 rows representing two different products. The columns include the product, sales, discount. I'm trying to calculate the percentage of sales per product that included a discount. The table looks like this:

product
sales
discount

1
10
0

1
10
5

2
20
10

2
20
0

2
20
10

My results should look like the below (which I know because I've calculated this in Excel):

product
perc_discount

1
50.00

2
66.67

For each of the two products we are calculating the count of sales with discount divided by the total count of sales, so for product 1 it would be (1/2)*100 = 50.
My SQL code looks like the below:
SELECT
    product,
    (SELECT COUNT(*) FROM sales WHERE discount >0)/COUNT(*)*100 AS perc_discount
FROM sales
GROUP BY product

However, the result I'm getting is:

product
perc_discount

1
150.0

2
100.0

It seems to be calculating the total count of discounted sales in the table and diving it by the count of each product and I can't seem to figure out how to change it. Any ideas on how I can improve this?
Thanks.

A: How about conditional sum?
SQL> select product,
  2         round(sum(case when discount > 0 then 1 else 0 end) / count(*) * 100, 2) perc_discount
  3  from sales
  4  group by product;

   PRODUCT PERC_DISCOUNT
---------- -------------
         1            50
         2         66,67

SQL>

So: add 1 for every discount row per product. Divide that sum with total number of rows per product (that's count). Round the result to 2 decimals (so that it looks prettier).

A: You can use conditional aggregation. For example:
select
  product,
  100.0 * count(case when discount <> 0 then 'x' end) / count(*) as perc_discount
from sales
group by product


text:
Q: Lost full screen on virtualbox I updated my virtual box hosted ubuntu from Ubuntu version 20.10 to 21.04. Upon update, the Ubuntu is no longer in full screen.
Host: "20.04.2 LTS (Focal Fossa)" Virtualbox version: Version 6.1.16_Ubuntu r140961
I checked all the guest additions, x11 etc.. on the guest OS (V 21.04) all the good things still remain.
Please help get back the full screen.
Thanks in advance.

A: Reinstall Guest Additions on the VM.  It's possible that it was corrupted during the upgrade, or a version mismatch could have occurred after upgrading.  I recently ran into this issue upgrading the Host, and the culprit was the version of Guest Additions installed on the VM was not supported by the version of VirtualBox on the host.


text:
Q: Bad font rendering Chrome How i fix this?
First "D" is rendered on Chrome 31.0.1650.63 m and second is rendered on IE11.

Update:
adding -webkit-font-smoothing: antialiased; the problem remains...

It could be a problem with the video card?
Update 2:
css font code:
 @font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  src: local('Open Sans Light'), local('OpenSans-Light'), url(../font/font1.woff) format('woff');
}
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans'), local('OpenSans'), url(../font/font2.woff) format('woff');
}

A: This is an issue with Chrome itself. The problem only exists on Chrome for Windows. Macs and Linux users of Chrome don't have this problem. There's nothing you can really do about it.

A: This is an issue with Chrome rendering engine but it looks like this is finally going to be fixed. See https://plus.google.com/u/0/+FrancoisBeaufort/posts/PGPpiQr6bwi
The issue is on Chromium's bugtracker:
https://code.google.com/p/chromium/issues/detail?id=333029
https://code.google.com/p/chromium/issues/detail?id=25541
EDIT:
The DirectWrite support which enables pretty font rendering has been added to Chrome 37.
(source: https://code.google.com/p/chromium/issues/detail?id=25541#c152)

A: Have you tried adding this CSS to the Chrome one?
-webkit-font-smoothing: antialiased
Give that a shot and see if it helps.

A: I had the same problem and the following code is the best work around that I found. Somehow if you hide and re-show the content of the body the font will load properly
Hope this helps
body {
    -webkit-animation-delay: 0.1s;
    -webkit-animation-name: fontfix;
    -webkit-animation-duration: 0.1s;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-timing-function: linear;
    font-family: folio_medium;
}

@-webkit-keyframes fontfix {
    from { opacity: 1; }
    to   { opacity: 1; }
}

A: I found that giving svg font files higher priority solves the issue.
@font-face {
  font-family: 'HelveticaNeueLTStd-Bd';
  src: url('../assets/fonts/helvetica/2B7A70_0_0.svg#wf') format('svg'), // first means higher priority
  url('../assets/fonts/helvetica/2B7A70_0_0.eot');
}


text:
Q: Matlab: fminsearch for functions that do not vary continuously I have a sequence of chars that I multialign with the Matlab function 'multialign'. The result is a char matrix with the multialigned sequences:
e.g. with only 3 seqences.
----GC
AT--GC
ATGCGC

Next I score every column of the alignment on the base of the similarity between the sequences. In the previous example: in the fist column the 'A' is the most frequent symbol and it appears 2 out of 3 times, so the score is 2/3, in the last column the letter 'C' appears every time so I score it 1, and so on. The final score is the mean of the single scores.
Now the real question: I create these sequences with a function that uses a threshold to decide whether to add a char or not, so I can have shorter or longer sequences. This is another example with a different threshold that I score in the same way:
-----ATATGGCGC
AT-ATGCA-G-C--
ATG-TGC--G-C--

I wanted to use fminsearch to search for the best threshold but my problem is that varying the threshold only a little the score doesn't change so the algorithm used by fminsearch doesn't work (for example if you start from 10 the value chosen for the next step is something like 9.75...).
This is a pseudo-Matlab code for what I do:
[bestthr, bestscore] = fminsearch(@(x) fcnthr(data,x),[10]);

function score = fcnthr(data,thr)

sequences = generateSequencesFromData(data,thr);
multialignmatrix = multialign(sequences);
score = scorealignments(multialignmatrix);

score = 1/score; %I want to find the maximum score so fminsearch searches the minimum of 1/score.

end

Can someone help me?


text:
Q: ASP.NET MVC How to determine if the e-mail didn't reach the receiver In my web application an e-mail with credential information is sent to every newly registered user.
For some reason, Hotmail and some other mail providers don't accept these e-mails at all (by the way, I send via hMailServer, maybe you know how to fix that) - they are neither in the spam nor in the inbox folder.
So the users leave the page, check mail and get nothing. They have to use a separate page to give another e-mail, which is not cool.
So how can I check if the mail was successfully sent or not?
Update
I realized that there's no way to do it...

A: With regard to best practice (e.g. setting up SPF records) Jeff Atwood has a great post on this, see: http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html
To check if the email sent, you simply place an image in the email which requests data via your application, and therefore log the fact the user has opened the email. If the request "/images/something.jpg?id={identify-the-user-and-message-here}" is routed through your app, you can just register the user has seen the email, then return the image, or indeed nothing.

A: It sounds like you're asking if there's a way in real time to check to see if your user got the message.  If so, I would recommend that you don't pursue that path.  While most times email delivery seems to be instantaneous, it could be held up for any length of time prior to being delivered to the recipient's mailbox.

A: In addition to the methods already posted, I can highly recommend the EmailVerify.NET component, which can perform quite a few levels of tests on a given email address before you attempt the send in the first place.


text:
Q: jQuery Validation this.optional is not a function I created my own custom validation method which uses the minlength method in turn, however I get this error:
this.optional is not a function

My code is here:
jQuery.validator.addMethod("validAccount", function(value, element, params) {
        var res = true;
        if (!isNaN(parseInt(value[0]))) {
            res = false;
        } else if (!$.validator.methods.minlength(value.split(""), element, params)) {
            res = false;
        }
        return res;
    }, "The inserted account isn't valid");

Can anyone help me? I want understand where the problem is.
Note: In the minlength method I use split because without it I also get getLength is not a function.

A: Quoting OP's comment:

"The account field shouldn't start for a number, there is no such built-in method. So I should create it. Also, the account field should be at least n characters. I thought about using the existing method for this instead of re-created it, but I see that this is a bad idea."

Perhaps you didn't know you can apply several rules to the same field at once. You can write a custom rule that says it should not start with a number, and then use it alongside the default minlength rule.
$("#idform").validate({
    rules: {
        account: {
            validAccount: true, // <- custom rule to make sure does not start with number
            minlength: 4        // <- default rule (at least 4 characters entered)
        }
    }
});

You can use as many default and/or custom rules (methods) as you need.  Also, check out the additional-methods.js file for even more.


text:
Q: Is it wrong to add instance variables to a Controller? If I want to share an object between multiple methods in a controller, is it wrong to create an instance var?  E.g.
class MyController {
    def index() {
        def user = verifyUserLogin()
        [messages:getMessages(user)]
    }

    private verifyUserLogin() {
        ...
        return user
    }

    private getMessages(user) {
        ...do something with `user`...
        return messages
    }
}

would become
class MyController {
    private user

    def index() {
        verifyUserLogin()
        [messages:getMessages()]
    }

    private void verifyUserLogin() {
        ...
        this.user = user
        return
    }

    private getMessages() {
        ...do something with `user`...
        return messages
    }
}

A: Grails controllers are not singleton they are created for every request so it should not be any issue to have instance level variables.
However I personally prefer to not to declare instance level variables as much as possible, because when code starts becoming lengthy it becomes difficult to figure out the flow of the code that initializes and uses the variables.
I rather choose to pass them as parameters. However there's no such rule of thumb and it highly depends on the problem at hand.

A: The traditional way - for Servlets at least - of storing state between controllers, i.e. passing information between requests is to use the session object.
class MyController(){
   def index(){
       session.user = getUser()
   }

   def postex(){
       def user = session.user
   }
}

A: In grails 3.2.1 the default scope of controllers changed from "prototype", controller instance per request, to "singleton", one instance of each controller.
This made instance variables in controllers no longer safe unless you change the scope!
https://docs.grails.org/3.2.1/ref/Controllers/scope.html singleton
https://docs.grails.org/3.2.0/ref/Controllers/scope.html prototype
If you do want to use instance variables in a controller change the scope static scope = "prototype".
Rather than use instance variables you can set variables on the request (as request attributes). request.user = user Note that these will persist for the life of the request (visible to all interceptors and views traversed by the request).


text:
Q: Third and Second person in one sentence referring to "you"? Is it correct to say: "You are the one who's saying that he can't understand what he wrote, therefore I can't help you."? How understandable it is? A friend and I were arguing about this.

A: In that sentence "he" refers to "the one". "You" are the noun-phrase beginning "one..." and ending " ...what he wrote". You could replace that noun phrase with a single noun, such as "fool" as in: "You are the fool, therefore I can't help you".
It is perfectly grammatical, therefore.
If you need to ask whether it is understandable, then maybe it isn't; what is understandable is in the mind of the reader, not of the writer. It is certainly a convoluted way of expressing a simple, if insulting, thought.


text:
Q: Efficient pagination of MongoDB aggregation? For efficiency, the Mongo documentation recommends that limit statements immediately follow sort statements, thus ending up with the somewhat nonsensical:
 collection.find(f).sort(s).limit(l).skip(p)

I say this is somewhat nonsensical because it seems to say take the first l items, and then drop the first p of those l.   Since p is usually larger than l, you'd think you'd end up with no results, but in practice you end up with l results.
Aggregation works more as you'd expect:
collection.aggregate({$unwind: u}, {$group: g},{$match: f}, {$sort: s}, {$limit: l}, {$skip: p})

returns 0 results if p>=l.
collection.aggregate({$unwind: u}, {$group: g}, {$match: f}, {$sort: s}, {$skip: p}, {$limit: l})

works, but the documentation seems to imply that this will fail if the match returns a result set that's larger than working memory.    Is this true?   If so, is there a better way to perform pagination on a result set returned through aggregation?
Source:  the "Changed in version 2.4" comment at the end of this page:  http://docs.mongodb.org/manual/reference/operator/aggregation/sort/

A: In MongoDB cursor methods (i.e. when using find()) like limit, sort, skip can be applied in any order => order does not matter. A find() returns a cursor on which modifications applied. Sort is always done before limit, skip is done before limit as well. So in other words the order is: sort -> skip -> limit.
Aggregation framework does not return a DB cursor. Instead it returns a document with results of aggregation. It works by producing intermediate results at each step of the pipeline and thus the order of operations really matters.
I guess MongoDB does not support order for cursor modifier methods because of the way it's implemented internally.
You can't paginate on a result of aggregation framework because there is a single document with results only. You can still paginate on a regular query by using skip and limit, but a better practice would be to use a range query due to it's efficiency of using an index.
UPDATE:
Since v2.6 Mongo aggregation framework returns a cursor instead of a single document. Compare: v2.4 and v2.6.

A:
The documentation seems to imply that this (aggregation) will fail if the match returns a result set that's larger than working memory. Is this true?

No. You can, for example, aggregate on a collection that is larger than physical memory without even using the $match operator. It might be slow, but it should work. There is no problem if $match returns something that is larger than RAM.
Here are the actual pipeline limits.
http://docs.mongodb.org/manual/core/aggregation-pipeline-limits/
The $match operator solely does not cause memory problems. As stated in the documentation, $group and $sort are the usual villains. They are cumulative, and might require access to the entire input set before they can produce any output. If they load too much data into physical memory, they will fail.

If so, is there a better way to perform pagination on a result set returned through aggregation?

I has been correctly said that you cannot "paginate" (apply $skip and $limit) on the result of the aggregation, because it is simply a MongoDB document. But you can "paginate" on the intermediate results of the aggregation pipeline.
Using $limit on the pipeline will help on keeping the result set within the 16 MB bounds, the maximum BSON document size. Even if the collection grows, you should be safe.
Problems could arise with $group and, specially, $sort. You can create "sort friendly" indexes to deal with them if they do actually happen. Have a look at the documentation on indexing strategies.
http://docs.mongodb.org/manual/tutorial/sort-results-with-indexes/
Finally, be aware that $skip does not help with performance. On the contrary, they tend to slow down the application since it forces MongoDB to scan every skipped document to reach the desired point in the collection.
http://docs.mongodb.org/manual/reference/method/cursor.skip/

A: MongoDB recommendation of $sort preceding $limit is absolutely true as when it happens it optimizes the memory required to do the operation for top n results.
It just that the solution you proposes doesn't fit your use case, which is pagination.
You can modify your query to to get the benefit from this optimization.
collection.aggregate([
  {
    $unwind: u
  },
  {
    $group: g
  },
  {
    $match: f
  },
  {
    $sort: s
  },
  {
    $limit: l+p
  },
  {
    $skip: p
  }
]);

or for find query
 collection.find(f).sort(s).limit(l+p).skip(p)

Though, as you can see the with big pagination the memory will grow more and more even with this optimization.


text:
Q: Strage issue with document path I am working on a ebook reader app. The issue i am facing is with loading a Kannada ebook.
I am loading xhtml files from document dir. to UIWebView.
Now the problem is,
If i give path to file like .../OPS/xhtml/ch1.xhtml
   Then the text is not displaying properly , but all images in book are displaying.
If i give path to file like .../OPS/xhtml//ch1.xhtml
    Then the text is displaying properly , but images in book are not displaying.
I am not able to figer out why this is happening and what is the solution.


text:
Q: How check different spellings of a persons full name I try to create a regular expression with searches in a huge document for a persons full name. In the text the name can be written in full, or the first names can be either abbreviated to a single letter or a letter followed by a dot or omitted. For instance my search for _ALBERTO JORGE ALONSO CALEFACCION_now is:
preg_match('/([;:.,&\s\xc2\-(){}!"'<>]{1})(ALBERTO|A.|A)[\s\xc2-]+
(JORGE|J.|J)?[\s\xc2,]+(ALONSO)[\s\xc2*-]+(CALEFACCION))([;:.,&\s\xc2(){}
!"'<>]{1})/i', $text, $match);

Between the first names and last names an asterisk (*) can be present.
This is working for the case all first names are at least present some way. But I don't know to extend the expression when first names are omitted. Can you help me?

A: Let's start by simplifying what you have;
start:
/([;:.,&\s\xc2\-(){}!"'<>]{1})(ALBERTO|A.|A)[\s\xc2-]+(JORGE|J.|J)?[\s\xc2,]+(ALONSO)[\s\xc2*-]+(CALEFACCION)([;:.,&\s\xc2(){}!"'<>]{1})/i

as I said in my comment, \b is "word break", so you can simplify a lot of that:
/\b(ALBERTO|A.|A)[\s\xc2-]+(JORGE|J.|J)?[\s\xc2,]+(ALONSO)[\s\xc2*-]+(CALEFACCION)\b/i

(added bonus: it won't match the characters either side now, and it will match at the start and end of the text)
Next, you can use the ? token for the dots (which should be escaped by the way; . is special and means "match anything")
/\b(ALBERTO|A\.?)[\s\xc2-]+(JORGE|J\.?)?[\s\xc2,]+(ALONSO)[\s\xc2*-]+(CALEFACCION)\b/i

Finally, to actually answer your question, you have 2 choices. Either make the entire bracketed name optional, or add a new blank option. The first is the most flexible, since we'll need to cope with the whitespace too:
/\b((ALBERTO|A\.?)[\s\xc2-]+((JORGE|J\.?)[\s\xc2,]+)?)?(ALONSO)[\s\xc2*-]+(CALEFACCION)\b/i

Note that if you're reading the matched parts you'll need to update your indices. Also note that this fixed an issue where omitting the second name (JORGE) still required an extra space.
This will match things like A. J. ALONSO CALEFACCION, A. ALONSO CALEFACCION and ALONSO CALEFACCION, but not J. ALONSO CALEFACCION (it's only a small tweak if you do want that)
Breaking up that final string for clarity:
/\b
(
    (ALBERTO|A\.?)[\s\xc2-]+
    (
        (JORGE|J\.?)[\s\xc2,]+
    )?
)?
(ALONSO)[\s\xc2*-]+
(CALEFACCION)
\b/i

Finally, it's an odd thought, but you could change the names which can be initials to be in this form: (A(LBERTO|\.|)), which means you're not repeating the initials (a potential source of mistakes)


text:
Q: Verify Microsoft Visual C++ Redistributable (x86) version with PowerShell I manage an application that requires Microsoft Visual C++ Redistributable (x86) version 14.25.x or higher.  The server I'm testing on has version 14.34.31931 and I can find that in PowerShell with:
$Key = Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Dependencies\VC,redist.x86,x86,14.34,bundle'

$Key.Version

I'm wondering, instead of having "VC,redist.x86,x86,14.34,bundle" in that last spot of the Get-ItemProperty, if I can search for something containing  "VC,redist.x86" and use that key, regardless of the version?  I know if I get that, I can compare the actual version number, but it seems with my current search, I can only search based on already knowing that it's version 14.34.x.


text:
Q: Asymptotic eigenvalue distribution of sum of two i.i.d random matrices with Marchenko Pastur distributed eigenvalues? Is there a method using random matrix theory and NOT using free probability to determine the asymptotic eigenvalue distribution of the random matrix $\mathbf{M}=\mathbf{X}_1+ \mathbf{X}_2$? where:
$\mathbf{X}_i=\mathbf{H}_i\mathbf{H}_i^{*}$ for $i\in\{1,2\}$ where $\mathbf{H}_i$ are both square $N\times N$ random matrices whose entries are i.i.d and follow a normalised Gaussian distribution $\sim {\mathcal{N}}(\mu=0 ,\sigma^{2}=\frac{1}{N})$, so that the asymptotic eigenvalue distributions of $\mathbf{X}_i$ are given by the Marchenko-Pastur law with $\beta=1$.
More generally, is there such a method for finding the AED of the linear combination $\mathbf{M}_p=\alpha\mathbf{X}_1+ \beta\mathbf{X}_2$ for $\alpha, \beta \in \mathbb{R}$?


text:
Q: cvxopt for Markowitz Portfolio Optimization - finding point of optimal Sharpe Ratio I've been trying for 3 days to understand how to use cvxopt module in python to calculate the efficient frontier. A code snippet that I found at: https://github.com/markharley/Markowitz/blob/master/markowitz.py
is probably the best way to illustrate my problem, and I have included in entirety at the bottom of this post.
Using the equations found on the wikipedia page for Modern Portoflio Theory:
https://en.wikipedia.org/wiki/Modern_portfolio_theory#Efficient_frontier_with_no_risk-free_asset

I understand why the first use of solvers.qp uses:
solvers.qp(S, -q*pbar, G, h, A, b)['x']

where q is a risk tolerance factor.
The code then goes on to calculate the point of optimal Sharpe Ratio using polyfit, which I also understand, but where I am lost is why the code now is:
# Calculate the optimal portfolio
wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)['x']

where x1 is the return at the point of optimal Sharpe Ratio. I am lost as to why all of a sudden we can multiply S (covariance matrix) by x1 and also get rid of q in the -pbar term.
Could anyone shed some light on this please? Apologies if I am not explaining this properly, any request for clarification would probably help me make my question clearer as well.
Thanks!
def optimal_portfolio(returns):
n = len(returns)
returns = np.asmatrix(returns)

N = 100
qs = [10**(-5.0 * t/N + 1.0) for t in range(N)]

# Convert to cvxopt matrices
S = opt.matrix(np.cov(returns))

# np.mean computes vector of means along
# as mean of each row
pbar = opt.matrix(np.mean(returns, axis=1))

# Create constraint matrices
# -- documentation at http://cvxopt.org/userguide/coneprog.html#quadratic-programming
G = -opt.matrix(np.eye(n)) # negative nxn id
h = opt.matrix(0.0, (n, 1)) # n x 1 zero vector
A = opt.matrix(1.0, (1, n)) # 1 x n 1-vector
b = opt.matrix(1.0) # [1.0]

## Calculate efficient frontier weights using quadratic programming
## https://en.wikipedia.org/wiki/Quadratic_programming
# Minimizes (1/2) w^T * S * w - q pbar^T * w for weights w
# subject to the constrains:
# G * w <= h (component-wise) -- positive weights
# and A*w = b -- Sum of weights == 1
# where S is the covariance matrix,
# pbar are the mean returns,
# q is a measure of risk tolerance
portfolios = [solvers.qp(S, -q*pbar, G, h, A, b)['x'] for q in qs]

## Could replace above with Lagrange multiplier (or convex hull)

# Calculate risks and mean returns for frontier
returns = [blas.dot(pbar, x) for x in portfolios]
risks = [np.sqrt(blas.dot(x, S * x)) for x in portfolios]

# Calculate quadratic for the frontier curve
m1 = np.polyfit(returns, risks, 2)
x1 = np.sqrt(m1[2] / m1[0])

# Calculate the optimal portfolio
wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)['x']

return np.asarray(wt), returns, risks


text:
Q: NetBeans Built file looks different from actual project I created and Clean and Built my NetBeans project. Unfortunately, my jar file looks VERY different from what it is when I run my project from the IDE.
I tried updating java and JDK versions, but those don't help.

Some differences are: Buttons appear square-shaped(on jar) than rounded edges(on IDE)
  Panels that were made translucent(IDE) appear light blue(jar)
  Font sizes differ
  etc.

Please tell me what must I do to make my built .jar file look exactly what it is on the NetBeans


text:
Q: Dirichlet character proof Let $X$ be a Dirichlet character modulo $m$ and let $a$ be an integer such that $gcd(a,m)=1$.
Prove that $X$ maps an inverse of $a$ modulo $m$ to the complex conjugate of $X(a)$.
Could anybody help me out with this proof? I'm unsure on how to begin.

A: Hint: the inverse of a complex number of absolute value $1$ is its complex conjugate.


text:
Q: XPath - Compare values from different documents This is my XPath expression
$XMLDESCRIPTION/myItems/ITEM[@TYPE="ok" and boolean($XML/myElements/element[ends-with(Description/@code, string(@CODE))])]

The ITEM node in $XMLDESCRIPTION has an attribute called CODE and i want to check in $XML if there is an "element" with a Description/@code that matches the @CODE from $XMLDESCRIPTION
The question is: how do I access the @CODE attribute in the $XML part of my filter?
extra info:

*

*I'm working in an XSLT context (I use stylevision)

*The expression works fine if I type a
fixed value in the "ends-with" part instead of string(@CODE)

XML
This is my $XMLDESCRIPTION snippet
<myItems>
    <ITEM CODE="003423" TYPE="ok">Hello</ITEM>
    <ITEM CODE="003123" TYPE="ok">hello12</ITEM>
    <ITEM CODE="003223" TYPE="notok">Hellollo</ITEM>
    <ITEM CODE="005423" TYPE="notok">Hellolol</ITEM>
    <ITEM CODE="003424" TYPE="ok">HellossSSSDDFFSQSSQDFQSDF</ITEM>
    <ITEM CODE="003442" TYPE="ok">Helloee</ITEM>
    <ITEM CODE="003342" TYPE="ok">Hellodd</ITEM>
    <ITEM CODE="008900" TYPE="ok">Helloee</ITEM>
    <ITEM CODE="003888" TYPE="inprogress">Helloaa</ITEM>
</myItems>

this is a snippet from my $XML document
<myElements>
    <element><Description code="009999">myinformation</Description></element>
    <element><Description code="008888">myinformation</Description></element>
    <element><Description code="003424">myinformation</Description></element>
    <element><Description code="002222">myinformation</Description></element>
    <element><Description code="003333">myinformation</Description></element>
    <element><Description code="005555">myinformation</Description></element>
</myElements>

With those two xml examples my outcome should be "HellossSSSDDFFSQSSQDFQSDF" because that's the only element that has an existing description node with a code "003424" in $XML so that's the only ITEM element's content that the xpath should get.

A: I'm pretty sure you're missing the current() function.
$XMLDESCRIPTION/myItems/ITEM[
  @TYPE="ok"
  and $XML/myElements/element/Description[
    ends-with(@code, current()/@CODE)
  ]
]

A: This XPath should dig out the code attribute from the $XML document:-
/myElements/element/Description[@code]


text:
Q: Solve the following equation algebraically for n. Show your working using factorial notation.?

a) $\dfrac{n!}{(n-2)!} = n(n-1)$
so the expression equivalent to $$\dfrac{n(n-1)}{6} = 12 \implies n(n-1)=72$$
I think its obvious the required solution is $8 \cdot 9 =72$, so $n=9$
b) $8Pn = \dfrac{8!}{(8-n)!} = 6720$
$$(8-n)! = \frac{8!}{6720} = 6 = 3!$$
so $8-n =3 \iff n=5$

A: Looks good. Your answers are correct! Nice work.
You could also algebraically solve for $n$ in $(a)$, though I agree the solution seems "obvious": $$n(n-1) = 72 \iff n^2 - n - 72 = 0 $$ $$\iff (n-9)(n+8) = 0 \iff n = 9, n=-8$$
But since we are talking about non negative integers $n$ in these equations (since we are evaluating expressions with factorials), we can "throw out" $\;n = -8\,$ as an option, and we are left with $\;n = 9.$


text:
Q: What happens to an EventHandler after calling "new" I have a little question and made up an example case:
 public class MyClass
{
    private ObservableCollection<string> PropertyA { get; set; }
    private ObservableCollection<string> PropertyB { get; set; }

    public MyClass()
    {
        PropertyA = new ObservableCollection<string>();
        PropertyA.CollectionChanged += (sender, e) => DoStuff();
        PropertyA.Add("AAAA");

        PropertyB = new ObservableCollection<string>();
        PropertyB.Add("BBBB");

        MyMethod();
    }

    private void MyMethod()
    {
        PropertyA = new ObservableCollection<string>(PropertyB.Where('some linq expression'));
        //does PropertyA still have its CollectionChanged handler from here on?
    }
}

As you might see from my comment the question is: Does the handler of my PropertyA still work after calling 'new' on the Property again? Or do I have to setup the handler again?

A: You will have to set up the property handler for the new object "AAAA".
However, the original object will still exist in memory and won't get garbage collected as the event handler keeps the reference alive. This will cause resource issues if you let it continue. You need to remove the event handler from the object before it either falls out of scope or you overwrite it.

A: You will have to setup the handler again.
Internally you are storing the delegate in the field of the first ObservableCollection instance. Creating a new object means new values for its fields.
You can also test this fast:
private void DoStuff()
{
    Console.WriteLine("handler called");
}

var obj = new MyClass();
obj.PropertyA.Add("1");
obj.MyMethod();
obj.PropertyA.Add("1");

The  code will print "handler called" only once. (see live demo at https://repl.it/DKjs)
You can also update the collection instead of replacing it.
public void MyMethod()
{
    var newValues = PropertyB.Where(x => true);
    PropertyA.Clear();
    foreach (var value in newValues)
    {
        PropertyA.Add(value);
    }
}

This will print "handler called" multiple times (once per each collection update, including removing items, see live demo at https://repl.it/DKlF)


text:
Q: BeautifulSoup not extracting all html (automatically deleting much of a page's html) I am trying to use BeautifulSoup to extract the contents from a website (http://brooklynexposed.com/events/). As an example of the problem I can run the following code:
import urllib
import bs4 as BeautifulSoup

url = 'http://brooklynexposed.com/events/'
html = urllib.urlopen(url).read()

soup = BeautifulSoup.BeautifulSoup(html)
print soup.prettify().encode('utf-8')

The output seems to cut off the html as follows:

        9:00pm - 11:00pm

         Comedy Sh

It is cutting off the listing with the name Comedy Show along with all html that comes after until the final closing tags. Majority of the html is being automatically removed. I have noticed similar things on numerous website, that if the page is too long, BeautifulSoup fails to parse the entire page and just cuts out text. Does anyone have a solution for this? If BeautifulSoup is not capable of handling such pages, does anyone know any other libraries with functions similar to prettify()?

A: I had troubles that bs4 cuts html on some machines and on some not. It was not reproducable....
I switched to this:
soup = bs4.BeautifulSoup(html, 'html5lib')

.. and it works now.

A: It's working fine for me, but I get error when I say soup.prettify().encode('utf-8')
>>> from BeautifulSoup import BeautifulSoup as bs
>>>
>>> import urllib
>>> url = 'http://brooklynexposed.com/events/'
>>> html = urllib.urlopen(url).read()
>>>
>>>
>>> soup = bs(html)
>>> soup.prettify().encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 8788: ordinal not in range(128)
>>>
>>> soup.prettify()
'<!doctype html>\n\n


text:
Q: svg "use" tag displays an svg icon upside down My designer gave me an svg icon.
I display this icon in a D3.js tree layout.
To be able to change the colors I embed the icon in a  tag.
The weird thing is that the icon is diplayed upside down (using chrome).
I dont really understand what is going on there.
I must apply a transformation to get it right
Any Idea ?
The HTML :

    <svg class="menu-icon" width="150" height="150"  style="opacity: 1;"><use x="0"y="0"width="50" height="50" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/img/PurchaseOrder.svg#PurchaseOrder.svg"></use></svg>
    <svg class="menu-icon" width="150" height="150"  style="opacity: 1;"><use x="0"y="0"width="50" height="50" transform="scale(1,-1) translate(0,-50)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/img/PurchaseOrder.svg#PurchaseOrder.svg"></use></svg>

The CSS
.menu-icon {
        pointer-events: none;
        fill:#626469;
    }

The result

The svg :
<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="24px" height="24px" viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;" xml:space="preserve">
<symbol  id="ProjectOrder.svg" viewBox="-12 -12 24 24">
    . . .
</symbol>
<use xlink:href="#ProjectOrder.svg"  width="24" height="24" x="-12" y="-12" transform="matrix(1 0 0 -1 11.9995 11.9995)" style="overflow:visible;"/>
</svg>

A: replace the HTML with the following

    <svg class="menu-icon" width="150" height="150"  style="opacity: 1;"><use x="0"y="0"width="50" height="50" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/img/PurchaseOrder.svg#PurchaseOrder.svg"></use></svg>
    <svg class="menu-icon" width="150" height="150"  style="opacity: 1;"><use x="0"y="0"width="50" height="50" transform="translate(0,-50)" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/img/PurchaseOrder.svg#PurchaseOrder.svg"></use></svg>

what i did is remove the scale(1,-1) from the transform.
what you are doing with scale is basically flipping the Y axis with -1
thats why it is upside-down.

A: css property
transform: rotate(180deg); will do flip.

A: This looks as the same problem that I raised here:
https://graphicdesign.stackexchange.com/questions/76574/adobe-illustrator-svg-upside-down-transform-matrix.
Converting an object to a symbol in illustrator is messed up.
The object is placed inside the symbol upside-down. The symbol is then placed in the document upside-down, too, so the overall effect looks right.


text:
Q: Primary and Secondary datasource using jakarta instead of javax After upgrading to Java 17 and Spring Boot 3.0.1, jakarta is also replacing javax. You can add as many datasources as you like, as long as they share the same username/password and driveClassName.  However, what if you have two datasources with different creds?  There doesn't seem to be an equivalent to how javax handles this. i.e., see first answer here with the Config class...
Spring Boot configure and use two data sources
What is the jakarta equivalent or how do we configure this?


text:
Q: How to import txt file in SAS using infile command I 'm beginner in SAS and currently using SAS 9.1 I want to import txt file using infile command but it is giving error. My code is as follows
data sasdata.twenty;

infile "C:\Users\Ravi Raghava\Desktop\Cricket.txt" firstobs=2;
input Position Runs    Sixes   Fours   balls;
run;
Any help will be highly appreciated.

A: Usually I do it by the following:
proc import datafile='data.txt'
     out=TableName
     replace;
     delimiter='09'x;
run;

It works correctly.

A: you are using the default sas input (i.e. maybe space is used as a separator, guess whether I meant numeric or alpha-numeric and so on). You assume the SAS knows what it is doing. You know what happens when you assume.
Use a
 Length Positions $20 Runs Sixes Fours balls 8;

statement. That will at least make sure the first word is treated as alpha numeric and the rest as numbers. also use the
infile ..... dlm=',';
if you got a CSV file. or
infile ..... dlm='09'x;

if it is a tab separated file.


text:
Q: Cumulative Sum with >=0 Restriction in Matlab I want to calculate the cumulative sum of a vector, but stop summing up once the sum becomes negative, and start again at positive elements.
Example:
We have a vector:
[1 1 -1 -1 -1 -1 1 1 1 1]

The normal cumulative sum would then be:
[1 2 1 0 -1 -2 -1 0 1 2]

But i want:
[1 2 1 0 0 0 1 2 3 4]

The only solution i could come up with was to loop over the elements of the vector like this:
test = [1 1 -1 -1 -1 -1 1 1 1 1];
testCumsum = zeros(size(test));

for i=1:length(test)
    if i==1
        testCumsum(i) = test(i);
    else
        testCumsum(i) = testCumsum(i-1) + test(i);
    end

    if testCumsum(i)<0
        testCumsum(i) = 0;
    end
end

Is the a more matlab-ish solution?
(The sum can become negative an arbitrary number of times, the vectors can become pretty large, and the elements can be any number, not just 1 and -1)

A: You won't be able to vectorize it since you have to decide on each elemenet based on previous ones. You can find regions of positive and negative runs but it would be unnecessarily complex and I don't know if you can gain over your own solution.
Here is a simplification of your code for input A and output C:
C=A;
C(1) = max(C(1), 0);
for k=2:numel(C)
    C(k) = max(C(k-1)+C(k), 0);
end

A: call your vector x,
y=x >0
z=x.*y
sum(z)

the y vector is 0 / 1 where the elemnts of x are greater than 0 the dot product to get z sets your negative values to 0, and then you can sum
_Ah i see more clearly what you want to do now, - looping is probably going to be quickest, you could break into block segments if the array is large and use parfor to speed it up


text:
Q: How to choose the ABI architecture for iOS app I am developing iOS app using Xamarin Forms and I have trouble in choosing the ABI architecture for iOS app. We are targeting iPhones and iPads with iOS version 9 and above.
After the lots of googling, I got the below,
https://www.innerfence.com/howto/apple-ios-devices-dates-versions-instruction-sets
http://wanderingcoder.net/2010/07/19/ought-arm/
My questions are below,
We have three types of architectures,

*

*ARMv7

*ARMv7s

*ARM64

Which architecture or architecture combination will cover the widest range of devices released after 2010?
Will the iOS app build with ARMv7 work in iOS devices having ARMv7s architecture?

A: Part of the answer to your question can be found here.
Part of this information can also be found when choosing the architecture in Xamarin Studio.

Which architecture or architecture combination will cover the widest range of devices released after 2010?

ARMv7 + ARM64
Which is the default in Xamarin.Forms Apps. Of course this is taking into consideration the app size because nothing stop you of using: ARMv7 + ARMv7s + ARM64 but your final application will be bigger in size.

Will the iOS app build with ARMv7 work in iOS devices having ARMv7s architecture?

Yes it does. Bellow is the compatibility table (an old one to show ARMv7s devices) a more updated can be seen here

As you can see ARMv7 builds runs even over iPhone 6
Hopes this helps!


text:
Q: Powerpoint Macro doesnt work on Slideshow Can anybody help me about this issue. I found a script to take snapshot from first page of my PowerPoint. it works when I run the macro in normal view. but when i use the action button (hyperlink it to created macro) and click on it at the slideshow, there is no action.
I expect it to take snapshot from my presentation view every time i click the Action button on slide show.. but nothing
this is the script (I do not have any programming knowledge)
Sub SaveCurrentSlideAsJpg()
Dim imagePath As String
Dim slideNum As Integer
  imagePath = "C:\JPG\"
  slideNum = ActiveWindow.Selection.SlideRange(1).SlideIndex

If Dir(imagePath & ActivePresentation.Name & "_" & slideNum & ".jpg") <> ""
Then
Kill imagePath & ActivePresentation.Name & "_" & slideNum & ".jpg"
End If

ActivePresentation.Slides(slideNum).Export _
FileName:=imagePath & ActivePresentation.Name & "_" & slideNum & ".jpg", _
FilterName:="JPG"

End Sub

A: If you are referencing the SlideIndex during a slideshow, you can do it like this:
slideNum = ActivePresentation.SlideShowWindow.View.Slide.SlideIndex
Here's the full code, with some slight modifications:
Sub SaveCurrentSlideAsJpg()
    Dim imagePath As String
    Dim slideNum As Integer
    Dim fullJpgName As String

    imagePath = "C:\JPG\"

    slideNum = ActivePresentation.SlideShowWindow.View.Slide.SlideIndex
    fullJpgName = imagePath & ActivePresentation.Name & "_" & slideNum & ".jpg"

    If Dir(fullJpgName) <> "" Then
        Kill fullJpgName
    End If

    ActivePresentation.Slides(slideNum).Export _
        FileName:=fullJpgName, FilterName:="JPG"
End Sub


text:
Q: Can I pass a string to istream_iterator I have a string object that contains the value "1 2 3"
Can I use the istream_iterator to extract the values 1, 2 and 3

A: You can, like this:
std::string str = "1 2 3";
std::vector<int> v;
std::istringstream iss(str);
std::istream_iterator<int> begin(iss), end;
std::copy(begin,end,back_inserter(v));

A: Use a std::istringstream:
#include<sstream>
#include<iterator>

// ...
std::string s("1 2 3");
std::istringstream ss(s);
std::copy(std::istream_iterator<int>(ss), std::istream_iterator<int>(),
          std::ostream_iterator<int>(std::cout, "-"));


text:
Q: How to switch to another running application using its process id in C++? How can I switch to another running application in Windows 7 and C++ when I know its process id?
I only have the process id. There might be several applications with the same name so using the window title does not work. I also do not have a reliable HWND to use.
I want the application to be active, visible and ready for input just as if I switched to it using alt-tab.

A: Try
HWND hNewWindow = FindWindow(...); // get window handle by title etc.
if (hNewWindow)
{
    DWORD hCurrentWindowThread = GetWindowThreadProcessId( hWndCurrentWindow, NULL );
    DWORD hNewWindowThread = GetWindowThreadProcessId( hNewWindow, NULL);
    AttachThreadInput( hCurrentWindowThread, hNewWindowThread, TRUE );
    SetForegroundWindow(hNewWindow);
    AttachThreadInput( hCurrentWindowThread, hNewWindowThread, FALSE );
}

SetForegroundWindow is doing the magic you want here. It has limitations outlined here SetforegroundWindow() API
Solution from here.


text:
Q: .LESS how to add width with duration? I'm trying to create a loading bar, which will go longer on width with duration, with .less and here's my layout:

The LESS part is here:
    div.preloader-1 {
        width: 100%;
        border-radius: 1px;
        border: thin solid #d5d5d5;

        em.loader {
            background: @main-red;
            width: @preload_width;
            .addBar('width', 5s);
        }
    }

@body-font: 'Droid Sans', sans-serif;
@heading-font: 'Oswald', sans-serif;

@flash-red: #ff0000;
@flash-green: #40bc88;

@main-green: #40bc88;

/* preloader 1 settings */

@preload_width: 10%;
@preloader1_class: 'preloader-1';

.addBar(@property, @duration, @style:ease-in-out) when(@preload_width <= 100%) {
    -webkit-transition-property: @property;
    -webkit-transition-duration: @duration;
    -webkit-transition-timing-function: @style;

    -moz-transition-property: @property;
    -moz-transition-duration: @duration;
    -moz-transition-timing-function: @style;

    -ms-transition-property: @property;
    -ms-transition-duration: @duration;
    -ms-transition-timing-function: @style;

    -o-transition-property: @property;
    -o-transition-duration: @duration;
    -o-transition-timing-function: @style;

    transition-property: @property;
    transition-duration: @duration;
    transition-timing-function: @style;

    @preload_width: (@preload_width + 10%);
}

Error came out like this:
>> SyntaxError: Recursive variable definition for @preload_width in app\assets\s
tylesheets\less\front\preloader_1.less on line 9, column 3:
>> 8            width: @preload-width;
>> 9            .addBar('width', 5s);
>> 10   }

I'm guessing it's on the whenpart in the less, but i'm not sure how to fix, can anyone explain to me how to do it? Thanks. (Oh yeah, the solution must not include JS or anything else, only pure .less)

A: Well, the problem is really here:
@preload_width: (@preload_width + 10%);

*

*LESS can't handle variable redefinitions (e.g. changing a variable's value)

*You're trying to create a variable with its own value.

Both of these problems can be solved by changing your new variable's name.


text:
Q: how to use a sub query from Dual table within an Oracle insert command? This command should insert a record whose one of fields is millisecond, which gets by a sub query, into a table but returns an error. What is the problem?
insert into table1 values ( select trunc( (to_date('2019-11-26 01:00:00', 'YYYY-MM-DD HH24:MI:SS') - to_date('1970-01-01', 'YYYY-MM-DD')) * power(60, 2) * 24 * power(10, 3)) from dual, 0, 0, 0);

Error report -
SQL Error:
ORA-00936: missing expression
00936. 00000 -  "missing expression"

A: You can just use insert . . . select:
insert into table1
    select trunc( (to_date('2019-11-26 01:00:00', 'YYYY-MM-DD HH24:MI:SS') - to_date('1970-01-01', 'YYYY-MM-DD')) * power(60, 2) * 24 * power(10, 3)),
           0, 0, 0
from dual;

The values keyword is not necessary.  However, you should be including the list of columns for the table.

A: Please use below query,
Also you can Specify the columns names in the query
insert into table1(col1, col2, col3 ...) ( select trunc( (to_date('2019-11-26 01:00:00', 'YYYY-MM-DD HH24:MI:SS') - to_date('1970-01-01', 'YYYY-MM-DD')) * power(60, 2) * 24 * power(10, 3)),0, 0, 0 from dual);

A: You don't need a SELECT and you should always specify the column for INSERT:
insert into table1 (col1, col2, col3, col4)
values (
   trunc( (to_date('2019-11-26 01:00:00', 'YYYY-MM-DD HH24:MI:SS') - DATE '1970-01-01') * 60*60*24*1000), 0, 0, 0
   );

Note, I assume you like to calculate a Javascript timestamp or similar. This is the number of Milliseconds since 1970-01-01 00:00:00 **UTC**. For precise values (i.e. if Milliseconds matters) and proper time zone handling you should use TIMESTAMP WITH TIME ZONE rather than DATE. For example like this:
TRUNC((TO_TIMESTAMP_TZ('2019-11-26 01:00:00.00 Europe/Zurich', 'YYYY-MM-DD HH24:MI:SS.FF TZR') - TIMESTAMP '1970-01-01 00:00:00 UTC') *  60*60*24*1000)


text:
Q: why don't solve that responsive web is different local and server http://api.vankow.com/file/images/8.9%20%EC%B6%9C%EA%B3%A0%EC%A0%95%EC%82%B0.HTML
-> loading page to server is not working responsive
but open to local page is working responsive. i don't understand
file:///C:/Users/mega79/8.9%20%EC%B6%9C%EA%B3%A0%EC%A0%95%EC%82%B0.HTML

A: your img DOM element doesn't have width property,
which will load image source's natural width and height.
that is why your img element was exceeding the layout.
you can simply add style width: 100%; to your img DOM element

A: I solve the problem!  I do it!
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width"/>

<title>VANKOW ERP 메뉴얼입니다.</title>

8.별도 - 8.9 출고정산


text:
Q: Execution stops after the instantiation of a variable with a scanner input I'm doing internships with a small project that asks the user to select a category of expenses, to later request quantities that are stored in a ArrayList and finally the amount of the total expenses of that category is printed on the screen. The problem comes at the moment in which I associate the variable 'quantity' with a Scanner entry, at that moment the execution thread remains in Execution and it does not return any type of error.
package gestioneconomica;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Scanner;
    /**
     *
     * @author Robin
     */
     class Gastos {
        //Declaración de los tipos de gastos organizados en ArrayList()

        ArrayList<Double> taberna=new ArrayList<>();
        ArrayList<Double> tPublico=new ArrayList<>();
        ArrayList<Double> alimentacion=new ArrayList<>();
        ArrayList<Double> formacion=new ArrayList<>();
        //Declaración e inicialización de la suma de los valores de cada ArrayList()
        double sumTaberna=0.0;
        double sumTPublico=0.0;
        double sumAlimentacion=0.0;
        double sumFormacion=0.0;

        //Instanciación del objeto 'sc' de la clase Scanner
        Scanner sd=new Scanner(System.in);
    //*************THE NEXT LINE CAUSES THE ERROR****************
        double quantity=sd.nextDouble();
        //Declaración e inicialización de métodos
        public void addTaberna(){
    System.out.print("Ingrese importe: ");
    while(quantity!=0){
        taberna.add(quantity);
    }
    System.out.print("El total consumido en esta categoría es de: ");
    Iterator <Double> itTaberna=taberna.iterator();
    while(itTaberna.hasNext()){
        System.out.println(itTaberna.next());
    }

}
public void addtPublico(){
    System.out.print("Ingrese importe: ");
    while(quantity!=0){
        tPublico.add(quantity);
    }
    Iterator <Double> itTPublico=tPublico.iterator();
    while(itTPublico.hasNext()){
        sumTPublico+=itTPublico.next();
    }
    System.out.println("Gastos totales en Transporte Público: " + sumTPublico);
                }
        public void addAlimentacion(){
            System.out.print("Ingrese importe: ");
            alimentacion.add(sd.nextDouble());
        }
        public void addFormacion(){
            System.out.print("Ingrese importe: ");
            formacion.add(sd.nextDouble());
        }
    }

//THIS IS THE DRIVER CLASS

package gestioneconomica;
import java.util.Scanner;

class GastosExe{
    public static void main(String[]args){

        System.out.println("###################################################");
        System.out.println("BIENVENIDO/A AL PROGRAMA DE GASTOS DE ROBIN");
        System.out.println("###################################################");
        System.out.println("(1)TABERNA\t(2)TRANSPORTE PÚBLICO\t(3)ALIMENTACIÓN\t (4)INVERSIÓN FORMATIVA");
        System.out.println("Seleccione el tipo de Gasto: ");

        Gastos gastos=new Gastos();
        Scanner sc=new Scanner(System.in);

        int tipo=sc.nextInt();
        switch(tipo){
            case 1:
                System.out.println("Ha seleccionado Taberna");
                gastos.addTaberna();

                break;
            case 2:
                System.out.println("Ha seleccionado Transporte Público");

                break;
            case 3:
                System.out.println("Ha seleccionado Alimentación");
                gastos.addAlimentacion();
                break;
            case 4:
                System.out.println("Ha seleccionado Inversión Formativa");
                gastos.addFormacion();
                break;
        }
    }
}

A: Welcome to SO. This is a very nicely phrased first question.

at that moment the execution thread remains in Execution and it does
  not return any type of error

That's because there is no error here. And the correct term is "at the moment the execution thread (main thread) remains blocked" Your program is behaving exactly the way you coded it to behave
Let's break it down from the main method.
Gastos gastos=new Gastos();

When you call the Gastos constructor here on the main method, the Gastos class initializes, which has the quantity field of type double, initialized directly with the input from the Scanner.
When execution reaches this line double quantity = sd.nextDouble(); it blocks the main thread, waiting for keyboard input from the user..
So you should enter a selection here 1
when you press enter, sd.nextDouble(); method returns, and main thread resumes.
Then, when the Gastos() constructor call returns and the main thread reaches this line int tipo = sc.nextInt();
Which blocks the main thread again, waiting for another keyboard input from the user.
So you should enter a selection here again 2
When you press enter, sc.nextInt(); method returns and the main thread resumes execution
Sample run
###################################################
BIENVENIDO/A AL PROGRAMA DE GASTOS DE ROBIN
###################################################
(1)TABERNA  (2)TRANSPORTE PÚBLICO   (3)ALIMENTACIÓN  (4)INVERSIÓN FORMATIVA
Seleccione el tipo de Gasto:
1
2
Ha seleccionado Transporte Público

A: try:
double quantity = Double.parseDouble(sd.nextLine());


text:
Q: See changes in a merge commit that do not appear in any parent A merge commit can potentially introduce changes that did not appear in any parent commit. For example, when making changes to resolve conflicts or in the case of evil merges. Is there a git command to only see such changes in a merge commit, instead of the default combined-diff format?

A: You audit merge resolutions by rerunning the merge and comparing the automerge result with the recorded result. If the automerge produced conflicts you probably want to look at the resolution even if it's just taking one or the other parents' versions, because, somebody had to choose which and that's a chance for human error right there.
To do this fast, do minimum-checkout merges in a scratch clone.
To make this easier, Git would have to slow down and bulk up every merge, and every repository, and Git's after not doing that.

A: Mechanical checking of a conflict resolution isn't a coherent concept. After all, the reason this is a "conflict" is exactly that a machine can't do the merge. That's all a merge "conflict" is: it's a merge that needs human intervention.
As for your proposed algorithm, it's incorrect: a "conflict" might quite legitimately be resolved by making changes that don't match the parent or either of the two branch diffs. For example:
base: Hello there
branch1: Hello world
branch2: Goodbye there

That's a "conflict". Resolution:
Goodbye world

That is arguably perfectly right, as it carries out exactly the intentions of both branches; but it doesn't match any of the precedents.


text:
Q: Angular Mat Table Column Select and Deselect Please go through link https://stackblitz.com/edit/angular-primeng-table-order-resize-toggle?file=src%2Fapp%2Fapp.component.html As per the link I need to do for Angular Mat table selecting and deselecting columns.

A: Here is a simple proof of concept: https://stackblitz.com/edit/poc-column-selector
The table is hidden if no columns are selected, if you select one or more column they are displayed using the full width (flex).
The displayed order of the columns is decided by their order in the string-array with column definitions, not by the order of the markup in the html file.


text:
Q: 403 error when upload file to Google Drive I'm uploading file to Google Drive (https://developers.google.com/drive/manage-uploads)
And when i click upload button,i get error : "403 Forbidden"
My code:
string access_token = "ya29.1.AADtN_USZWM44X_WIxgAr-f6NcdQ-XG8TEturcGXRADzdeVvXZhSVR8d6Qf98veHqy3ZGLQ";
        string result = "";
        byte[] buffer = uploader.FileBytes;
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");

        req.Method = "POST";
        req.ContentType = "image/jpeg";
        req.ContentLength = buffer.Length;
        req.Headers["Authorization"] = "Bearer "+access_token;

        Stream strm = req.GetRequestStream();
        strm.Write(buffer, 0, buffer.Length);
        strm.Close();

        HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();//Get error here
        if (webResponse.StatusCode == HttpStatusCode.OK)
        {
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            result = responseStreamReader.ReadToEnd();//parse token from result
        }
        lblMessage.Text = result;
        webResponse.Close();

Please help me!


text:
Q: In batch script how to loop through registry sub keys From windows registry I am able to get the list of java version that are installed on my system using below code. But how to loop through the list and store Java home in an array?
@ECHO OFF
REG QUERY "HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit" /S
PAUSE

Output as follows:
output
-----------
D:\ITM\configuration
experience\apm_datacollectors_win_8.1.4.0\j2se_datacollecto
r_win_8.1.4.0\j2sedc\.gdc\7.3.0.5.0\bin>config.bat

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit
CurrentVersion    REG_SZ    1.8

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit\1.7
JavaHome    REG_SZ    C:\Program Files\jdk1.7.0_79
MicroVersion    REG_SZ    0

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit\1.7.0_79
JavaHome    REG_SZ    C:\Program Files\jdk1.7.0_79
MicroVersion    REG_SZ    0

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit\1.8
JavaHome    REG_SZ    C:\Program Files\Java\jdk1.8.0_121
MicroVersion    REG_SZ    0

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit\1.8.0_121
JavaHome    REG_SZ    C:\Program Files\Java\jdk1.8.0_121
MicroVersion    REG_SZ    0

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit\1.8.0_121\MSI
INSTALLDIR    REG_SZ    C:\Program Files\Java\jdk1.8.0_121\
NOSTARTMENU    REG_SZ    0

Press any key to continue . . .

A: There is no such thing as an array in MS-DOS, but you can loop through the results, and get the values for JavaHome like this:
for /f "tokens=3* usebackq" %%a in (`reg query "HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit" /S ^| find "JavaHome"`) do (
    echo %%a %%b
)

A: First of all thanks for the answer and making me (a java developer) aware that arrays are not supported in batch script :-)
What I want to accomplish? --> I am working on a monitoring agent, its currently supplied to the customers in form of a zip file. Customer unzips it and runs a config.bat file to configure the agent on its machine. This config.bat asks user to input JAVA_HOME (directory where java is installed in customers machine), as the agent is java based. My task is to enhance this customer experience by automatically searching for any java installed in his machine and do not to ask customer to actually input JAVA_HOME.
Now, one use case is that there is only a version of Java installed in customers machine. Then config.bat script should read that entry of java from windows registry. But what if there are multiple instances of java installed in customers machine? In such a case I will have to show to the customer that he has multiple instances of java in his machine and he can choose one out of those for the agent installation.
@Berend: Thanks, the for loop that you shared above works fine and returns the result as below. In that for loop %%a is the variable which stores the value after iteration? Is my understanding correct and then what is %%b?
D:\ITM\configuration
experience\apm_datacollectors_win_8.1.4.0\j2se_datacollecto
r_win_8.1.4.0\j2sedc\.gdc\7.3.0.5.0\bin>config.bat
C:\Program Files\jdk1.7.0_79
C:\Program Files\jdk1.7.0_79
C:\Program Files\Java\jdk1.8.0_121
C:\Program Files\Java\jdk1.8.0_121


text:
Q: QUERY function not properly counting matching values with OR criteria in Google Sheets [Goal]
I'm trying to count the number of tickets per employee that has a status with either "Finished," "Finished (Scope)," or "Routed (Sales)." The data that I'm pulling from to count the tickets has the following column names.
Column A: Ticket ID,
Column B: Status,
Column C: Employee,
Column D: Date
In the formula, you'll notice that it's referring to cell H1, which the cell contains the current week with this formula: TODAY()-MOD(TODAY()-2,7)-1
[Current Formula]

=QUERY('Data'!$A$3:$F,"Select C, COUNT(A)
      where B matches 'Finished|Finished (Scope)|Routed (Sales)'
      AND D >= "&H1&" GROUP BY C
      LABEL COUNT(A) 'Total Tickets'",0)

[Issue]
I was able to create a formula that counts the number of tickets per employee with the status called "Finished," however for some reason, it's not counting tickets that has the status name "Finished (Scope)" or "Routed (Sales)." Can someone please help?

A: its a regex so you may need to escape brackets. try:
=QUERY('Data'!$A$3:$F,
 "select C,count(A)
  where lower(B) matches 'finished \(scope\)|routed \(sales\)|finished'
    and D >= "&H1&"
  group by C
  label count(A) 'Total Tickets'", 0)


text:
Q: REGEX statement to pull out digits after a variable string I am trying to pull out a few digits that occur within a complex string, based on the identifier "bas". As an example, if I have a string: "went ahead 5m, backed @45 degrees, bas = 30", I want to pull out the digits "30." Doing this for the above string is simple, but the syntax of the string is rarely regular, which is what I can't figure out how to deal with: the location of "bas + digits" within the string varies (front, middle, end), the digits may come before "bas" (such as "30 = bas"), and/or there may be something else between the digits and bas, such as "bas: 30" or "30-bas" or even "30-40 bas".
Here is the code I have written that does a good job pulling out the digits from one specific string format:
import re
p="went ahead 5m, backed @45 degrees, bas = 30"
c = re.search('bas = (\d{,5})', p, re.IGNORECASE)
print(c.group(1))

result: 30

The issue is I have several thousand rows of data that I want to search through and pull out the bas-associated digits, and the formatting of the strings varies as described above. Any ideas on how to deal with this so I can implement a code that successfully deals with varying string formats?

A: As there are no word characters between the bas word and the number, I suggest using
(\d+(?:-\d+)?)\W*bas\b|\bbas\W*(\d+(?:-\d+)?)

See this regex demo. Note: there are two alternatives in this pattern, and either the first or the second capturing group matches, so either one will always contain some value.
Details

*

*(\d+(?:-\d+)?)\W*bas\b - one or more digits and then an optional occurrence of a - and one or more digits (captured into Group 1) and then zero or more non-word chars and a whole word bas

*| - or

*\bbas\W*(\d+(?:-\d+)?) - a whole word bas, then zero or more non-word chars and then one or more digits and then an optional occurrence of a - and one or more digits (captured into Group 2).

See this Python demo:
import re
pattern = r"(\d+(?:-\d+)?)\W*bas\b|\bbas\W*(\d+(?:-\d+)?)"
texts = ["went ahead 5m, backed @45 degrees, bas = 30", "30 = bas", "bas: 30", "30-bas", "30-40 bas"]
for text in texts:
    m = re.search(pattern, text, re.I)
    if m:
        print(text, [x for x in m.groups() if x][0], sep=" :=>: " )

Output:
went ahead 5m, backed @45 degrees, bas = 30 :=>: 30
30 = bas :=>: 30
bas: 30 :=>: 30
30-bas :=>: 30
30-40 bas :=>: 30-40


text:
Q: How to add a configuration dialog to a Confluence plugin I'd like to have a configuration UI for when someone selects my plugin, to allow them to select a mode/title of the page it will create.
In much the same way the "Retrospective" option does...

Can someone point me in the direction of what I need to do for this please.

A: Have a look to page and space blueprints. When you click on the main "Create" button, you see all the available page blueprints on the wiki. When you click on "Create Space", the space blueprints. Check the following documentation:
https://developer.atlassian.com/confdev/confluence-plugin-guide/confluence-blueprints
Regards,
Gorka


text:
Q: Mathematical operations in Android layout attributes I need to use following otherwise my custom widget was overlapped by a Toolbar:
android:layout_marginTop="?android:attr/actionBarSize"

But I want to have additional margin, say 10dp. I cannot do something like:
android:layout_marginTop="?android:attr/actionBarSize + 10dp"

because + is not allowed character there. Is there any other way except coding a rule programmatically?

A: Layout XML files do not support expressions. So You can't Perform exepression on it. You can perform in XSLT.
There is one trick describe below.
margin + padding as describe in this Answer.
Source : How do I apply mathematical operations to Android dimensions?

A: You could wrap your ViewGroup into another one just to add the 10dp margin. Not optimal but that would work.


text:
Q: Is it possible to get LinkedIn "Competitors analytics" data from LinkedIn API? As a company page admin, I can access a section on the linkedIn website called "competitor analytics" where I can see some metrics about a list of competitors (number of followers, posts etc...).
I wonder if I could get these data from a LinkedIn API? Or any other possibility to get the data in an automated way?
Thank you for your help!


text:
Q: Setting Row Height not working for EPPlus I am trying to set up the height in an existing excel sheet with EPPlus. It does not seem to be working at all. Any idea on what else I could try ?
I have tried setting it before and after initial styling and have tried setting it after filling values but an exception is thrown.
    private static void SetStyleForLine(ExcelWorksheet ws, int lineIndex)
    {
        .....
        ws.Row(lineIndex).CustomHeight = true;
        ws.Row(lineIndex).Height = 50;

    }

Excel sheet is still showing a height of 15.


text:
Q: Python input and output threading I want to create a python script that prints out messages from one thread, while still waiting for you to input on another. Is this possible? And if so, how?
System: Windows 7
Language: Python 2.7
I have tried this (modified from a different question):
import threading
import time

def message_loop():
    while True:
        time.sleep(1)
        print "Hello World"

thread = threading.Thread(target = message_loop)
thread.start()

while True:
    input = raw_input("Prompt> ")

But what happens is: the program waits until I have finished inputting before it outputs Hello World.

A: It's absolutely possible. If you have a function that prints output (let's call it print_output) you can start it up in a different thread using the threading module:
>>> import threading
>>> my_thread = threading.Thread(target=print_output)
>>> my_thread.start()

You should now start getting your output. You can then run the input bit on the main thread. You could also run it in a new thread, but there are some advantages to running input in the main thread.

A: This works for me.
The code prints message before you input 'q'
import threading
import time

def run_thread():
    while True:
        print('thread running')
        time.sleep(2)
        global stop_threads
        if stop_threads:
            break

stop_threads = False
t1 = threading.Thread(target=run_thread)
t1.start()
time.sleep(0.5)

q = ''
while q != 'q':
    q = input()

stop_threads = True
t1.join()
print('finish')


text:
Q: SQL Select TOP 1 for each group in subquery Good morning,
I want to alter my query in such a way, that only the top 1, filtered from h.started asc is selected.
select h.started, *  from wshhistory h
join asset a on h.assetid = a.uid
inner join
(
    select Count(*) as TotalLatest, a.uid, a.deleted from asset a
    join wshhistory h on a.uid = h.assetid
    where h.latest = 1
    group by a.uid, a.deleted
    having Count(*) > 1
) X
on X.uid = h.assetid
where X.deleted = 0 and h.latest = 1
order by h.assetid desc

I searched all over, and found in most posts, to use:
ROW_NUMBER() OVER (PARTITION BY a.uid ORDER BY h.started asc) as rn

But I can't seem to use this since I need use group by, and this results in the error message:

Column 'wshhistory.started' is invalid in the select list because it
  is not contained in either an aggregate function or the GROUP BY
  clause.

To give some extra info about my query:
I need to search where I have duplicates of Latest = 1 (table: wshhistory), of the same assetid.  And then I need to set the them all on 0 except the latest one.

A: I think you want something like this:
with toupdate as (
      select h.*,
             row_number() over (partition by h.assetid order by h.started desc) as seqnum
      from wshhistory h
      where h.latest = 1
     )
update toupdate
    set latest = 0
    where seqnum > 1 and
          exists (select 1
                  from asset a
                  where a.uid = toupdate.assetid and a.deleted = 0
                 );

Sample data and desired results are much easier to work with than non-working queries.


text:
Q: Can't login to the webpage via AFNetworking (Iphone) I want to log in to this webpage and see the logged version in my UIWebView, but my code doesn't work.
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = @{@"username": @"myUsername", @"password": @"myPassword"};
    [manager POST:@"http://9gag.com/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Response: %@", responseObject);
        NSData *data = (NSData*)responseObject;
        NSString *string = [NSString stringWithCString:[data bytes] encoding:NSISOLatin1StringEncoding];
        NSDictionary *headerFields = operation.response.allHeaderFields;
        NSString *cookie = [headerFields valueForKey:@"Set-Cookie"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://9gag.com"]];
        [request addValue:cookie forHTTPHeaderField:@"Cookie"];
        WebViewController *wvc = [[WebViewController alloc] initWithRequest:request];
        [self.navigationController pushViewController:wvc animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

What do you think I am doing wrong? Any help is appreciated!


text:
Q: best way to share data between c codes I have 3 C code running on a RPI. They all start at boot and do some stuff (e.g. reading some data and driving an LCD)
I have implemented the codes separately but now I need to share a 30 byte buffer to be shared between them.
what is your advice to do this?
program1.c<-----------> program2.c<-----------> program3.c
buff[30] <----------->   buff[30] <-----------> buff[30]

A: You can use shared memory IPC, which simply allows you to access the same physical memory from multiple cooperating processes.  I say cooperating because they need to be careful about synchronization, or reads may observe partially written data etc.  Here's one tutorial: http://www.raspberry-projects.com/pi/programming-in-c/memory/shared-memory

A: You basically want to implement an IPC between those processes. Personally, I would like to go with FIFO ( a named pipe ) because they implement the queue structure for you. So, you can focus more on interpreting the data and less on sync problems.
this might help you.


text:
Q: How to pass array query params to AWS API Gateway? A Rails API typically likes array query params like this:
example.com?colors[]=cyan&colors[]=magenta&colors[]=yellow&colors[]=black
How would I map that through to a lambda function?

A: One thing you can't do is have duplicated query string param keys as per https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html:

Duplicated headers are not supported.

API Gateway maps the parameters to a JSON object so as long as each item has their own unique key, you won't get any clobbering.
Your option is good but I brainstormed some other options. You could do something like adding indicies in the square brackets:
example.com?colors[0]=cyan&colors[1]=magenta&colors[2]=yellow&colors[3]=black

You could send the query string in the POST body if you were willing to swap from GET to POST. Then you can parse the raw query string yourself. You can even have repeated param keys here because you are parsing it.
?colors=cyan&colors=magenta&colors=yellow&colors=black

Another POST option is to send a JSON array in the POST body. I know POST isn't as easy to work with as GET but it's an option.
["cyan","magenta","yellow","black"]

A: As discussed in @kjs3 answer, API Gateway doesn't support duplicate parameters in the query string or headers. However you can use the single parameter array format.
Supporting duplicate parameter keys+values is something we do want to do, but I don't have an ETA at the moment.

A: If anyone is using OpenAPI 3.0 spec in AWS Api Gateway then you need to define this in your x-amazon-apigateway-integration like so.
x-amazon-apigateway-integration:
        ...
        requestParameters:
            integration.request.querystring.colors: method.request.multivaluequerystring.colors
        ...

A: Multiple arguments with same name in query string are now supported in API Gateway proxies.
They are passed in the multiValueQueryStringParameters dictionary.
E.g.
 GET /api/path/?param=value&param=othervalue&something=thing

Will generate the following request:
{
    "resource": "/{proxy+}",
    "path": "/ap/path/",
    "httpMethod": "GET",
    "queryStringParameters": {
        "param": "othervalue",  # only the last value is kept here
        "something": "thing"
    },
    "multiValueQueryStringParameters": {
        "param": [
            "value",
            "othervalue"
        ],
        "something": [
            "thing"
        ]
    },
    "pathParameters": {
        "proxy": "api/path"
    },
    # etc
}

See documentation.

A: A little trial and error shows that it's like this:
example.com?colors=['cyan','magenta','yellow','black']