date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/19 | 196 | 767 | <issue_start>username_0: How to show vertical axis of chart where sign of value is always presented.
Positive values should have sign '+' before the value and negative '-'.<issue_comment>username_1: We've had a delay pushing the configuration changes to make it appear in the explorer. [Working on it!]
Upvotes: 3 <issue_comment>username_2: Most likely this is because the recently added export/import functionality is still being polished.
The `!` badges with a `New!` popup when hovering over are still visible in the [Exporting and Importing Entities](https://cloud.google.com/datastore/docs/export-import-entities) left-side navigation bar:
[](https://i.stack.imgur.com/C8t7i.png)
Upvotes: 1 |
2018/03/19 | 3,083 | 9,481 | <issue_start>username_0: I'm facing a problem with a query.
I'm using phpMyAdmin and MySQL.
I'm trying to make a report of all my active clients (`in ___Kardex where KDX_Status='active'`) and :
* count the number of booking they made (`in ___Bookings where BOO_Status!='cancel'`).
* count the number of night they passed (`in ___Bookings where BOO_Status!='cancel'`).
For clarity, here is a sample dataset
```
CREATE TABLE `___Bookings` (
`BOO_Id` int(10) NOT NULL AUTO_INCREMENT,
`BOO_HotelId` varchar(20) NOT NULL,
`BOO_ClientId` int(10) NOT NULL,
`BOO_CompanyId` int(10) NOT NULL,
`BOO_BillingId` int(10) NOT NULL,
`BOO_DateCI` date NOT NULL,
`BOO_DateCO` date NOT NULL,
`BOO_Status` enum('confirmed','notconfirmed','option','cancel','checkin','checkout') NOT NULL,
UNIQUE KEY `BOO_Id` (`BOO_Id`),
KEY `id` (`BOO_Id`)
) ENGINE=MyISAM AUTO_INCREMENT=73 DEFAULT CHARSET=utf8;
INSERT INTO `___Bookings` VALUES
(70,'cus_CNHLMiMOzP5cuM',18,0,30,'2018-03-07','2018-03-12','confirmed'),
(71,'cus_CNHLMiMOzP5cuM',61,62,0,'2018-03-01','2018-03-02','cancel'),
(72,'cus_CNHLMiMOzP5cuM',19,0,0,'2018-03-04','2018-03-06','confirmed'),
(73,'cus_CNHLMiMOzP5cuM',61,0,0,'2018-03-01','2018-03-09','notconfirmed'),
(74,'cus_CNHLMiMOzP5cuM',61,0,0,'2018-03-10','2018-03-11','notconfirmed'),
(75,'cus_CNHLMiMOzP5cuM',19,62,63,'2018-03-10','2018-03-21','option');
CREATE TABLE `___Hotels` (
`HOT_HotelId` varchar(20) NOT NULL,
`HOT_AutoLabel_VIP_Bookings` tinyint(4) NOT NULL,
`HOT_AutoLabel_VIP_Nights` tinyint(4) NOT NULL,
`HOT_AutoLabel_Regular_Bookings` tinyint(4) NOT NULL,
`HOT_AutoLabel_Regular_Nights` tinyint(4) NOT NULL,
`HOT_Status` enum('active','inactive','pending') NOT NULL,
PRIMARY KEY (`HOT_HotelId`),
UNIQUE KEY `HOT_HotelId` (`HOT_HotelId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `___Hotels` VALUES
('cus_CNHLMiMOzP5cuM', 10, 15, 20, 25, 'active');
CREATE TABLE `___Kardex` (
`KDX_Id` int(10) NOT NULL AUTO_INCREMENT,
`KDX_HotelId` varchar(20) NOT NULL,
`KDX_Type` enum('client','company','billing') NOT NULL,
`KDX_Status` enum('active','inactive') NOT NULL,
UNIQUE KEY `KDX_Id` (`KDX_Id`),
KEY `id` (`KDX_Id`)
) ENGINE=MyISAM AUTO_INCREMENT=63 DEFAULT CHARSET=utf8;
INSERT INTO `___Kardex` VALUES
(18,'cus_CNHLMiMOzP5cuM','client','active'),
(19,'cus_CNHLMiMOzP5cuM','client','active'),
(30,'cus_CNHLMiMOzP5cuM','billing','active'),
(61,'cus_CNHLMiMOzP5cuM','client','active'),
(62,'cus_CNHLMiMOzP5cuM','company','inactive'),
(63,'cus_CNHLMiMOzP5cuM','company','active'),
(91,'cus_CNHLMiMOzP5cuM','company','active'),
(92,'cus_CNHLMiMOzP5cuM','company','active');
```
...and my best effort to date...
```
SELECT KDX_Id, KDX_Type,
(
SELECT COUNT(BOO_Id)
FROM ___Bookings
WHERE BOO_Status!='cancel'
AND (
KDX_Id = ___Bookings.BOO_ClientId
OR KDX_Id = ___Bookings.BOO_CompanyId
OR KDX_Id = ___Bookings.BOO_BillingId
)
) AS nb_bookings,
(
SELECT SUM(DATEDIFF(___Bookings.BOO_DateCO, ___Bookings.BOO_DateCI))
FROM ___Bookings
WHERE BOO_Status!='cancel'
AND (
KDX_Id = ___Bookings.BOO_ClientId
OR KDX_Id = ___Bookings.BOO_CompanyId
OR KDX_Id = ___Bookings.BOO_BillingId
)
) AS nb_nights,
HOT_HotelId,
HOT_AutoLabel_VIP_Bookings,
HOT_AutoLabel_VIP_Nights,
HOT_AutoLabel_Regular_Bookings,
HOT_AutoLabel_Regular_Nights
FROM ___Kardex
JOIN ___Hotels
ON ___Kardex.KDX_HotelId = ___Hotels.HOT_HotelId
JOIN ___Bookings
ON ___Kardex.KDX_HotelId = ___Bookings.BOO_HotelId
WHERE KDX_Status='active'
AND HOT_Status='active'
GROUP BY KDX_Id
```
And SQLFiddle of same:
<http://sqlfiddle.com/#!9/67775f/1>
The desired output should be like in my SQLFiddle above except the row 91 and 92 because I do not have any bookings or nights to show for these two entries.
Actually, the query returns me these rows with `NULL` or `0` entries.
**expected results**
```
| KDX_Id | KDX_Type | nb_bookings | nb_nights | HOT_HotelId | HOT_AutoLabel_VIP_Bookings | HOT_AutoLabel_VIP_Nights | HOT_AutoLabel_Regular_Bookings | HOT_AutoLabel_Regular_Nights |
|--------|----------|-------------|-----------|--------------------|----------------------------|--------------------------|--------------------------------|------------------------------|
| 18 | client | 1 | 5 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 19 | client | 2 | 13 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 30 | billing | 1 | 5 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 61 | client | 2 | 9 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 63 | company | 1 | 11 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
```
Any help will be appreciated.
Thanks.<issue_comment>username_1: I've rewritten the query so you don't need GROUP BY to filter out duplicates.
**Query**
```
SELECT
kardex_bookings.KDX_id
, kardex_bookings.KDX_type
, kardex_bookings.nb_bookings
, kardex_bookings.nb_nights
, hotels.HOT_HotelId
, hotels.HOT_AutoLabel_VIP_Bookings
, hotels.HOT_AutoLabel_VIP_Nights
, hotels.HOT_AutoLabel_Regular_Bookings
, hotels.HOT_AutoLabel_Regular_Nights
FROM (
SELECT
kardex.KDX_id
, kardex.KDX_HotelId
, kardex.KDX_type
, kardex.KDX_Status
, (
SELECT
COUNT(bookings.BOO_Id)
FROM
___Bookings bookings
WHERE
bookings.BOO_Status != 'cancel'
AND (
kardex.KDX_Id = bookings.BOO_ClientId
OR
kardex.KDX_Id = bookings.BOO_CompanyId
OR
kardex.KDX_Id = bookings.BOO_BillingId
)
) AS nb_bookings
, (
SELECT
SUM(DATEDIFF(bookings.BOO_DateCO, bookings.BOO_DateCI))
FROM
___Bookings bookings
WHERE
bookings.BOO_Status != 'cancel'
AND (
kardex.KDX_Id = bookings.BOO_ClientId
OR
kardex.KDX_Id = bookings.BOO_CompanyId
OR
kardex.KDX_Id = bookings.BOO_BillingId
)
) AS nb_nights
FROM
___Kardex kardex
)
AS kardex_bookings
INNER JOIN
___Hotels hotels
ON
kardex_bookings.KDX_HotelId = hotels.HOT_HotelId
WHERE
kardex_bookings.KDX_Status = 'active'
AND
# filter out non-bookings
kardex_bookings.nb_bookings != 0
AND
kardex_bookings.nb_nights IS NOT NULL
AND
hotels.HOT_Status = 'active'
ORDER BY
kardex_bookings.KDX_Id ASC
```
**Results**
```
| KDX_id | KDX_type | nb_bookings | nb_nights | HOT_HotelId | HOT_AutoLabel_VIP_Bookings | HOT_AutoLabel_VIP_Nights | HOT_AutoLabel_Regular_Bookings | HOT_AutoLabel_Regular_Nights |
|--------|----------|-------------|-----------|--------------------|----------------------------|--------------------------|--------------------------------|------------------------------|
| 18 | client | 1 | 5 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 19 | client | 2 | 13 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 30 | billing | 1 | 5 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 61 | client | 2 | 9 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 63 | company | 1 | 11 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
```
**demo**
<http://sqlfiddle.com/#!9/67775f/56>
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here i made certain changes to your query:
```
SELECT KDX_Id, KDX_Type,nb_bookings,nb_nights,
HOT_HotelId,
HOT_AutoLabel_VIP_Bookings,
HOT_AutoLabel_VIP_Nights,
HOT_AutoLabel_Regular_Bookings,
HOT_AutoLabel_Regular_Nights
FROM (
SELECT KDX_Id, KDX_Type,COUNT(BOO_Id) AS nb_bookings,SUM(DATEDIFF(___Bookings.BOO_DateCO, ___Bookings.BOO_DateCI)) AS nb_nights,
___Kardex.KDX_HotelId
FROM ___Bookings
INNER JOIN ___Kardex
WHERE BOO_Status!='cancel' AND KDX_Status='active'
AND (
KDX_Id = ___Bookings.BOO_ClientId
OR KDX_Id = ___Bookings.BOO_CompanyId
OR KDX_Id = ___Bookings.BOO_BillingId
)
GROUP BY KDX_Id
) aa
JOIN ___Hotels ON aa.KDX_HotelId = ___Hotels.HOT_HotelId AND HOT_Status='active'
```
This is giving the result as you want. Please let me know if it works for you!!
This is for the case of **disabling** 'only\_full\_group\_by' sql\_mode.
Upvotes: 0 |
2018/03/19 | 1,932 | 6,517 | <issue_start>username_0: Please bear with me as my question is kinda two-fold. But I'll be very clear.
I have written a `python` script which I intend to be able to install using `pip install` .
Let's say inside this folder I have following structure
```
\_\_init\_\_.py
area.py
```
I have a function `area_of_triangle` inside `area.py` that accepts command line arguments and computes the area of a triangle.
Below is the content of `area.py`
```
import argparse
from math import sqrt
def area_of_triangle():
parser = argparse.ArgumentParser(prog="Area of Triangle")
parser.add_argument("-v", "--verbose", type=int, help="turn verbosity ON/OFF", choices=[0,1])
parser.add_argument("-a", "--sideA", type=float, help="side A of triangle")
parser.add_argument("-b", "--sideB", type=float, help="side B of triangle")
parser.add_argument("-c", "--sideC", type=float, help="side C of triangle")
args = parser.parse_args()
s = (args.sideA + args.sideB + args.sideC)/2
area_hero = sqrt(s*(s-args.sideA)*(s-args.sideB)*(s-args.sideC))
if args.verbose==1:
print("for triangle of sides {:<6f}, {:<6f}, {:<6f}, ".format(args.sideA, args.sideB, args.sideC))
print("the semi perimeter is {:<6f} while the area is {:<6f}".format(s, area_hero))
else:
print("area = {:<6f}".format(area_hero))
if __name__ == "__main__":
area_of_triangle()
```
I can fire up `cmd.exe` inside `package_name` directory and do `python area.py -a 5 -b 7 -c 10` and I would get the value of the area.
What I want to ask now is this: If inside of that open `cmd.exe` I now type `python` to enter into the python shell proper, is there anyway I can still pass those arguments to the function?
In essence, what I would like to be able to do is
```
from package_name import area_of_triangle
area_of_triangle() -a 5 -b 7 -c 10
```
I have tried this and found that it won't work. So is there any way of accomplishing something equivalent?
I expect the answer is NO. In that case (perhaps I should as this in a separate question, but I just want to give a good enough context) how do I add `package_name` to `path` during `pip install package_name` so that the user can just go ahead and run `area_of_triangle() -a 5 -b 7 -c 10`. I want to be able to accomplish something like `mkvirtualenv envname`
Thanks for answers.<issue_comment>username_1: I've rewritten the query so you don't need GROUP BY to filter out duplicates.
**Query**
```
SELECT
kardex_bookings.KDX_id
, kardex_bookings.KDX_type
, kardex_bookings.nb_bookings
, kardex_bookings.nb_nights
, hotels.HOT_HotelId
, hotels.HOT_AutoLabel_VIP_Bookings
, hotels.HOT_AutoLabel_VIP_Nights
, hotels.HOT_AutoLabel_Regular_Bookings
, hotels.HOT_AutoLabel_Regular_Nights
FROM (
SELECT
kardex.KDX_id
, kardex.KDX_HotelId
, kardex.KDX_type
, kardex.KDX_Status
, (
SELECT
COUNT(bookings.BOO_Id)
FROM
___Bookings bookings
WHERE
bookings.BOO_Status != 'cancel'
AND (
kardex.KDX_Id = bookings.BOO_ClientId
OR
kardex.KDX_Id = bookings.BOO_CompanyId
OR
kardex.KDX_Id = bookings.BOO_BillingId
)
) AS nb_bookings
, (
SELECT
SUM(DATEDIFF(bookings.BOO_DateCO, bookings.BOO_DateCI))
FROM
___Bookings bookings
WHERE
bookings.BOO_Status != 'cancel'
AND (
kardex.KDX_Id = bookings.BOO_ClientId
OR
kardex.KDX_Id = bookings.BOO_CompanyId
OR
kardex.KDX_Id = bookings.BOO_BillingId
)
) AS nb_nights
FROM
___Kardex kardex
)
AS kardex_bookings
INNER JOIN
___Hotels hotels
ON
kardex_bookings.KDX_HotelId = hotels.HOT_HotelId
WHERE
kardex_bookings.KDX_Status = 'active'
AND
# filter out non-bookings
kardex_bookings.nb_bookings != 0
AND
kardex_bookings.nb_nights IS NOT NULL
AND
hotels.HOT_Status = 'active'
ORDER BY
kardex_bookings.KDX_Id ASC
```
**Results**
```
| KDX_id | KDX_type | nb_bookings | nb_nights | HOT_HotelId | HOT_AutoLabel_VIP_Bookings | HOT_AutoLabel_VIP_Nights | HOT_AutoLabel_Regular_Bookings | HOT_AutoLabel_Regular_Nights |
|--------|----------|-------------|-----------|--------------------|----------------------------|--------------------------|--------------------------------|------------------------------|
| 18 | client | 1 | 5 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 19 | client | 2 | 13 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 30 | billing | 1 | 5 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 61 | client | 2 | 9 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
| 63 | company | 1 | 11 | cus_CNHLMiMOzP5cuM | 10 | 15 | 20 | 25 |
```
**demo**
<http://sqlfiddle.com/#!9/67775f/56>
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here i made certain changes to your query:
```
SELECT KDX_Id, KDX_Type,nb_bookings,nb_nights,
HOT_HotelId,
HOT_AutoLabel_VIP_Bookings,
HOT_AutoLabel_VIP_Nights,
HOT_AutoLabel_Regular_Bookings,
HOT_AutoLabel_Regular_Nights
FROM (
SELECT KDX_Id, KDX_Type,COUNT(BOO_Id) AS nb_bookings,SUM(DATEDIFF(___Bookings.BOO_DateCO, ___Bookings.BOO_DateCI)) AS nb_nights,
___Kardex.KDX_HotelId
FROM ___Bookings
INNER JOIN ___Kardex
WHERE BOO_Status!='cancel' AND KDX_Status='active'
AND (
KDX_Id = ___Bookings.BOO_ClientId
OR KDX_Id = ___Bookings.BOO_CompanyId
OR KDX_Id = ___Bookings.BOO_BillingId
)
GROUP BY KDX_Id
) aa
JOIN ___Hotels ON aa.KDX_HotelId = ___Hotels.HOT_HotelId AND HOT_Status='active'
```
This is giving the result as you want. Please let me know if it works for you!!
This is for the case of **disabling** 'only\_full\_group\_by' sql\_mode.
Upvotes: 0 |
2018/03/19 | 601 | 2,387 | <issue_start>username_0: I am using a `QWebView` to display plots using javascript and D3. There is a combobox to select different datasets. Each time a new dataset is selected, some calculations are done, then the javascript is reinitialized with the new data and set as an html string. Then the `QWebview` is reset using `QWebView::setHtml()`.
If I change the combobox value a few times, the plots load exponentially slower each time until it eventually freezes. Sometimes it will eventually load and sometimes not.
(I'm not sure the javascript is relevant - it is not my area of expertise so I haven't taken the time to understand it yet. I'm hoping the problem can be resolved with Qt code - but let me know and I can include that)
From the QWebView documentation: "The html is loaded immediately; external objects are loaded asynchronously."
My guess is that the javascript continues to execute in the background and it doesn't stop when the html is updated and reloaded. Is there a way to stop this?
The code for initializing and updating are as follows:
```
dataView::dataView(QWidget* parent) : QWidget(parent)
{
init();
}
void dataView::init()
{
webView = new QWebView();
// Need path to exe as this is where the local copies of the js files are.
QUrl path = webView->url();
path.setUrl(QCoreApplication::applicationDirPath());
m_jsPath = path.toString().toStdString();
// Initialise the html string
htmlText=""
webSetting = webView->settings();
// Maybe doing nothing-----------------------
webSetting->setObjectCacheCapacities(0, 0, 0);
webSetting->setMaximumPagesInCache(1);
//--------------------------------------------
QPointer mainLayout = new QVBoxLayout();
mainLayout->addWidget(webView);
setLayout(mainLayout);
}
void dataview::updatePlot()
{
//Get new value and do some calculations
// Update html string with new data
std::string htmlString = "[new javascript]";
webView->setHtml(QString::fromLocal8bit(htmlString.c\_str()));
}
```<issue_comment>username_1: There seems to be a problem with QWebkit 5.5. I compiled with Qt5.3 and the issue is not present.
Upvotes: 1 <issue_comment>username_2: I had a problem with this in QML and webview. I resolved it by placing this in the html. Granted it will only work if you have control of the HTML
```
stuff
body stuff
```
the 12 = 12 seconds
Upvotes: 0 |
2018/03/19 | 524 | 2,285 | <issue_start>username_0: ```
bootstrap3 &bootstrap4 in same html file
some code here which require bootstrap3 css files
some code here which requires bootstrap4 css files
```
i have problem in this section so please help me out to solve this<issue_comment>username_1: I believe the quick answer is No, for a number of reasons.
Note, While I believe you're talking about CSS, you don't exactly state whether you're talking about the CSS of bootstrap or the JS of bootstrap, or both.
Regardless, surely both bootstrap 3 and 4 both have styles and JS functions with the same names, and would surely conflict - or just be overwritten. (The last thing loaded usually overwrites the previous thing loaded).
Secondly, a little comment here about cooperation.
The team should standardize on what to use, not go in different directions on something like this. ("Too many chefs in the kitchen" comes to mind.)
There should be a serious talk / debate (not argument ) about the pluses and minuses of which bootstrap to use. I acknowledge, that there are perfectly valid reasons not to use Bootstrap 4 (that's another story), but honestly - just because something is the latest thing, doesn't mean you HAVE to use it, and there are many more examples and "best practices" of Bootstrap 3 out there, at this point in time.
Regardless,I'd suggest that your team stay focused on solving the current problem at hand, IMHO.
Upvotes: 4 <issue_comment>username_2: It's not possible to integrate both bootstrap3 and bootstrap 4 because of many classes of the bootstrap library with the same name.
Upvotes: 2 <issue_comment>username_3: The best practice is to stick to particular bootstrap and use it Throughout your project. As the functionality of every bootstrap differs from one another, it is not a good practice to use different bootstraps for 1 project.
So I would suggest you to use Bootstrap based on your project needs like for e.g: whether you want to build mobile-responsive site first or web-responsive, come to conclusion and then decide which Bootstrap suits your needs.
Upvotes: 0 <issue_comment>username_4: Technically you can only if you duplicate any one css version and rename class so both version con't conflict. But this is not something feasible to do.
Upvotes: 0 |
2018/03/19 | 287 | 995 | <issue_start>username_0: I want to feed a list of identities from
```
get-msoluser | select userprincipalname
```
to:
```
Set-CsOnlineDialInConferencingUser -allowpstnonlymeetings $true -Identity <EMAIL>
```
But integrating these two is where I'm struggling, I'm guessing a `foreach` loop is the best approach? But I just can't get it to work.<issue_comment>username_1: You should be able to do a `foreach-object` loop like so:
```
get-msoluser |
select-object userprincipalname |
Foreach-object {
set-csonlinedialinconferencinguser `
-allowpstnonlymeetings $true `
-identity $_.userprincipalname
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Foreach-loop is faster than foreach-object. (data stored to memory before execution)
```
$Users = get-msoluser
Foreach ($User in $Users)
{
Set-CsOnlineDialInConferencingUser -allowpstnonlymeetings $true -Identity $User.userprincipalname
}
```
Upvotes: 0 |
2018/03/19 | 394 | 1,423 | <issue_start>username_0: I use `"cypress": "2.1.0"` for website functional test.
Also I have condition in tests:
```
if (WIDTH < 1025 && WIDTH > 480) {
it('Open search sidebar', function () {
cy.wait(500);
cy.get('.FilterStroke_resultsLabel_7gBlM').safeClick();
});
}
```
My question is how to get screen size `(WIDTH, HEIGHT)`?<issue_comment>username_1: It depends on how you are using viewPorts. If you are using [cy.viewport(...)](https://docs.cypress.io/api/commands/viewport.html#Syntax) command, then you are easily able to store arguments to a variable.
However, I'm assuming, that you are trying to get width and height of the browser without explicitly setting viewport before the test.
In this way, cypress takes the default windows width and height from the configuration.
You are able to access the [configuration](https://docs.cypress.io/api/cypress-api/config.html#Name-and-Value) trough the global `Cypress` variable, e.g.:
```
Cypress.config("viewportWidth") // => 800
OR
Cypress.config().viewportWidth // => 800
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: You could also get what is *actually being displayed at the time* rather than the global default configuration with:
```js
const WIDTH = window.innerWidth
```
This matches the viewport dimensions displayed by Cypress wherever I have tested it. There is a matching `innerHeight` property if needed.
Upvotes: -1 |
2018/03/19 | 856 | 2,687 | <issue_start>username_0: I have the following PHP post from HTML
The output from the `mvsce -d 1234-56-78 -l 1 -s 1` command is displayed from bash as follows
```
TAR 332
PCXLA-TAACC
```
over the two lines.
The code below only ever outputs the 2nd line `PCXLA-TAACC`
```
php
$mvdate=$_POST['fdate'];
$mvlevel=$_POST['flevel'];
$mvsite=$_POST['fsite'];
$mvse = shell_exec ('/usr/local/bin/mvsce -d "'.$mvdate.'" -l "'.$mvlevel.'" -s "'.$mvsite.'"');
echo $mvse;
?
```
---
**How can I get the code to display both lines in a browser windows?**
---
The HTML I use to post for the PHP
```
makeVSCE Output
===============
Date (YYYY-MM-DD):
Level:
Sequence:
```<issue_comment>username_1: >
> How can I get the code to display both lines in a browser window?
>
>
>
**Short answer: You have to render a minimal HTML page and format output according to HTML.**
---
Let your script `makevsce.php` begin sending the client **a minimal HTML page with the body "*open*"**:
```
php
header( "Content-Type: text/html; charset=utf-8" );
echo "<!DOCTYPE html\n";
echo "\n";
echo "\n";
echo "\n";
echo "Shell Output (or whatever...)\n";
echo "\n";
echo "\n";
```
---
**Let PHP properly escape the arguments** injected in the string passed to the shell.
```
$mvdate = escapeshellarg( $_POST['fdate'] );
$mvlevel = escapeshellarg( $_POST['flevel']);
$mvsite = escapeshellarg( $_POST['fsite'] );
```
---
Use **[`exec`](http://cn2.php.net/manual/en/function.exec.php)** instead of `shell_exec`
```
exec( "/usr/local/bin/mvsce -d $mvdate -l $mvlevel -s $mvsite",
$mvse,
$return_value );
```
`$mvse` (passed by reference) will receive an array containing all the lines sent as output from the invoked command.
While the (optional) parameter `$return_value` holds the return value of the shell command.
---
**To display the output:**
```
foreach( $mvse as $line ) {
echo htmlspecialchars( $line ) . "
\n";
```
Note that prior printing each output line text is properly HTML escaped since you're talking about displaying output in a browser.
At the end of each line a will be interpreted by the browser as a line break.
---
Finally to close the HTML page:
```
echo "\n";
echo "";
```
---
**Security notice:**
Be aware you're executing via the shell a command created using input from the **client**.
A properly forged request may cause execution of arbitrary command with the same privileges as the PHP runtime.
Upvotes: 1 <issue_comment>username_2: OK,
This is not an issue with PHP code.
If I write the output from the command to anything other than console it only writes the 2nd line.
Thanks for all your help.
Upvotes: 0 |
2018/03/19 | 624 | 2,299 | <issue_start>username_0: When I turn on Live Testing my tests show "Excluded from live unit testing". This only happens if I use NUnit, using MSTest works fine.
I have:
Visual Studio Enterprise 2017 (15.6.2)
NUnit 3.10.1
A brief example of code
```
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
}
}
[TestFixture]
public class NUnitTest1
{
[Test]
public void NUnitTestMethod1()
{
}
}
}
```
`TestMethod1()` has a green checkmark next to the beaker indicating Live Unit testing is on and covered by a test.
`NUnitTestMethod1()` has the beaker, but no checkmark and mousing over it shows "Excluded from live unit testing".
What am I missing? Outside of me adding NUnit through Nuget and adding the extra test class/method there were no other edits or changes done. I'm running on a fresh install of Visual Studio where the only other thing added is ReSharper Ultimate (2017.3.2).<issue_comment>username_1: Do you have both NUnit and the NUnit3TestAdapter? According to the [docs](https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing), you need NUnit 3.5.0 and NUnit3TestAdapter 3.5.1.
Upvotes: 0 <issue_comment>username_2: You cannot mix two test frameworks in one project. Visual Studio checks each installed test adapter to see if it handles the given test project. Once it finds one that works, it stops checking the others. In your case, the MSTest adapter will be used and since the MSTest adapter doesn't understand NUnit tests, it will not run those tests.
Create a separate NUnit test project, ensure you don't reference MSTest and add NUnit 3.10.0 and the NUnit3TestAdapter 3.10 NuGet packages to your project. If you are using .NET 4.x, that should get you up and running. If you are targeting .NET Core, see the NUnit docs for more information, <https://github.com/nunit/docs/wiki/.NET-Core-and-.NET-Standard>
This is live unit testing of an NUnit project in 15.6.2. Notice the green checkmarks.
[](https://i.stack.imgur.com/8e3rA.png)
Upvotes: 3 [selected_answer] |
2018/03/19 | 639 | 2,641 | <issue_start>username_0: I am trying to do something with Flutter.io
But i have some problems. Its not well documented for my Action.
I want to get an Android Application with an AlertDialog. But my keyboard are over the Alertdialog. So i found a workaround to push the Dialog up when the keyboard opens, but i dont really understand it.
So my plan is to move up the AlertDialog. Its centered at the moment. I want to add an Margin bottom to the "AlertDialog".
Here is my function which will opens the Dialog if i click the Fabbutton.
```
void _openNewInputPopup() {
print("popup will open");
AlertDialog dialog = new AlertDialog(
content: new SingleChildScrollView(
child: new Column(
children: [
new Text('Wie lautet das Versteck?',
style: new TextStyle(fontSize: 18.0),),
new TextField(onChanged: (String value) {
{
print("changed $value");
}
},),
],
),
),
actions: [
new FlatButton(onPressed: () {
\_dialogResult(MyDialogAction.Abbrechen);
}, child: new Text('Abbrechen')),
new FlatButton(onPressed: () {
\_dialogResult(MyDialogAction.Anlegen);
}, child: new Text('Anlegen')),
]
);
showDialog(context: context, child: dialog);
}
```
It would be very nice if someone of you has a little bit more experience with flutter and could help me :) Thanks<issue_comment>username_1: I adjust padding according to textfield has focus or not. I hope it will help..
```
return SingleChildScrollView(
padding: EdgeInsets.only(top: yourFocus.hasFocus ?
MediaQuery.of(context).size.height / 2 - 250 // adjust values according to your need
: MediaQuery.of(context).size.height / 2 - 130),// adjust values according to your need
child: AlertDialog(
title: Text("your Alert header text"),
content: TextField(
focusNode: yourFocus,
controller: yourTextController,
decoration: InputDecoration.collapsed(
hintText: "your hint text."),
),
actions: [
FlatButton(
child: Text("Your button Title"),
onPressed: () {
yourFunction();
})
]));
```
Upvotes: 2 <issue_comment>username_2: Add padding or margin to the bottom of parent Widget:
```
margin: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
```
OR
```
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
```
and add `resizeToAvoidBottomInset: false,` this to your Scaffold Widget
Upvotes: 1 |
2018/03/19 | 1,468 | 5,808 | <issue_start>username_0: I am currently participating in several machine learning competitions as I am trying to learn this field.
For a regression problem, I'm using a `xgboost`.
Here is the procedure I use :
After feature engineering, I split my data into 2 sets, one training set, and one testing set, as usual. Then I fit my `xgboost` on the training set and validate on the testing set. Here are the results I get : (I also show the public set results when I used the trained algorithm to predict the target for submission, the metric is mae).
```
Iteration training score testing score public score
100 8.05 12.14 17.50
150 7.10 11.96 17.30
```
Remarks :
* All data sets (train/test/public set) are roughly the same size, approximately 200 000 samples.
* It is a time serie, so I didn't shuffle the data when splitting, even though shuffling it doesn't change the results..
* I also tried to train my xgboost on the samples that are temporaly close to the public data set, but the results aren't better.
* When I train on all data (train+test) before I submit, I got an improvement on public score of 0.35.
Here are my questions :
* Can we really estimate the over-fitting by just looking at the difference between training and testing score? Or is it only an indicator of over-fitting?
* Why does my submission score improved by increasing the number of iterations even if it shows that I'm increasingly over-fitting?
* Why is the improvement in submission score even better than the improvement in the testing score?
* Why testing score and submission score are not closer? Why do I have systemically a big difference between testing and submission score, regardless of the hyperparameters or "over-fitting rate".
Is this statement true: If the ratio of useful information learned over the useless information (training set specific information) is greater than 1, then you can continue over-fitting and still improve the model?
I hope it's not too confusing, I'm sorry I may not have the proper vocabulary.
I have to mention that, even with over-fitting and the big difference between testing and public score, I still am currently the second on the leaderboard with 50 people participating.<issue_comment>username_1: First of all understand what over-fitting is.
you can see over fit when the training score is increasing (or error is decreasing) while your testing set score is decreasing (or error is increasing)
Over fit is when your training model is too precise and doesn't generalize on the problem you try to solve. In other words its too FIT for the training, and the training alone, so that it cannot solve/predict a different data set.
In your example it seems like both the errors of the train and the test are decreasing, which means you are not over fitting.
Over fitting is always a **bad** thing.
As for your current problem. If you want to run multiple cross validations, or manually split your data for many training and many testing sets you can do the following:
1. Split the data for training and testing (50%, 50%) or (70%, 30%), what ever you think is right for you
2. Then, randomly sample with X% your training data, and it'll be the training set.
3. Randomly sample the testing data with Y% and it'll be your testing set
4. I suggest X = Y = 75%. And the above split to be 70% training and 30% testing.
As for your questions:
1. It is just an indicator for over fit.
2. You are not over fitting by your example
3. Score will varies on different data sets
4. Same answer as 3
Adding a picture to describe over fitting: [](https://i.stack.imgur.com/tH9oz.jpg)
There is a point (10) in complexity where keep training will decrease the training error but will INCREASE the testing error.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Just some thoughts that might help you...
The final result of a Kaggle competition is the private leaderboard, where your model will be tested on data you haven't yet seen. It is no use optimising your model to predict well on the public leaderboard (submission dataset) and then dropping 10 places because you overfitted and didn't cross-validate, so your model didn't generalise well. You have to do some cross-validation and I would advise you to trust the results.
Note that in percentage terms, your decreases in MAE are 11.8%, 1.5% and 1.1%, so your submission score is improving the least.
You have to be careful sometimes with time series data – which part of the data is most similar to the public/private leaderboard data? For example, if you have a years’ worth of data and you train on Jan-Jun 16, test on Jul-Dec 16 and then validate (submit) on Jan-Jun 17 then you might expect a better result for your submission than you test dataset. In that case, you might discard Jul-Dec 16 data completely and train/test only on Jan-Jun 16.
You are obviously doing something right if you are in 2nd place but please remember to cross-validate. There were competitions in the past where people fall hundreds of places because their models didn't generalise well!
Upvotes: 2 <issue_comment>username_3: Check out this image trying to fit data points:
[](https://i.stack.imgur.com/UdwZB.png)
your function will fit given data points perfectly, resulting in Xi squared lower than 1.
Further see : <https://en.wikipedia.org/wiki/Reduced_chi-squared_statistic>
In essence:
* your model will not generalize
* work well on the test set
P.S check kaggle leader boards pre and post win. They evaluate on a different subset of data. Mostly leading algorithms do badly on the 'not seen before' data.
Upvotes: 2 |
2018/03/19 | 372 | 1,414 | <issue_start>username_0: I'm trying to connect my PHP app to MongoDB in Google Cloud but I'm getting an error. Those are the steps I followed.
1- MongoDB is installed and working with Bitnami's launcher
2- I installed mongodb PHP extension
```
sudo apt-get install mongodb
```
[](https://i.stack.imgur.com/MilOe.png)
3- I created a php.ini file in the root (same directory as app.yaml) and added the extension
```
extension=mongodb.so
```
**Error**
Neither `phpinfo` or `extension_loaded` shows mongodb extension as loaded in my server, therefore, I can't connect. Can anyone help me to figure out what am I missing?<issue_comment>username_1: Correct way to add mongodb extension is as follows(see [this](https://cloud.google.com/appengine/docs/standard/php/runtime#PHP_Enabled_extensions)):
```
extension = "mongo.so"
```
Also as <NAME> commented, `sudo apt-get install mongodb` installs the mongodb itself. My understanding is that you don't need to install neither that nor the extension, Google App Engine Flex environment already supports this via `php.ini` configuration.
Upvotes: 0 <issue_comment>username_2: I already found the solution. The problem, as Alex suggested in his comment, was that I was installing the server and not the PHP driver.
That made the trick:
```
sudo apt-get install php-mongodb
```
Upvotes: 1 |
2018/03/19 | 960 | 3,643 | <issue_start>username_0: Note: This question is different from [this](https://stackoverflow.com/questions/37964187/preload-multiple-images-with-glide) question as no answers given for the question explain how to cancel the image request which we make for preloaded image.
I have an infinite list(`RecyclerView`). I need to preload images of next 'x'(read 3) items from the last bound item of the `RecyclerView`. Also, when a particular `Viewholder` is detached from the window, I need to cancel the preload image request if it is already not successful.
I have achieved it in the following way.
```
Map simpleTargetMap = new HashMap<>();
public void preloadImage(int position, Context context, String imageUrl) {
SimpleTarget simpleTarget = new SimpleTarget() {
@Override
public void onResourceReady(@NonNull Object resource, @Nullable Transition transition) {
simpleTargetMap.remove(position);
}
};
Glide.with(context)asBitmap().load(imageUrl).into(simpleTarget);
simpleTargetMap.put(position, simpleTarget);
}
@Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder);
SimpleTarget simpleTarget = simpleTargetMap.get(holder.getAdapterPosition());
Glide.with(context).clear(simpleTarget);
simpleTargetMap.remove(holder.getAdapterPosition());
}
```
I am able to achieve the desired result. But I am facing memory issues with this approach. If I don't use the preloading, my memory usage is between 150-200 mb. But if I start using the preload, the memory usage jumps to 250-300 mb. After taking a heap dump, I see a lot of Bitmap objects which are not there(not as many) if I don't use preload.
So what is the best way to preload an image in Glide where I can also cancel the image request in the future? And if I don't use SimpleTarget, is there any way of cancelling an image request based only of the imageUrl?<issue_comment>username_1: Load images into memory cache using preload method:
```
Glide.with(context)
.load(url)
.preload(500, 500);
```
You can later use the cached images using:
```
Glide.with(yourFragment)
.load(yourUrl)
.into(yourView);
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: In your case, instead of preloading one item at a time, you should be using ListPreloader in conjunction with the RecyclerViewPreloader which handles the loading one batch at a time.
Refer to <https://github.com/bumptech/glide/blob/master/library/src/main/java/com/bumptech/glide/ListPreloader.java> and
<https://github.com/bumptech/glide/blob/master/integration/recyclerview/src/main/java/com/bumptech/glide/integration/recyclerview/RecyclerViewPreloader.java>
```
* Loads a few resources ahead in the direction of scrolling in any {@link AbsListView} so that
* images are in the memory cache just before the corresponding view in created in the list. Gives
* the appearance of an infinitely large image cache, depending on scrolling speed, cpu speed, and
* cache size.
```
If you are adamant about creating a cancel mechanism yourself, then look at how Glide do it in their ListPreloader class. Specifically they use a requestManager to handle the cancelling. Below is their code snippet for cancelAll.
```
private void cancelAll() {
for (int i = 0; i < maxPreload; i++) {
requestManager.clear(preloadTargetQueue.next(0, 0));
}
}
```
PreloadTargetQueue is a custom inner class in that file.
Upvotes: 1 <issue_comment>username_3: Best way to cancel the image request is to call `Glide.clear()`
Here is the sample code.
```
Glide.with(context).clear(imageviewRef);
```
Upvotes: 3 |
2018/03/19 | 728 | 3,059 | <issue_start>username_0: I want to know if it is possible generate a dynamic pdf.
Let me tell you more about what we want and if you can help us:
We have an entity called "Application" what we want to do is from the Application data generate a pdf. The problem is that the application does not have the same "structure" always. The application has a list of questions. And the number of question could be or not the same for all the applications.
So If I upload a template with 4 possible questions, but my application have 5 I will not able to map the data correctly.
So basically the structure of the pdf is based on my entity "Application".
I have research about this and found this question:
[Docusign: Creating a Document with dynamic content](https://stackoverflow.com/questions/37151325/docusign-creating-a-document-with-dynamic-content)
They ask for a Purchase Order that has some detail data that is not allways the same.
So I was wondering if my scenario is the same as the question?
Do you have any kind of solution for this?
Thanks for all your help!<issue_comment>username_1: You cannot use DocuSign server template in this scenario as generated PDF is dynamic in nature, instead when you are generating PDF on your end then think of generating PDF to use either Anchor String or create PDF Field Names as per DS Standards so that DocuSign can automatically place DS Tabs on the PDF.
Anchor String is already explained in the link which you shared in your post. To create PDF Field Names you can refer to [PDF Field Transformation](https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST%20API%20References/Document%20Parameters.htm#Transfor) and to use that PDF fields for creating an envelope is explained [here](https://stackoverflow.com/questions/24189713/docusign-transform-pdf-fields-for-multiple-recipients)
Upvotes: 1 <issue_comment>username_2: I will add to Amit's fine answer some additional comments:
1. As Amit says, your app needs to compose the document. You can compose the document in PDF or in other formats. HTML can be a good alternative to PDF since it is often easier to create. You can include css and graphics inline since external css and image files are not supported.
2. You can add additional document(s) to an envelope if you want. So the base agreement can be one document and the variable data can be another.
3. Your envelope (a set of documents) can include a "signing page" as the last document, this could be a constant document.
4. When you add a document to an envelope, you can apply a template to it. That way the anchor strings in the document will be used for field (tab) placement.
5. After you add a document to an envelope, your app can explicitly add additional tabs (fields) to the document--you don't have to use a template for doing this.
6. Compositing Templates and documents together can be used to create an envelope that includes multiple templates and documents. If you're creating a document dynamically for an envelope, Composite Templates may not be as needed.
Upvotes: 0 |
2018/03/19 | 664 | 2,283 | <issue_start>username_0: I have a solution that consists of both single-target and multi-target projects. The solution can be built in Visual Studio 2017 and Developer Command Prompt for VS 2017 without problems.
I build the solution by below code in Developer Command Prompt for VS 2017
```
msbuild MySolution.sln /t:Rebuild /p:Configuration=Release
```
I want to do this process in Jenkins. Then I added below command to Jenkins.
```
pushd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools"
call VsDevCmd.bat
msbuild "C:\Workspace\My Solution\MySolution.sln" /t:Build /p:Configuration=Release
```
When I build the Jenkins project it throws an exception.
```
C:\Program Files\dotnet\sdk\2.1.101\Sdks\Microsoft.NET.Sdk\build\
Microsoft.PackageDependencyResolution.targets(327,5): error : Assets file
'C:\Workspace\My Solution\Source\MyProject\obj\project.assets.json' not found.
Run a NuGet package restore to generate this file.
```
Thanks a lot<issue_comment>username_1: Visual Studio usually will do the nuget package restore for you (It can be turned off in settings).
Building the solution from the command line is a different story. You are not using visual studio, but rather plain old MSBuild. MSBuild does not know about your nuget package.
So you have to manually restore your nuget packages first.
```
pushd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools"
call VsDevCmd.bat
nuget restore "C:\Workspace\My Solution\MySolution.sln"
msbuild "C:\Workspace\My Solution\MySolution.sln" /t:Build /p:Configuration=Release
```
Upvotes: 1 <issue_comment>username_2: Jenkins cannot recognize **msbuild** command. When I change the code like below it started working.
```
C:\nuget.exe restore "C:\Workspace\My Solution\MySolution.sln"
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\amd64\MSBuild.exe" "C:\Workspace\My Solution\MySolution.sln" /t:Build /p:Configuration=Release;VisualStudioVersion=15.0
```
I added nuget restore command and changed **msbuild** command with full path of **msbuild.exe**. Finally I put **VisualStudioVersion** as a parameter.
Thanks [@c-johnson](https://stackoverflow.com/users/321866/c-johnson/ "c-johnson")
Upvotes: 1 [selected_answer] |
2018/03/19 | 871 | 3,233 | <issue_start>username_0: I'm looking for a way to automatically make a list of all object names in a PowerPoint presentation through a simple VBA script. I name certain objects using the selection pane on several slides and need to generate a list of all objects' names on each slide. My knowledge is unfortunately close to nil but I managed to adapt a script I found on here
```
Sub ListAllShapes()
Dim curSlide As Slide
Dim curShape As Shape
For Each curSlide In ActivePresentation.Slides
Debug.Print curSlide.SlideNumber
For Each curShape In curSlide.Shapes
Debug.Print curShape.Name
Next curShape
Next curSlide
End Sub
```
The problem with the script is that it reaches the limit of the debug screen buffer of 190 or so lines and cuts the first portion of the shapes list. If it is possible to write the debug output to an external txt file that would be great.
Another solution which would bypass the debug line limit is to put a filter of the shape name so it only prints names with a certain prefix. e.g. all shapes that have a name starting with "ph-"
Other solutions are welcome as well. Thanks.<issue_comment>username_1: I once wrote some code, aiming to do just that - try it out, hope that helps!
```
Sub ReadPPT()
Dim WB As Workbook
Dim PP As PowerPoint.Application
Dim Pres As PowerPoint.Presentation
Dim SLD As PowerPoint.Slide
Dim SHP As PowerPoint.Shape
Dim PresPath As String
Dim r As Long
Dim sh As Long
Set WB = ThisWorkbook
With ThisWorkbook.Sheets(1)
'Let user select a ppt-file and select its path
PresPath = Application.GetOpenFilename("PowerPoint Presentations (*.pptx), *.pptx", _
, "Open Presentation", "Open", 0)
If PresPath = "" Then Exit Sub
'Create ppt-Application and show it
Set PP = CreateObject("PowerPoint.Application")
PP.Visible = True
'Open previously selected ppt-file
Set Pres = PP.Presentations.Open(PresPath)
sh = 1
For Each SLD In Pres.Slides
r = 2
If SLD.Shapes.Count > 9 Then
' .Cells(0 + r, 2) = SLD.SlideID
' r = r + 1
For Each SHP In SLD.Shapes
If SHP.HasTextFrame Then
If SHP.TextFrame.HasText Then
.Cells(0 + r, 2) = CStr(SHP.Name)
.Cells(0 + r, 3) = CStr(SHP.TextFrame.TextRange.Text)
r = r + 1
End If
End If
Next SHP
sh = sh + 1
End If
Next SLD
PP.Quit
End With
End Sub
```
Upvotes: 0 <issue_comment>username_2: Using your code and as @SteveRindsberg suggests - output to a text file.
This code will create the file in the same folder as your presentation:
```
Sub ListAllShapes()
Dim curSlide As Slide
Dim curShape As Shape
Dim lFile As Long
Dim sPath As String
sPath = ActivePresentation.Path
lFile = FreeFile
Open sPath & "\Object Names.txt" For Append As #lFile
For Each curSlide In ActivePresentation.Slides
Print #lFile, curSlide.SlideNumber
For Each curShape In curSlide.Shapes
If Left(curShape.Name, 3) = "ph-" Then
Print #lFile, curShape.Name
End If
Next curShape
Next curSlide
Close #lFile
End Sub
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 740 | 2,544 | <issue_start>username_0: I want to generate Base64 string for a specific image.
for that I've wrote below code
```
let imageData = UIImagePNGRepresentation(imgProfile.image!)!
var imageStr = imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
```
and I'm getting [this](http://dpaste.com/1DNSD2P) output string as Base64 which is not decoded (i.e. wrong).
but when I'm generating Base64 from [here](http://freeonlinetools24.com/base64-image), I'm getting [this](http://dpaste.com/1HNM669) output string, which is successfully decoded and getting the image back (i.e. correct)
Please help me to find the issue.
Thanks in advance
I've already visited following threads.
1. <https://stackoverflow.com/a/47610733/3110026>
2. <https://stackoverflow.com/a/46309421/3110026><issue_comment>username_1: try below UIImage extension:
```
extension UIImage {
/// Encoded Base64 String of the image
var base64: String? {
guard let imageData = UIImageJPEGRepresentation(self, 1.0) as NSData? else {
print("Error occured while encoding image to base64. In \(self), \(#function)")
return nil
}
return imageData.base64EncodedString()
}
}
```
Upvotes: 0 <issue_comment>username_2: The string is properly encoded. You are adding CRLF (`\n\r`) after each 64 characters with the options you passed.
The simplest solution is to pass **no options**
```
let imageData = UIImagePNGRepresentation(imgProfile.image!)!
let imageStr = imageData.base64EncodedString()
```
Or decode the data with options `ignoreUnknownCharacters`
```
let imageData = UIImagePNGRepresentation(imgProfile.image!)!
let imageStr = imageData.base64EncodedString(options: .lineLength64Characters)
...
if let data = Data(base64Encoded: imageStr, options: .ignoreUnknownCharacters) { ...
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: Additional,
I was getting the same problem, but for me \r\n was not the issue, when i get the base64 string from server there were blank spaces between some characters and after comparing it with correct Base64 string what i found is that i have to add "+" sign in blank spaces. When I did that...Bingooooo......
"yourBase64String" can contain \r\n..
```
if let cleanImageString = yourBase64String.replacingOccurrences(of: " ", with: "+") {
if let data = Data(base64Encoded: cleanImageString, options: .ignoreUnknownCharacters) {
yourImageView.image = UIImage(data: data)
}
}
```
Upvotes: 1 |
2018/03/19 | 275 | 1,167 | <issue_start>username_0: We have a build definition in VSTS, where the build triggers are scheduled with "Only schedule builds if the source or the definition has changed" checkbox selected.
The issue that we have noticed is that the schedule build is triggered when there is no change to either the build definition or the source code. The scheduled build is triggered even when there is a manually triggered build with the same source version.<issue_comment>username_1: I submit a feedback here: [VSTS build Only schedule builds if the source](https://developercommunity.visualstudio.com/content/problem/218545/vsts-build-only-schedule-builds-if-the-source-or-d.html) or definition has changed that you can vote.
Upvotes: 0 <issue_comment>username_2: This is as designed. It looks at the most recent successful scheduled build. Does not consider manually queued builds here because they could have run with a different set of properties. [VSTS build Only schedule builds if the source or definition has changed](https://developercommunity.visualstudio.com/content/problem/218545/vsts-build-only-schedule-builds-if-the-source-or-d.html)
Upvotes: 2 [selected_answer] |
2018/03/19 | 495 | 1,833 | <issue_start>username_0: I have a very strange problem with a website: for some unknown reason it loads very slow some images.
For example: There are 16 images to load ( each image is .jpg, around 10k ) and every time 3-4 of this images are (random) loaded in 4-5 seconds and all others in a good time 600ms.
Is insane that to load 30-40k of 3-4 images the Waterfall is >= 15s by considering also that the domain is SSL, have CloudFlare active and is running on a good dedicated server with cPanel.
Are several days that I'm trying to find a solution and I have already: try to disable cloudflare, try to load the images from a subdomain, try to compress the images, try several .htaccess settings.
Regarding lazyload, in this case it can't help me because all 16 images are in the browser view ( like the youtube homepage )
GTMetrix report ID: cA72pYL1
Any suggestion is good, thank you a lot.
--- Additional informations and tests ---
* Using cPanel - Apache
* To load an image of 10k now the average is around 0.7s
* Any error log ( web/server side )
* The rest of website/server load without problems<issue_comment>username_1: I submit a feedback here: [VSTS build Only schedule builds if the source](https://developercommunity.visualstudio.com/content/problem/218545/vsts-build-only-schedule-builds-if-the-source-or-d.html) or definition has changed that you can vote.
Upvotes: 0 <issue_comment>username_2: This is as designed. It looks at the most recent successful scheduled build. Does not consider manually queued builds here because they could have run with a different set of properties. [VSTS build Only schedule builds if the source or definition has changed](https://developercommunity.visualstudio.com/content/problem/218545/vsts-build-only-schedule-builds-if-the-source-or-d.html)
Upvotes: 2 [selected_answer] |
2018/03/19 | 306 | 958 | <issue_start>username_0: I want to make a layout which is divided into 3 parts like this :
[](https://i.stack.imgur.com/fqT0a.jpg)
And here is my code :
```
xml version="1.0" encoding="utf-8"?
```
Is it correct way to make this or there is a better way ? I am new to android and that's why asking this. Thanks :)<issue_comment>username_1: Try this code :
```
xml version="1.0" encoding="utf-8"?
```
Hope it will help
Upvotes: 2 [selected_answer]<issue_comment>username_2: use grid layout with 2 rows and 2 column for that vertical relativelayout use rowspan
you can also have look on it - [Android: Layout with row span](https://stackoverflow.com/questions/8302203/android-layout-with-row-span)
Upvotes: 0 <issue_comment>username_3: [](https://i.stack.imgur.com/OP8WP.png)Paste this
`
```
```
`
Upvotes: 0 |
2018/03/19 | 419 | 1,713 | <issue_start>username_0: I have an EditText view in a fragment and when showing that fragment, I need to let it get focus and the soft keyboard pops up to allow user type in directly, however, the EditText view seems can only get focus but not show the keyboard even though I manually force it to show. The user has to touch it to bring up the soft keyboard. I tried to get a minimum app to reproduce this, it's simply an activity with an EditText. Any idea?
Activity
```
package com.example.litaos.testeditview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editText = findViewById(R.id.edit_text);
editText.requestFocus();
final InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}
```
Layout
```
xml version="1.0" encoding="utf-8"?
```<issue_comment>username_1: Have you tried adding **requestFocus** ?
```
```
Upvotes: 1 <issue_comment>username_2: I think it's not enough to just request focus. Please try adding following code to your onCreate method:
```
if(editText.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
```
I hope this helps you!
Upvotes: 3 [selected_answer] |
2018/03/19 | 1,297 | 5,305 | <issue_start>username_0: I have one already created project.
In this they are using one method for encrypting the String.
In this project now I have to create a method which I can used for decrypting the encrypted string.
For encrypting a string the below method is used
```
private String EncryptPwd(String pwd) {
String encryptPwd = "";
if (!pwd.isEmpty()) {
byte[] sha1Bytes = EncryptionUtils.getSha1(pwd);
StringBuilder sb = new StringBuilder();
for (byte b : sha1Bytes) {
sb.append(b);
}
encryptPwd = sb.toString();
}
return encryptPwd;
}
```
EncryptionUtils class code is given below
```
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.Logger;
public final class EncryptionUtils {
private static QueueCacheValueCloner byteArrayCloner = new QueueCacheValueCloner() {
public byte[] cloneBean(byte[] original) {
return (byte[]) original.clone();
}
};
private static Logger logger = MiscUtils.getLogger();
private static final MessageDigest messageDigest = initMessageDigest();
private static final QueueCache sha1Cache = new QueueCache(4, 2048, byteArrayCloner);
private static final int MAX\_SHA\_KEY\_CACHE\_SIZE = 2048;
private static MessageDigest initMessageDigest() {
try {
return MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
logger.error("Error", e);
}
return null;
}
public static byte[] getSha1(String s) {
byte[] b = (byte[]) sha1Cache.get(s);
if (b == null) {
b = getSha1NoCache(s);
if (s.length() < 2048) {
sha1Cache.put(s, b);
}
}
return b;
}
protected static byte[] getSha1NoCache(String s) {
}
public static SecretKey generateEncryptionKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
}
public static SecretKeySpec generateEncryptionKey(String seed) {
byte[] sha1 = getSha1(seed);
SecretKeySpec secretKey = new SecretKeySpec(sha1, 0, 16, "AES");
return secretKey;
}
public static byte[] encrypt(SecretKey secretKey, byte[] plainData) throws IllegalBlockSizeException,
BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
if (secretKey == null) {
return plainData;
}
Cipher cipher = Cipher.getInstance("AES");
cipher.init(1, secretKey);
byte[] results = cipher.doFinal(plainData);
return results;
}
public static byte[] decrypt(SecretKey secretKey, byte[] encryptedData) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
if (secretKey == null) {
return encryptedData;
}
Cipher cipher = Cipher.getInstance("AES");
cipher.init(2, secretKey);
byte[] results = cipher.doFinal(encryptedData);
return results;
}
}
```
Now I have to create a method for decrypting the encrypted string.
So can anyone suggest me how can I decrypt a String which is encrypted by above `EncryptPwd` method.<issue_comment>username_1: SHA1 is a hash function designed in a way that you should not be able to decrypt anything that is "encrypted" (well really it's not encrypted - it's just hash of the message - as suggested in comments) with it (as it's on-directional function)
Instead you can store in your system SHA signature (not original password) and compare the signature (if you know how to generate it).
This has advantage that nobody knows the password (except the user), and you still can verify if he entered it correctly (you just know how to generate SHA from user input, but do not store his password in plain text)
Upvotes: 1 <issue_comment>username_2: Hashing is not encryption. Secure hashing is a one way function that creates output of a certain length indistinguishable from random to an attacker not knowing the original input.
The only way to "reverse" the hash is to test all possible input values. If you find the correct hash then you've found the input, as it is computationally impossible to find two messages that generate the same output value. At least, that used to be the case until Google found a way to create so called SHA-1 collisions using the *Shattered* attack. This will however not have any effect on strings like password that usually have size and format limitations.
Just hashing the password using SHA-1 is making yourself susceptible to rainbow table attacks. Duplicate passwords can also easily be identified (if there are multiple accounts). Caching the result will also make your password table susceptible to simple timing attacks. Just maybe using a real *password hash* such as Argon2 and requiring a specific password strength would be a good idea.
The way to verify a password hash is then to perform the same calculation, starting from a given password (salt and work factor) and then compare the result. Decryption doesn't come into it.
Upvotes: 2 |
2018/03/19 | 853 | 2,911 | <issue_start>username_0: I'm trying to add an array of `Funcionarios` objects into a `Equipa` object, but when i try to `push` a `new Funcionarios` it pops and this error `TypeError: Cannot read property 'push' of undefined`, i have gone over the code several times and initialized all variables, but it keeps always giving me the same error.
```
export class Funcionarios {
id : Number;
codFunc: Number;
nomeFunc: string;
constructor(codFunc: Number, nomeFunc: string) {
this.codFunc = codFunc;
this.nomeFunc = nomeFunc;
}
}
export class Equipa {
id : Number;
codEquipa: Number;
nomeEquipa: string;
ocorFuncs: Funcionarios[] = [];
constructor(id : Number, codEquipa: Number, nomeEquipa: string, funcs: Funcionarios[]) {
this.id = id;
this.codEquipa = codEquipa;
this.nomeEquipa = nomeEquipa;
this.ocorFuncs = funcs;
}
}
export class TestComponent implements OnInit {
equipa: Equipa = new Equipa(null, null, null, null);
ngOnInit() {
this.equipa.ocorFuncs.push(new Funcionarios(1, "qwe"));
this.equipa.ocorFuncs.push(new Funcionarios(2, "asd"));
this.equipa.ocorFuncs.push(new Funcionarios(3, "zxc"));
}
}
```<issue_comment>username_1: Okay, so you see what you are truing to do right now.
You want to push value to the `null`, `null` have no push method.
if you change this declaration line to
```
equipa: Equipa = new Equipa(null, null, null, []);
```
it will work fine, checked on stackblitz
Upvotes: 2 [selected_answer]<issue_comment>username_2: The constructor for `Equipa` assigns `ocorFuncs` with whatever comes from the parameter `funcs` which in your case is `null`, and thus overrides the value you initialize the field with. You should check if the parameter is null and leave the default value if the parameter is null:
```
export class Equipa {
id : Number;
codEquipa: Number;
nomeEquipa: string;
ocorFuncs: Funcionarios[] = [];
constructor(id : Number, codEquipa: Number, nomeEquipa: string, funcs: Funcionarios[]) {
this.id = id;
this.codEquipa = codEquipa;
this.nomeEquipa = nomeEquipa;
this.ocorFuncs = funcs || this.ocorFuncs;
}
}
```
Upvotes: 0 <issue_comment>username_3: You create your `Equipa` object like so:
`new Equipa(null, null, null, null);`
The fourth argument, to initialize `ocorFuncs` is passed as `null` so:
`this.equipa.ocorFuncs.push(new Funcionarios(3, "zxc"))`
is invoking `push` on an object that has not been initialised correctly.
Upvotes: 0 <issue_comment>username_4: You are initializing your `equipa` with `null` values. So after calling
`new Equipa(null, null, null, null)`
it is setting them inside the constructor as `null`
`this.ocorFuncs = funcs;`
try initializing it with an empty array
`equipa: Equipa = new Equipa(null, null, null, []);`
Upvotes: 0 |
2018/03/19 | 868 | 2,959 | <issue_start>username_0: I have imported a calendar table from datameer over to my sql server database. I am fairly new to SQL so I do not have the best understanding of the convert function. I have a calendar table with 5 columns (cal\_month, cal\_year, Toronto, Montreal, National\_Avg). The data types are (nvarchar, nvarchar, numeric, numeric, float).
Example of a row in the table would be:
```
Month | Year | Toronto | Montreal | National Average
---------+------+---------+----------+------------------
January | 2018 | 20 | 21 | 20.5
```
Below is my attempt at the convert function, my query is supposed to identify current month and -1 to grab the national average from the previous month so in this instance it would be for February 2018.
```
select convert(date, cal_month), convert(date,cal_year), National_Avg
from dbo.CALENDAR
where month(cal_month) = month(dateadd(month,-1,current_timestamp))
and year(cal_year) = year(dateadd(month,-1,current_timestamp))
```
The error I am receiving is:
```
Conversion failed when converting date and/or time from character string.
```<issue_comment>username_1: The problem is probably that you're trying to convert a month/year integer to a date.
Try:
```
SELECT DATEADD(month, cal_month -1, DATEADD(year, cal_year-1900, 0))
from dbo.CALENDAR
```
Or if you need to get the month/year from today, try
```
DECLARE @oneMonthAgo datetime
SET @oneMonthAgo = DATEADD(MONTH, -1, CURRENT_TIMESTAMP)
DECLARE @cal_month int
SET @cal_month = MONTH(@oneMonthAgo)
DECLARE @cal_year int
SET @cal_year = YEAR(@oneMonthAgo)
SELECT National_Avg
FROM dbo.CALENDAR
WHERE cal_year = @cal_year AND cal_month = @cal_month
```
Ah, just noticed you use the monthname - that is stupid, but anyway:
```
DECLARE @cal_month nvarchar(200)
SET @cal_month = DATENAME(month, @oneMonthAgo)
```
Everything else stays the same.
Or you could add a computed column to the calendar table:
```
ALTER TABLE dbo.Calendar ADD MonthNum AS
CASE Month
WHEN 'January' THEN 1
WHEN 'February' THEN 2
WHEN 'March' THEN 3
WHEN 'April' THEN 4
WHEN 'May' THEN 5
WHEN 'June' THEN 6
WHEN 'July' THEN 7
WHEN 'August' THEN 8
WHEN 'September' THEN 9
WHEN 'October' THEN 10
WHEN 'November' THEN 11
WHEN 'December' THEN 12
END PERSISTED
```
That way, you do the lookup faster, as integer.
Which will come in handy as the table fills and gets larger.
Upvotes: -1 <issue_comment>username_2: You don't need to manipulate the data in the table. You just need to manipulate your search parameter `current_timestamp` to fit the data's data-types.
```
SELECT cal_month, cal_year, National_Avg
FROM dbo.CALENDAR
WHERE cal_month = DATENAME(mm, DATEADD(month,-1,current_timestamp))
AND cal_year = DATENAME(yyyy, DATEADD(month,-1,current_timestamp))
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 793 | 2,680 | <issue_start>username_0: I am trying to run a simple web application with using Spring Boot but there is a problem with resolving view. When I go to <http://localhost:8080/> it shows;
```
There was an unexpected error (type=Not Found, status=404).
```
Is there any missing property or library? Why it cannot resolve my html page?
My application.properties;
```
spring.mvc.view.prefix: WEB-INF/html/
spring.mvc.view.suffix: .html
```
[](https://i.stack.imgur.com/2QnWu.png)
```
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Controller
public class InfoController {
@RequestMapping("/")
public String getServerInfo(Map model){
//This method works without any problem.
model.put("message", "server info");
return "info";
}
}
```<issue_comment>username_1: Try create tree of files like in [here](https://spring.io/guides/gs/serving-web-content/).
```
src/main/resources/static
```
or
```
src/main/resources/templates/ //here put html files
```
Upvotes: 1 <issue_comment>username_2: If you use spring boot with some template engine, for example, thymeleaf. You don't need to set `spring.mvc.view.prefix` or `spring.mvc.view.suffix` by default.
You just need to put your template files under the directory `src/main/resources/templates/`:
[](https://i.stack.imgur.com/HiXY7.png)
And your controller will be something like:
```
@GetMapping("/temp")
public String temp(Model model) {
model.addAttribute("attr", "attr");
return "index";
}
```
If you are **NOT** using any template engine and just want to serve HTML page as static content, put your HTML files under the directory `src/main/resources/static/`:
[](https://i.stack.imgur.com/hPpRe.png)
And your controller will become:
```
@GetMapping("/test")
public String test() {
return "test.html";
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_3: putting in here worked for me in a spring-boot web sample:
```
src/main/webapp/index.xhtml
```
then in the browser enter:
```
http://localhost:8080/index.html
```
here is a linkt to the sample:
```
https://www.logicbig.com/tutorials/spring-framework/spring-boot/boot-primefaces-integration.html
```
Upvotes: 0 <issue_comment>username_4: if you are using thymeleaf for spring boot. just add below to `pom.xml`
```
org.springframework.boot
spring-boot-starter-thymeleaf
```
Upvotes: 2 |
2018/03/19 | 473 | 1,439 | <issue_start>username_0: I have crawler that extract links from page only if the link text include given text and I'm writing the output to html file. Its working but I would like to add whole link text next to these links like this - "Junior Java developer - <https://www.jobs.cz/junior-developer/>" How can I do this?
Thanks
```
import requests
from bs4 import BeautifulSoup
import re
def jobs_crawler(max_pages):
page = 1
file_name = 'links.html'
while page < max_pages:
url = 'https://www.jobs.cz/prace/praha/?field%5B%5D=200900011&field%5B%5D=200900012&field%5B%5D=200900013&page=' + str(page)
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
page += 1
file = open(file_name,'w')
for link in soup.find_all('a', {'class': 'search-list__main-info__title__link'}, text=re.compile('IT', re.IGNORECASE)):
href = link.get('href') + '\n'
file.write('['+ 'LINK TEXT HERE' + '](' + href + ')' + '
')
print(href)
file.close()
print('Saved to %s' % file_name)
jobs_crawler(5)
```<issue_comment>username_1: Try this:--
```
href = link.get('href') + '\n'
txt = link.get_text('href') #will give you text
```
Upvotes: 0 <issue_comment>username_2: This should help.
```
file.write('''[{1}]({0})
'''.format(link.get('href'), link.text ))
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 224 | 558 | <issue_start>username_0: Input string: `["1189-13627273","89-13706681","118-13708388"]`
Expected Output: `["14013627273","14013706681","14013708388"]`
What I am trying to achieve is to replace any numbers till the '-' for each item with hard coded text like '140'<issue_comment>username_1: Try this:--
```
href = link.get('href') + '\n'
txt = link.get_text('href') #will give you text
```
Upvotes: 0 <issue_comment>username_2: This should help.
```
file.write('''[{1}]({0})
'''.format(link.get('href'), link.text ))
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 216 | 811 | <issue_start>username_0: I am working on creating an application which is very dynamic in nature and needs to create API on the fly. I have decided to use loopback as my backend, I want to create an API by just passing the model as json it create an endpoint and have the functionality of crud operation on the fly. Is there a way to do this in loopback? Or can someone guide me in the right direction? I have checked the StackOverflow other questions in this regard but they are not guiding me in the right direction.<issue_comment>username_1: Try this:--
```
href = link.get('href') + '\n'
txt = link.get_text('href') #will give you text
```
Upvotes: 0 <issue_comment>username_2: This should help.
```
file.write('''[{1}]({0})
'''.format(link.get('href'), link.text ))
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 413 | 1,740 | <issue_start>username_0: I am using the Talend open studio for Data Integration tool for transfer sql server table data to mysql server database.
I have a 40 million records into the table.
I created and run the job but after inserting 20 million approx, connection failed.
When i Tried again to insert the Data then talend job firstly truncate the data from the table then it is inserting data from the beginning,<issue_comment>username_1: The question seems to be incomplete, but assuming that you want the table not to truncate before each load, check the "Action on table" property. It should be set as "Default" or "Create Table if does not exist".
Now, if you're question is to handle restart-ability of the job where the job should resume from 20 million rows on the next run, there are multiple ways you could achieve this. In your case since you are dealing with high number of records, having a mechanism like pagination would help in which you load the data in chunks (lets say 10000 at a time) and loop it setting the commit interval as 10000. After each successful entry in the database of 10000 records, make an entry into one log table with the timestamp or incremental key in your data (to mark the checkpoint). Your job should look something like this:
tLoop--{read checkpoint from table}--tMSSqlInput--tMySqlOutput--{load new checkpoint in table}
Upvotes: 1 <issue_comment>username_2: You can set the a property in context variable, say 'loadType' which will have value either 'initial' or 'incremental'.
And before truncating table you should have 'if' link to check what is the value of this variable, if it is 'initial' it will truncate and it is 'incremental' then you can run your subjob to load data.
Upvotes: 0 |
2018/03/19 | 1,026 | 4,644 | <issue_start>username_0: I have a really complex aggregation query, so I thought to use view as below:
```
db.createView("weNeed","Master",
[
{$project:
{
_id:"$_id",
documents:{
$concatArrays:[
{$ifNull:
[{$map:{
input:"$documents.COMPLETED",
as:"document",
in:{
entity:"$name",
status:"COMPLETED",
name:"$$document.name",
category:"$$document.category",
description:"$$document.description",
submittedDate:"$$document.submittedDate",
expirationDate:"$$document.expirationDate",
uri:"$$document.uri"
}
}},[]]},
{$ifNull:
[{$map:{
input:"$documents.REQUIRED",
as:"document",
in:{ entity:"$name",
status:"REQUIRED",
name:"$$document.name",
category:"$$document.category",
description:"$$document.description",
submittedDate:"$$document.submittedDate",
expirationDate:"$$document.expirationDate",
uri:"$$document.uri"
}
}},[]]},
{$ifNull:
[{$map:{
input:"$documents.DEFERRED",
as:"document",
in:{ entity:"$name",
status:"DEFERRED",
name:"$$document.name",
category:"$$document.category",
description:"$$document.description",
submittedDate:"$$document.submittedDate",
expirationDate:"$$document.expirationDate",
"uri":"$$document.uri"
}
}},[]]}
]
}
}
}
]
)
```
Now, I could easily use aggregation on it. Also, In `java-springdata` I could easily create a matching Repository and access the data easily.Same applies to any other language or framework. This also gives a good view of what I need.
See Below query which is very concise in size:-
```
db.weNeed.aggregate([
{
$project:{
documents:"$documents"
}
},
{$unwind:"$documents"},
{$sort:{
"documents.entity":1,
"documents.category":1,
"documents.status":1,
"documents.name":1
}}
]
)
```
I tried to find if there are any performance fall backs of using views over single aggregation query. Haven't got any.
Below are some advantages of view as per me:-
1. Cleaner code.
2. A view of your data, hence could be viewed from database without running complex query.
3. Gets updated as soon as there is any save or update in original Collection.
4. Better performance as not single collection is queried.
Disadvantages:- This i am not sure much about. Still I think
1. Could not be good with Clustreing.
2. Could be good for people who have less knowledge of mongo and want to use any wrapper framework.
Also, there is no official documentation mentioning any advantages and disadvantages.
Please help!<issue_comment>username_1: In terms of performance, I believe you don't get any benefit as view does not store any data. It only stores the query in `system.views`. So every time you are going to access the views it will actually execute the aggregation query if you do not have a proper index on your collection then you can expect a slow response. As views don't store any data, so it `can't be indexed`.
Take a look at [this](https://dzone.com/articles/taking-a-look-at-mongodb-views) for some information.
Upvotes: 4 [selected_answer]<issue_comment>username_2: I am finding views quite useless for work with any larger collection, and unfortunately that is where I live. Looks to me that the view `find()` execution does not have an intelligence to integrate `find()` filter object into the view, but rather runs the view by scanning the whole collection, and then attempts to filter the resulting list, resulting in slow performance.
**Example:**
```
db.createView(myView,myCol,[{stage1}..{stageN}]);
db.myView.find({myFilter});
```
...is MUCH slower on large myCol than:
```
db.myCol.aggregate([{"$match":{myFilter}},{stage1}..{stageN}])
```
(provided that `{"$match":{myFilter}`} is a valid aggregation stage)
Dynamically integrating filter into views aggregation would actually make the view concept workable.
Upvotes: 3 |
2018/03/19 | 1,025 | 3,450 | <issue_start>username_0: Some API is reply with non-json string so how to read value data from response?
Response Format:
onSuccess Response:
>
> status=success:orderId=a089f02724ed4a8db6c069f6d30b3245:txnId=None:paymentId=MOJO7918005A76494611:token=<KEY>
>
>
>
I need to read `orderID` and `txnid` it's not JSON.
I tried with splite by : but it's not proper working.
```
String message = "status=" + status + ":orderId=" + orderID + ":txnId="
+ transactionID + ":paymentId=" + paymentID + ":token="
+ Instamojo.this.accessToken;
```
String response created like this.<issue_comment>username_1: You can use [String.split()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)) to separate every parts of your response. Then look for the part that start with orderID using [String.startWith()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#startsWith(java.lang.String)). Finally get the value by obtaining the substring containing the value using [String.substring()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)). Use [String.lastIndexOf()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf(int)) to obtain the index of the `=` symbol.
This should look like this:
```
String response = getResponse(); //Don't know how you obtain it but its for the example
String[] array = response.split(':');
String orderIdPart;
for(int i=0; i
```
Edit:
If you want to avoid the loop you could use this (but it supposed its always followed by txnID) :
```
int begginingIndex = response.indexOf("orderId=") + "orderId=".length();
int endIndex = response.indexOf(":txnId");
String value = response.substring(begginingIndex, endIndex);
```
Upvotes: 0 <issue_comment>username_2: There is a cool way to convert the Instamojo string response to json response by using the following code snippet!
```
public void onInstaSuccess(String strResponse) {
String strWithoutColon = strResponse.replace(":", "\",\"");
String strWithoutEquals = strWithoutColon.replace("=", "\":\"");
String perfectJSON = "{\"" + strWithoutEquals + "\"}";
Log.i("Perfect", perfectJSON);
// COnvert the json to POJO
InstaMojoModel instaMojoModel = new Gson().fromJson(perfectJSON, InstaMojoModel.class);
}
```
Here is the Instamojo class
```
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class InstaMojoModel {
@SerializedName("status")
@Expose
private String status;
@SerializedName("orderId")
@Expose
private String orderId;
@SerializedName("txnId")
@Expose
private String txnId;
@SerializedName("paymentId")
@Expose
private String paymentId;
@SerializedName("token")
@Expose
private String token;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getTxnId() {
return txnId;
}
public void setTxnId(String txnId) {
this.txnId = txnId;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
```
Upvotes: 2 |
2018/03/19 | 631 | 2,521 | <issue_start>username_0: I have a Kepware OPC server and I am able to connect with my client (OPC Foundation UA lib). I created a device in Kepware and a group inside. I would like to read opc tags from the database and create them dynamically.
How do I create an item with address in PLC dynamically ?<issue_comment>username_1: Within the Kepware Configuration, only certain drivers have the ability to dynamically create tags. For example, most of the Allen-Bradley suite can dynamically search and add tags while lower level drivers like Modbus can not. So it always depends on what driver the device in Kepware is using. To find individual configuration manuals for each driver, search here:
<https://www.kepware.com/en-us/products/kepserverex/product-search/>
Upvotes: 1 <issue_comment>username_2: I can recommend you take a look at KepServerEX [Configuration API](https://www.kepware.com/en-us/products/kepserverex/features/configuration-api/). Basically, it gives you complete remote management and configuration control over all your KEPServerEX instances. In your case, you can dynamically generate tags through a simple RESTful API call at the device level after reading required information (e.g. tag name, tag address, tag datatype) from your database.
Please refer to [this guide](https://www.kepware.com/en-us/products/kepserverex/features/configuration-api/documents/configuration-api-easy-guide/) for more information in order to enable and test Configuration API.
I also copied the following piece of code from Kepware's sample project to give you an idea:
```
function createTag(inputServer, inputChannel, inputDevice, inputTag, inputTagAddr) {
console.log("Creating " + inputTag + " with address " + inputTagAddr);
$.ajax({
type: 'POST',
url: 'http://' + inputServer + '/config/v1/project/channels/' + inputChannel + '/devices/' + inputDevice + '/tags',
data: '{"common.ALLTYPES_NAME":"' + inputTag + '","servermain.TAG_ADDRESS":"' + inputTagAddr + '","servermain.TAG_DATA_TYPE":' + inputTagType + '}',
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
'Authorization': 'Basic ' + encodeAuth
},
success: function(JSON, status, xhr) {
console.log(inputTag + " created under " + inputDevice);
},
error: function(JSON, status, xhr) {
console.log("Creation of " + inputTag + " failed!");
}
});
}
```
Upvotes: 2 |
2018/03/19 | 612 | 2,449 | <issue_start>username_0: i have a web application which is created using .net framework 2.0 which is running on windows server 2003.is it possible to migrate that to Microsoft azure.if so does it require an entire rebuild on azure?<issue_comment>username_1: Within the Kepware Configuration, only certain drivers have the ability to dynamically create tags. For example, most of the Allen-Bradley suite can dynamically search and add tags while lower level drivers like Modbus can not. So it always depends on what driver the device in Kepware is using. To find individual configuration manuals for each driver, search here:
<https://www.kepware.com/en-us/products/kepserverex/product-search/>
Upvotes: 1 <issue_comment>username_2: I can recommend you take a look at KepServerEX [Configuration API](https://www.kepware.com/en-us/products/kepserverex/features/configuration-api/). Basically, it gives you complete remote management and configuration control over all your KEPServerEX instances. In your case, you can dynamically generate tags through a simple RESTful API call at the device level after reading required information (e.g. tag name, tag address, tag datatype) from your database.
Please refer to [this guide](https://www.kepware.com/en-us/products/kepserverex/features/configuration-api/documents/configuration-api-easy-guide/) for more information in order to enable and test Configuration API.
I also copied the following piece of code from Kepware's sample project to give you an idea:
```
function createTag(inputServer, inputChannel, inputDevice, inputTag, inputTagAddr) {
console.log("Creating " + inputTag + " with address " + inputTagAddr);
$.ajax({
type: 'POST',
url: 'http://' + inputServer + '/config/v1/project/channels/' + inputChannel + '/devices/' + inputDevice + '/tags',
data: '{"common.ALLTYPES_NAME":"' + inputTag + '","servermain.TAG_ADDRESS":"' + inputTagAddr + '","servermain.TAG_DATA_TYPE":' + inputTagType + '}',
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
'Authorization': 'Basic ' + encodeAuth
},
success: function(JSON, status, xhr) {
console.log(inputTag + " created under " + inputDevice);
},
error: function(JSON, status, xhr) {
console.log("Creation of " + inputTag + " failed!");
}
});
}
```
Upvotes: 2 |
2018/03/19 | 466 | 1,622 | <issue_start>username_0: I am trying to implement the ear clipping algorithm based on <https://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf> but I can't grasp how to find reflex and convex vertices.
The document linked mentiones that a vertex is reflex if its interior angle is > 180. I tried calculating the angle by creating 2 direction vectors (going away from the vertex) and then getting the dot of the two. But this is never above 180 for me.
My background is 3D Art and this is a way for me to learn more about trigonometry. Apologies if I'm missing something very basic!
[](https://i.stack.imgur.com/qlcEH.png)<issue_comment>username_1: I think to find if vertex is reflex do following :
Given point is A take two adjacent point to A , Lets say B and C.
Then find vectors (B-A).(C-A) = cos (angle) .
Find inverse cosine of angle in above equation for get the angle . So ,If this cos^-1 (angle) is > 180 then vertex A is reflex.
If you dont know order of vertices
then how to find Adjacent points to A.
For this you can use some part of Convex Hull Algorithm.
Upvotes: -1 <issue_comment>username_2: The link that @AlessandroTeruzzi posted helpe me solve the issue. No idea how to mark it as the answer. I needed to find the determinate. The link in question: [polygon triangulation reflex vertex](https://stackoverflow.com/questions/40410743/polygon-triangulation-reflex-vertex)
[This is my result](https://i.stack.imgur.com/jZ8Zp.png)
Upvotes: 1 |
2018/03/19 | 795 | 2,841 | <issue_start>username_0: On this **[page](https://www.ishares.com/uk/individual/en/products/251712/?referrer=tickerSearch)** I would like Selenium for Python to grab the text contents of the "*Investment Objective*", excluding the `###` header. I want to use XPath.
The nodes look like this:
```
### INVESTMENT OBJECTIVE
The Fund seeks to track the performance of an index composed of 25 of the largest Dutch companies listed on NYSE Euronext Amsterdam.
```
To retrieve the text, I'm using:
```
string = driver.find_element_by_xpath(xpath).text
```
---
If use I the this XPath for the top node:
```
xpath = '//div[@class="carousel-content column fund-objective"]'
```
It will work, but it includes the `###` header `INVESTMENT OBJECTIVE` — which I want to exclude.
---
However, if I try to use `/text()` to address the actual text content, it seems that Selenium for Python doesn't let me grab it whilst using the `.text` to get the attribute:
```
xpath = '//div[@class="carousel-content column fund-objective"]/text()'
```
*Note that there seems to be multiple nodes with this XPath on this particular page, so I'm specifying the correct node like this:*
```
xpath = '(//div[@class="carousel-content column fund-objective"]/text())[2]'
```
My interpretation of the problem is that `.text` doesn't allow me to retrieve the text contents of the XPath sub-node `text()`. My apologies for incorrect terminology.<issue_comment>username_1: To retrieve the text **The Fund seeks to track the performance of an index composed of 25 of the largest Dutch companies listed on NYSE Euronext Amsterdam.** you can use the following line of code :
```
string = driver.find_element_by_xpath("//div[@class='carousel-content column fund-objective' and not (@class='carousel-header')]").text
```
Upvotes: 1 <issue_comment>username_2: You can try below code to get required output:
```
div = driver.find_element_by_xpath('(//div[@class="carousel-content column fund-objective"])[2]')
driver.execute_script('return arguments[0].lastChild.textContent;', div).strip()
```
The output is
```
'The Fund seeks to track the performance of an index composed of 25 of the largest Dutch companies listed on NYSE Euronext Amsterdam.'
```
Upvotes: 2 <issue_comment>username_3: `/text()` will locate and [return text node, which is not an element node](https://stackoverflow.com/questions/15920496/difference-between-element-node-and-text-node). It doesn't have `text` property.
One solution will be to locate both elements and remove the unwanted text
```
xpath = '//div[@class="carousel-content column fund-objective"]'
element = driver.find_element_by_xpath(xpath)
all_text = element .text
title_text = element.find_element_by_xpath('./*[@class="carousel-header"]').text
all_text.replace(title_text, '')
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 781 | 2,575 | <issue_start>username_0: I have an Ubuntu server which is running on 14.04.05 LTS.
There are several applications that is ugins mongodb installed also on this server. MongoDB version is 3.4.2
I'm trying to increase max process ulimit of mongodb process.
I first put these lines to `/etc/security/limits.conf`
`* soft nproc unlimited
* hard nproc unlimited
* soft nofile 64000
* hard nofile 64000
* soft sigpending unlimited
* hard sigpending unlimited
root soft nproc unlimited
root hard nproc unlimited
root soft nofile 64000
root hard nofile 64000
root soft sigpending unlimited
root hard sigpending unlimited
mongodb soft nproc unlimited
mongodb hard nproc unlimited
mongodb soft nofile 64000
mongodb hard nofile 64000
mongodb soft sigpending unlimited
mongodb hard sigpending unlimited`
and also put required pam.limits to proper locations and reboot but no success.
Then i tried to manually run `ulimit -u unlimited` command which is reflected immediately after i executed it (i seen the result with `ulimit -a` command). And then reboot the mongodb process but the limits are didn't changed.
Then i tried to put these lines to:
`ulimit -f unlimited
ulimit -t unlimited
ulimit -v unlimited
ulimit -n 64000
ulimit -m unlimited
ulimit -u unlimited`
to `/etc/init.d/mongodb` file and try to start mongodb process with `/etc/init.d/mongodb start` but i got this error:
`/etc/init.d/mongodb: 67: ulimit: Illegal option -u`
I also put this line `mongod soft nproc 64000` to `/etc/security/limits.d/90-nproc.conf` and tried to reboot but no success.
On this thread `https://stackoverflow.com/questions/9361816/maximum-number-of-processes-in-linux` i saw that one user reported about `kernel.threads-max` is limiting this number but on my another server i can get more max connection limit then `kernel.threads-max / 2`
So I'm not sure where do i doing wrong but any help is much appreciated.<issue_comment>username_1: Try adding -S to each line, like this:
ulimit -S -n 4096
Upvotes: 0 <issue_comment>username_2: For the change to be persistent you have to edit de init script, for example, in Red Hat 7, the init script has the following line:
```
LimitNOFILE=64000
```
You have to add the next one:
```
LimitNPROC=32000
```
Then restart the service.
I hope this helps.
Upvotes: 0 <issue_comment>username_3: Adding "@" to the lines is working for me:
```
@mongodb soft nproc unlimited
@mongodb hard nproc unlimited
@mongodb soft nofile 64000
@mongodb hard nofile 64000
```
Upvotes: 1 |
2018/03/19 | 185 | 686 | <issue_start>username_0: Please I want to know how to redirect my blogger post from my old domain to my new domain name pointing each post to their respective post<issue_comment>username_1: Go to **Settings** > **Search preferences** > **Custom Redirects** and make a new redirect.
URL must start with `/` like this `/2017/12/living-can-bring-does-comments-letter.html`
Upvotes: 1 <issue_comment>username_2: On the old domain's Blogger template, add the following Javascript snippet in the region -
```
window.location.href = window.location.href.replace(window.location.origin,"http://www.newdomain.com")
```
Replace `http://www.newdomain.com` with your new domain
Upvotes: 0 |
2018/03/19 | 350 | 1,139 | <issue_start>username_0: I have a text:
>
> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste
> mollitia similique, blanditiis quisquam suscipit optio quam culpa odit
> ad magni sunt officiis, recusandae deleniti alias, natus commodi sed
> expedita labore.
>
>
> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae
> distinctio atque, eos quo. Autem commodi dicta, numquam natus illum
> recusandae quos! Veniam nulla et temporibus necessitatibus vero
> recusandae tempora saepe!
>
>
>
How I can with php paste a symbol `{{id}}` after every paragraph
? I need use `preg_replace`?<issue_comment>username_1: Go to **Settings** > **Search preferences** > **Custom Redirects** and make a new redirect.
URL must start with `/` like this `/2017/12/living-can-bring-does-comments-letter.html`
Upvotes: 1 <issue_comment>username_2: On the old domain's Blogger template, add the following Javascript snippet in the region -
```
window.location.href = window.location.href.replace(window.location.origin,"http://www.newdomain.com")
```
Replace `http://www.newdomain.com` with your new domain
Upvotes: 0 |
2018/03/19 | 245 | 827 | <issue_start>username_0: I have and expression:
```
=UCASE(Fields!MotherFullName.Value)
```
and an expression:
```
=IIF(ISNOTHING(Fields!MotherFullName.Value) ,"-",Fields!MotherFullName.Value)
```
I want to nest them into one expression since they are operating on the same value, what must I do?<issue_comment>username_1: Go to **Settings** > **Search preferences** > **Custom Redirects** and make a new redirect.
URL must start with `/` like this `/2017/12/living-can-bring-does-comments-letter.html`
Upvotes: 1 <issue_comment>username_2: On the old domain's Blogger template, add the following Javascript snippet in the region -
```
window.location.href = window.location.href.replace(window.location.origin,"http://www.newdomain.com")
```
Replace `http://www.newdomain.com` with your new domain
Upvotes: 0 |
2018/03/19 | 709 | 2,170 | <issue_start>username_0: I have a nested tuple in the form:
```
nested_tup = [('15MAR18 103000', '15MAR18 103758'), ('15MAR18 120518', '15MAR18 121308')] etc...
```
The 1st element in each tuple is the start date and the 2nd element in each tuple is the end date.
I want to find the difference in time between the 2 dates and then append the answer as a 3rd element in each tuple... So far I have the following:
```
for start, end in nested_tup:
after = datetime.strptime(end, '%d%b%y %H%M%S')
before = datetime.strptime(start, '%d%b%y %H%M%S')
duration = after - before
```
I need this duration value to be appended as the 3rd element in each tuple.. I don't know how though..
Any help appreciated.<issue_comment>username_1: Here is one way:
```
for i, (start, end) in enumerate(nested_tup):
after = datetime.strptime(end, '%d%b%y %H%M%S')
before = datetime.strptime(start, '%d%b%y %H%M%S')
duration = after - before
nested_tup[i] += (duration, )
```
which could be slightly easier to read as:
```
f = '%d%b%y %H%M%S'
for i, (start, end) in enumerate(nested_tup):
nested_tup[i] += (datetime.strptime(end, f) - datetime.strptime(start, f), )
```
Even though you cannot mutate `tuple` objects to append a new component, you can concatenate `tuple` objects using `+`, which creates a new `tuple` from the constituent `tuple` objects, and this is perfectly good for your problem at hand.
Upvotes: 2 <issue_comment>username_2: Tuples are immutable data structure. So you cannot append values to tuple.
[Check out immutable sequence types.](https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types)
This may work for you,
```
strptime = lambda dt: datetime.strptime(dt, f)
[(start, end, strptime(end) - strptime(start)) for start, end in nested_tup]
```
Upvotes: 0 <issue_comment>username_3: You can use map in combination with a conversion function.
```
def convert(tup):
after = datetime.strptime(tup[1], '%d%b%y %H%M%S')
before = datetime.strptime(tup[0], '%d%b%y %H%M%S')
duration = after - before
return (tup[0], tup[1], duration)
ans = list(map(convert, nested_tup))
```
Upvotes: 1 |
2018/03/19 | 1,556 | 5,259 | <issue_start>username_0: I want to send PDF file in attachment using sendRawEmail(Node: aws-sdk) function, I have tried lots of ways, email sends successfully but PDF goes plain.
Please correct my code and help to solve it.
Code is here:
```
try {
data = fs.readFileSync('files/demo-invoice-new.pdf', 'utf8');
console.log(data.toString());
var ses_mail = "From: 'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">\n";
ses_mail = ses_mail + "To: " + toEmail + "\n";
ses_mail = ses_mail + "Subject: AWS SES Attachment Example\n";
ses_mail = ses_mail + "MIME-Version: 1.0\n";
ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";
ses_mail = ses_mail + "--NextPart\n";
ses_mail = ses_mail + "Content-Type: text/html; charset=us-ascii\n\n";
ses_mail = ses_mail + "This is the body of the email.\n\n";
ses_mail = ses_mail + "--NextPart\n";
ses_mail = ses_mail + "Content-Type: application/octet;\n";
ses_mail = ses_mail + "Content-Disposition: attachment; filename=\"demo-invoice-new.pdf\"\n\n";
ses_mail = ses_mail + data.toString('utf8') + "\n\n";
ses_mail = ses_mail + "--NextPart--";
var params = {
RawMessage: { Data: new Buffer(ses_mail) },
Destinations: [toEmail],
Source: "'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">'"
};
console.log(params);
var sendPromise = new AWS.SES(AWS_SES_CONFIG).sendRawEmail(params).promise();
return sendPromise.then(
data => {
console.log(data);
return data;
}).catch(
err => {
console.error(err.message);
throw err;
});
} catch (e) {
console.log('Error:', e.stack);
}
```<issue_comment>username_1: SES raw messages [must be base64-encoded](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendRawEmail.html). So, you'll need to get the file content as buffer and encode it as base64 string attachment. Also, you don't need to create a new buffer for raw message data since it already accepts a string data type.
**OPTIONAL**: You can also omit the `Destinations` parameter since you're already providing the `To` field in the raw message data. (You can also provide the `Cc` and `Bcc` fields as well)
You could try this for example:
```
data = fs.readFileSync("files/demo-invoice-new.pdf");
var ses_mail = "From: 'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">\n";
ses_mail += "To: " + toEmail + "\n";
ses_mail += "Subject: AWS SES Attachment Example\n";
ses_mail += "MIME-Version: 1.0\n";
ses_mail += "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";
ses_mail += "--NextPart\n";
ses_mail += "Content-Type: text/html\n\n";
ses_mail += "This is the body of the email.\n\n";
ses_mail += "--NextPart\n";
ses_mail += "Content-Type: application/octet-stream; name=\"demo-invoice-new.pdf\"\n";
ses_mail += "Content-Transfer-Encoding: base64\n";
ses_mail += "Content-Disposition: attachment\n\n";
ses_mail += data.toString("base64").replace(/([^\0]{76})/g, "$1\n") + "\n\n";
ses_mail += "--NextPart--";
var params = {
RawMessage: {Data: ses_mail},
Source: "'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">'"
};
```
**NOTE**: The `/([^\0]{76})/` regular expression replacement breaks your long lines to make sure that mail servers do not complain about message lines being too long when there is an encoded attachment, which might result in a transient bounce. (See [RFC 5321](https://www.rfc-editor.org/rfc/rfc5321#section-4.5.3.1.6))
Upvotes: 6 [selected_answer]<issue_comment>username_2: Hi there for anybody who stumbles upon this problem I managed to solve it using [nodemailer](https://nodemailer.com/about/) and [SESV2](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SESV2.html#sendEmail-property), I had base64 encoded data so your script might be a little different from mine but the snippet below should give you an idea... Here's my solution hope it helps someone:
```js
const MailComposer = require("nodemailer/lib/mail-composer");
const AWS = require("aws-sdk");
const generateRawMailData = (message) => {
let mailOptions = {
from: message.fromEmail,
to: message.to,
subject: message.subject,
text: message.bodyTxt,
html: message.bodyHtml,
attachments: message.attachments.map(a => ({ filename: a.name, content: a.data, encoding: 'base64' }))
};
return new MailComposer(mailOptions).compile().build();
};
const exampleSendEmail = async () => {
var message = {
fromEmail: "<EMAIL>",
to: "<EMAIL>",
subject: "Message title",
bodyTxt: "Plaintext version of the message",
bodyHtml: "HTML version of the message
",
attachments: [{
name: 'hello.txt',
data: 'aGVsbG8gd29ybGQ='
}]
};
let ses = new AWS.SESV2(),
params = {
Content: { Raw: { Data: await generateRawMailData(message) } },
Destination: {
ToAddresses: message.to,
BccAddresses: message.bcc,
},
FromEmailAddress: message.fromEmail,
ReplyToAddresses: message.replyTo,
};
return ses.sendEmail(params).promise();
}
```
Upvotes: 3 |
2018/03/19 | 265 | 879 | <issue_start>username_0: I would like to use regex to get the stylesheets inside it, I use this regex now: `/(`
but this returns me all `but I want to filter on link and `rel="stylesheet"``
could someone help me out on this regex?<issue_comment>username_1: >
> but this returns me all
>
>
>
Why not use the built-in `querySelectorAll`
```
var links = document.querySelectorAll("link[rel='stylesheet']");
console.log(links.length);
```
`links` is the list of link `Element`s.
**Demo**
```js
var links = document.querySelectorAll("link[rel='stylesheet']");
console.log(links.length);
```
```html
```
Upvotes: 2 <issue_comment>username_2: If I have got you correctly then you are trying to get all `links` with `rel="stylesheet"` attribute. To do so you can use following `regex`
`//gi`
For demonstrations have a look [here](https://regexr.com/3mfid).
Upvotes: 0 |
2018/03/19 | 946 | 3,787 | <issue_start>username_0: I'm trying to write a extension method for Aspose's `DocumentBuilder` class that allows you to check if inserting a number of paragraphs into a document will cause a page break or not, I hoped this would be rather simple, but it turns out otherwise:
```
public static bool WillPageBreakAfter(this DocumentBuilder builder, int numParagraphs)
{
// Get current number of pages
int pageCountBefore = builder.Document.PageCount;
for (int i = 0; i < numParagraphs; i++)
{
builder.InsertParagraph();
}
// Get the number of pages after adding those paragraphs
int pageCountAfter = builder.Document.PageCount;
// Delete the paragraphs, we don't need them anymore
...
if (pageCountBefore != pageCountAfter)
{
return true;
}
else
{
return false;
}
}
```
MY problem is, that inserting paragraphs does not seem to update the `builder.Document.PageCount` property. Even plugging in something crazy like 5000 paragraphs does seem to modify that property. I've also tried `InsertBreak()` (including using `BreakType.PageBreak`) and `Writeln()` but those don't work either.
What's going on here? Is there anyway I can achieve the desired result?
**UPDATE**
It seems that absolutely nothing done on the `DocumentBuilder` parameter actually happens on the `DocumentBuilder` that is calling the method. In other words:
If I modify the for loop to do something like `builder.InsertParagraph(i.ToString());` and then remove the code that deletes the paragraphs afterwords. I can call:
```
myBuilder.WillPageBreakAfter(10);
```
And expect to see 0-9 written to the document when it is saved, however it is not. None of the `Writeln()`s in the extension methods seem to do anything at all.
**UPDATE 2**
It appears for what ever reasons, I cannot write anything with the `DocumentBuilder` after accessing the page count. So calling something like `Writeln()` before the `int pageCountBefore = builder.Document.PageCount;` line works, but trying to write after that line simply does nothing.<issue_comment>username_1: And it seems I've figured it out.
From the Aspose docs:
>
>
> ```
> // This invokes page layout which builds the document in memory so note that with large documents this
> // property can take time. After invoking this property, any rendering operation e.g rendering to PDF or image
> // will be instantaneous.
> int pageCount = doc.PageCount;
>
> ```
>
>
The most important line here:
>
> This invokes page layout
>
>
>
By "invokes page layout", they mean it calls `UpdatePageLayout()`, for which the docs contain this note:
>
> However, if you modify the document after rendering and then attempt to render it again - Aspose.Words will not update the page layout automatically. In this case you should call UpdatePageLayout() before rendering again.
>
>
>
So basically, given my original code, I have to call `UpdatePageLayout()` after my `Writeln()`s in order to get the updated page count.
// Get current number of pages
int pageCountBefore = builder.Document.PageCount;
```
for (int i = 0; i < numParagraphs; i++)
{
builder.InsertParagraph();
}
// Update the page layout.
builder.Document.UpdatePageLatout();
// Get the number of pages after adding those paragraphs
int pageCountAfter = builder.Document.PageCount;
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: The Document.PageCount invokes page layout. You are modifying the document after using this property. Note that when you modify the document after using this property, Aspose.Words will not update the page layout automatically. In this case you should call Document.UpdatePageLayout method.
I work with Aspose as Developer Evangelist.
Upvotes: 1 |
2018/03/19 | 622 | 2,150 | <issue_start>username_0: I want to create a skeleton console app for Scala i.e. a single entry class with a main function that prints "Hello world".
I was able to create a Scala library init project by executing:
`gradle init --type scala-library`
however there seems to be no scala-application, running:
`gradle init --type scala-application`
>
> The requested build setup type 'scala-application' is not supported. Supported types: 'basic', 'groovy-application', 'groovy-library', 'java-application', 'java-library', 'pom', 'scala-library'.
>
>
>
Is there no Scala console app template for Gradle?<issue_comment>username_1: No, there is no scala application template, however it is easy to make your generated "scala-library" project into a scala application in two steps:
1. Create your main class and method under a package under src/main/scala
2. Add two lines to your gradle.build, to add the 'application' plugin and specify your main class.
For example, you add src/main/scala/com/example/myapp/Main.scala:
```
package com.example.myapp
object Main {
def main(args: Array[String]): Unit = {
println("Hello")
}
}
```
Then to your gradle.build you add:
```
apply plugin: 'application'
mainClassName='com.example.myapp.Main'
```
Upvotes: 3 <issue_comment>username_2: On top of what you have for `Java` you pretty much only need to add `apply plugin: 'scala'` and change `Main` to be:
```
object Main extends App {
println('Hello, World!')
}
```
I ended up doing just that.
Additionally, if you want joint compilation (and have compiler understand `Java` and `Scala` in the same place) you can add the below snippet (one block per source set: `main`, `test`, `jmh`, etc.):
```
sourceSets.main {
java.srcDirs = []
scala.srcDirs = ['src/main/scala', 'src/main/java']
scala.include '**/*.*'
}
sourceSets.test {
java.srcDirs = []
scala.srcDirs = ['src/test/scala', 'src/test/java']
scala.include '**/*.*'
}
```
Upvotes: 2 <issue_comment>username_3: As of [Gradle 6.7](https://docs.gradle.org/6.7/userguide/build_init_plugin.html) the `scala-application` build type exists now.
Upvotes: 1 |
2018/03/19 | 723 | 2,395 | <issue_start>username_0: I have the following dataframes:
```
print(df1)
day month quantity Operation_type
21 6 6 2
24 6 4 2
...
print(df2)
day month quantity Operation_type
22 6 10 1
23 6 15 1
...
```
I would like to get the following dataset:
```
print(final_df)
day month quantity Operation_type
21 6 6 2
22 6 10 1
23 6 15 1
24 6 4 2
...
```
I tried using:
`final_df = pd.merge(df1, df2, on=['day','month'])` but it creates a huge dataset and does not seem to be working properly;
Furthermore, if day and month are the same, I would like to paste the line whose `Operation_type == 2` before the one with `==1`.
How can I solve this problem?<issue_comment>username_1: No, there is no scala application template, however it is easy to make your generated "scala-library" project into a scala application in two steps:
1. Create your main class and method under a package under src/main/scala
2. Add two lines to your gradle.build, to add the 'application' plugin and specify your main class.
For example, you add src/main/scala/com/example/myapp/Main.scala:
```
package com.example.myapp
object Main {
def main(args: Array[String]): Unit = {
println("Hello")
}
}
```
Then to your gradle.build you add:
```
apply plugin: 'application'
mainClassName='com.example.myapp.Main'
```
Upvotes: 3 <issue_comment>username_2: On top of what you have for `Java` you pretty much only need to add `apply plugin: 'scala'` and change `Main` to be:
```
object Main extends App {
println('Hello, World!')
}
```
I ended up doing just that.
Additionally, if you want joint compilation (and have compiler understand `Java` and `Scala` in the same place) you can add the below snippet (one block per source set: `main`, `test`, `jmh`, etc.):
```
sourceSets.main {
java.srcDirs = []
scala.srcDirs = ['src/main/scala', 'src/main/java']
scala.include '**/*.*'
}
sourceSets.test {
java.srcDirs = []
scala.srcDirs = ['src/test/scala', 'src/test/java']
scala.include '**/*.*'
}
```
Upvotes: 2 <issue_comment>username_3: As of [Gradle 6.7](https://docs.gradle.org/6.7/userguide/build_init_plugin.html) the `scala-application` build type exists now.
Upvotes: 1 |
2018/03/19 | 840 | 2,827 | <issue_start>username_0: I have the following tables:
```
CREATE TABLE `orders` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`billing_profile_id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`currency` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
`valid_until` timestamp NULL DEFAULT NULL
)
```
And:
```
CREATE TABLE `items` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`order_id` int(10) unsigned NOT NULL,
`status` enum('pending','processing','completed','on-hold','cancelled'),
`code` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`quantity` int(10) unsigned NOT NULL DEFAULT '1',
`term` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`discounts` int(10) unsigned NOT NULL,
`total` int(10) unsigned NOT NULL
)
```
How do I SELECT only the `orders` that have **all** of its items with status `completed`?
I tried with this:
```
SELECT o.* FROM
FROM orders o INNER JOIN items i on o.id=i.order_id
GROUP BY o.id, i.status
HAVING i.status = 'completed'
```
But that returns only the orders that have **some** items `completed`, not **all**.
EDIT: An `order` with no `items` is also a valid result.<issue_comment>username_1: Try this:
```
SELECT *
FROM orders
WHERE EXISTS (SELECT *
FROM items
WHERE orders.id = items.order_id
AND items.status = 'completed')
AND NOT EXISTS (SELECT *
FROM items
WHERE orders.id = items.order_id
AND items.status <> 'completed')
```
Upvotes: 2 <issue_comment>username_2: Easy:
```
select * from orders
where id not in (
select order_id from items where status <> 'completed'
)
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: ```
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
`id` SERIAL PRIMARY KEY
);
INSERT INTO orders VALUES
(100),(101);
DROP TABLE IF EXISTS items;
CREATE TABLE `items` (
`id` SERIAL PRIMARY KEY,
`order_id` int(10) unsigned NOT NULL,
`status` enum('pending','processing','completed','on-hold','cancelled')
);
INSERT INTO items VALUES
(1,100,'completed'),
(2,100,'completed'),
(3,100,'completed'),
(4,101,'completed'),
(5,101,'processing');
SELECT DISTINCT o.*
FROM orders o
LEFT
JOIN items i
ON i.order_id = o.id
AND i.status <> 'completed'
WHERE i.id IS NULL;
+-----+
| id |
+-----+
| 100 |
+-----+
```
...or...
```
SELECT DISTINCT o.*
FROM orders o
WHERE NOT EXISTS (SELECT 1
FROM items i
WHERE i.order_id = o.id
AND i.status <> 'completed');
```
Upvotes: 1 |
2018/03/19 | 1,417 | 4,388 | <issue_start>username_0: I have a cache-like structure which internally uses a `HashMap`:
```
impl Cache {
fn insert(&mut self, k: u32, v: String) {
self.map.insert(k, v);
}
fn borrow(&self, k: u32) -> Option<&String> {
self.map.get(&k)
}
}
```
[Playground with external mutability](https://play.rust-lang.org/?gist=c454143b5fba0a7e26850134b6bc78f9&version=stable)
Now I need internal mutability. Since `HashMap` does not implement `Copy`, my guess is that `RefCell` is the path to follow. Writing the `insert` method is straight forward but I encountered problems with the borrow-function. I could return a `Ref`, but since I'd like to cache the result, I wrote a small `Ref`-wrapper:
```
struct CacheRef<'a> {
borrow: Ref<'a, HashMap>,
value: &'a String,
}
```
This won't work since `value` references `borrow`, so the struct can't be constructed. I know that the reference is always valid: The map can't be mutated, because `Ref` *locks* the map. Is it safe to use a raw pointer instead of a reference?
```
struct CacheRef<'a> {
borrow: Ref<'a, HashMap>,
value: \*const String,
}
```
Am I overlooking something here? Are there better (or faster) options? I'm trying to avoid `RefCell` due to the runtime overhead.
[Playground with internal mutability](https://play.rust-lang.org/?gist=27c1d442e0cbbd0b507fae9aaa581940&version=nightly)<issue_comment>username_1: I'm going to ignore your direct question in favor of a definitely safe alternative:
```
impl Cache {
fn insert(&self, k: u32, v: String) {
self.map.borrow_mut().insert(k, v);
}
fn borrow<'a>(&'a self, k: u32) -> Option> {
let borrow = self.map.borrow();
if borrow.contains\_key(&k) {
Some(Ref::map(borrow, |hm| {
hm.get(&k).unwrap()
}))
} else {
None
}
}
}
```
[`Ref::map`](https://doc.rust-lang.org/std/cell/struct.Ref.html#method.map) allows you to take a `Ref<'a, T>` and convert it into a `Ref<'a, U>`. The ugly part of this solution is that we have to lookup in the hashmap twice because I can't figure out how to make the ideal solution work:
```
Ref::map(borrow, |hm| {
hm.get(&k) // Returns an `Option`, not a `&...`
})
```
This *might* require Generic Associated Types (GATs) and even then the return type might be a `Ref>`.
Upvotes: 1 <issue_comment>username_2: I'll complement @username_1's safe but not quite as efficient answer with the unsafe version. For this, we'll pack some unsafe code in a utility function.
```
fn map_option<'a, T, F, U>(r: Ref<'a, T>, f: F) -> Option>
where
F: FnOnce(&'a T) -> Option<&'a U>
{
let stolen = r.deref() as \*const T;
let ur = f(unsafe { &\*stolen }).map(|sr| sr as \*const U);
match ur {
Some(u) => Some(Ref::map(r, |\_| unsafe { &\*u })),
None => None
}
}
```
I'm pretty sure this code is correct. Although the compiler is rather unhappy with the lifetimes, they work out. We just have to inject some raw pointers to make the compiler shut up.
With this, the implementation of `borrow` becomes trivial:
```
fn borrow<'a>(&'a self, k: u32) -> Option> {
map\_option(self.map.borrow(), |m| m.get(&k))
}
```
[Updated playground link](https://play.rust-lang.org/?gist=c0ce130dbfe1a6162658ba7d3940e65e&version=nightly)
The utility function only works for `Option<&T>`. Other containers (such as `Result`) would require their own modified copy, or else GATs or HKTs to implement generically.
Upvotes: 3 [selected_answer]<issue_comment>username_3: As mentioned by username_1, it is better to avoid unsafe when possible.
There are multiple possibilities:
* [`Ref::map`](https://doc.rust-lang.org/std/cell/struct.Ref.html#method.map), with double look-up (as illustrated by username_1's answer),
* `Ref::map` with sentinel value,
* Cloning the return value.
Personally, I'd consider the latter first. Store `Rc` into your map and your method can easily return a `Option>` which completely sidesteps the issues:
```
fn get(&self, k: u32) -> Option> {
self.map.borrow().get(&k).cloned()
}
```
As a bonus, your cache is not "locked" any longer while you use the result.
Or, alternatively, you can work-around the fact that `Ref::map` does not like `Option` by using a sentinel value:
```
fn borrow<'a>(&'a self, k: u32) -> Ref<'a, str> {
let borrow = self.map.borrow();
Ref::map(borrow, |map| map.get(&k).map(|s| &s[..]).unwrap_or(""))
}
```
Upvotes: 1 |
2018/03/19 | 1,519 | 4,561 | <issue_start>username_0: I am trying to add chapters to a ogg file containing vorbis audio.
From [this link](https://trac.videolan.org/vlc/ticket/10016) I copied the following ffmpeg command.
```
ffmpeg -threads auto -y -i in.ogg -i metadata_OGG.txt -map_metadata 1 -codec copy out_METADATA.ogg
```
My metadata\_OGG.txt file is as given below.
```
CHAPTER00=00:00:00.000
CHAPTER00NAME=Chapter 01
CHAPTER01=00:00:05.000
CHAPTER01NAME=Chapter 02
CHAPTER02=00:00:10.000
CHAPTER02NAME=Chapter 03
```
I am getting the following error.
```
[ogg @ 00000000006d6900] Unsupported codec id in stream 0
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
```
But if i change `-codec copy` to `-acodec copy` there is no error in ffmpeg but the text file is converted to video. i.e. the output file will have a static video frame with the text of metadata\_OGG.txt in it. Also, I observe the following log message during conversion.
```
Stream #1:0 -> #0:0 (ansi (native) -> theora (libtheora))
Stream #0:0 -> #0:1 (copy)
```
Anybody please tell me what is going wrong here?
Also, I would like to know what is the right way to add chapters to ogg. I searched for some tools also. I did not get any.<issue_comment>username_1: I found the issue.
For ffmpeg to work, the metadata file should have the following header.
```
;FFMETADATA1
```
I followed the steps given in [ffmpeg documentation for metadata](https://www.ffmpeg.org/ffmpeg-all.html#Metadata-1).
**But the issue is not resolved completely.**
With the above steps I am able to add metadata to mp4, mkv and other container files but not to ogg files. I am not sure whether ffmpeg supports adding chapters to ogg files.
Upvotes: 0 <issue_comment>username_2: Here is what worked for me using `ffmpeg` 4.3.1.
I have a **metadata file** which almost respects [`ffmpeg`'s metadata file format](https://www.ffmpeg.org/ffmpeg-all.html#Metadata-1):
```
;FFMETADATA1
title=Evolution theory
[CHAPTER]
TIMEBASE=1/1000
START=0
END=
title=Darwin's point of view
[CHAPTER]
TIMEBASE=1/1000
START=78880
END=
title=Genghis Khan's children
```
*Notice the file format requires an `END` time, but leaving it empty didn't bother in my case.*
Now **I add chapter information** to my opus/ogg file:
```
ffmpeg -i darwin.opus.ogg -i darwin_chapters.txt -map_metadata 1 -c copy darwin_withchapters.opus.ogg
```
*Note: if you want to overwrite existing chapter information from the file, you may need to add a `-map_chapters 1` parameter in the `ffmpeg` command line above.*
That creates the file `darwin_withchapters.opus.ogg`. I **check if chapter info has really been added** to the file:
```
opusinfo darwin_withchapters.opus.ogg
```
*You would use `ogginfo` for Ogg/Vorbis files.*
And here is the result (I removed a few irrelevant lines):
```
ENCODER=opusenc from opus-tools 0.1.10
ENCODER_OPTIONS=--bitrate 112
title=Evolution theory
CHAPTER000=00:00:00.000
CHAPTER000NAME=Darwin's point of view
CHAPTER001=00:01:19.880
CHAPTER001NAME=G<NAME>'s children
[...]
```
Here you go. `ffmpeg` did the conversion between its metadata file format to [the vorbis tag/comment chapter format](https://wiki.xiph.org/Chapter_Extension).
You could also directly write metadata in the Vorbis Chapter Extension [format](https://wiki.xiph.org/Chapter_Extension), and use the classic `vorbiscomment` tool, or other tools which allow editing of opus/ogg in-file tags.
Upvotes: 2 <issue_comment>username_3: Opus has been mentioned here. I was trying to make `opusenc` from `opus-tools` add chapters when encoding and couldn’t find a command line example anywhere. Thanks to the hints in this thread I managed to figure it out, perhaps someone may find it helpful.
```
opusenc --comment "CHAPTER000=00:00:00.000" --comment "CHAPTER000NAME=Hello" --comment "CHAPTER001=01:23:45.678" --comment "CHAPTER001NAME=World" input.wav output.opus
```
The chapter key/value scheme is the aforementioned [Ogg/Matroska](https://wiki.xiph.org/Chapter_Extension) one. Of course, more metadata options like `--title, --artist` etc. can be added.
Using `ffmpeg` to add the chapters resulted in two problems for me: The artwork image in the ogg/opus input file was missing in the output file, and ffmpeg rejected empty `END` chapter times.
I did this on Windows 10 using
* `opusenc opus-tools 0.2-3-gf5f571b (using libopus 1.3)`
* `ffmpeg version 4.4.1-essentials_build-www.gyan.dev`
* `opusinfo`, MPC-HC (64-bit) v1.7.11 and VLC Media Player 3.0.14 Vetinari to confirm.
Upvotes: 1 |
2018/03/19 | 804 | 3,263 | <issue_start>username_0: Our client has complained about the count of `.dll` files in the .NET Core app we made for them. Their dissatisfaction persists even after we explained that this is how .NET Core works.
Now I do understand their position completely, my jaw dropped too when I created the package for the first time:
[](https://i.stack.imgur.com/IsOSs.png)
Note how small the scroll bar is. Most of the library names begin with `Microsoft.` or `System.` - those that don't are libraries that I use and installed manually.
So the question is: is there anything I can do about this to make our client happy? Aren't the `System.*` libraries already installed on their machine as a part of .NET Core runtime?
We're targeting .NET Core 1.0 at this moment.<issue_comment>username_1: Core is designed to do this. In old .NET Framework apps, there's a runtime dependency on .NET Framework, i.e. the end-user must have the version of the .NET Framework the application targets installed on the machine as well. Core takes a different approach; it brings everything it needs into the build. As a result, you can drop this folder on any machine, no matter how it's set up and "run" it. (Now technically, you need dotnet.exe in order to run it, unless you build as an executable, but that's just to run the main app DLL.)
Anyways, this is by design, and it's actually much better when you think about it. Your app has just the dependencies it actually needs and nothing else. You don't have to worry about external things like what version of .NET Framework is installed, etc.
That said, I know there's some third-party applications (mostly commercial) that can enable you to "bundle" DLLs or even package up everything into a single executable. However, I'm not sure how compatible, if at all, these are with .NET Core. Still, if your client insists, I'd just see if you can find some tool that does that and essentially "hide" the DLLs.
Upvotes: 1 <issue_comment>username_2: You can create [two types of deployments for .NET Core applications](https://learn.microsoft.com/en-us/dotnet/core/deploying/index#framework-dependent-deployments-fdd):
* Framework-dependent deployment
* Self-contained deployment
It seems you need Framework-dependent deployments (FDD).
Portable (FDD) application is similar to the traditional .NET Framework application. In this case, a certain version of the .NET Core Framework (also known as shared framework, .NET Core Runtime, redist) should be on the target computer, and when the host starts, the process will load Core CLR, Core FX from the frame folder.
Artifacts of the same Portable Application for different versions of the .NET Core platform
[](https://i.stack.imgur.com/ciFWu.png)
You can see what [Directory structure of published ASP.NET Core apps](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/directory-structure) should be
To run Portable applications, at least one .NET Core Runtime (shared framework) must be installed on the target machine. The framework files (s) are stored in the `C:\Program Files\dotnet\shared` folder.
Upvotes: 4 [selected_answer] |
2018/03/19 | 422 | 1,449 | <issue_start>username_0: With Qt, I am trying to convert a `Format_Indexed8` image to `Format_RGB30` by using a custom conversion rule defined by a color table. I thought this would be simple, since `QImage::convertToFormat` can take a color table as an argument, but I can't make it work.
Here is my code:
```
QImage image = QImage(data, width, height, QImage::Format_Indexed8);
QVector colorTable(256);
for (int i = 0; i < 255; i++)
colorTable[i] = qRgb(255 - i, i, i);
image = image.convertToFormat(QImage::Format\_RGB30, colorTable);
```
This code just gives me an image that is in RGB format, but that looks identical to the eye to the grayscale image.<issue_comment>username_1: I think the color table argument in `QImage::convertToFormat` is required to convert from RGB to indexed, while you're converting the other way around.
I would try setting the color table directly in the indexed file (source), using `QImage::setColorTable`, then call `convertToFormat` passing the format argument only:
```
QImage image = QImage(data, width, height, QImage::Format_Indexed8);
image.setColorTable(colorTable);
image = image.convertToFormat(QImage::Format_RGB30);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: This is not necessary since Qt 5.5 (released in July of 2015). You can now use `QImage::Format_Grayscale8`. Your code would be simply:
```
QImage image{data, width, height, QImage::Format_Grayscale8};
```
Upvotes: 0 |
2018/03/19 | 985 | 2,968 | <issue_start>username_0: I have a specific case and I don't even know if it is possible to achieve.
Given the input array.
```
var originalArr = [
[
{ ID: 3, name: 'Beef' },
{ ID: 4, name: 'Macaroni' },
{ ID: 5, name: 'Sauce#1' }
],
[{ ID: 1, name: 'Lettuce' }, { ID: 2, name: 'Brocoli' }]
];
```
I would like to iterate over the inner arrays and pick the ID's from objects then create new one in place of array. So my output should look something like this.
```
var output = [
{
'1': {
name: 'Lettuce',
ID: 1
},
'2': {
name: 'Brocoli',
ID: 2
}
},
{
'3': {
name: 'Beef',
ID: 3
},
'4': {
name: 'Macaroni',
ID: 4
},
'5': {
name: 'Sauce#1'
}
}
];
```
It is easy to iterate over the inner arrays with `map` but how can I create new `Object` in place of the array and have its key value dynamically pulled up ? And is it even possible given my input to produce the desired output.<issue_comment>username_1: Use `map` and `reduce`
```
originalArr.map( s => //iterate outer array
s.reduce( (acc, c) => ( //iterate inner array using reduce
acc[c.ID] = c, acc //assign the id as key to accumulator and return the accumulator
) , {}) //initialize accumulator to {}
)
```
**Demo**
```js
var originalArr = [
[
{ ID: 3, name: 'Beef' },
{ ID: 4, name: 'Macaroni' },
{ ID: 5, name: 'Sauce#1' }
],
[{ ID: 1, name: 'Lettuce' }, { ID: 2, name: 'Brocoli' }]
];
var output = originalArr.map( s => s.reduce( (acc, c) => ( acc[c.ID] = c, acc ) , {}) );
console.log(output);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can achieve using recursion with pure javascript
```
var originalArr = [
[{
ID: 3,
name: 'Beef'
}, {
ID: 4,
name: 'Macaroni'
}, {
ID: 5,
name: 'Sauce#1'
}],
[{
ID: 1,
name: 'Lettuce'
}, {
ID: 2,
name: 'Brocoli'
}]
]
function bindInObject(object, array) {
for (var i = 0; i < array.length; i++) {
var it = array[i];
if (it instanceof Array) {
bindInObject(object, it);
} else {
var id = it.ID;
object[id] = it;
}
}
}
var output = {};
bindInObject(output, originalArr);
console.log(output)
```
Upvotes: 1 <issue_comment>username_3: ```
const original_array = [
[
{ ID: 3, name: 'Beef' },
{ ID: 4, name: 'Macaroni' },
{ ID: 5, name: 'Sauce#1' }
],
[
{ ID: 1, name: 'Lettuce' },
{ ID: 2, name: 'Brocoli' }
]
]
let new_array = []
for (let i=0; i < original_array.length; i++) {
if (original_array[i + 1]) new_array =
new_array.concat(original_array[i].concat(original_array[i+1]))
}
let output = []
for (let i=0; i
```
Upvotes: 0 |
2018/03/19 | 482 | 1,941 | <issue_start>username_0: ```
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = await keyVaultClient
.GetSecretAsync("https://KeyvaultName.vault.azure.net/secrets/test1")
.ConfigureAwait(false);
ViewData["keyvaultName"] = secret.Value;
```
//It is working fine. But now i want to get all the secrets in a single call and bind it to the fields<issue_comment>username_1: Key Vault only supports retrieving a single secret value at a time.
Upvotes: 2 <issue_comment>username_2: But this code will not run in local, i.e, while development. For this we need to install Azure CLI (azure-cli-2.0.29.msi) to make use of MSI in local environment. After installing this open Microsoft azure command prompt and run
"az login" command and open the url mentioned in the command prompt and copy the code mentioned in prompt in that url. Now you would be able to make use of key vault using MSI in local and app service as well.
```
Dictionary secretlist = new Dictionary();
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
// TO get access token to azureServices
Task accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");
accessToken.Wait();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var all = keyVaultClient.GetSecretsAsync("https://keyvaultName.vault.azure.net/");
string seperator = "secrets/";
foreach (Microsoft.Azure.KeyVault.Models.SecretItem someItem in all.Result)
{
var secretName = someItem.Identifier;
var secretValue = keyVaultClient.GetSecretAsync(secretName.ToString());
secretValue.Wait();
secretlist.Add(secretName.ToString().Substring(secretName.ToString().IndexOf(seperator) + seperator.Length), secretValue.Result.Value);
}
```
Upvotes: 1 |
2018/03/19 | 924 | 3,524 | <issue_start>username_0: I tried to sort an array of objects. With key and value. I could able to sort with age .but I don't know how to sort with age and score from my object array
Any help will be much appreciated
[Fiddle](https://jsfiddle.net/39u8q/56/)
```js
var unsorted = [{
name: 'Peter',
age: 0,
work:'driving',
score : 20
}, {
name: 'John',
age: 0,
work:'document',
score : 30
}, {
name: 'Jess',
age: 46,
work:'teacxhing',
score :10
}, {
name: 'Alice',
age: 0,
work:'singing',
score:80
}],
sortedByAge = sortByKey(unsorted.slice(0), 'age');
/**
* Get a DOM element by ID
* @param {String} id
* @return {Object}
*/
function $dom(id) {
return document.getElementById(id);
}
/**
* Sort an array of Objects based on key
* @param {Array} array
* @param {String} key
* @returns {Array}
*/
function sortByKey(array, key) {
return array.sort(function (a, b) {
var x = a[key],
y = b[key];
if (typeof x === 'string') {
x = x.toLowerCase();
y = y.toLowerCase();
if (!isNaN(x) && !isNaN(y)) {
x = parseInt(x, 10);
y = parseInt(y, 10);
}
}
return (x > y ? -1 : (x < y ? 1 : 0));
});
}
/**
* Build a HTML String with the people their age
* @param {Array} array
* @return {String}
*/
function getPeople(array) {
for (var i = 0, len = array.length, returnString = ''; i < len; i ++) {
returnString += array[i].name + ', ' + array[i].age +',' +array[i].work+','+array[i].score+'
';
}
return returnString;
}
// Update the DOM
$dom('sortedByAge').innerHTML = getPeople(sortedByAge);
```<issue_comment>username_1: Key Vault only supports retrieving a single secret value at a time.
Upvotes: 2 <issue_comment>username_2: But this code will not run in local, i.e, while development. For this we need to install Azure CLI (azure-cli-2.0.29.msi) to make use of MSI in local environment. After installing this open Microsoft azure command prompt and run
"az login" command and open the url mentioned in the command prompt and copy the code mentioned in prompt in that url. Now you would be able to make use of key vault using MSI in local and app service as well.
```
Dictionary secretlist = new Dictionary();
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
// TO get access token to azureServices
Task accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");
accessToken.Wait();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var all = keyVaultClient.GetSecretsAsync("https://keyvaultName.vault.azure.net/");
string seperator = "secrets/";
foreach (Microsoft.Azure.KeyVault.Models.SecretItem someItem in all.Result)
{
var secretName = someItem.Identifier;
var secretValue = keyVaultClient.GetSecretAsync(secretName.ToString());
secretValue.Wait();
secretlist.Add(secretName.ToString().Substring(secretName.ToString().IndexOf(seperator) + seperator.Length), secretValue.Result.Value);
}
```
Upvotes: 1 |
2018/03/19 | 846 | 3,224 | <issue_start>username_0: I am trying out [flutter](https://flutter.io/) and I have hooked up an [http post](https://www.w3schools.com/tags/ref_httpmethods.asp) for logging-in.
I created a file that will take care of my [http request](https://www.tutorialspoint.com/http/http_requests). In the file wrote the following codes:
```
Map data;
Future logIn(email, password) async {
String url = "...";
Object userData = { "email": email, "password": <PASSWORD> };
var userDataBody = JSON.encode(userData);
Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};
http.Response response = await http.post(
Uri.encodeFull(url),
headers: userHeader,
body: userDataBody
);
data = JSON.decode(response.body);
print(data);
return data;
}
```
Http returns the following data:
```
{message: Login Successful, status: success}
```
The coded above are used in a [stateful widget](https://docs.flutter.io/flutter/widgets/StatefulWidget-class.html):
```
// imported the file above as userService
import 'services/user_services.dart' as userService;
// created a method for a button
void submitData() {
final form = formKey.currentState;
if (form.validate()) { // no validations so far
form.save(); // save email and password
userService.logIn("$userEmail", "$userPassword"); // .then(JSON.decode(responseContent['message']));
}
}
// button in container
new Container(
padding: new EdgeInsets.all(20.0),
child: new RaisedButton(
onPressed: submitData,
child: new Text('LogIn'),
)
),
```
My problem is that with the returned json data, I am struggling to take the status returned (success) / message (Login Successful) and do whatever I like with them.<issue_comment>username_1: Key Vault only supports retrieving a single secret value at a time.
Upvotes: 2 <issue_comment>username_2: But this code will not run in local, i.e, while development. For this we need to install Azure CLI (azure-cli-2.0.29.msi) to make use of MSI in local environment. After installing this open Microsoft azure command prompt and run
"az login" command and open the url mentioned in the command prompt and copy the code mentioned in prompt in that url. Now you would be able to make use of key vault using MSI in local and app service as well.
```
Dictionary secretlist = new Dictionary();
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
// TO get access token to azureServices
Task accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");
accessToken.Wait();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var all = keyVaultClient.GetSecretsAsync("https://keyvaultName.vault.azure.net/");
string seperator = "secrets/";
foreach (Microsoft.Azure.KeyVault.Models.SecretItem someItem in all.Result)
{
var secretName = someItem.Identifier;
var secretValue = keyVaultClient.GetSecretAsync(secretName.ToString());
secretValue.Wait();
secretlist.Add(secretName.ToString().Substring(secretName.ToString().IndexOf(seperator) + seperator.Length), secretValue.Result.Value);
}
```
Upvotes: 1 |
2018/03/19 | 487 | 1,829 | <issue_start>username_0: I want to add click for tags and at the same time add attribute "active" for the current ;
I had done it like this, but it doesn't work:
HTML:
```
[今日动态](/)
[您的关注](/recommend)
[热门活动](/activity)
[排行榜](/rank)
```
JS:
```
$(document).ready(function(){
"use strict";
$('.leftFocus a').on('click', function(){
$(this).addClass('active').siblings('.leftFocusItem').removeClass('active');
});
});
```
How should to write the right js for this problem?<issue_comment>username_1: Clicking a link causes the browser to *leave the current page* and load a new one.
Any DOM modifications you make to the current page will be lost.
You need to add the class *in the new page*. Ideally, you would do this using server-side code but you could use client-side JavaScript by comparing `location.href` to the `href` property of each link in the menu.
Upvotes: 1 <issue_comment>username_2: Your logic is fine but you will lose what has been selected as soon as the browser loads a new page.
You could add `preventDefault()` to the code to stop the browser from following the link, but then the links won't work ;)
```
$(document).ready(function(){
"use strict";
$('.leftFocus a').on('click', function(e){
// link will have correct class but no longer will navigate
e.preventDefault();
$(this).addClass('active').siblings('.leftFocusItem').removeClass('active');
});
});
```
It seems like you should instead be checking to see which link is the current path and setting the class on that, like so:
```
"use strict";
$(document).ready(function(){
document.querySelectorAll('.leftFocus a').forEach(function (link) {
if (link.href === window.location.href) {
link.classList.add('active');
}
});
});
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 457 | 1,486 | <issue_start>username_0: I would like to display just some text with a background. Despite my attempts, there is a lot of empty space around the text.
```
Gui, +AlwaysOnTop -Border -SysMenu -Caption
Gui, Add, Text, , Some text
Gui, Show, AutoSize
WinSet, Style, -0xC00000, A
WinSet, Style, -0x40000, A
WinSet, ExStyle, -0x00000200, A
```
If, instead of `AutoSize`, I manually set the size, the text is cut.<issue_comment>username_1: This is close to what you are looking for but not the same. This code will change the BG Color to transparent leaving only the text. Figured it would be worth showing off here for future users.
This example is using the CustomColor as a color to turn into the transparent field.
```
CustomColor = EEAA99
Gui, +LastFound +AlwaysOnTop -Caption +ToolWindow
Gui, Font, s32
Gui, Add, Text, , Some text
Gui, Color, %CustomColor%
WinSet, TransColor, %CustomColor% 1000
Gui, Show, AutoSize,NoActivate
```
Upvotes: 1 <issue_comment>username_2: If you add a border to the text, i.e.,
```
Gui Add, Text, Border, Some text
```
you'll see it is indeed the window itself with the extra space and not the text control. By default, if no margin is given to a GUI before a control is added it [chooses one that is proportional to the font](https://autohotkey.com/docs/commands/Gui.htm#Margin). So, just set the margin to zero before you add the text control:
```
Gui Margin, 0, 0
Gui Add, Text,, Some text
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 774 | 2,389 | <issue_start>username_0: I have a database with transfers orders between two cities. I have, in each record, a departure date, the amount to be delivered, a returning date and the amount to be returned.
The database is something like this:
```
df = pd.DataFrame({"dep_date":[201701,201701,201702,201703], "del_amount":[100,200,300,400],"ret_date":[201703,201702,201703,201705], "ret_amount":[50,75,150,175]})
df
dep_date del_amount ret_date ret_amount
0 201701 100 201703 50
1 201701 200 201702 75
2 201702 300 201703 150
3 201703 400 201705 175
```
I want to get a pivot table with dep\_data as index, showing the sum of del\_amount in that month and the returned amount scheduled for the same month of departure date.
It's an odd construction, cause it seems to has two indexes. The result that I need is:
```
del_amount ret_amount
dep_date
201701 300 0
201702 300 75
201703 400 200
```
Note that some returning dates does not match with any departure month. Does anyone know if it is possible to build a proper aggfunc in pivot\_table enviroment to achieve this? If it is not possible, can anyone tell me the best approach?
Thanks in advance<issue_comment>username_1: This is close to what you are looking for but not the same. This code will change the BG Color to transparent leaving only the text. Figured it would be worth showing off here for future users.
This example is using the CustomColor as a color to turn into the transparent field.
```
CustomColor = EEAA99
Gui, +LastFound +AlwaysOnTop -Caption +ToolWindow
Gui, Font, s32
Gui, Add, Text, , Some text
Gui, Color, %CustomColor%
WinSet, TransColor, %CustomColor% 1000
Gui, Show, AutoSize,NoActivate
```
Upvotes: 1 <issue_comment>username_2: If you add a border to the text, i.e.,
```
Gui Add, Text, Border, Some text
```
you'll see it is indeed the window itself with the extra space and not the text control. By default, if no margin is given to a GUI before a control is added it [chooses one that is proportional to the font](https://autohotkey.com/docs/commands/Gui.htm#Margin). So, just set the margin to zero before you add the text control:
```
Gui Margin, 0, 0
Gui Add, Text,, Some text
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 3,331 | 12,753 | <issue_start>username_0: I stared little project of mine.
I have a form filled with buttons. The buttons (Example#) are added during runtime based on the provided resource. See example below:
[](https://i.stack.imgur.com/Ft8ia.png)
The underlying JFrame has GridBox layout. The first row is what you see,
```
button|button|textbox|button|button
```
the second row is simple JScrollPane with GridWidth and GridHeight set to "remainder", effectively that should fill rest of the window safe from the slight padding I added to the right.
This JScrollPane contains another JPanel without any preset layout and I fill it with the controls (Buttons Example#0 through #9 here) by absolute values. When I shrink the window, the panel correctly adds scrollbars allowing me to scroll through these 9. See below:
[](https://i.stack.imgur.com/ZxGRI.png)
Unfortunately, when I add manually another Example, the scrollbars fail to appear. The button is half out-of boundaries of the window, but I cannot scroll to it. EDIT: Actually, all Examples above these 10 does not display correctly. No matter if they have been created along these 10 or added later in runtime or by myself. See:
[](https://i.stack.imgur.com/cWP1o.png)
I suspect that there are some fixed boundaries for either the scroll pane or for the panel that is inside the scroll pane, but I can't seem to find, where is the problem and what should I do to make the program work correctly.
Thanks in advance.
Form Code (stripped of unnecessary handlers and irrelevant methods)
if you see TestCommonsButton, it is a class that extends standard JButton only adding a TestSuite type property to it. By all means and purposes behaves as standard JButton
```
package forms;
import java.awt.Container;
import model.ModelConstants;
import java.awt.event.MouseEvent;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import model.*;
public class MainFrame extends javax.swing.JFrame {
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
//
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
backBtn = new javax.swing.JButton();
runBtn = new javax.swing.JButton();
headerTf = new javax.swing.JTextField();
addBtn = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
mainPanel = new javax.swing.JPanel();
detailsButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT\_ON\_CLOSE);
java.awt.GridBagLayout layout = new java.awt.GridBagLayout();
layout.columnWidths = new int[] {0, 6, 0, 6, 0, 6, 0, 6, 0};
layout.rowHeights = new int[] {0, 15, 0};
getContentPane().setLayout(layout);
backBtn.setText("Back");
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
getContentPane().add(backBtn, gridBagConstraints);
runBtn.setText("Run");
runBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runBtnActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
getContentPane().add(runBtn, gridBagConstraints);
headerTf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
headerTfActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 500;
gridBagConstraints.weightx = 1.0;
getContentPane().add(headerTf, gridBagConstraints);
addBtn.setText("Add");
addBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addBtnMouseClicked(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE\_END;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
getContentPane().add(addBtn, gridBagConstraints);
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 889, Short.MAX\_VALUE)
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 506, Short.MAX\_VALUE)
);
jScrollPane2.setViewportView(mainPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 7;
gridBagConstraints.ipady = 200;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
getContentPane().add(jScrollPane2, gridBagConstraints);
detailsButton.setText("Details");
detailsButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
detailsButtonMouseClicked(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 0;
getContentPane().add(detailsButton, gridBagConstraints);
pack();
}//
private void addBtnMouseClicked(java.awt.event.MouseEvent evt) {
if (currentlySelected == null) {
System.out.println("Adding Test Suite.");
TestSuite ts = new TestSuite("Name Please");
testSuites.add(ts);
TestCommonButton tcb = new TestCommonButton(ts);
mainPanel.add(tcb);
new TestCommonsDetailsForm(ts).setVisible(true);
} else {
System.out.println("Attempting to add Test level" + (currentlySelected.getDepth() + 1));
}
}
private void initTestSuites() {
clearFrameButtons();
headerTf.setText("Test Suites");
headerTf.setEditable(false);
int leftBound = ModelConstants.INIT_LEFT; //some padding
int upperBound = ModelConstants.INIT_TOP; //some padding
boolean top = true;
for (TestSuite tc : testSuites) {
TestCommonButton jb = new TestCommonButton(tc, tc.name);
jb.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
TestSuiteButtonMouseClicked(evt);
}
});
mainPanel.add(jb);
this.testCommonsButtons.add(jb);
jb.setBounds(leftBound, upperBound, ModelConstants.TEST_SUITE_WIDTH, ModelConstants.TEST_SUITE_HEIGHT);
if (top) {//we put button to top row, now put one below.
upperBound += ModelConstants.TEST_SUITE_HEIGHT + ModelConstants.Y_MARGIN_BETWEEN_TESTS;
}
if (!top) {//we put button to bottom row. Return to top row and shift right.
upperBound = ModelConstants.INIT_TOP;
leftBound += ModelConstants.TEST_SUITE_WIDTH + ModelConstants.X_MARGIN_BETWEEN_TESTS;
}
top = !top;
}
revalidate();
repaint();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Metal look and feel */
//
/\* If Metal (introduced in Java SE 6) is not available, stay with the default look and feel.
\* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
\*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Metal".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
MainFrame frame = new MainFrame();
//Load TestSuites
//TestingPurposes, replace with parser later.
List tss = new ArrayList();
for (int i = 0; i < 10; i++) {
tss.add(new TestSuite("Example#" + i));
}
//---------
for (TestSuite ts : tss) {
frame.testSuites.add(ts);
}
frame.initTestSuites();
/\* Create and display the form \*/
java.awt.EventQueue.invokeLater(() -> {
frame.setVisible(true);
});
}
private List testCommonsButtons = new ArrayList<>();
private List testSuites = new ArrayList<>();
private TestCommons currentlySelected = null;
// Variables declaration - do not modify
private javax.swing.JButton addBtn;
private javax.swing.JButton backBtn;
private javax.swing.JButton detailsButton;
private javax.swing.JTextField headerTf;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JPanel mainPanel;
private javax.swing.JButton runBtn;
// End of variables declaration
```
}<issue_comment>username_1: Without a code example (see the comment of <NAME>) one cannot be absolutely sure, but I think invalidating the ScrollPane, the panel inside it or both (you just need to try it out) after adding the button might solve the problem. Just call `yourScrollPane.invalidate()` and/or `yourPanel.invalidate()` after the button is added and report if it worked out.
Upvotes: 0 <issue_comment>username_2: ```
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
```
Your mainPanel uses a GroupLayout. GroupLayout is one of the most complicated layout manager and is generally only used by IDEs as it requires you to set vertical and horizontal constraints.
In your code you use:
```
mainPanel.add(tcb);
```
without any constraints so the layout manager doesn't work correctly.
I have never used GroupLayout because the constraints are too complex for me. So I suggest you don't generate your form using the IDE. Instead create your form manually so you are in control of the layout manager used and then you can use the appropriate layout manager (or nested panels using different layout managers) for your requirement.
Read the section from the Swing tutorial on [Layout Managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) for more information and working examples.
There tutorial does have an example of using a GroupLayout if you want to take the time to learn how to use it.
Upvotes: 1 <issue_comment>username_3: The problem was after all in boundaries of the `JPanel mainPanel`. Despite being able to be stretched and shrank, the underlying JScrollPane always treated it as it was exactly "preferred size" wide/tall (that was set in initComponents().
To counter this, I have added the following code to recalculate the necessary size right before revalidate() and repaint() methods in the init method.
```
GroupLayout gl = (GroupLayout) mainPanel.getLayout();
gl.setHorizontalGroup(gl.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, leftBound, Short.MAX_VALUE));
gl.setVerticalGroup(gl.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, upperBound, Short.MAX_VALUE));
```
Because it always creates new and new instances of `ParallelGroup`, it is probably not the most efficient way to achieve this functionality, but it works as needed.
Upvotes: 0 |
2018/03/19 | 1,071 | 3,531 | <issue_start>username_0: I've been attempting to implement an alert script for Zabbix. Zabbix attempts to run the script in Shell for some reason, whilst the script is written in Bash.
```
#!/bin/bash
# Slack incoming web-hook URL and user name
url='https://hooks.slack.com/services/this/is/my/webhook/' # example: https://hooks.slack.com/services/QW3R7Y/D34DC0D3/BCADFGabcDEF123
username='Zabbix Notification System'
## Values received by this script:
# To = $1 (Slack channel or user to send the message to, specified in the Zabbix web interface; "@username" or "#channel")
# Subject = $2 (usually either PROBLEM or RECOVERY/OK)
# Message = $3 (whatever message the Zabbix action sends, preferably something like "Zabbix server is unreachable for 5 minutes - Zabbix server (127.0.0.1)")
# Get the Slack channel or user ($1) and Zabbix subject ($2 - hopefully either PROBLEM or RECOVERY/OK)
to="$1"
subject="$2"
# Change message emoji depending on the subject - smile (RECOVERY/OK), frowning (PROBLEM), or ghost (for everything else)
recoversub='^RECOVER(Y|ED)?$'
if [[ "$subject" =~ ${recoversub} ]]; then
emoji=':smile:'
elif [ "$subject" == 'OK' ]; then
emoji=':smile:'
elif [ "$subject" == 'PROBLEM' ]; then
emoji=':frowning:'
else
emoji=':ghost:'
fi
# The message that we want to send to Slack is the "subject" value ($2 / $subject - that we got earlier)
# followed by the message that Zabbix actually sent us ($3)
message="${subject}: $3"
# Build our JSON payload and send it as a POST request to the Slack incoming web-hook URL
payload="payload={\"channel\": \"${to//\"/\\\"}\", \"username\": \"${username//\"/\\\"}\", \"text\": \"${message//\"/\\\"}\", \"icon_emoji\": \"${emoji}\"}"
curl -m 5 --data-urlencode "${payload}" $url -A "https://hooks.slack.com/services/this/is/my/web/hook"
~
```
When I run the script locally using 'bash slack.sh' it sends an empty notification, which I recieve in Slack.
When I run the script locally using 'sh slack.sh' I get the following error.
```
slack.sh: 19: slack.sh: [[: not found
slack.sh: 21: [: unexpected operator
slack.sh: 23: [: unexpected operator
slack.sh: 34: slack.sh: Bad substitution
```
Thanks for the assistance.<issue_comment>username_1: Your shebang is wrong.
```
# !/bin/bash
```
Remove that first space.
Upvotes: 1 <issue_comment>username_2: you seems to use [sh](/questions/tagged/sh "show questions tagged 'sh'") instead [bash](/questions/tagged/bash "show questions tagged 'bash'") when calling the script.
Use
```
bash script.sh
```
or
```
chmod +x script.sh
/full/path/to/script.sh
```
Note :
------
So now, you know the problem. One solution is to change the script to POSIX shell or search how to force zabbix to handle bash scripts
Upvotes: 0 <issue_comment>username_3: Failing to convince Zabbix to use `bash` to execute the script, you'll have to forgo regular expression matching (the `expr` command, bizarrely, does not support any form of alternation, which means its regular expressions can only recognize a subset of regular languages):
```
# if RECOVER(Y|ED)$ were a valid POSIX basic regular expression,
# you could use
#
# if expr "$subject" : "$recoverysub"; then
#
# but it is not, so you need...
if [ "$subject" = RECOVERY ] || [ "$subject" = RECOVERED ]; then
```
Upvotes: 0 <issue_comment>username_4: You can force your script to run with bash by adding
```
#! /bin/bash
if [ -z "$BASH" ]
then
exec /bin/bash "$0" "$@"
fi
...
```
Upvotes: 1 [selected_answer] |
2018/03/19 | 699 | 2,175 | <issue_start>username_0: I'm looking to set up a VBA macro which automatically runs through a list of data in a column and picks out the missing values. The code I've got at the moment (see below) works, but I believe it starts looking in cell A2. I'd like it to start in B1.
How could I make this change?
Apologies, I'm a beginner to VBA!
```
Sub Check_Sequential()
Dim LR As Long, i As Long
LR = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
ALR = ActiveSheet.Range("C" & Rows.Count).End(xlUp).Row + 1
x = 2
Cells(1, 3) = "Missing Numbers"
For i = 2 To LR
0
If Cells(i, 1) <> x Then
Cells(ALR, 3) = x
ALR = ActiveSheet.Range("C" & Rows.Count).End(xlUp).Row + 1
x = x + 1
Else
x = x + 1
End If
If Cells(i, 1) > x Then GoTo 0
If Cells(i, 1) = x Then
x = x + 1
End If
Next i
MsgBox "Done"
End Sub
```<issue_comment>username_1: Your shebang is wrong.
```
# !/bin/bash
```
Remove that first space.
Upvotes: 1 <issue_comment>username_2: you seems to use [sh](/questions/tagged/sh "show questions tagged 'sh'") instead [bash](/questions/tagged/bash "show questions tagged 'bash'") when calling the script.
Use
```
bash script.sh
```
or
```
chmod +x script.sh
/full/path/to/script.sh
```
Note :
------
So now, you know the problem. One solution is to change the script to POSIX shell or search how to force zabbix to handle bash scripts
Upvotes: 0 <issue_comment>username_3: Failing to convince Zabbix to use `bash` to execute the script, you'll have to forgo regular expression matching (the `expr` command, bizarrely, does not support any form of alternation, which means its regular expressions can only recognize a subset of regular languages):
```
# if RECOVER(Y|ED)$ were a valid POSIX basic regular expression,
# you could use
#
# if expr "$subject" : "$recoverysub"; then
#
# but it is not, so you need...
if [ "$subject" = RECOVERY ] || [ "$subject" = RECOVERED ]; then
```
Upvotes: 0 <issue_comment>username_4: You can force your script to run with bash by adding
```
#! /bin/bash
if [ -z "$BASH" ]
then
exec /bin/bash "$0" "$@"
fi
...
```
Upvotes: 1 [selected_answer] |
2018/03/19 | 331 | 1,374 | <issue_start>username_0: I´m looking at Azure Functions capabilities and the documentation does not say anything about uploading, creating or deleting a Function programmatically, nor anything about listing enabled/disabled Functions. Any ideas on how to do that? The Azure API reference has no section for Azure Functions.<issue_comment>username_1: This functionality exists within the [Azure CLI toolset](https://learn.microsoft.com/en-us/cli/azure/?view=azure-cli-latest).
* Here is a guide on [creating functions via the CLI](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-azure-function-azure-cli)
* [Documentation for the functions segment of Azure CLI](https://learn.microsoft.com/en-us/cli/azure/functionapp?view=azure-cli-latest)
Hopefully these two resources should help get started. If you were looking for a publicly facing API, you may be out of luck.
Upvotes: 2 <issue_comment>username_2: You can create functions from the cli using:
```
func new
```
Alternatively you can pass in some parameters (not required):
```
func new --language JavaScript --template HttpTrigger --name MyFunction
```
If you don't pass in the parameters, you are prompted with the questions and you can choose the correct options.
I've done deletion by removing the function specific folder and then deploying the application again.
Upvotes: 0 |
2018/03/19 | 1,278 | 3,967 | <issue_start>username_0: Hi Guys I am trying to make a request and get a response for authenticating my SOAP request.
I tried many different options but this one was the only one which gave me response(even an error 404).
This is my code
```
$client = new SOAPClient('http://devapi.stellatravelgateway.stellatravelservices.co.uk/DirectoryService.svc?singleWsdl',
array(
'location' => 'http://stellatravelgateway.stellatravelservices.co.uk/DirectoryService/IDirectoryService/Authenticate',
'trace' => 1,
'style' => SOAP_RPC,
'use' => SOAP_ENCODED,
)
);
$request = array(
"BranchCode" => "xxx",
"UserName" => "xxx",
"Password" => "xxx",
"Application" => "xxx",
"Client" => "x",
"BranchID" => 0
);
$result = array();
try {
$result = $client->__soapCall('Authenticate', $request);
} catch (SoapFault $e) {
echo "SOAP Fault: ".$e->getMessage()."
\n";
}
echo "
```
";
echo htmlspecialchars($client->__getLastRequestHeaders())."\n";
echo htmlspecialchars($client->__getLastRequest())."\n";
echo "Response:\n".htmlspecialchars($client->__getLastResponseHeaders())."\n";
echo htmlspecialchars($client->__getLastResponse())."\n";
echo "
```
";
var_dump($result);
```
What am i doing wrong? I dont get any response I get thsi
```
POST /DirectoryService/IDirectoryService/Authenticate HTTP/1.1
Host: stellatravelgateway.stellatravelservices.co.uk
Connection: Keep-Alive
User-Agent: PHP-SOAP/5.5.38
Content-Type: text/xml; charset=utf-8
SOAPAction:"http://stellatravelgateway.stellatravelservices.co.uk/DirectoryService/IDirectoryService/Authenticate"
Content-Length: 367
xml version="1.0" encoding="UTF-8"?
xxxxxxxxxx0
Response:
HTTP/1.1 404 Not Found // Here
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Mon, 19 Mar 2018 13:34:51 GMT
Connection: close
Content-Length: 1245
```
This is the exact request I need to send :
```
xxx
```
EDIT: This is what I get on raw from SoapUI:
```
POST http://stellatravelgateway.stellatravelservices.co.uk/AirService HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "http://stellatravelgateway.stellatravelservices.co.uk/DirectoryService/IDirectoryService/Authenticate"
Content-Length: 602
Host: stellatravelgateway.stellatravelservices.co.uk
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
```
Please guys any help would be great, any feedback! Thank you in advance.<issue_comment>username_1: Try to pass the credentials as otions when creating the client:
```
$client = new \SoapClient('http://devapi.stellatravelgateway.stellatravelservices.co.uk/DirectoryService.svc?singleWsdl', array(
'login' => $username,
'password' => $<PASSWORD>,
'exceptions' => true,
'trace' => true
));
```
Upvotes: 0 <issue_comment>username_2: Remove the 'location' param from options, and call the Authenticate() function like this:
```
try {
$result = $client->Authenticate(array('authenticateRequest'=>$request));
} catch (SoapFault $e) {
```
result:
```
POST /DirectoryService.svc HTTP/1.1
Host: devapi.stellatravelgateway.stellatravelservices.co.uk
Connection: Keep-Alive
User-Agent: PHP-SOAP/5.6.32
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://stellatravelgateway.stellatravelservices.co.uk/DirectoryService/IDirectoryService/Authenticate"
Content-Length: 446
xml version="1.0" encoding="UTF-8"?
0
Response:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Mon, 19 Mar 2018 14:06:43 GMT
Connection: close
Content-Length: 522
object(stdClass)#2 (1) {
["AuthenticateResult"]=>
object(stdClass)#3 (6) {
["Success"]=>
bool(false)
["Narrative"]=>
string(39) "Invalid details. Please check request. "
["CanBeOpenedInEditMode"]=>
bool(false)
["ErrorCode"]=>
int(200002)
["Token"]=>
NULL
["Expiry"]=>
NULL
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 2,917 | 8,921 | <issue_start>username_0: I'm a student who just started learning Python and I just can't seem to fix this error which keeps popping up. I've been at it for hours with no avail, so I'd love some input from the experts.
The program idea is simple, just a program which can calculate the costs of all the components needed to build a computer.
Code:
```
import datetime
Comp = [["Processor",["P3", "P5", "P7"],[100, 120, 200],[10, 10, 10],[0,0,0]], #Component - Choices - Price - Stock - Total of each component sold.
["RAM",["16GB", "32GB"],[75,150],[10, 10],[0,0]],
["Storage",["1TB", "2TB"],[50,100], [10, 10],[0,0]],
["Screen",["19", "23"],[65, 120], [10, 10],[0,0]],
["Case",["MT", "IT"],[40,70], [10,10],[0,0]],
["USB",["2", "4"],[10, 20], [10, 10]],[0,0]]
cList = [] #List of updating items.
cPrice = [] #List of updating prices.
fullPrice = [] #After order is complete, total price is added to this array for final day stats.
orderNo = 1 #Order number counter.
time = datetime.datetime.now() #Datetime counter.
print ("Welcome to Build Your PC! \n\nSelect the components below to estimate the final price for the product!\n")
def Pick():
print ("Order Number #",orderNo) #Print order number.
for i in range (6): #Repeat 6 times each for all the Components.
print ("\nPlease choose an available", Comp[i][0],"component from the list below.")
print ("Component: Price:")
for x,y in zip(Comp[i][1], Comp[i][2]): #Zips the two lists (Component + Price) together to format the two lists side by side.
print ("{:10} $".format(x) ,y) #Format variable to add padding between lists.
choice = input("\nEnter here : ").upper() #Force lowercase to fit with array variables.
if choice in Comp[i][1]: #Validation if chosen Component is in list.
cIndex = Comp[i][1].index(choice) #Indexes chosen Component location for future reference.
cList.append(choice) #Adds chosen Component to cList list (Line 9).
cPrice.append(Comp[i][2][cIndex]) #Adds chosen Component to cPrice list (Line 10).
if Comp[i][3][cIndex] > 0: #Validation if item is in stock.
Comp[i][3][cIndex] = (Comp[i][3][cIndex] - 1) #Minus 1 to current stock.
print ("Item is in stock. Now", Comp[i][3][cIndex], "is left in stock.")
tPrice = sum(cPrice) #Sums up total price of all the items in the shopping cart.
print ("Total cost in shopping cart is $", tPrice,".")
Comp[i][4][cIndex] = (Comp[i][4][cIndex] + 1) #Adds plus 1 to Total of each component sold.
else :
print ("Item is out of stock!")
Pick()
else :
print ("Invalid entry.")
Pick()
print ("\nOrder received. Calculating final details...")
print ("\nOrder Number #", orderNo, time.strftime("%Y-%m-%d %H:%M"))
print ("Shopping cart :")
for x,y in zip(cList, cPrice): #Print two lists in two columns with list of components and prices.
print ("{:4} $".format(x), y)
print ("Final price + 20% taxes : $", (tPrice*1.2))
print ("Thank you for shopping at Build Your PC!")
Pick()
rOrder = input("\nDo you wish to add another order? Y or N?").upper() #Repeat order.
if rOrder == ("Y"):
orderNo = (orderNo + 1) #Counts number of orders.
fullPrice.append(tPrice) #Adding total price variables per build for final earnings.
cList = []
cPrice = [] #Resetting both arrays for next order.
Pick()
else :
print ("\nTotal orders made today : #", orderNo)
print ("Total earnings today : $", sum(fullPrice)) #Adding up all variables array for final earnings.
print ("Component: Amount Sold:")
for i in range(6): #Repeats 6 times to print component amounts sold for each section.
for x,y in zip(Comp[i][1], Comp[i][4]): #Zips two lists (Choice + Total Sold) to display side by side.
print ("{:4}".format(x) ,y)
print ("Closing Build Your PC program...")
```
Log :
```
Welcome to Build Your PC!
Select the components below to estimate the final price for the product!
Order Number # 1
Please choose an available Processor component from the list below.
Component: Price:
P3 $ 100
P5 $ 120
P7 $ 200
Enter here : P3
Item is in stock. Now 9 is left in stock.
Total cost in shopping cart is $ 100 .
Please choose an available RAM component from the list below.
Component: Price:
16GB $ 75
32GB $ 150
Enter here : 16GB
Item is in stock. Now 9 is left in stock.
Total cost in shopping cart is $ 175 .
Please choose an available Storage component from the list below.
Component: Price:
1TB $ 50
2TB $ 100
Enter here : 1TB
Item is in stock. Now 9 is left in stock.
Total cost in shopping cart is $ 225 .
Please choose an available Screen component from the list below.
Component: Price:
19 $ 65
23 $ 120
Enter here : 19
Item is in stock. Now 9 is left in stock.
Total cost in shopping cart is $ 290 .
Please choose an available Case component from the list below.
Component: Price:
MT $ 40
IT $ 70
Enter here : MT
Item is in stock. Now 9 is left in stock.
Total cost in shopping cart is $ 330 .
Please choose an available USB component from the list below.
Component: Price:
2 $ 10
4 $ 20
Enter here : 2
Item is in stock. Now 9 is left in stock.
Total cost in shopping cart is $ 340 .
Traceback (most recent call last):
File "Computer v2.py", line 64, in
Pick()
File "Computer v2.py", line 44, in Pick
Comp[i][4][cIndex] = (Comp[i][4][cIndex] + 1) #Adds plus 1 to Total of each component sold.
IndexError: list index out of range
```
The error on line 44 giving me this - IndexError: list index out of range
It's really perplexing. The fact is, it runs 5 times before on the 6th run, it just stops working? There is nothing wrong with the snippet itself as I have tested it in its own environment, but for some reason it just breaks down on the 6th run for component USB.
Thank you for taking your time to help me. I'm still in my learning stages, so any additional suggestions to improve this program unrelated to this specific bug will also be appreciated!<issue_comment>username_1: You have a small typo:
```
["USB",["2", "4"],[10, 20], [10, 10]],[0,0]]
```
Should be:
```
["USB",["2", "4"],[10, 20], [10, 10],[0,0]]]
```
This is causing your 6th entry in the list to be cut short thus not incluing the `[0,0]` in the fourth slot of the list.
---
Also on Line 69, `tPrice` isn't defined in the scope (it's defined in the function scope but outside of the function the variable isn't created, perhaps you want to return `tPrice` from the function and assign it to the function call:
```
#previous code that I didn't include
print ("Thank you for shopping at Build Your PC!")
return tPrice
tPrice = Pick()
rOrder = input("\nDo you wish to add another order? Y or N?").upper() #Repeat order.
if rOrder == ("Y"):
orderNo = (orderNo + 1) #Counts number of orders.
fullPrice.append(tPrice) #Adding total price variables per build for final earnings.
cList = []
cPrice = [] #Resetting both arrays for next order.
Pick()
#rest of the code I didn't include
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Your list has an error so that the last sublist is too short: ["USB",["2", "4"],[10, 20], [10, 10]],[0,0]] should be ["USB",["2", "4"],[10, 20], [10, 10],[0,0]]].
Debug printouts are useful, that's how I found it.
Upvotes: 1 <issue_comment>username_3: The problem here is the initial data that is set in the `Comp` array. One of the square brackets is in the wrong place, causing the `USB` array to be closed early.
The problem is at the end of the USB array:
```
Comp = [["Processor",["P3", "P5", "P7"],[100, 120, 200],[10, 10, 10],[0,0,0]], #Component - Choices - Price - Stock - Total of each component sold.
["RAM",["16GB", "32GB"],[75,150],[10, 10],[0,0]],
["Storage",["1TB", "2TB"],[50,100], [10, 10],[0,0]],
["Screen",["19", "23"],[65, 120], [10, 10],[0,0]],
["Case",["MT", "IT"],[40,70], [10,10],[0,0]],
["USB",["2", "4"],[10, 20], [10, 10]],[0,0]]
```
There is a `]` after `[10,10]` that should be after the `[0, 0]]` section instead.
To fix this error, update the `Comp` array to this:
```
Comp = [["Processor",["P3", "P5", "P7"],[100, 120, 200],[10, 10, 10],[0,0,0]], #Component - Choices - Price - Stock - Total of each component sold.
["RAM",["16GB", "32GB"],[75,150],[10, 10],[0,0]],
["Storage",["1TB", "2TB"],[50,100], [10, 10],[0,0]],
["Screen",["19", "23"],[65, 120], [10, 10],[0,0]],
["Case",["MT", "IT"],[40,70], [10,10],[0,0]],
["USB",["2", "4"],[10, 20], [10, 10],[0,0]]]
```
Upvotes: 0 |
2018/03/19 | 470 | 1,588 | <issue_start>username_0: I need to kill a process behind a service on a remote computer with PowerShell for a program/script I am creating.
The problem is that the process doesn't always have the same PID and the name is not always the same either. The only thing that always is the same is the name.
I have found out that I can get the PID of the service with this command:
```
taskkill /s rasmuspc /u rasmus123 /p 12345 /PID (Get-WmiObject Win32_Service|where{$_.Name -eq 'Spooler'}).ProcessID /F
```
I use this command to skip `tasklist`, so I can make it automated instead of manually looking up and typing in the PID.
But that command will only get the PID from my own computer, and I can't see is there a way to to get the PID of a service on a remote PC, only knowing the name of the service?<issue_comment>username_1: try this
`Get-Process -ComputerName "ServerName" -Name notepad | stop-Process`
you need to have able in the remote machine to stop process
Upvotes: 0 <issue_comment>username_2: ```
Taskkill /s rasmuspc /u rasmus123 /p 12345 /PID (Get-WmiObject -CN $remotepcname -filter 'name="spooler"}).processID /F
```
Thanks to <NAME>, this command worked.
Upvotes: 2 [selected_answer]<issue_comment>username_3: tasklist /s *Server name*.
This can be used to get the list of tasks running on a remote server
Upvotes: 1 <issue_comment>username_4: To kill a corresponding process in Powershell, one line:
```
Get-Process -PID (Get-WmiObject -CN $RemotePCName -filter 'name="spooler"' -Class Win32_service).processID | Stop-Process -Force
```
Upvotes: 0 |
2018/03/19 | 918 | 4,095 | <issue_start>username_0: I'm totally lost on this topic . I've researched Spring Autowiring on internet trying to figure out what it does and everything I find is mostly saying "Spring Autowiring helps you autowire collaborating Beans " and thats it . I would greatly appreciate if someone can explain to me from scratch what is Spring Bean, What is Autowiring and how these two work together with examples and explanations of this examples. Don't just say that "Spring Autowiring is autowiring two beans " because I don't get it what it means .
What I understand right now is that lets say if have a simple class :
```
Public class Car(){
public int numberOfWheels;
}
```
and we declare this class as a Bean, we than can create the instance of the object of this class without saying "new" keyword. So we can just declare it in a bean and insert value of this "numberOfWheels" property outside the java class . I might be super wrong here or using very bad example , because I've been trying to learn Spring Framework and it's just been very hard for me , so any help would be greatly appreciated.<issue_comment>username_1: To basically, Spring has a bean pool which means Spring creates java objects and put them into a pool. Whenever you want to use an object, you fetch object from pool using **@Autowired** annotation.
Spring basically uses Reflection to create objects by its own, instead of passing objects from class to class. This is what basically Autowire is.
This concept is called Dependency Injection. Spring injects components, services, repositories whenever you want.
Upvotes: -1 <issue_comment>username_2: Well, Spring is a Dependency Injection framework, so you should start learning about this.
**DEPENDENCY INJECTION**
This is a technique whereby one object supplies the dependencies of another object. Such as, for example: object a of type A need is dependent of an object b of type B. In a code example:
Customer it's dependent of Person:
```
public class Person {
private String name;
private String lastName;
}
public class Customer {
private Person person;
}
```
In this case, any Customer object will have a Person object dependency.
Now, in Spring scope, all objects are named beans, so this is a bean, an Object that it's injected into Spring Context.
Spring provides a Dependency Injection mechanism that it's very easy. For our example, you can put put some of the following annotation: @Component, @Bean, @Service on class Person, and Spring will create an object of type Person with calling default constructor. Afer that, in class Customer, you can put @Autowired annotation on top of the Person person attribute. This annotation, will tell Spring to search for a specific bean of type Person that was injected into the Spring Context, and Spring using Reflection(searching by name) will find a Person object type that was creating by using one of the @Component, @Bean, @Service annotations. After that, Spring will pass the reference of the Person object that was found to the Customer object that requires it.
Upvotes: 1 [selected_answer]<issue_comment>username_3: **Spring Bean** is an object which is instantiated and maintained automatically by Spring Framework. They usually depend on each other in some way, and the dependencies therefore must be resolved.
**Autowiring** is one of the ways how to resolve these dependencies. You don't manually specify which concrete dependency should be provided to the class, you just choose the way how Spring should automatically find the correct dependency (by matching the class's property name and name of the desired bean, for instance).
Spring's documentation is very extensive and you can find a lot of useful information there. For more info about Spring Beans, you can read [this](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-definition), if you want to know more about autowiring, try [this](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-autowire).
Upvotes: 0 |
2018/03/19 | 2,009 | 5,608 | <issue_start>username_0: I'm using Microsoft Azure Machine Learning Studio to try an experiment where I use previous analytics captured about a user (at a time, on a day) to try and predict their next action (based on day and time) so that I can adjust the UI accordingly. So if a user normally visits a certain page every Thursday at 1pm, then I would like to predict that behaviour.
Warning - I am a complete novice with ML, but have watched quite a few videos and worked through tutorials like the movie recommendations example.
I have a csv dataset with userid,action,datetime and would like to train a matchbox recommendation model, which, from my research appears to be the best model to use. I can't see a way to use date/time in the training. The idea being that if I could pass in a userid and the date, then the recommendation model should be able to give me a probably result of what that user is most likely to do.
I get results from the predictive endpoint, but the training endpoint gives the following error:
```html
{
"error": {
"code": "ModuleExecutionError",
"message": "Module execution encountered an error.",
"details": [
{
"code": "18",
"target": "Train Matchbox Recommender",
"message": "Error 0018: Training dataset of user-item-rating triples contains invalid data."
}
]
}
}
```
[Here is a link to a public version of the experiment](https://gallery.cortanaintelligence.com/Experiment/User-analytics)
Any help would be appreciated.
Thanks.
[](https://i.stack.imgur.com/Z6Uhr.png)<issue_comment>username_1: So from messing with this for a while, I think I may see where the issue may lie. I *think* that the first three inputs of the Train Matchbox Recommender would need to be filled in for an accurate prediction. I'll include screenshots of the sample for recommending restaurants, as well.
The first input would be the dataset consisting of the user, item, and rating.
[](https://i.stack.imgur.com/h0IK7.png)
The second input would be the features of each user.
[](https://i.stack.imgur.com/fEfn2.png)
And the third input would be the features of each feature (restaurant in this case).
[](https://i.stack.imgur.com/I3SI8.png)
So to help with the date/time issue, I'm wondering if the data would need to be munged to match something similar to the restaurant and user data.
I know it's not much, but I hope it helps lead you down the right track.
Upvotes: 1 <issue_comment>username_2: Maybe [this answer](https://stackoverflow.com/questions/37375506/azureml-train-matchbox-recommender-is-not-working-and-does-not-descibe-the-er) could be helpful, you may also take a look [on this](https://social.msdn.microsoft.com/Forums/azure/en-US/24a06c13-bde0-4955-86f3-85a2f2b37153/test-dataset-contains-invalid-data?forum=MachineLearning) where you can read:
>
> The problem is probably with the range of rating data. There's an upper limit for rating range, because the training gets expensive if the range between smallest and largest rating is too large.
>
>
> [...]
>
>
> One option would be to scale the ratings to a narrower range.
>
>
>
According to this MSDN, please note that you cannot have a gap between the min and max note higher than `100`.
So you have to make a pre-processing on your csv file column data (userid, action, datetime etc...) in order to keep all column data in the `[0-99]` range.
Please see bellow a Python implementation (to share the logic):
```
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
big_gap_arr = [-250,-2350,850,-120,-1235,3212,1,5,65,48,265,1204,65,23,45,895,5000,3,325,3244,5482] #data with big gap
abs_min = abs(min(big_gap_arr)) #get the absolute minimal value
max_diff= ( max(big_gap_arr) + abs_min ) #get the maximal diff
specific_range_arr=[]
for each_value in big_gap_arr:
new_value = ( 99/1. * float( abs_min + each_value) / max_diff ) #get a corresponding value in the [0,99] range
specific_range_arr.append(new_value)
print specific_range_arr #post computed data => all in range [0,99]
```
Which give you:
```
[26.54494382022472, 0.0, 40.449438202247194, 28.18820224719101, 14.094101123595506, 70.3061797752809, 29.71769662921348, 29.76825842696629, 30.526685393258425, 30.31179775280899, 33.05477528089887, 44.924157303370784, 30.526685393258425, 29.995786516853933, 30.27387640449438, 41.01825842696629, 92.90730337078652, 29.742977528089888, 33.813202247191015, 70.71067415730337, 99.0]
```
Note that all data are now in the `[0,99]` range
---
Following this process:
* *User id could be float instead an integer*
* *Action is an integer (if you got less than 100 actions) or float (if more than 100 actions)*
* *Datetime will be splited in two integer (or one integer and one float), please see bellow:*
---
Concerning:
>
> (A) way to use date/time in the training
>
>
>
You may split your datetime in two column, something like:
* one column for the **weekday**:
+ 0: Sunday
+ 1: Monday
+ 2: Tuesday
+ [...]
+ 6: Saturday
* one column for the **time in the day**:
+ 0: Between 00:00 & 00:15
+ 1: Between 00:15 & 00:30
+ 2: Between 00:30 & 00:40
+ [...]
+ 95 : Between 23:45 & 00:00
If you need a better granularity (here it is a 15 min window) you may also use float number for the time column.
Upvotes: 2 |
2018/03/19 | 1,002 | 2,882 | <issue_start>username_0: I'm trying to use the built in pandas method .str.extract to extract a substring from within a column in a dataframe I have imported. The entries within the column all follow this structure:
```
x.xx% Test1 Test2 Test3 XYZ|ZYX Oct 2018
```
So essentially it is always a float %, following by a string (which doesn't always have the same length of words), followed by a three letter code which is either XYZ or ZYX and a date afterwards.
I'm trying to extract the Test1, Test2 and Test3 from the example above, meaning I want to strip out the percentage at the beginning, and where XYZ|ZYX occur I want everything after gone (including the three letter code).
I've been reading up on regex all morning but I'm struggling a bit to build some code using pandas extract that can pull out exactly what I want. Any suggestions? Furthest I've gotten is the below, which only pulls through the percentages at the beginning (was trying to split it into three categories):
```
.str.extract('(\d\.\d+%.)')
```<issue_comment>username_1: You can use a pattern with a lookahead to determine when to stop matching.
```
([\w\s]+?)(?=\w{3}\|)'
```
**Details**
```
( # first capture group
[\w\s]+? # match letters or whitespaces
)
(?= # lookahead
\w{3} # fixed length 3 chars
\| # literal `|`
)
```
---
```
s = pd.Series(['x.xx% Test1 Test2 Test3 XYZ|ZYX Oct 2018'])
s.str.extract(r'([\w\s]+?)(?=\w{3}\|)', expand=False)
0 Test1 Test2 Test3
dtype: object
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: A regex you can you could be the following:
```
r"(\d\.\d+%.)(.*)\s([A-Z]{3})\s([A-Z]{1}[a-z]{2})\s([0-9]{4}$)"
```
where `\d\.\d+%.` matches the percentage
`[A-Z]{3}` matches the letter code
`[A-Z]{1}[a-z]{2}` matches the month
`[0-9]{4}$` matches the year, at the end
`.*` matches the remaining, thus the tests.
the `\s` match a single space, and it's outside the matches.
The resulting code could be something like this:
```
import re
string = "3.14% Test1 Test2 Test3 XYZ Oct 2018"
matches = re.findall(r"(\d\.\d+%.)(.*)\s([A-Z]{3})\s([A-Z]{1}[a-z]{2})\s([0-9]{4}$)", string)[0]
percentage = matches[0]
mytest = matches[1].split(' ')
letter_code = matches[2]
month = matches[3]
year = matches[4]
print(percentage) # 3.14%
print(mytest) # ['Test1', 'Test2', 'Test3']
print(letter_code) # XYZ
print(month) # Oct
print(year) # 2018
```
Upvotes: 0 <issue_comment>username_3: You can try Positive Lookbehind :
```
import re
pattern=r'(?<=%)(\s.+)?XYZ|ZYX'
text="""x.xx% Test1 Test2 Test3 XYZ|ZYX Oct 2018
x.xx% Test1 Test2 Test3 ZYX|XYZ Oct 2018"""
for i in re.findall(pattern,text):
data=re.sub(re.escape('ZYX|'),' ',i)
if data.split():
print(data.split())
```
output:
```
['Test1', 'Test2', 'Test3']
['Test1', 'Test2', 'Test3']
```
Upvotes: 0 |
2018/03/19 | 754 | 2,475 | <issue_start>username_0: How to stop a horizontal scrollbar from affecting the vertical align of the text inside a div? I want the text centered and the scrollbar can be under it.
Is it also possible to place the scrollbar on the underside of the outer div (without affecting its height) and affecting the scroll of the inner div with it?
```css
.outer {
width: 50%;
padding: 30px;
background-color: #008000;
}
.inner {
border: 1px solid red;
height: 50px;
overflow: scroll;
white-space: nowrap;
}
```
```html
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget nulla ac leo ullamcorper tristique. Donec lobortis a dolor sit amet congue. Etiam nisl lectus, euismod id enim ac, pretium blandit lectus. Cras congue placerat purus in malesuada. In
ex dui, iaculis id nisi eget, fermentum condimentum ante. Etiam a facilisis justo, vitae auctor lacus. Duis at nisi sed lacus tincidunt accumsan at id lacus. Praesent at luctus velit, eget interdum turpis.
```
**Screenshot**
The red line is the middle and the text needs to be there, which isn't because it's centering the whole div including the scrollbar in it
[](https://i.stack.imgur.com/29QgA.png)<issue_comment>username_1: You can vertically center your text easily with flex :
```
.inner {
display: flex;
align-items: center;
border: 1px solid red;
height: 50px;
overflow: scroll;
white-space: nowrap;
}
.text {
margin: auto;
}
```
---
```
Text here
```
For your second question for the scrollbar outside the div i don't think you can do it, but maybe someone here have the solution :)
Upvotes: 1 <issue_comment>username_2: Add `line-height`. `line-height = height`.
```css
.outer {
width: 50%;
padding: 30px;
background-color: #008000;
}
.inner {
border: 1px solid red;
height: 50px;
line-height: 50px;
overflow: scroll;
white-space: nowrap;
}
```
```html
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget nulla ac leo ullamcorper tristique. Donec lobortis a dolor sit amet congue. Etiam nisl lectus, euismod id enim ac, pretium blandit lectus. Cras congue placerat purus in malesuada. In
ex dui, iaculis id nisi eget, fermentum condimentum ante. Etiam a facilisis justo, vitae auctor lacus. Duis at nisi sed lacus tincidunt accumsan at id lacus. Praesent at luctus velit, eget interdum turpis.
```
Upvotes: 0 |
2018/03/19 | 1,315 | 5,680 | <issue_start>username_0: Example ViewModel:
```
public class NameViewModel extends ViewModel {
// Create a LiveData with a String
private MutableLiveData mCurrentName;
public MutableLiveData getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<>();
}
return mCurrentName;
}
}
```
Main activity:
```
mModel = ViewModelProviders.of(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer nameObserver = textView::setText;
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
```
I want to call `mModel.getCurrentName().setValue(anotherName);` in second activity and make MainActivity receive changes. Is that possible?<issue_comment>username_1: When you call `ViewModelProviders.of(this)`, you actually create/retain a `ViewModelStore` which is bound to `this`, so different Activities have different `ViewModelStore` and each `ViewModelStore` creates a different instance of a `ViewModel` using a given factory, so you can not have the same instance of a `ViewModel` in different `ViewModelStore`s.
But you can achieve this by passing a single instance of a custom ViewModel factory which acts as a singleton factory, so it will always pass the same instance of your `ViewModel` among different activities.
For example:
```
public class SingletonNameViewModelFactory extends ViewModelProvider.NewInstanceFactory {
NameViewModel t;
public SingletonNameViewModelFactory() {
// t = provideNameViewModelSomeHowUsingDependencyInjection
}
@Override
public NameViewModel create(Class modelClass) {
return t;
}
}
```
So what you need is to make `SingletonNameViewModelFactory` singleton (e.g. using Dagger) and use it like this:
```
mModel = ViewModelProviders.of(this,myFactory).get(NameViewModel.class);
```
**Note:**
Preserving `ViewModel`s among different scopes is an anti-pattern. It's highly recommended to preserve your data-layer objects (e.g. make your DataSource or Repository singleton) and retain your data between different scopes (Activities).
Read [this](https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing) article for details.
Upvotes: 7 [selected_answer]<issue_comment>username_2: When getting the view model using the ViewModelProviders you are passing as lifecycle owner the MainActivity, this will give the view model for the that activity. In the second activity you will get a different instance of that ViewModel, this time for your second Activity. The second model will have a second live data.
What you can do is maintain the data in a different layer, like a repository, which may be a singleton and that way you can use the same view model.
[](https://i.stack.imgur.com/uUJUw.png)
```
public class NameViewModel extends ViewModel {
// Create a LiveData with a String
private MutableLiveData mCurrentName;
public MutableLiveData getCurrentName() {
if (mCurrentName == null) {
mCurrentName = DataRepository.getInstance().getCurrentName();
}
return mCurrentName;
}
}
//SingleTon
public class DataRepository
private MutableLiveData mCurrentName;
public MutableLiveData getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<>();
}
return mCurrentName;
}
//Singleton code
...
}
```
Upvotes: 5 <issue_comment>username_3: Simply create the instance of your **ViewModel**, in this case **NameViewModel**
Your ViewModel Factory be like
```
class ViewModelFactory : ViewModelProvider.NewInstanceFactory() {
override fun create(modelClass: Class) =
with(modelClass){
when {
isAssignableFrom(NameViewModel::class.java) -> NameViewModel.getInstance()
else -> throw IllegalArgumentException("Unknown viewModel class $modelClass")
}
} as T
companion object {
private var instance : ViewModelFactory? = null
fun getInstance() =
instance ?: synchronized(ViewModelFactory::class.java){
instance ?: ViewModelFactory().also { instance = it }
}
}
}
```
And your ViewModel
```
class NameViewModel : ViewModel() {
//your liveData objects and many more...
companion object {
private var instance : NameViewModel? = null
fun getInstance() =
instance ?: synchronized(NameViewModel::class.java){
instance ?: NameViewModel().also { instance = it }
}
}
}
```
Now you can use `ViewModelProviders` to get the same instance of your ViewModel to use in any activity
```
ViewModelProviders.of(this, ViewModelFactory.getInstance()).get(NameViewModel::class.java)
```
**OR**
create an extension function for easier access
```
fun AppCompatActivity.getViewModel(viewModelClass: Class) =
ViewModelProviders.of(this, ViewModelFactory.getInstance()).get(viewModelClass)
```
Upvotes: 2 <issue_comment>username_4: ViewModel scope/lifecycle is tied to an activity simply because the ViewModelStoreOwner that you pass to the ViewModelProvider constructor happens to be the activity.
Since you get to provide the ViewModelStoreOwner, you can just as easily provide one that has a longer lifecycle, such as the application.
You can
1. Provide your own subclass of Application and make it implement ViewModelStoreOwner (and have a ViewModelStore)
2. In ViewModelProvider constructor calls, pass activity.application rather than activity.
This will cause the ViewModelProvider to interact with the application-level ViewModelStore, allowing you to create ViewModel instances that will have application scope.
Upvotes: 1 |
2018/03/19 | 1,104 | 3,923 | <issue_start>username_0: We got OOMKilled event on our K8s pods. We want in case of such event to run Native memory analysis command BEFORE the pod is evicted. Is it possible to add such a hook?
Being more specific: we run with `-XX:NativeMemoryTracking=summary` JVM flag. We want to run `jcmd VM.native\_memory summary.diff` just BEFORE pod eviction to see what causes OOM.<issue_comment>username_1: Looks like it is almost impossible to handle.
Based on an [answer on Github](https://github.com/kubernetes/kubernetes/issues/40157) about a gracefully stop on OMM Kill:
>
> It is not possible to change OOM behavior currently. Kubernetes (or runtime) could provide your container a signal whenever your container is close to its memory limit. This will be on a best effort basis though because memory spikes might not be handled on time.
>
>
>
Here is from [official documentation](https://kubernetes.io/docs/tasks/administer-cluster/out-of-resource/#node-oom-behavior):
>
> If the node experiences a system OOM (out of memory) event prior to the kubelet is able to reclaim memory, the node depends on the oom\_killer to respond.
> The kubelet sets a oom\_score\_adj value for each container based on the quality of service for the Pod.
>
>
>
So, as you understand, you have not much chance to handle it somehow.
Here is the large [article](https://lwn.net/Articles/590960/) about the handling of OOM, I will take just a small part here, about memory controller out of memory handling:
>
> Unfortunately, there may not be much else that this process can do to respond to an OOM situation. If it has locked its text into memory with mlock() or mlockall(), or it is already resident in memory, it is now aware that the memory controller is out of memory. It can't do much of anything else, though, because most operations of interest require the allocation of more memory.
>
>
>
The only thing I can offer is getting a data from [cAdvisor](https://github.com/google/cadvisor) (here you can get an OOM Killer event) or from Kubernetes API and run your command when you see by metrics that you are very close to out of memory. I am not sure that you will have a time to do something after you will get OOM Killer event.
Upvotes: 4 <issue_comment>username_2: Here are some steps we used to analyze the pod OOMKilled in K8S.
* Memory usage monitor through Prometheus
+ Not only the metric `container_memory_working_set_bytes` used to monitor the memory usage but also the `container_memory_max_usage_bytes`.
+ We could find some abnormal memory increase from the above metrics, to further investigate based on our logic codes.
* Check the system Log
+ In a systemd based Linux Distribution. The tool to use is `journalctl`.
```
sudo journalctl --utc -ke
```
+ `-ke` show only kernel messages and jumps to end of the log.
Some logs below
```
memory: usage 4194304kB, limit 4194304kB, failcnt 1239
memory+swap: usage 4194304kB, limit 9007199254740988kB, failcnt 0
kmem: usage 13608kB, limit 9007199254740988kB, failcnt 0
Memory cgroup stats for /kubepods.slice/kubepods-burstable.slice/kubepods-burst...
```
+ We could find some abnormal memory usage in System View.
* Check memory cgroup stats from the above folder
+ Check the files under the folder `/sys/fs/cgroup/memory/kubepods.slice/kubepods-burstable.slice` to find the memory allocation information.
* Memory dump of pod
+ We could add one hook to `preStop` of pod to dump the memory of pod, further investigation could be done based on the dump file. Here is one sample of Java
```
lifecycle:
preStop:
exec:
command:
- sh
- -c
- "jmap -dump:live,format=b,file=/folder/dump_file 1"
```
* Continues Profile
+ Use continue profile tools like [pyroscope](https://github.com/grafana/pyroscope) to monitor memory usage of the pod, and find the leak point profile data.
Upvotes: 1 |
2018/03/19 | 413 | 1,374 | <issue_start>username_0: I've been testing a regex of mine. The goal is getting a concrete and named url parameter from a website for replacing it.
Now I almost achieved to get the parameter with this regex:
```
.website.com.+tag=(?P.+&|.+\s)
```
This works fine when the tag is at the end but it gets the value for 'tag' with a trailing '&' like 'value&' when it's in the middle.
I want to get the value but not capturing the ampersand. I tried to extract the termination characters out of the named group like this:
```
.website.com.+tag=(?P.+)&|\s
```
but this regex doesn't work. It always gets until end of line. I want:
1. Check if there is a '&' character . If it is, capturing the parameter value without '&'
2. If 1 is not true and there is **not** a '&' character, then capture the value until end of line (I think this until a \s, because I'm processing text and the url comes inside it).
You can test the regex with some test text here:
<https://regex101.com/r/mWetmI/1><issue_comment>username_1: Try with lazy repetition:
```
.website.com.+tag=(?P.+?)(:?\s|&)
```
<https://regex101.com/r/mWetmI/2>
Upvotes: 0 <issue_comment>username_2: You can accomplish that with the following regex:
```
.website.com.+tag=(?P[^&\s]+)
```
This will capture the values for the tag up to but not including the next `&` or whitespace
Upvotes: 2 [selected_answer] |
2018/03/19 | 394 | 1,509 | <issue_start>username_0: I have two textEdits and a bunch of buttons that serve as an input to these two textEdits (similar to a calculator). How do I prevent the softkeyboard from appearing when the use presses on any of the textEdits and allow my buttons to input the values as they are pressed.
To summarize:
I want to prevent system soft keyboard from appearing when textEdit is active.
I want my buttons to be the input source to my two textEdits.
Finally, how do I know in my buttons listener which TextEdit is active so that I can append the number pressed.
The following picture shows an example:
[](https://i.stack.imgur.com/0Fmqg.png)<issue_comment>username_1: 1) you can try it using editexts default methods like :
```
android:editable="false"
android:focusable="false"
android:clickable="false"
```
2) on your other button click you can set text to edittext like :
```
editText.setText(btnValue);
```
Upvotes: 1 <issue_comment>username_2: I found the solution:
first you need to disable the input method for your textEdit as follow:
```
yourTextEdit.setInputType(InputType.TYPE_NULL);
```
the above will prevent the soft keyboard from being an input to your textEdit
They in your button listener `.setOnClickListener` you can identify which textEdit is active by checking `yourTextEdit.isFocused()` and do whatever you want to do in your listener.
Hope this helps someone out there
Upvotes: 1 [selected_answer] |
2018/03/19 | 625 | 2,231 | <issue_start>username_0: I'm trying to launch the following code. The Application window opens but as soon as I click on the button, the window crashes.
```
import sys
from qtpy import QtWidgets
from src.ui.mainwindow import Ui_MainWindow
from src.Run_OMD_Process import run_omd
app = QtWidgets.QApplication(sys.argv)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setWindowTitle("OMD Tool")
print("MainWindow")
self.ui.pushButton.clicked.connect(self.onPushOmdButton)
# self.ui.pushButton_2.clicked.connect(self.exitUi)
def onPushOmdButton(self):
self.ui.pushButton.clicked.connect(run_omd())
window = MainWindow()
window.show()
sys.exit(app.exec_())
```<issue_comment>username_1: It is crashing because you left the parentheses on your `run_omd` call when you connected it to your button in `onPushOmdButton`.
Try:
```
self.ui.pushButton.clicked.connect(run_omd)
```
This method is also only reconnecting the button to a different function. So basically, you will have to click the button twice to get the result I believe you are after. I'm not sure if this is what you intended.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I agree with MalloyDekacroix on this one:
```
import sys
from pyqt import QtWidgets
from src.ui.mainwindow import Ui_MainWindow
from src.Run_OMD_Process import run_omd
app = QtWidgets.QApplication(sys.argv)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setWindowTitle("OMD Tool")
print("Main`enter code here`Window")
self.ui.pushButton.clicked.connect(self.onPushOmdButton)
# self.ui.pushButton_2.clicked.connect(self.exitUi)
def onPushOmdButton(self):
// i.e. this could so something else.
// for instance, open a new window.
// perform a calculation.
// As your code I also feel requires the user to click again.
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
Upvotes: 0 |
2018/03/19 | 1,396 | 3,639 | <issue_start>username_0: I had a problem, maybe easy but I couldn't handle this. How to remove all k8s containers and images from local machine?
```
gcr.io/google_containers/k8s-dns-sidecar-amd64 Up 36 minutes k8s_sidecar_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/k8s-dns-dnsmasq-nanny-amd64 Up 36 minutes k8s_dnsmasq_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/k8s-dns-kube-dns-amd64 Up 36 minutes k8s_kubedns_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/kubernetes-dashboard-amd64 Up 36 minutes k8s_kubernetes-dashboard_kubernetes-dashboard-xpg2v_kube-system_fd403866-c63c-11e7-b3c8-28d24484a79b_222
gcr.io/google-containers/kube-addon-manager Up 36 minutes k8s_kube-addon-manager_kube-addon-manager-lenovo-e540_kube-system_9831e93c3188555873fdb49f43198eef_186
gcr.io/google_containers/pause-amd64:3.0 Up 36 minutes k8s_POD_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/pause-amd64:3.0 Up 36 minutes k8s_POD_kube-addon-manager-lenovo-e540_kube-system_9831e93c3188555873fdb49f43198eef_186
gcr.io/google_containers/pause-amd64:3.0 Up 36 minutes k8s_POD_kubernetes-dashboard-xpg2v_kube-system_fd403866-c63c-11e7-b3c8-28d24484a79b_186
```
It's unpossible to stop them (they restart always), also to remove them by `rm` and `rmi`. Also tryint to kill `kubelet`.
```
$ ps ax | grep kubelet
17234 pts/18 S+ 0:00 grep --color=auto kubelet
$ kill -KILL 17234
bash: kill: (17234) - No such process
systemctl stop kubelet
Failed to stop kubelet.service: Unit kubelet.service not loaded.
```
Also trying to force remove this containers:
`$ docker rm -f $(docker ps -a -q --filter "name=k8s")`
but they will recreate after that...
Checking available pods results like this...
```
$ kubectl get po -n=kube-system
Unable to connect to the server: dial tcp 192.168.99.100:8443: getsockopt: network is unreachable
```
I was looking for it in documentations, stack etc. but with no effect.
Here's bug on github, but no one could help: <https://github.com/kubernetes/kubernetes/issues/61173>
Thanks in advance!
Best regards,
Marcin<issue_comment>username_1: I was working with this guide a half year ago: <https://kubernetes.io/docs/getting-started-guides/minikube/> so I guess it using VirtualBox. Maybe you know how I can check this?
@Remario thanks for the tip, now when I execute
`$ systemctl disable localkube.service` and
`$ systemctl stop localkube.service`
**I'm able to delete k8s containers and they didn't restart immediately, so we resolve problem partially. Great!**
I got this error when trying to execute `docker rmi`:
`Error response from daemon: No such image: gcr.io/...`
But images are still in `docker images` list. **So I run
`$ docker system prune -a` and all `gcr.io` images was deleted.**
Thanks for your time.
Best regards,
username_1
Upvotes: 2 [selected_answer]<issue_comment>username_2: Something useful
```
kubectl get deployment nginx-app
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-app 1/1 1 1 2m
kubectl get po -l run=nginx-app
NAME READY STATUS RESTARTS AGE
nginx-app-2883164633-aklf7 1/1 Running 0 2m
kubectl delete deployment nginx-app
deployment "nginx-app" deleted
kubectl get po -l run=nginx-app
# Return nothing
```
Upvotes: 0 |
2018/03/19 | 271 | 1,093 | <issue_start>username_0: I'm new to react and gulp. And I have a question that night look silly to experts but I've been struggling with it for quite sometime
I'm building a react project with a few react files and I try to bundle then with browserify and gulp but it seems browserify only receives one entry. Considering that I have imported all the necessary files to App.js, will those files be bundled as well?<issue_comment>username_1: In simple words, entry point is the point where your compiler starts compiling. From thereon, it checks all of your file imports and keeps adding it to the bundle file.
So yes, all the imported and used modules will be compiled in your application.
Also, if you're new, I suggest you try the `create-react-app`. Once you're experienced with how things work, you can delve deeper into `create-react-app` by ejecting it (which is not recommended ;))
Upvotes: 1 <issue_comment>username_2: If you decide not to use `create-react-app`, you can look into [webpack](https://webpack.js.org/) or [parcel](https://parceljs.org/) to replace `gulp`.
Upvotes: 0 |
2018/03/19 | 457 | 1,385 | <issue_start>username_0: * [WWW::Mechanize::Chrome](http://p3rl.org/WWW::Mechanize::Chrome) 0.10
* Iridium 2017.11 in a headed desktop session
I want to set the value of a certain **formless** input field.
```
my $field = $w->selector('tr.edit td[data-attribute="name"] input', single => 1);
```
finds it.
```
$field->attributes->{value} = 'test';
```
has no apparent effect.
Both
```
$w->field($field => 'test');
```
and
```
$w->field('tr.edit td[data-attribute="name"] input' => 'test');
```
error out with `No elements found for form number 1`.<issue_comment>username_1: When I ran into this problem, I would just use the `eval` method and let Javascript (or jQuery if it's loaded in the page) take care of selecting and setting values. For me it was mostly selecting drop-downs, where the Angular application on the page required a *change* or *click* event.
```
$mech->eval( q{$(tr.edit td[data-attribute="name"] input).val('test')} );
```
If there is no jQuery I am sure your Google fu will help you out.
Upvotes: 3 <issue_comment>username_2: You maybe able to use something like below
```
$w->driver->send_message('DOM.setAttributeValue', nodeId => 0+$field->nodeId, name => 'value', value => "test" )->get
```
Reference from the actual source code
<https://metacpan.org/source/CORION/WWW-Mechanize-Chrome-0.10/lib/WWW/Mechanize/Chrome.pm#L3137>
Upvotes: 2 |
2018/03/19 | 866 | 2,933 | <issue_start>username_0: So I'm trying to print out the values inside a 2D array, through a
function called printArray, but everytime when i try
it saysidentifier "print" is undefined.. I'm sure im doing something
super super wrong, so any pointers would be greately appreciated :).
Also i'm trying to do it as simple as possible, no pointers or adresses ^^
```
#include "stdafx.h"
#include "iostream"
using namespace std;
int A[3][5];
class Matrix {
public:
Matrix() {
A[0][1] = 5;
A[1][2] = 3;
A[2][1] = 2;
A[3][4] = 10;
}
void printArray(int height, int width);
};
int main()
{
printArray(A[3][5]);
return 0;
}
void Matrix::printArray(int width, int height) {
for (int i = 0; i < width ; i++) {
for (int y = 0; y < height; y++) {
cout << A[i][y] << " ";
}
cout << endl;
}
}
```<issue_comment>username_1: Yes, as it says, in your `main()` you're trying to call function `print` that is mentioned nowhere else. Additionally, even if it was, it probably would trigger UB, as you're trying to call it with an unexisting element of the array, to the north-west of it northwestern corner (if you only meant the array itself, you don't need to specify its dimensions, for in the expression context square brackets `[]` signify element index, not the array dimensions).
And your `printArray` accepts two arguments but you're calling it with a single array (non-)element as an argument. In your case, it should be `printArray(3, 5);`.
Upvotes: 0 <issue_comment>username_2: `printArray` is a member function of a class. So you need an instance of the class to call it on.
```
Matrix m;
m.printArray(3, 5);
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Inside your `main()`, try:
```
int main()
{
Matrix a;
a.printArray(3, 5);
return 0;
}
```
I believe a better design is possible for this code. Also, please check `A[3][4]`. Your row index shouldn't be more than 2, in this case.
Upvotes: 0 <issue_comment>username_4: There are a few problems:
1. You are calling a method which it does not exist: `print` - that's why the error.
2. Still, if your intention was to call `printArray` you have to be careful because it has 2 parameters, not one(also of different types). Your send a `bidimensional array of type int`, and `printArray` should receive 2 parameters of type `int`.
3. Calling a class's method it should be done by creating an object of that class first and only then, through that object call the method.
4. If you want to call it without creating an object, you should use the keyword `static` - read [here](https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm) about it.
I could give you the direct answer, but I think it will help you more if you read from [here](https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm). Knowing how to declare a class it's not everything. You also need to learn how to use it.
Upvotes: 0 |
2018/03/19 | 1,933 | 5,789 | <issue_start>username_0: I have dataframe `users` with different columns. My goal is to add the column [`uses_name`] which should be `True` when a password is the same as each users first or last name.
For example, [`user_name`] in twelve row contain `milford.hubbard`. Then in [`uses_name`] will be `True`, because the [`password`] and [`last_name`] are the same.
To do this, I create two columns [`first_name`] and [`last_name`] with regular expressions. When create [`uses_name`] I have trouble with `|` operator. I am read more in pandas doc about Boolean indexing but not find an answer.
My code:
```
import pandas as pd
users = pd.read_csv('datasets/users.csv')
# Extracting first and last names into their own columns
users['first_name'] = users['user_name'].str.extract(r'(^\w+)', expand=False)
users['last_name'] = users['user_name'].str.extract(r'(\w+$)', expand=False)
# Flagging the users with passwords that matches their names
users['uses_name'] = users['password'].isin(users['first_name'] | users['last_name'])
# Counting and printing the number of users using names as passwords
print(users['uses_name'].count())
# Taking a look at the 12 first rows
print(users.head(12))
```
When I try to compile this, I give an error:
```
TypeError: unsupported operand type(s) for |: 'str' and 'bool'
```
First 12 rows in `users` dataframe with created `first_name` and `last_name` columns:
```
id user_name password first_name last_name
0 1 vance.jennings joobheco vance jennings
1 2 consuelo.eaton 0869347314 consuelo eaton
2 3 mitchel.perkins fabypotter mitchel perkins
3 4 odessa.vaughan aharney88 odessa vaughan
2 3 mitchel.perkins fabypotter mitchel perkins
3 4 odessa.vaughan aharney88 odessa vaughan
4 5 araceli.wilder acecdn3000 araceli wilder
5 6 shawn.harrington 5278049 shawn harrington
6 7 evelyn.gay master evelyn gay
7 8 noreen.hale murphy noreen hale
8 9 gladys.ward lwsves2 gladys ward
9 10 brant.zimmerman 1190KAREN5572497 brant zimmerman
10 11 leanna.abbott aivlys24 leanna abbott
11 12 milford.hubbard hubbard milford hubbard
```<issue_comment>username_1: Use [`numpy.union1d`](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.union1d.html):
```
val = np.union1d(users['first_name'], users['last_name'])
users['uses_name'] = users['password'].isin(val)
print (users)
id user_name password first_name last_name uses_name
0 1 vance.jennings joobheco vance jennings False
1 2 consuelo.eaton 0869347314 consuelo eaton False
2 3 mitchel.perkins fabypotter mitchel perkins False
3 4 odessa.vaughan aharney88 odessa vaughan False
2 3 mitchel.perkins fabypotter mitchel perkins False
3 4 odessa.vaughan aharney88 odessa vaughan False
4 5 araceli.wilder acecdn3000 araceli wilder False
5 6 shawn.harrington 5278049 shawn harrington False
6 7 evelyn.gay master evelyn gay False
7 8 noreen.hale murphy noreen hale False
8 9 gladys.ward lwsves2 gladys ward False
9 10 brant.zimmerman 1190KAREN5572497 brant zimmerman False
10 11 leanna.abbott aivlys24 leanna abbott False
11 12 milford.hubbard hubbard milford hubbard True
```
Upvotes: 2 <issue_comment>username_2: I think the best would be to perform a `set` union and pass that to `isin`:
```
users['uses_name'] = users['password'].isin(
set(users['first_name']).union(users['last_name'])
)
```
```
users
id user_name password first_name last_name uses_name
0 1 vance.jennings joobheco vance jennings False
1 2 consuelo.eaton 0869347314 consuelo eaton False
2 3 mitchel.perkins fabypotter mitchel perkins False
3 4 odessa.vaughan aharney88 odessa vaughan False
2 3 mitchel.perkins fabypotter mitchel perkins False
3 4 odessa.vaughan aharney88 odessa vaughan False
4 5 araceli.wilder acecdn3000 araceli wilder False
5 6 shawn.harrington 5278049 shawn harrington False
6 7 evelyn.gay master evelyn gay False
7 8 noreen.hale murphy noreen hale False
8 9 gladys.ward lwsves2 gladys ward False
9 10 brant.zimmerman 1190KAREN5572497 brant zimmerman False
10 11 leanna.abbott aivlys24 leanna abbott False
11 12 milford.hubbard hubbard milford hubbard True
```
Note that `|` is the logical OR, it has no meaning for string columns in pandas.
Upvotes: 1 <issue_comment>username_3: You can concat , since both of then are Series
```
users['password'].isin(pd.concat([users['first_name'],users['last_name']]))
```
Since you change the question , Update one
```
df[['first_name','last_name']].eq(df.password,axis=0).any(1)
```
Upvotes: 2 <issue_comment>username_4: This works:
```
users['uses_name']= (users['password']==users['first_name'] )| (users['password']==users['last_name'])
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 1,661 | 5,070 | <issue_start>username_0: Given two faces f and f' with a common edge e, i'm looking for a way to rotate f around e.
See: [illustration of f/f' and e](https://i.stack.imgur.com/KWW99.png)
My goal is to unfold f and f' so they can be mapped on the same plan. More specifically, I want the coordinate of the vertex r of f that is not part of e after such unfolding (r').
See: [after unfolding with r/r'](https://i.stack.imgur.com/uoVXD.png)
Currently i've tried to apply the method described here: <https://sites.google.com/site/glennmurray/Home/rotation-matrices-and-formulas/rotation-about-an-arbitrary-axis-in-3-dimensions>
In the case from the screenshot, i've simplified it as the rotation axis is already on the Z-axis. So my code looks like this:
```
// Object contains only two faces
var geometry = object.children[0].geometry;
var f = geometry.faces[0];
var fprime = geometry.faces[1];
// Find two vertices in common
var edge = [f.a, f.b];
if (f.a != fprime.a && f.a != fprime.b && f.a != fprime.c) {
edge = [f.b, f.c];
} else if (f.b != fprime.a && f.b != fprime.b && f.b != fprime.c) {
edge = [f.a, f.c];
}
var v1 = geometry.vertices[edge[0]];
var v2 = geometry.vertices[edge[1]];
polyhedron.translateOnAxis(v1, -1);
polyhedron.rotateOnAxis(v2, THREE.Math.degToRad(90));
polyhedron.translateOnAxis(v1, 1);
```
But this only send my object into space:
[Before](https://i.stack.imgur.com/dLTI2.png)
[After](https://i.stack.imgur.com/4lADy.png)
Without the rotation, the object does not move (as expected). Any hints on how to fix the rotation ?<issue_comment>username_1: If I got you correctly, here's a rough concept of you can rotate a vertex around an axis:
```js
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(1, 5, 10);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.GridHelper(10, 10));
var planeGeom = new THREE.PlaneGeometry(5, 5);
planeGeom.rotateZ(Math.PI * 0.25);
planeGeom.vertices[0].basePosition = new THREE.Vector3().copy(planeGeom.vertices[0]);
planeGeom.vertices[2].set(0, 0, 0); // let's make a triangle from the plane
var plane = new THREE.Mesh(planeGeom, new THREE.MeshBasicMaterial({
color: "aqua",
wireframe: true
}));
scene.add(plane);
var axis = new THREE.Vector3(0, 1, 0); // in three.js, up is positive Y
render();
function render() {
requestAnimationFrame(render);
planeGeom.vertices[0].copy(planeGeom.vertices[0].basePosition).applyAxisAngle(axis, (Math.sin(Date.now() * 0.001) * 0.5 + 0.5) * Math.PI * 0.5); // we'll use .applyAxisAngle() method
planeGeom.verticesNeedUpdate = true;
renderer.render(scene, camera);
}
```
```css
body {
overflow: hidden;
margin: 0;
}
```
Upvotes: 1 <issue_comment>username_2: I was able to unfold a triangle to another triangle using the following snippet: [Rotate object on specific axis anywhere in Three.js - including outside of mesh](https://stackoverflow.com/questions/31953608/rotate-object-on-specific-axis-anywhere-in-three-js-including-outside-of-mesh)
```
// Object contains only two faces
var geometry = object.children[0].geometry;
geometry.computeFaceNormals();
geometry.computeVertexNormals();
var f = geometry.faces[0];
var fprime = geometry.faces[1];
// Find two vertices in common
var edge = [f.a, f.b];
if (f.a != fprime.a && f.a != fprime.b && f.a != fprime.c) {
edge = [f.b, f.c];
} else if (f.b != fprime.a && f.b != fprime.b && f.b != fprime.c) {
edge = [f.a, f.c];
}
var point = geometry.vertices[edge[0]].clone();
var axis = geometry.vertices[edge[1]].clone();
axis = axis.sub(point);
axis.normalize();
// Adds a triangle to show rotation
var newGeometry = new THREE.Geometry();
newGeometry.vertices.push(
geometry.vertices[f.a].clone(),
geometry.vertices[f.b].clone(),
geometry.vertices[f.c].clone()
);
newGeometry.faces.push(new THREE.Face3(0, 1, 2));
var material = new THREE.MeshBasicMaterial({color: 0xffff00, side: THREE.DoubleSide});
var mesh = new THREE.Mesh(newGeometry, material);
scene.add(mesh);
var dot_product = f.normal.dot(fprime.normal); // Give cosinus of the angle
var angle = Math.acos(dot_product);
mesh.rotateAroundWorldAxis(point, axis, angle);
THREE.Object3D.prototype.rotateAroundWorldAxis = function() {
// rotate object around axis in world space (the axis passes through point)
// axis is assumed to be normalized
// assumes object does not have a rotated parent
var q = new THREE.Quaternion();
return function rotateAroundWorldAxis(point, axis, angle) {
q.setFromAxisAngle(axis, angle);
this.applyQuaternion(q);
this.position.sub(point);
this.position.applyQuaternion(q);
this.position.add(point);
return this;
}
}();
```
[Result](https://i.stack.imgur.com/kI6Re.png)
Upvotes: 1 [selected_answer] |
2018/03/19 | 635 | 2,482 | <issue_start>username_0: I am using genymotion to run my React Native dev environment. When a specific component loads, I get the console.error message: `there was a problem sending log messages to your development environment` with a weird stack trace that uses in place of several named functions.
I narrowed the problem down to just one component in my code:
```
class Questions extends React.Component {
constructor(props){
super(props);
this.state = {
style: 'all',
selected: ''}
}
render = () => {
return (
{(this.props.questions && this.state.style == 'all')&&
this.props.questions.map(post => {
return (
this.loadQuestion(post)} key={post.ID + new Date(post.post\_date)} style={styles.questionCard} >
{post.post\_title}
- {post.display\_name} {utils.timeSince(new Date(post.post\_date))}
)
})
}
)
}
}
```
Whenever this component loads, I got the console.error mentioned above. I know this isn't much to go on and I don't really even expect an answer, but I'm at a loss.
If you google that exact error message you will find one issue on Github with no resolution, mentioning that it may be an error in the expo sdk (which makes sense) and linking another issue that 404s.<issue_comment>username_1: Okay I think I solved it, the problem was actually in my utils function `timeSince`. I had a stray console.log() statement and when I removed it the error went away. Apparently with this configuration you cannot call console.log() from internal assets.
EDIT: Okay so after some further debugging, this error is thrown when you try to console.log() an object, it doesn't matter where the log originates.
Upvotes: 5 [selected_answer]<issue_comment>username_2: >
> Okay I think I solved it, the problem was actually in my utils function `timeSince`. I had a stray console.log() statement and when I removed it the error went away. Apparently with this configuration you cannot call console.log() from internal assets.
>
>
> EDIT: Okay so after some further debugging, this error is thrown when you try to console.log() an object, it doesn't matter where the log originates.
>
>
>
I hope this sheds some more light to the origin of this "error":
The object you are referring to is actually the response from the call, and it doesn't like it bc of the size. It's not any object, just the `response` object from a call. If you try destructuring the part you want, then it goes away
Upvotes: 0 |
2018/03/19 | 576 | 2,175 | <issue_start>username_0: i'm writing tests in selenium and want to change proxy to auto-detect in firefox, default is proxy from system settings. How to do it?
I have code below:
```
public class SodirRejestracja {
String baseUrl = "http://google.pl";
String driverPath= "C:\\geckodriver.exe";
WebDriver driver;
@BeforeTest
public void beforeTest() {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.type", 2);
System.setProperty("webdriver.gecko.driver", driverPath);
driver=new FirefoxDriver(profile);
}
@Test
public void test(){
driver.get("http://google.com");
}
}
```
Code above is from [How do I set a proxy for firefox using Selenium webdriver with Java?](https://stackoverflow.com/questions/45810476/how-do-i-set-a-proxy-for-firefox-using-selenium-webdriver-with-java)
but in line driver=new FirefoxDriver(profile) i get: "The constructor FirefoxDriver(FirefoxProfile) is undefined"<issue_comment>username_1: Okay I think I solved it, the problem was actually in my utils function `timeSince`. I had a stray console.log() statement and when I removed it the error went away. Apparently with this configuration you cannot call console.log() from internal assets.
EDIT: Okay so after some further debugging, this error is thrown when you try to console.log() an object, it doesn't matter where the log originates.
Upvotes: 5 [selected_answer]<issue_comment>username_2: >
> Okay I think I solved it, the problem was actually in my utils function `timeSince`. I had a stray console.log() statement and when I removed it the error went away. Apparently with this configuration you cannot call console.log() from internal assets.
>
>
> EDIT: Okay so after some further debugging, this error is thrown when you try to console.log() an object, it doesn't matter where the log originates.
>
>
>
I hope this sheds some more light to the origin of this "error":
The object you are referring to is actually the response from the call, and it doesn't like it bc of the size. It's not any object, just the `response` object from a call. If you try destructuring the part you want, then it goes away
Upvotes: 0 |
2018/03/19 | 526 | 2,236 | <issue_start>username_0: I am trying to make I/O (db) calls on input event of a Node-Red Node. So, If I have many input events, all the calls to db are added to callback queue and are processed only after nothing is left on call stack.
This is adding up to memory and I am getting heap out of memory after some 50K input events and because I need response from I/O to be sent to next node, the process is stopped there.
Is there any way I can prioritize processes from callback queue so that it is not piled up ?
Code :
```
node.on('input', function (msg) {
console.log("before create");
app.models.ModelName.create(msg.payload, function (err, response) {
if(err){
return node.error(err);
}
console.log("after create")
///Process the response before sending
msg.payload.msg_num = response.msg_num;
node.send(msg);
})
});
```
Output:
before create
before create
before create
before create
before create
before create
.
.
.
(N number of times)
after create
after create
after create
after create
after create
after create
after create
.
.
.
(N times)
Is there any way I can get the create() actually execute before all the input events are executed ?<issue_comment>username_1: TLDR; No
There is no callback queue, it's all one event queue and tasks are processed in order. The problem here is that the database is taking longer to reply than it takes to inject all the input data so all the inputs arrive and blow the memory before the database can process enough to free up enough memory.
The only way you can fix this is to introduce some back pressure into what ever is injecting the messages. e.g. if it's a HTTP-in/HTTP-out pair only allow a certain number of inflight sessions.
Upvotes: 1 <issue_comment>username_2: I think that in this case, you can use.
<https://caolan.github.io/async/docs.html#each>
using the callback function to finish the process.
Upvotes: 0 |
2018/03/19 | 517 | 1,887 | <issue_start>username_0: I am writing a question with LINQ to join li. How do I get the result table with 3 table combinations? I have to combine the table in one line.
Any ideas?
```
Peole
---------------
Id | 1 Id |2
Name | David Name |Ameyy
Surname| David1 Surname |Ameyy2
Appointment
---------------
Id |19
PeopleId |1
Subject |description
Participant
---------------
Id |1 Id |2
AppointmentId |19 AppointmentId |19
PeopleId |1 PeopleId |2
Result
----------------------------------
Id | 1
Subject | Subject
Participant| David David1, Ameyy Ameyy2
```
Linq query;
```
IQueryable query = db.Randevu.Join(db.Kisi,
appointment => appointment .TALEPEDENKISI,
people=> people.ID,
(appointment , people)
=> new AppointmentPoolModel
{
Id = appointment.ID,
Subject = appointment.Subject,
Note = appointment .NOTLAR,
NameSurname = people.Name+ " " + people.Surname,
RequestedId = people.ID,
//Participan = string.Join(",", )
});
var result = query.OrderBy(appointment => randevu.AppointmentStartDate).ToList();
```<issue_comment>username_1: TLDR; No
There is no callback queue, it's all one event queue and tasks are processed in order. The problem here is that the database is taking longer to reply than it takes to inject all the input data so all the inputs arrive and blow the memory before the database can process enough to free up enough memory.
The only way you can fix this is to introduce some back pressure into what ever is injecting the messages. e.g. if it's a HTTP-in/HTTP-out pair only allow a certain number of inflight sessions.
Upvotes: 1 <issue_comment>username_2: I think that in this case, you can use.
<https://caolan.github.io/async/docs.html#each>
using the callback function to finish the process.
Upvotes: 0 |
2018/03/19 | 373 | 1,381 | <issue_start>username_0: I am trying to attach a `*.mdf` file to a SQL Server Express version. But I still have a problem with attach and then I removed a database and create a new but same problem when I use `Update-Database` in Package Manager Console.
My default connection string is:
```
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDBFilename=App_Data\\TVK3.mdf;Database=TVK3;Trusted_Connection=true;MultipleActiveResultSets=true;"
```
I get this error:
>
> Cannot attach the file 'App\_Data\TVK3.mdf' as database 'TVK3'.
>
>
>
I searching on google and trying some advice but nothing helped to me. Thank you for any advice.<issue_comment>username_1: TLDR; No
There is no callback queue, it's all one event queue and tasks are processed in order. The problem here is that the database is taking longer to reply than it takes to inject all the input data so all the inputs arrive and blow the memory before the database can process enough to free up enough memory.
The only way you can fix this is to introduce some back pressure into what ever is injecting the messages. e.g. if it's a HTTP-in/HTTP-out pair only allow a certain number of inflight sessions.
Upvotes: 1 <issue_comment>username_2: I think that in this case, you can use.
<https://caolan.github.io/async/docs.html#each>
using the callback function to finish the process.
Upvotes: 0 |
2018/03/19 | 255 | 992 | <issue_start>username_0: Are Instrumentation tests for Android Espresso available on CircleCI 2.0?
If yes, can anybody, please, help to configure config.yml file for me?
I’ve made thousand attempts and no luck. I can run unit tests, but not Instrumentation.
Thanks<issue_comment>username_1: TLDR; No
There is no callback queue, it's all one event queue and tasks are processed in order. The problem here is that the database is taking longer to reply than it takes to inject all the input data so all the inputs arrive and blow the memory before the database can process enough to free up enough memory.
The only way you can fix this is to introduce some back pressure into what ever is injecting the messages. e.g. if it's a HTTP-in/HTTP-out pair only allow a certain number of inflight sessions.
Upvotes: 1 <issue_comment>username_2: I think that in this case, you can use.
<https://caolan.github.io/async/docs.html#each>
using the callback function to finish the process.
Upvotes: 0 |
2018/03/19 | 992 | 3,370 | <issue_start>username_0: This has got to be a common problem with a simple answer but I can't seem to turn up a solution. Using an Excel macro, I examine a website home page for links and put those links into a range in Excel.
Now I want to make those values into hyperlinks.
```
Set allLinks = objIE.document.GetElementsByTagName("A")
For Each link In allLinks
If InStr(link.href, inspectOneCat) Then
inspectLink(linkCount) = link
linkCount = linkCount + 1
End If
Next
```
In the next step, the one-dimensional array is converted to a two-dimensional array with a descriptive column in inspectLink(i,0) and the link values in inspectLink(i,1). Then the array loaded into a range, like this:
```
Sheets("Awesomepova").Range("a2:b300").Value = inspectLink
```
This works. But these links appear as values, not as hyperlinks. I want to do something like this:
```
'Sheets("Awesomepova").Hyperlinks.Add Sheets("Awesomepova").Range("a2:b300"), Sheets("Awesomepova").Range("a2:b300").Value
```
This doesn't work. But I went into the worksheet manually and changed the first cell so it was hyperlinked and I noticed that even when I reload the entire range programmatically, the hyperlink remains, so I'm thinking this is a characteristic of the cell format, not the actual data in the cell.
Maybe the problem can be fixed by applying the same formatting to all the cells in the column where the rule is to use the cell value as the hyperlink value.<issue_comment>username_1: Considering that you already have crawled the websites in the array `inspectLink`, something like this works:
```
Public Sub TestMe()
Dim myArr As Variant
Dim myUnit As Variant
Dim myCell As Range
myArr = Array("www.sugarpova.com", "www.stackoverflow.com")
Set myCell = Worksheets(1).Cells(1, 1)
For Each myUnit In myArr
myCell.Hyperlinks.Add myCell, myUnit
Set myCell = myCell.Offset(1, 0)
Next myUnit
End Sub
```
It prints working hyperlinks on the first worksheet:
[](https://i.stack.imgur.com/tXau8.png)
Upvotes: 2 <issue_comment>username_2: This is the equivalent using a `For i...` loop
```
Public Sub TestMe()
Dim myArr As Variant
Dim i As Long
myArr = Array("www.bbc.com", "www.stackoverflow.com")
For i = 0 To UBound(myArr)
Worksheets(1).Cells(i + 1, 1).Hyperlinks.Add Worksheets(1).Cells(i + 1, 1), myArr(i)
Next i
End Sub
```
Upvotes: 2 <issue_comment>username_3: Try looping through a2:b300 one hyperlink at a time using Hyperlinks.add instead of trying to force Hyperlinks.Add to apply to an entire range in one command:
```
For Row = 2 To 300
URL = Sheets("Awesomepova").Range("B" & Row).Value
Text = Sheets("Awesomepova").Range("A" & Row).Value
If URL <> "" Then
Set result = Sheets("Awesomepova").Hyperlinks.Add(Range("C" & Row), URL, "", TextToDisplay:=Text)
End If
Next
```
Upvotes: 0 <issue_comment>username_4: Several ways you can do the same. How about this?
```
Sub Demo()
Dim storage As Variant, cel As Variant, r&
storage = [{"https://www.google.com/", "https://www.yahoo.com/","https://www.wikipedia.org/"}]
For Each cel In storage
r = r + 1: Cells(r, 1).Hyperlinks.Add Cells(r, 1), cel
Next cel
End Sub
```
Upvotes: 0 |
2018/03/19 | 557 | 2,108 | <issue_start>username_0: I have 2 microservices built using Netflix eureka. They communicate using feign client. In my local environment feign client works without any issue. But in the Predix (a cloud foundry) environment they fail to communicate. Feign client always gives connection time out error. As found that feign client try to connect using instance ip address (I think feign client uses the internal ip address). Is there a way to fix this issue, may be enabling container communication or using public uri
EDIT:
I managed to get the public url by changing hostname like below.
```
eureka:
instance:
hostname: ${vcap.application.uris[0]}
```
but in the eureka server it register as ${vcap.application.uris[0]}:[random port] (like xxxxxx.run.aws-usw02-pr.ice.predix.io:61142/yyy)
is there a way to remove that random port.<issue_comment>username_1: There's currently no way to assign a specific port to an application running in Predix Cloud Foundry. CF assigns a random port, as you've discovered, but this is only used inside the CF environment. Any other microservice/client/application should only use port 443 for HTTPS. So, maybe you can hardcode your Eureka client to use 443, if possible.
Upvotes: 1 [selected_answer]<issue_comment>username_2: We have managed to fix feign client issue using following configuration,
```
eureka:
client:
serviceUrl:
defaultZone: https://someeurekaserver/eureka/
registerWithEureka: true
fetchRegistry: false
healthcheck:
enabled: true
instance:
hostname: ${vcap.application.application_uris[0]}
instanceId: ${spring.application.name}:${random.int}
secure-port: 443
non-secure-port: 443
secure-port-enabled: true
non-secure-port-enabled: false
preferIpAddress: false
leaseRenewalIntervalInSeconds: 10
home-page-url: https://${eureka.instance.hostname}:${eureka.instance.secure-port}
secure-virtual-host-name: https://${vcap.application.application_uris[0]}
```
importance configuration is `secure-virtual-host-name: https://${vcap.application.application_uris[0]}`
Upvotes: 1 |
2018/03/19 | 973 | 2,765 | <issue_start>username_0: So I have a dataframe (or series) where there are always 4 occurrences of each of column 'A', like this:
```
df = pd.DataFrame([['foo'],
['foo'],
['foo'],
['foo'],
['bar'],
['bar'],
['bar'],
['bar']],
columns=['A'])
A
0 foo
1 foo
2 foo
3 foo
4 bar
5 bar
6 bar
7 bar
```
I also have another dataframe, with values like the ones found in column A, but they don't always have 4 values. They also have more columns, like this:
```
df_key = pd.DataFrame([['foo', 1, 2],
['foo', 3, 4],
['bar', 5, 9],
['bar', 2, 4],
['bar', 1, 9]],
columns=['A', 'B', 'C'])
A B C
0 foo 1 2
1 foo 3 4
2 bar 5 9
3 bar 2 4
4 bar 1 9
```
I wanted to merge them such they end up like this using something like:
```
df.merge(df_key, how='left', on='A', copy=False)
A B C
0 foo 1 2
1 foo 3 4
2 foo NaN NaN
3 foo NaN NaN
4 bar 5 9
5 bar 2 4
6 bar 1 9
7 bar NaN NaN
```
But instead I end up with something like this. Any advice?
```
A B C
0 foo 1 2
1 foo 3 4
2 foo 1 2
3 foo 3 4
4 foo 1 2
5 foo 3 4
6 foo 1 2
7 foo 3 4
8 bar 5 9
9 bar 2 4
10 bar 1 9
11 bar 5 9
12 bar 2 4
13 bar 1 9
14 bar 5 9
15 bar 2 4
16 bar 1 9
17 bar 5 9
18 bar 2 4
19 bar 1 9
```<issue_comment>username_1: You'll need to create surrogate columns with `groupby` + `cumcount` to deduplicate your rows, then include those columns when calling `merge`:
```
a = df.assign(D=df.groupby('A').cumcount())
b = df_key.assign(D=df_key.groupby('A').cumcount())
a.merge(b, on=['A', 'D'], how='left').drop('D', 1)
A B C
0 foo 1.0 2.0
1 foo 3.0 4.0
2 foo NaN NaN
3 foo NaN NaN
4 bar 5.0 9.0
5 bar 2.0 4.0
6 bar 1.0 9.0
7 bar NaN NaN
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Or you can just repeat the column A of `df_key` the remaining number of times from `df`.
```
s=df.A.value_counts()-df_key.A.value_counts()
pd.concat([df_key,pd.DataFrame({'A':s.index.repeat(s)})]).sort_values('A')
Out[469]:
A B C
2 bar 5.0 9.0
3 bar 2.0 4.0
4 bar 1.0 9.0
0 bar NaN NaN
0 foo 1.0 2.0
1 foo 3.0 4.0
1 foo NaN NaN
2 foo NaN NaN
```
Upvotes: 2 |
2018/03/19 | 375 | 1,445 | <issue_start>username_0: I am getting this error after upgrading one of my project dependencies (ngx-config). Here is the full error from the console.
`Unhandled Promise rejection: Endpoint unreachable! ; Zone: ; Task: Promise.then ; Value: Endpoint unreachable! undefined (zone.js:630)`
Note: `ng serve` works and compiles just fine, this error occurs at runtime.<issue_comment>username_1: This error is being thrown by ngx-config.
Turns out we are using `HTTP_INTERCEPTORS` which depends on `HttpClient`. The newest version of ngx-config also uses `HttpClient` (instead of the old `Http`). Upon upgrading ngx-config/core and ngx-config/http-loader to version `5.0.0` there arose a circular dependency. The call to get `config.json` was now going through the interceptor but the interceptor depended upon the config settings in `config.json`. I simply added the following to the interceptor:
```
if (req.url.endsWith(".json")) {
return next.handle(req).do((event: HttpEvent) => { return })
}
```
I wish there was a way to globally add exceptions to the interceptor (black list, white list or both) but there doesn't appear to be any plan to implement such a feature <https://github.com/angular/angular/issues/20203>.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try to include to your providers in app.module.ts this one:
```
{ provide: LocationStrategy, useClass: HashLocationStrategy }
```
That's work for me
Upvotes: 0 |
2018/03/19 | 726 | 2,503 | <issue_start>username_0: I'm using:
* Google App Engine with Google Datastore
* Zk 8.5 with the MVVM design
I'm having an issue trying to display an arrayList in a grid like this:
```
```
It will display for each row something in this format :
**com.mypackage.entity.Client@3c3f784e**
My Entity:
```
@Entity
public class Client implements Serializable{
private static final long serialVersionUID = -6603526588403725762L;
@Id
private Long id;
@Index
private String nom;
private Sexe sexe;
private Contact contact;
@Load
private Ref mesures;
public Client() {
contact = new Contact();
}
}
```
My Service:
```
public List getAll() {
return ofy().consistency(Consistency.STRONG).load().type(Client.class).order("nom").list();
}
```
My ViewModel:
```
public class RepertoireViewModel extends PageViewModel implements Serializable {
private static final long serialVersionUID = -3656947251943967000L;
private ListModelList clientListModel;
private List clients;
@Init
public void init() {
clients = ClientService.getInstance().getAll();
clientListModel = new ListModelList<>(clients);
}
}
```<issue_comment>username_1: I found that the problem is related to the rowRenderer.
In an normal environnement like WildFly(not a Clustering environnement like Google App Engine) I don't have this problem with model="@load(vm.clientListModel)"
If I add this code to the RepertoireViewModel.java
```
public RowRenderer getRenderer(){
return new RowRenderer() {
@Override
public void render(Row row, Client data, int index) throws Exception {
final Label lblNom = new Label(data.getNom());
final Label lblTelephone = new Label(data.getContact().getTelephone());
final Div div = new Div();
Button btn1 = new Button();
btn1.setIconSclass("z-icon-eye");
Button btn2 = new Button();
btn2.setIconSclass("z-icon-edit");
Button btn3 = new Button();
btn3.setIconSclass("z-icon-remove");
div.appendChild(btn1);
div.appendChild(btn2);
div.appendChild(btn3);
row.appendChild( lblNom );
row.appendChild( lblTelephone );
row.appendChild( div);
}
};
}
```
and change my view to this:
```
```
It works fine.
If someone knows how to make it work in the MVVM way it would be welcomed else I can use this solution
Upvotes: 0 <issue_comment>username_1: I found out that the problem was from the use of xmlns="native" xmlns:u="zul" xmlns:x="xhtml" in my zul. After I have removed it, it works fine.
Best regards
Upvotes: -1 |
2018/03/19 | 524 | 2,335 | <issue_start>username_0: I'm new to python, so please be gentle.
In learning python and writing my first few scripts, I quickly glossed over any tutorial sections on `virtualenv`, figuring it wouldn't provide me any benefit in my nascent stage.
I proceeded to hack away, installing packages as I went with `pip3 install package`
Now I've built something that is potentially useful to my organization, and I'd like to share it. In this case, I want to distribute it as a windows executable.
Before building this distribution, I figure it's now time to take the next leap from individual scripts to proper python projects. It seems like `virtualenv` should be part of that.
Given that I've installed a number of packages to my "base" python environment: in order to do development in a "clean" virtual environment, do I need to somehow "revert" my base python environment (i.e. uninstall all non-standard packages), or will `virtualenv` shield a project within a virtual environment from non-standard packages installed to my "base" environment?<issue_comment>username_1: You can specify separately the required libraries and check if they are installed and if not then you can install them automatically.
Have a look at:
<https://packaging.python.org/discussions/install-requires-vs-requirements/>
Upvotes: 0 <issue_comment>username_2: Go install [VirtualEnvWrapper](https://pypi.python.org/pypi/virtualenvwrapper "VirtualEnvWrapper") first. After that, create a new virtualenv, activate it, and run pip freeze. You should see nothing in there because nothing is installed. Deactivate the env to go back to your 'Base' environment and pip freeze again. You will see all the installs you have.
A best practice is to create a requirements.txt file and version control it so everyone can use the same versions of the same packages. If you don't want to do this, simply activate your new virtual env and pip install everything you want.
Upvotes: 1 <issue_comment>username_3: If you are using the `venv` module there is `--system-site-packages` flag that will grant the created virtual environment access to the system-wide site-packages directory:
```
--system-site-packages
Give the virtual environment access to the system
site-packages dir.
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 450 | 1,845 | <issue_start>username_0: I am using Redux-Form, where I have 2 fields 'client income' and 'partner income', and I need to show the sum of the values in another field, *onChange* of above 2 fields.
I tried storing the sum in a global variable but it's not working.
The behavior is like below, if I try adding 12+ 13 instead of 25, it's coming as 27. I identified the cause, it's happening as it is taking it as 1+12+1+13. I am not sure how to mitigate the issue.
I could have used *onBlur*, but *onChange* is the requirement.
Any help would be appreciated.<issue_comment>username_1: You can specify separately the required libraries and check if they are installed and if not then you can install them automatically.
Have a look at:
<https://packaging.python.org/discussions/install-requires-vs-requirements/>
Upvotes: 0 <issue_comment>username_2: Go install [VirtualEnvWrapper](https://pypi.python.org/pypi/virtualenvwrapper "VirtualEnvWrapper") first. After that, create a new virtualenv, activate it, and run pip freeze. You should see nothing in there because nothing is installed. Deactivate the env to go back to your 'Base' environment and pip freeze again. You will see all the installs you have.
A best practice is to create a requirements.txt file and version control it so everyone can use the same versions of the same packages. If you don't want to do this, simply activate your new virtual env and pip install everything you want.
Upvotes: 1 <issue_comment>username_3: If you are using the `venv` module there is `--system-site-packages` flag that will grant the created virtual environment access to the system-wide site-packages directory:
```
--system-site-packages
Give the virtual environment access to the system
site-packages dir.
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 737 | 2,499 | <issue_start>username_0: I have a jQuery get request like this
```
get('myfile.php', function(data) {
alert(data);
}
```
It is working correctly but sometimes it can take a long time to process myfile.php
How can I add a spinner gif to this so that it gives the user some indication that it is loading?
Is there some sort of success function I can use to hide and show one?<issue_comment>username_1: Yeah.. Just call your showSpinner statment like
e.g `$('.spinner').show()` right before your async request.
And then hide it in the success callback where you have your alert like this.
```
get('myfile.php', function(data) {
$('.spinner').hide()
alert(data);
}
```
Upvotes: 1 <issue_comment>username_2: Instead of displaying a gif, you can use an HTML/CSS spinner.
Here is an explanation to make it : <https://www.w3schools.com/howto/howto_css_loader.asp>
You have to make that spinner hidden by default and display it before your async call (jquery `.show()` function for example).
In the success function (where you have your `alert(data);`, you hide it (jquery function `.hide()` for example)
Upvotes: 1 <issue_comment>username_3: Sure, before calling the `$.get` show the loader.
After getting the results, hide it again.
```
$('.loaderDiv').show();
get('myfile.php', function(data) {
alert(data);
$('.loaderDiv').hide();
}
```
Or what I like to do, is change the cursor:
```
$('body').css('cursor','progress');
get('myfile.php', function(data) {
alert(data);
$('body').css('cursor','default');
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: Had a similar issue, was trying to implement a loading gif, but the gif , even a 18Kb one was taking long time to load.
Finally, thanks to @username_2's post, used the CSS method and it worked very well:
js/jquery(snippet):
```
$(".loader").show()
fetch('gsxapi.php?regex=' + encodeURIComponent(regex))
.then(res => res.json())
.then(data => {
$("#hiddenloader").hide()
if (data && data.length > 0) {
$('#result')
.show()
```
html:
```
```
css:
```
#hiddenloader{ display:none; }
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
```
Upvotes: 0 |
2018/03/19 | 1,176 | 4,175 | <issue_start>username_0: I'm rather confused about how the code below works.
I expect that after Promise.resolve() returns a resolved promise - not a pending one - .then() whould immediately consume it/fulfill it, meaning;
in each reduce callback call, two questions will be asked (the chain of promises) - BUT de-facto they all chain and only on return from the function chainPromises, do they consume each other and run together.
Is this because we're waiting for the 'call stack' to empty and each .then() is waiting for the previous .then() callback to end so it returns a promise, etc.?
How does reduce come into play?
Can someone help me understand the code and the concepts behind it better?
```js
var fs = require("fs");
var readline = require("readline");
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let questionsData = [];
promisifyQuestion('How many languages do you know? \n')
.then((numOfLanguauges) => {
return chainPromises(numOfLanguauges)
})
.then((data) => {
fs.writeFile("./langs.json", JSON.stringify(questionsData), () => {});
return promisifyQuestion('Display lang?');
})
.then(x => {
console.log(JSON.stringify(questionsData.find(el => el.name == x)));
rl.close();
});
function promisifyQuestion(msg) {
return new Promise((resolve, reject) => {
rl.question(msg, resolve);
});
}
function chainPromises(length) {
for (var i = 0; i < length; questionsData[i++] = {});
let singleValue = questionsData.reduce(outerReduce, Promise.resolve());
//Promise chain does fire only on chainPromises end
return singleValue;
}
function outerReduce(prevRes, currentElement, currentIndex) {
return prevRes
.then(() => promisifyQuestion('language name:'))
.then(x => {
questionsData[currentIndex].name = x;
return promisifyQuestion('years of speaking it:');
})
.then(x => {
return questionsData[currentIndex].years = x
});
}
```<issue_comment>username_1: Yeah.. Just call your showSpinner statment like
e.g `$('.spinner').show()` right before your async request.
And then hide it in the success callback where you have your alert like this.
```
get('myfile.php', function(data) {
$('.spinner').hide()
alert(data);
}
```
Upvotes: 1 <issue_comment>username_2: Instead of displaying a gif, you can use an HTML/CSS spinner.
Here is an explanation to make it : <https://www.w3schools.com/howto/howto_css_loader.asp>
You have to make that spinner hidden by default and display it before your async call (jquery `.show()` function for example).
In the success function (where you have your `alert(data);`, you hide it (jquery function `.hide()` for example)
Upvotes: 1 <issue_comment>username_3: Sure, before calling the `$.get` show the loader.
After getting the results, hide it again.
```
$('.loaderDiv').show();
get('myfile.php', function(data) {
alert(data);
$('.loaderDiv').hide();
}
```
Or what I like to do, is change the cursor:
```
$('body').css('cursor','progress');
get('myfile.php', function(data) {
alert(data);
$('body').css('cursor','default');
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: Had a similar issue, was trying to implement a loading gif, but the gif , even a 18Kb one was taking long time to load.
Finally, thanks to @username_2's post, used the CSS method and it worked very well:
js/jquery(snippet):
```
$(".loader").show()
fetch('gsxapi.php?regex=' + encodeURIComponent(regex))
.then(res => res.json())
.then(data => {
$("#hiddenloader").hide()
if (data && data.length > 0) {
$('#result')
.show()
```
html:
```
```
css:
```
#hiddenloader{ display:none; }
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
```
Upvotes: 0 |
2018/03/19 | 765 | 2,849 | <issue_start>username_0: I am trying to create a pipeline that wait for new csv files in a GCS folder to process them and write an output to BigQuery.
I wrote the following code:
```java
public static void main(String[] args) {
Pipeline p = Pipeline.create(PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class));
TableReference tableRef = new TableReference();
tableRef.setProjectId(PROJECT_ID);
tableRef.setDatasetId(DATASET_ID);
tableRef.setTableId(TABLE_ID);
//Pipeline p = Pipeline.create(PipelineOptionsFactory.as(Options.class));
// Read files as they arrive in GS
p.apply("ReadFile", TextIO.read()
.from("gs://mybucket/*.csv")
.watchForNewFiles(
// Check for new files every 30 seconds
Duration.standardSeconds(30),
// Never stop checking for new files
Watch.Growth.never()
)
)
.apply(ParDo.of(new DoFn() {
@ProcessElement
public void processElement(ProcessContext c) {
String[] items = c.element().split(",");
if (items[0].startsWith("\_", 1)) {
// Skip header (the header is starting with \_comment)
LOG.info("Skipped header");
return;
}
Segment segment = new Segment(items);
c.output(segment);
}
}))
.apply(ParDo.of(new FormatSegment()))
.apply(BigQueryIO.writeTableRows()
.to(tableRef)
.withSchema(FormatSegment.getSchema())
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE\_APPEND)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE\_IF\_NEEDED));
// Run the pipeline.
p.run();
}
```
If I remove the `watchForNewFiles` part my code is working great (I see INFO logs regarding the parallelization of the writing to GCS temp location and final output is written to BigQuery).
But if I let the `watchForNewFiles` (code above) then I only see 1 INFO log (regarding the writing to GCS temp location) and execution gets stuck. No more logs, nor error and no output in BigQuery.
Any idea?<issue_comment>username_1: It looks like when using `waitForNewFiles()` we must write to BigQuery with the `BigQueryIO.Write.Method.STREAMING_INSERTS` method.
Code that works is now like this:
```
.apply(BigQueryIO.writeTableRows()
.to(tableRef)
.withSchema(FormatSegment.getSchema())
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: With DataflowRunner I get this error trying to use..
java.lang.UnsupportedOperationException: DataflowRunner does not currently support splittable DoFn: org.apache.beam.sdk.transforms.Watch$WatchGrowthFn@4a1691ac
With direct runner I see it polling but rest of pipeline doesn't seem to fire and no errors. Writing to datastore and bigquery.
Upvotes: 1 |
2018/03/19 | 1,340 | 5,412 | <issue_start>username_0: My application uses a third party API that throws an exception belonging to another api-handling module. The code looks something like this:
```
#API Module
def getdatafromapi(req):
# Trying to get data ...
if response_err in data:
raise APIModuleException('API error')
if conn_err in data:
raise APIConnectionError('API error')
# Do some processing
return response
# My Module
def get_data_and_crunch(req):
response = getdatafromapi(req)
if not response:
raise ValueError('Something happened')
# Proceed to number crunch
# Main script
def main():
# Sanitize api request...
try:
get_data_and_crunch(req)
except ValueError:
print('Something happened')
```
The main module behaves the same way no matter if `APIModuleException` or `APIConnectionError` occurs, but I would still like to log which exception class actually caused the exception.
Is there a way I could avoid having `APIModuleException` and `APIConnectionError` classes in my main script and still propagate the exceptions up just using `ValueError` to tell which exception class actually caused the exception in the API Module?<issue_comment>username_1: not sure i understand correctly. but this would be the standard way to differentiate exceptions:
```
class APIModuleException(Exception): pass
class APIConnectionError(Exception): pass
def get_data_and_crunch(req):
# raise ValueError
raise APIConnectionError
# raise APIModuleException
def main():
# Sanitize api request...
try:
req = None
get_data_and_crunch(req)
except APIModuleException as exc:
# ...handle
print('APIModuleException')
except APIConnectionError as exc:
# ...handle
print('APIConnectionError')
except ValueError as exc:
# ...handle
print('ValueError')
main()
```
Upvotes: 0 <issue_comment>username_2: Make sure that your module's exception is not the exact same type as the API's. It can be a base type, as `ValueError` seems to be in your case. Your raising code is fine in this regard.
Add multiple `except` blocks to catch the different types of exception:
```
try:
get_data_and_crunch()
except (APIModuleException, APIConnectionError) as e:
print('API error caught:', str(e))
except ValueError as e:
print('My module!:', str(e))
```
You can have as many `except` blocks as you like, and each one can catch as many types of exceptions as you like.
It is very important to put the `ValueError` catch after the one for the API exceptions if they inherit from `ValueError`. The blocks are evaluated in order, using `instanceof`, so if the `ValueError` block came first, all the exceptions would trigger it, and you would never see the API-specific messages.
If you need to know arbitrarily specific information about the exception, use the exception objects available through the `as ...` syntax shown above. The function [`sys.exc_info`](https://docs.python.org/3/library/sys.html#sys.exc_info) will also help you get information like the calling sequence that led to the error. You can use the [`traceback`](https://docs.python.org/3/library/traceback.html) module to get even more details.
**UPDATE**
Based on your latest comment you want to get the exception information without additional imports. **Disclaimer**: This is technically possible, and I will explain a way of doing it below, but I **highly** recommend against this approach.
The trick is to catch the base class of all the possible exceptions that you will be getting, as you attempted to do with `ValueError`. The problem is that [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError), despite being one of the most widely-used exception types, is *not* the base of all your exceptions, [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception) is. You could go overboard and catch [`BaseException`](https://docs.python.org/3/library/exceptions.html#BaseException), but then things like pressing `Ctrl+C` would stop working, so don't do it (just mentioning it for [completeness](https://docs.python.org/3/library/exceptions.html#exception-hierarchy)).
You can get the type (and therefore the name of the type) using the same notation I showed you above. Tracebacks will work as usual as well, to show you calling sequences and where the exception occurred:
```
try:
get_data_and_crunch()
except Exception as e:
print('Got a', type(e).__name__)
```
As per [@abarnert's comment](https://stackoverflow.com/questions/49364859/exception-propagation-in-python/49365190?noredirect=1#comment85770157_49365190), there are a few common ways of getting basic exception info before you delve into `sys.exc_info` and `traceback`. `type(e)` will get you the class of the thrown error. `str(e)` returns just the message of the error in 99% of sane exception classes. `repr(e)` will generally return the standard `type: message` string you see at the end of a printout.
As a disclaimer to my disclaimer, I have to add that while techniques like this are not *recommended*, they can be used quite effectively if you know what you are doing. So read the docs I linked carefully and make sure you understand your code thoroughly. This is much more important than heeding any sort of generic unqualified warnings.
Upvotes: 3 [selected_answer] |
2018/03/19 | 284 | 1,127 | <issue_start>username_0: My cod is that one and this error appears in the last line of the class, what should I do to solve it?
```
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces = CNCopySupportedInterfaces() {
for i in 0..
```<issue_comment>username_1: You can try
```
if let interfaceData = unsafeInterfaceData! as? [String:Any]
{
currentSSID = interfaceData["SSID"] as? String
}
```
Upvotes: 0 <issue_comment>username_2: The only lines that uses a subscript are:
```
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData?["SSID"] as String
```
Accessing with a string like this: `interfaceData?["SSID"]` requires you to define your dictionary differently, your current dictionary is declared as `[NSObject: AnyObject]` but to use a String subscript it would need to be `[String: AnyObject]`
Try changing this line to:
```
let interfaceData = unsafeInterfaceData! as [String: AnyObject]
```
Note: Best to use if let rather than force unwrapping with `!`
Upvotes: 1 |
2018/03/19 | 967 | 3,684 | <issue_start>username_0: Unable to refresh the Config files by using '<http://localhost:9001/refresh>'.
If I restart the Client application, the updated config's are loading fine.
The following is the simple rest controller I am using to test the same.
The refresh is run using the curl command 'curl -d {} localhost:9001/refresh/',which is giving 404 error.
```
@RestController
@RefreshScope
class ExampleController {
@Value("${Message2}")
private String message2 = "Hello World";
@RequestMapping
public String sayValue() {
return message2;
}
}
```
The following is the pom.xml which I am using
```
MyConfigurationClient
0.0.1-SNAPSHOT
jar
MyConfigurationServer
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.0.RELEASE
UTF-8
UTF-8
1.8
Finchley.M8
org.springframework.cloud
spring-cloud-config-server
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
false
```<issue_comment>username_1: Refresh endpoint is included in actuator. Please add actuator dependency and try this with "<http://localhost:9001/actuator/refresh>" endpoint.
Upvotes: -1 <issue_comment>username_2: I found the answer in [another stack overflow question](https://stackoverflow.com/questions/50114501/actuator-refresh-is-not-being-provided-in-springboot-2-0-1).
In my case I had to set the property
```
management.endpoints.web.exposure.include=*
# management.endpoints.web.exposure.include=xyz
```
which enables the "/actuator/refresh" url (note the actuator part!), and add a class
```
package here.org.your.put;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
*
*/
@Component
@ConfigurationProperties(prefix = "encrypted")
public class PropertyConfiguration {
private String property;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
```
which has a method setProperty that is invoked by "refresh". It takes my encrypted property (encrypted.password in application.properties of my client) from a git repository and decrypts using the spring config server I am also running. It then sets the value in this class.
Upvotes: 0 <issue_comment>username_3: Actuator dependency should be added in pom.xml to use.
```
org.springframework.boot
spring-boot-starter-actuator
```
Include refresh endpoint by adding below entry in application.properties or bootstrap.properties.
```
management.endpoints.web.exposure.include=refresh
```
Call refresh endpoint to reload properties without restarting the application.
<http://localhost:8080/actuator/refresh> (Use http post method not get)
@ConfigurationProperties
- Will reload respective properties with actuator refresh call itself.
@Value
- Will load properties at startup and will not reload with refresh call.
- To reload properties annotated with @Value you need to,
* Restart the application.
* It can also be done without restart just by annotating the class with @RefreshScope (spring cloud config annotation) that uses
@Value.
Upvotes: 3 <issue_comment>username_4: Just check, you config-client has set the property
```
server.port: 8080
management.endpoints.web.exposure.include=*
```
And then run the POST refresh request (Not GET)
```
curl --location --request POST 'http://localhost:8080/actuator/refresh'
```
Good luck!
Upvotes: 0 |
2018/03/19 | 363 | 1,210 | <issue_start>username_0: I am trying to check if the field is 0 or null and if so, the remaining amount will be equal the invoice amount.
This error appears and I searched for it but I found nothing!
[](https://i.stack.imgur.com/Rde3x.png)
Here is the code:
```
IF (G_Invoice.Amount_Paid = 0 OR G_Invoice.Amount_Paid is null )
then
Remaining_Amount := G_Invoice.Invoice_Amount
else
G_Invoice.Invoice_Amount-G_Invoice.Amount_Paid
end if;
```<issue_comment>username_1: The error is easy to explain (I did so in a brief Comment).
But the same result may be obtained much more simply:
```
Remaining_Amount := G_Invoice.Invoice_Amount-NVL(G_Invoice.Amount_Paid, 0)
```
No need for an IF statement (that is hidden within NVL). No need to treat the case of the paid amount being zero as a special case (if you subtract 0, that is the same as returning the INVOICE\_AMOUNT unchanged). NVL will cause a `null` to be converted to zero.
Upvotes: 0 <issue_comment>username_2: If the measure is being calculated in Oracle BI, the LSQL code should be:
```
Remaining_Amount - ifnull(G_Invoice.Amount_Paid,0)
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,037 | 3,777 | <issue_start>username_0: Im working on a Flutter app and trying to add a segment to my app. Is it possible to achieve it in Flutter. So i would like 2 different widgets for the 2 buttons. It is similar to the TabBar in Flutter or Segment in native apps
[](https://i.stack.imgur.com/0kkzK.png)<issue_comment>username_1: As you tried, you can acheive it with `TabBarView` easily. The below code shows a very basic implementation of how it can be acheived.
Example:
```
class Example extends StatefulWidget {
@override
_ExampleState createState() => new _ExampleState();
}
class _ExampleState extends State with SingleTickerProviderStateMixin {
// TabController to control and switch tabs
TabController \_tabController;
// Current Index of tab
int \_currentIndex = 0;
@override
void initState() {
super.initState();
\_tabController =
new TabController(vsync: this, length: 2, initialIndex: \_currentIndex);
}
@override
void dispose() {
\_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Example"),
),
body: new Column(
children: [
new Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0),
child: new Container(
decoration:
new BoxDecoration(border: new Border.all(color: Colors.blue)),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
// Sign In Button
new FlatButton(
color: \_currentIndex == 0 ? Colors.blue : Colors.white,
onPressed: () {
\_tabController.animateTo(0);
setState(() {
\_currentIndex = 0;
});
},
child: new Text("SignIn"),
),
// Sign Up Button
new FlatButton(
color: \_currentIndex == 1 ? Colors.blue : Colors.white,
onPressed: () {
\_tabController.animateTo(1);
setState(() {
\_currentIndex = 1;
});
},
child: new Text("SignUp"),
)
],
),
),
),
new Expanded(
child: new TabBarView(
controller: \_tabController,
// Restrict scroll by user
physics: const NeverScrollableScrollPhysics(),
children: [
// Sign In View
new Center(
child: new Text("SignIn"),
),
// Sign Up View
new Center(
child: new Text("SignUp"),
)
]),
)
],
),
);
}
}
```
Hope that helps!
Upvotes: 4 [selected_answer]<issue_comment>username_2: CupertinoSegmentedControl is your friend
Example (inside StatefulWidget):
```
int segmentedControlValue = 0;
Widget _segmentedControl() => Container(
width: 500,
child: CupertinoSegmentedControl(
selectedColor: Colors.blue,
borderColor: Colors.white,
children: {
0: Text('All'),
1: Text('Recommendations'),
},
onValueChanged: (int val) {
setState(() {
segmentedControlValue = val;
});
},
groupValue: segmentedControlValue,
),
);
```
[](https://i.stack.imgur.com/eVtEe.png)
Upvotes: 3 <issue_comment>username_3: Just use DefaultTabController
```
Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: TabBar(
isScrollable: false,
indicator: BoxDecoration(
borderRadius: BorderRadius.circular(8.0),
color:
Theme.of(context).colorScheme.primary.withOpacity(0.3)),
labelColor: Theme.of(context).colorScheme.primary,
//Theme.of(context).brightness == Brightness.light ? Colors.black : Colors.white,
unselectedLabelColor:
Theme.of(context).brightness == Brightness.light
? Colors.black54
: Colors.white60,
tabs: _tabs,
)),
body: TabBarView(
children: [
```
Upvotes: 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.