qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
51,610,180
I am trying to create a transition using react and css. I want to add a class to the `span` to create the animation - See example below. Does anyone know if the issue is with the css or my javascript. ```js class App extends React.Component { state = { class: null }; componentDidMount() { this.setState({ class: "active" }); } render() { return ( <div className="progress-bar-container"> <span className={this.state.class ? "progress-bar" : `${this.state.class} progress-bar`} /> </div> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); ``` ```css .progress-bar-container { border: 0; height: 4px; position: relative; background: red; } .progress-bar { -webkit-transition: width 2s; /* Safari */ transition: width 5s; width: 0%; } .progress-bar.active { width: 100%; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> ```
2018/07/31
['https://Stackoverflow.com/questions/51610180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4756106/']
You could use a different approach and append `active` class with `setTimeout` method. ```js class App extends React.Component { state = { class: null }; componentDidMount() { setTimeout(() => this.refs.progressBar.classList.add("active"), 100) } render() { return ( <div className = "progress-bar-container" > <span className="progress-bar" ref="progressBar"/> </div> ); } } const rootElement = document.getElementById("root"); ReactDOM.render( < App / > , rootElement); ``` ```css .progress-bar-container { border: 0; height: 4px; position: relative; background: red; } .progress-bar { position: absolute; left: 0; top: 0; height: 100%; background: green; transition: width 5s; width: 0px; } .progress-bar.active { width: 100%; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> ```
You can use `requestAnimationFrame()` to trigger the transition on mount. I'd presume that doing this is more robust than relying on a `setTimeout()`. ``` componentDidMount() { requestAnimationFrame(() => { this.setState({ class: "active" }); }); } ``` Source: <https://www.pluralsight.com/guides/handling-componentdidmount-issue-css-transition>
49,276,120
I want to open Google Street View Android directly from my app. Can anyone help me in doing this? I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. I actually want to open Streetview camera directly from my app so I can take a panoramic photo. My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) Please help in this!
2018/03/14
['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']
u are using python 3.6 . so pip3 install numpy should be used, make a try .
You need to make sure all the dependent libraries AND the Python file containing your function are all in one zip file in order for it to detect the correct dependencies. So essentially, you will need to have Numpy, Panda and your own files all in one zip file before you upload it. Also make sure that your code is referring to the local files (in the same unzipped directory) as dependencies. If you have done that already, the issue is probably how your included libraries gets referenced. Make sure you are able to use the included libraries as a dependency by getting the correct relative path on AWS once it's deployed to Lambda.
49,276,120
I want to open Google Street View Android directly from my app. Can anyone help me in doing this? I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. I actually want to open Streetview camera directly from my app so I can take a panoramic photo. My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) Please help in this!
2018/03/14
['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']
u are using python 3.6 . so pip3 install numpy should be used, make a try .
So like Wai kin chung said, you need to use pip3 to install the libraries. so to figure out which python version is default you can type: ``` which python ``` or ``` python -v ``` So in order to install with python3 you need to type: ``` python3 -m pip install sklearn, pandas, numpy --user ``` Once that is done, you can make sure that the packages are installed with: ``` python3 -m pip freeze ``` This will show all the python libraries installed with your python model. Once you have the libraries you would want to continue with you regular steps. Of course you would first want to delete everything that you have placed in ~/venv/lib/python3.6/site-packages/\*. ``` cd ~/lambda_code zip -r9 ~/package.zip ```
49,276,120
I want to open Google Street View Android directly from my app. Can anyone help me in doing this? I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. I actually want to open Streetview camera directly from my app so I can take a panoramic photo. My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) Please help in this!
2018/03/14
['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']
u are using python 3.6 . so pip3 install numpy should be used, make a try .
If you're running this on Windows (like I was), you'll run into an issue with the libraries being compiled on an incompatible OS. You can use an Amazon Linux EC2 instance, or a Cloud9 development instance to build your virtualenv as detailed above. Or, you could just download the pre-compiled wheel files as discussed on this post: <https://aws.amazon.com/premiumsupport/knowledge-center/lambda-python-package-compatible/> Essentially, you need to go to the project page on <https://pypi.org> and download the files named like the following: * For Python 2.7: module-name-version-cp27-cp27mu-manylinux1\_x86\_64.whl * For Python 3.6: module-name-version-cp36-cp36m-manylinux1\_x86\_64.whl Then unzip the .whl files to your project directory and re-zip the contents together with your lambda code.
49,276,120
I want to open Google Street View Android directly from my app. Can anyone help me in doing this? I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. I actually want to open Streetview camera directly from my app so I can take a panoramic photo. My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) Please help in this!
2018/03/14
['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']
u are using python 3.6 . so pip3 install numpy should be used, make a try .
Was having a similar problem on Ubuntu 18.04. Solved the issue by using `python3.7` and `pip3.7`. Its important to use `pip3.7` when installing the packages, like `pip3.7 install numpy` or `pip3.7 install numpy --user` To install `python3.7` and `pip3.7` on Ubuntu you can use `deadsnakes/ppa` ``` sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update sudo apt-get install python3.7 curl https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py python3.7 /tmp/get-pip.py ``` This solution should also work on Ubuntu 16.04.
37,541,683
Well, OpenCv comes with its function findCheckerboardCorners() in C++ which goes like ``` bool findChessboardCorners(InputArray image, Size patternSize, OutputArray corners, int flags=CALIB_CB_ADAPTIVE_THRESH+CALIB_CB_NORMALIZE_IMAGE ) ``` After using this function for a while, one thing that i understood was that the pattern size must comply with the image to a very good extent, else the algorithm refuses to detect any Chessboard altogether. I was wondering if there were any random image of a chessboard, this function would fail as it is impractical to enter the precise values of the patternSize. Is there a way, the patternSize for this function could be obtained from the image provided. Any help would be appreciated. Thanks.
2016/05/31
['https://Stackoverflow.com/questions/37541683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4633925/']
Short answer: you cannot. The OpenCV checkerboard detection code assumes that the pattern is uniform (all squares have the same size) and therefore, in order to uniquely locate its position in the image, the following two conditions must be true: 1. The pattern is entirely visible. 2. The pattern has a known numbers of rows and columns. If either 1 or 2 is violated there is no way to know which corner is, say, the "top left" one. For a more general case, and in particular if you anticipate that the pattern may be partially occluded, you must use a different algorithm and a non-uniform pattern, upon which corners can be uniquely identified. There are various way to do that. My favorite pattern is Matsunaga and Kanatani's "2D barcode" one, which uses sequences of square lengths with unique crossratios. See the paper [here](https://www.semanticscholar.org/paper/Optimal-Grid-Pattern-for-Automated-Matching-Using-Matsunaga-Kanatani/8c57a5a20eaf9d8d0f16faa2153a80003ef50cdb). In order to match it, once you have sorted the corners into a grid, you can use a simple majority voting algorithm: * Precompute the crossratios of all the pattern's consecutive 4-tuples of corners, in both the horizontal and vertical directions. * Do the above for the detected corners in the grid. * For every possible horizontal shift + Over every row - Accumulate the number of crossratios that agree within a threshold * Select the horizontal shift with the highest number of agreements. * Repeat the above for every possible vertical shift, counting crossratios along the columns. * Repeat the above two steps reversing the order of the crossratios in the vertical and horizontal and vertical direction, separately and jointly, to account for reflections and rotations. Placing the detected corners in a grid can be achieved in various ways. There is an often-rediscovered [algorithm](https://somelightprojections.blogspot.com/2016/06/checkerboards.html) that uses topological proximity. The idea is to first associate each corner to all the squares within a small window of it, thus building a corner->squares table, and then traverse it as a graph to build a global table of the offsets of each corner from one another.
The doc for [`findChessboardCorners`](http://docs.opencv.org/3.0.0/d9/d0c/group__calib3d.html#ga93efa9b0aa890de240ca32b11253dd4a) says that > > `patternSize` – Number of inner corners per a chessboard row and > column > > > So `patternSize` is not the size of the chessboard inside the image but the number of inner corners. The number of inner corners does not depend from the size of the chessboard inside the image. For example for the following image <https://github.com/Itseez/opencv/blob/3.1.0/samples/data/chessboard.png> [![enter image description here](https://i.stack.imgur.com/4Tnr6.png)](https://i.stack.imgur.com/4Tnr6.png) `patternSize` should be `cv::Size(7,7)`.
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
try: figure,imshow(your\_image), axis image This changes the image axis to the original size
There are 3 things to take care of in order to display image in its original size (1:1): * The figure size and units. * The axes size and units. * The axes data aspect ratio. Once all of that are set according to the image size even using MATLAB's `image()` function one could generate 1:1 display of an image. Here is the sample code: ``` %% Load Data mI = imread('7572939538_04e373d8f4_z.jpg'); numRows = size(mI, 1); numCols = size(mI, 2); %% Setings horMargin = 30; verMargin = 60; %<! Title requires more %% Display Image vFigPos = [100, 100, numCols + (2 * horMargin), numRows + (2 * verMargin)]; %<! [Left, Bottom, Width, Height] vAxesPos = [horMargin, verMargin, numCols, numRows]; hFigure = figure('Position', vFigPos, 'Units', 'pixels'); hAxes = axes('Units', 'pixels', 'Position', vAxesPos); hImageObj = image(hAxes, mI); set(hAxes, 'DataAspectRatio', [1, 1, 1]); set(get(hAxes, 'Title'), 'String', {['Landscape by Roman Vanur']}, ... 'Fontsize', fontSizeTitle); set(hAxes, 'XTick', []); set(hAxes, 'YTick', []); ``` The result (Based on the image - [Landscape by Roman Vanur](https://www.flickr.com/photos/80272075@N02/7572939538/)): [![Landscape by Roman Vanur](https://i.stack.imgur.com/wo4Te.png)](https://i.stack.imgur.com/wo4Te.png) The full code in my [Stack Overflow Q1427602 Github Repository](https://github.com/RoyiAvital/StackExchangeCodes/tree/master/StackOverflow/Q1427602).
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
I believe what you're looking for is the [IMTOOL](http://www.mathworks.com/access/helpdesk/help/toolbox/images/imtool.html) utility (which is a part of the [Image Processing Toolbox](http://www.mathworks.com/products/image/)). It's a MATLAB GUI that allows you to view images in their original size (100% magnification) with horizontal and vertical sliders. **EDIT:** The above solution will display your image in a new figure window (the IMTOOL GUI). If you don't want the image appearing in a new window, but instead want to adjust its size in a window of your own, it will be more difficult. To adjust the size of the image, which I assume you've displayed on a set of axes using the [IMAGE](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/image.html) command, you will have to adjust a number of [axes properties](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/axes_props.html) for the axes containing the image. The following are the properties you will likely end up modifying: * `'Units'`: This can be set to `'inches'`, `'centimeters'`, or `'pixels'`, for example. * `'Position'`: This controls where the axes are placed in the figure window, in units governed by the `'Units'` property. * `'DataAspectRatio'/'PlotBoxAspectRatio'`: These control the relative scaling of the axes and the surrounding plot box. * `'XLim'/'YLim'`: The minimum and maximum values of the axes. After getting the size and scaling of the image to display the way you want, parts of the image could be outside the figure window area. Unfortunately, horizontal and vertical sliders *will not* be automatically added. You will have to create these slider controls yourself using the [UICONTROL](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontrol.html) function. You will have to write the callback functions for the slider controls such that they move the axes around in the window. If you choose to venture down the above path, here are a few links to GUI design tutorials that may help you: [a slider tutorial on blinkdagger](http://blinkdagger.com/matlab/matlab-gui-tutorial-slider/), [a blog post by Doug Hull](http://blogs.mathworks.com/videos/2009/08/06/gui-tutorials-from-the-file-exchange/), and [a video from Doug on GUIDE basics](http://www.mathworks.com/matlabcentral/fileexchange/7598).
There are 3 things to take care of in order to display image in its original size (1:1): * The figure size and units. * The axes size and units. * The axes data aspect ratio. Once all of that are set according to the image size even using MATLAB's `image()` function one could generate 1:1 display of an image. Here is the sample code: ``` %% Load Data mI = imread('7572939538_04e373d8f4_z.jpg'); numRows = size(mI, 1); numCols = size(mI, 2); %% Setings horMargin = 30; verMargin = 60; %<! Title requires more %% Display Image vFigPos = [100, 100, numCols + (2 * horMargin), numRows + (2 * verMargin)]; %<! [Left, Bottom, Width, Height] vAxesPos = [horMargin, verMargin, numCols, numRows]; hFigure = figure('Position', vFigPos, 'Units', 'pixels'); hAxes = axes('Units', 'pixels', 'Position', vAxesPos); hImageObj = image(hAxes, mI); set(hAxes, 'DataAspectRatio', [1, 1, 1]); set(get(hAxes, 'Title'), 'String', {['Landscape by Roman Vanur']}, ... 'Fontsize', fontSizeTitle); set(hAxes, 'XTick', []); set(hAxes, 'YTick', []); ``` The result (Based on the image - [Landscape by Roman Vanur](https://www.flickr.com/photos/80272075@N02/7572939538/)): [![Landscape by Roman Vanur](https://i.stack.imgur.com/wo4Te.png)](https://i.stack.imgur.com/wo4Te.png) The full code in my [Stack Overflow Q1427602 Github Repository](https://github.com/RoyiAvital/StackExchangeCodes/tree/master/StackOverflow/Q1427602).
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
I believe what you're looking for is the [IMTOOL](http://www.mathworks.com/access/helpdesk/help/toolbox/images/imtool.html) utility (which is a part of the [Image Processing Toolbox](http://www.mathworks.com/products/image/)). It's a MATLAB GUI that allows you to view images in their original size (100% magnification) with horizontal and vertical sliders. **EDIT:** The above solution will display your image in a new figure window (the IMTOOL GUI). If you don't want the image appearing in a new window, but instead want to adjust its size in a window of your own, it will be more difficult. To adjust the size of the image, which I assume you've displayed on a set of axes using the [IMAGE](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/image.html) command, you will have to adjust a number of [axes properties](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/axes_props.html) for the axes containing the image. The following are the properties you will likely end up modifying: * `'Units'`: This can be set to `'inches'`, `'centimeters'`, or `'pixels'`, for example. * `'Position'`: This controls where the axes are placed in the figure window, in units governed by the `'Units'` property. * `'DataAspectRatio'/'PlotBoxAspectRatio'`: These control the relative scaling of the axes and the surrounding plot box. * `'XLim'/'YLim'`: The minimum and maximum values of the axes. After getting the size and scaling of the image to display the way you want, parts of the image could be outside the figure window area. Unfortunately, horizontal and vertical sliders *will not* be automatically added. You will have to create these slider controls yourself using the [UICONTROL](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontrol.html) function. You will have to write the callback functions for the slider controls such that they move the axes around in the window. If you choose to venture down the above path, here are a few links to GUI design tutorials that may help you: [a slider tutorial on blinkdagger](http://blinkdagger.com/matlab/matlab-gui-tutorial-slider/), [a blog post by Doug Hull](http://blogs.mathworks.com/videos/2009/08/06/gui-tutorials-from-the-file-exchange/), and [a video from Doug on GUIDE basics](http://www.mathworks.com/matlabcentral/fileexchange/7598).
Funny, nobody here has mentioned [`truesize`](https://www.mathworks.com/help/images/ref/truesize.html) yet: > > `truesize(fig)` adjusts the display size such that each image pixel covers one screen pixel. If you do not specify a figure, `truesize` adjusts the display size of the current figure. > > >
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Matlab slider has a problem that it fires callback only on MouseUp and not on MouseMove, so pure matlab implementation would always feels strange. Better way - go for Java in Matlab. So you do not have to re-implement whole scroll logics. You can put Java Swing GUI component inside Matlab window, it is not difficult at all. Specifically you have to use Swing `JScrollPane` Class. With Matlab `javacomponent()` function you can put it inside matlab window. There are tons of examples on the web on how to get image into scroll pane, just browse for `JScrollPane image`. You can use Java classes inside matlab with usual Matlab syntax (no need for `new` keyword, ecc.)
There are 3 things to take care of in order to display image in its original size (1:1): * The figure size and units. * The axes size and units. * The axes data aspect ratio. Once all of that are set according to the image size even using MATLAB's `image()` function one could generate 1:1 display of an image. Here is the sample code: ``` %% Load Data mI = imread('7572939538_04e373d8f4_z.jpg'); numRows = size(mI, 1); numCols = size(mI, 2); %% Setings horMargin = 30; verMargin = 60; %<! Title requires more %% Display Image vFigPos = [100, 100, numCols + (2 * horMargin), numRows + (2 * verMargin)]; %<! [Left, Bottom, Width, Height] vAxesPos = [horMargin, verMargin, numCols, numRows]; hFigure = figure('Position', vFigPos, 'Units', 'pixels'); hAxes = axes('Units', 'pixels', 'Position', vAxesPos); hImageObj = image(hAxes, mI); set(hAxes, 'DataAspectRatio', [1, 1, 1]); set(get(hAxes, 'Title'), 'String', {['Landscape by Roman Vanur']}, ... 'Fontsize', fontSizeTitle); set(hAxes, 'XTick', []); set(hAxes, 'YTick', []); ``` The result (Based on the image - [Landscape by Roman Vanur](https://www.flickr.com/photos/80272075@N02/7572939538/)): [![Landscape by Roman Vanur](https://i.stack.imgur.com/wo4Te.png)](https://i.stack.imgur.com/wo4Te.png) The full code in my [Stack Overflow Q1427602 Github Repository](https://github.com/RoyiAvital/StackExchangeCodes/tree/master/StackOverflow/Q1427602).
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Matlab slider has a problem that it fires callback only on MouseUp and not on MouseMove, so pure matlab implementation would always feels strange. Better way - go for Java in Matlab. So you do not have to re-implement whole scroll logics. You can put Java Swing GUI component inside Matlab window, it is not difficult at all. Specifically you have to use Swing `JScrollPane` Class. With Matlab `javacomponent()` function you can put it inside matlab window. There are tons of examples on the web on how to get image into scroll pane, just browse for `JScrollPane image`. You can use Java classes inside matlab with usual Matlab syntax (no need for `new` keyword, ecc.)
This code from MATLAB's Answers forum creates a window where the image is shown at native resolution (100%), and also gives a "navigation" window showing where your viewed section of the image (in the main window) fits into the whole image. ``` % Create a scroll panel with a Magnification Box and an Overview tool. hFig = figure('Toolbar','none',... 'Menubar','none'); hIm = imshow('saturn.png'); hSP = imscrollpanel(hFig,hIm); % Handle to scroll panel. set(hSP,'Units','normalized',... 'Position',[0 .1 1 .9]) % Add a Magnification Box and an Overview tool. hMagBox = immagbox(hFig,hIm); pos = get(hMagBox,'Position'); set(hMagBox,'Position',[0 0 pos(3) pos(4)]) imoverview(hIm) ``` ([Forum post link](https://au.mathworks.com/matlabcentral/answers/151402-why-isn-t-truesize-working-properly))
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
This code from MATLAB's Answers forum creates a window where the image is shown at native resolution (100%), and also gives a "navigation" window showing where your viewed section of the image (in the main window) fits into the whole image. ``` % Create a scroll panel with a Magnification Box and an Overview tool. hFig = figure('Toolbar','none',... 'Menubar','none'); hIm = imshow('saturn.png'); hSP = imscrollpanel(hFig,hIm); % Handle to scroll panel. set(hSP,'Units','normalized',... 'Position',[0 .1 1 .9]) % Add a Magnification Box and an Overview tool. hMagBox = immagbox(hFig,hIm); pos = get(hMagBox,'Position'); set(hMagBox,'Position',[0 0 pos(3) pos(4)]) imoverview(hIm) ``` ([Forum post link](https://au.mathworks.com/matlabcentral/answers/151402-why-isn-t-truesize-working-properly))
There are 3 things to take care of in order to display image in its original size (1:1): * The figure size and units. * The axes size and units. * The axes data aspect ratio. Once all of that are set according to the image size even using MATLAB's `image()` function one could generate 1:1 display of an image. Here is the sample code: ``` %% Load Data mI = imread('7572939538_04e373d8f4_z.jpg'); numRows = size(mI, 1); numCols = size(mI, 2); %% Setings horMargin = 30; verMargin = 60; %<! Title requires more %% Display Image vFigPos = [100, 100, numCols + (2 * horMargin), numRows + (2 * verMargin)]; %<! [Left, Bottom, Width, Height] vAxesPos = [horMargin, verMargin, numCols, numRows]; hFigure = figure('Position', vFigPos, 'Units', 'pixels'); hAxes = axes('Units', 'pixels', 'Position', vAxesPos); hImageObj = image(hAxes, mI); set(hAxes, 'DataAspectRatio', [1, 1, 1]); set(get(hAxes, 'Title'), 'String', {['Landscape by Roman Vanur']}, ... 'Fontsize', fontSizeTitle); set(hAxes, 'XTick', []); set(hAxes, 'YTick', []); ``` The result (Based on the image - [Landscape by Roman Vanur](https://www.flickr.com/photos/80272075@N02/7572939538/)): [![Landscape by Roman Vanur](https://i.stack.imgur.com/wo4Te.png)](https://i.stack.imgur.com/wo4Te.png) The full code in my [Stack Overflow Q1427602 Github Repository](https://github.com/RoyiAvital/StackExchangeCodes/tree/master/StackOverflow/Q1427602).
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Matlab slider has a problem that it fires callback only on MouseUp and not on MouseMove, so pure matlab implementation would always feels strange. Better way - go for Java in Matlab. So you do not have to re-implement whole scroll logics. You can put Java Swing GUI component inside Matlab window, it is not difficult at all. Specifically you have to use Swing `JScrollPane` Class. With Matlab `javacomponent()` function you can put it inside matlab window. There are tons of examples on the web on how to get image into scroll pane, just browse for `JScrollPane image`. You can use Java classes inside matlab with usual Matlab syntax (no need for `new` keyword, ecc.)
try: figure,imshow(your\_image), axis image This changes the image axis to the original size
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
I believe what you're looking for is the [IMTOOL](http://www.mathworks.com/access/helpdesk/help/toolbox/images/imtool.html) utility (which is a part of the [Image Processing Toolbox](http://www.mathworks.com/products/image/)). It's a MATLAB GUI that allows you to view images in their original size (100% magnification) with horizontal and vertical sliders. **EDIT:** The above solution will display your image in a new figure window (the IMTOOL GUI). If you don't want the image appearing in a new window, but instead want to adjust its size in a window of your own, it will be more difficult. To adjust the size of the image, which I assume you've displayed on a set of axes using the [IMAGE](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/image.html) command, you will have to adjust a number of [axes properties](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/axes_props.html) for the axes containing the image. The following are the properties you will likely end up modifying: * `'Units'`: This can be set to `'inches'`, `'centimeters'`, or `'pixels'`, for example. * `'Position'`: This controls where the axes are placed in the figure window, in units governed by the `'Units'` property. * `'DataAspectRatio'/'PlotBoxAspectRatio'`: These control the relative scaling of the axes and the surrounding plot box. * `'XLim'/'YLim'`: The minimum and maximum values of the axes. After getting the size and scaling of the image to display the way you want, parts of the image could be outside the figure window area. Unfortunately, horizontal and vertical sliders *will not* be automatically added. You will have to create these slider controls yourself using the [UICONTROL](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontrol.html) function. You will have to write the callback functions for the slider controls such that they move the axes around in the window. If you choose to venture down the above path, here are a few links to GUI design tutorials that may help you: [a slider tutorial on blinkdagger](http://blinkdagger.com/matlab/matlab-gui-tutorial-slider/), [a blog post by Doug Hull](http://blogs.mathworks.com/videos/2009/08/06/gui-tutorials-from-the-file-exchange/), and [a video from Doug on GUIDE basics](http://www.mathworks.com/matlabcentral/fileexchange/7598).
try: figure,imshow(your\_image), axis image This changes the image axis to the original size
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Matlab slider has a problem that it fires callback only on MouseUp and not on MouseMove, so pure matlab implementation would always feels strange. Better way - go for Java in Matlab. So you do not have to re-implement whole scroll logics. You can put Java Swing GUI component inside Matlab window, it is not difficult at all. Specifically you have to use Swing `JScrollPane` Class. With Matlab `javacomponent()` function you can put it inside matlab window. There are tons of examples on the web on how to get image into scroll pane, just browse for `JScrollPane image`. You can use Java classes inside matlab with usual Matlab syntax (no need for `new` keyword, ecc.)
Funny, nobody here has mentioned [`truesize`](https://www.mathworks.com/help/images/ref/truesize.html) yet: > > `truesize(fig)` adjusts the display size such that each image pixel covers one screen pixel. If you do not specify a figure, `truesize` adjusts the display size of the current figure. > > >
1,427,602
Can we show an image in its original size in MATLAB? Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. Any ideas on how to achieve this? Is this possible?
2009/09/15
['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
I believe what you're looking for is the [IMTOOL](http://www.mathworks.com/access/helpdesk/help/toolbox/images/imtool.html) utility (which is a part of the [Image Processing Toolbox](http://www.mathworks.com/products/image/)). It's a MATLAB GUI that allows you to view images in their original size (100% magnification) with horizontal and vertical sliders. **EDIT:** The above solution will display your image in a new figure window (the IMTOOL GUI). If you don't want the image appearing in a new window, but instead want to adjust its size in a window of your own, it will be more difficult. To adjust the size of the image, which I assume you've displayed on a set of axes using the [IMAGE](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/image.html) command, you will have to adjust a number of [axes properties](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/axes_props.html) for the axes containing the image. The following are the properties you will likely end up modifying: * `'Units'`: This can be set to `'inches'`, `'centimeters'`, or `'pixels'`, for example. * `'Position'`: This controls where the axes are placed in the figure window, in units governed by the `'Units'` property. * `'DataAspectRatio'/'PlotBoxAspectRatio'`: These control the relative scaling of the axes and the surrounding plot box. * `'XLim'/'YLim'`: The minimum and maximum values of the axes. After getting the size and scaling of the image to display the way you want, parts of the image could be outside the figure window area. Unfortunately, horizontal and vertical sliders *will not* be automatically added. You will have to create these slider controls yourself using the [UICONTROL](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontrol.html) function. You will have to write the callback functions for the slider controls such that they move the axes around in the window. If you choose to venture down the above path, here are a few links to GUI design tutorials that may help you: [a slider tutorial on blinkdagger](http://blinkdagger.com/matlab/matlab-gui-tutorial-slider/), [a blog post by Doug Hull](http://blogs.mathworks.com/videos/2009/08/06/gui-tutorials-from-the-file-exchange/), and [a video from Doug on GUIDE basics](http://www.mathworks.com/matlabcentral/fileexchange/7598).
This code from MATLAB's Answers forum creates a window where the image is shown at native resolution (100%), and also gives a "navigation" window showing where your viewed section of the image (in the main window) fits into the whole image. ``` % Create a scroll panel with a Magnification Box and an Overview tool. hFig = figure('Toolbar','none',... 'Menubar','none'); hIm = imshow('saturn.png'); hSP = imscrollpanel(hFig,hIm); % Handle to scroll panel. set(hSP,'Units','normalized',... 'Position',[0 .1 1 .9]) % Add a Magnification Box and an Overview tool. hMagBox = immagbox(hFig,hIm); pos = get(hMagBox,'Position'); set(hMagBox,'Position',[0 0 pos(3) pos(4)]) imoverview(hIm) ``` ([Forum post link](https://au.mathworks.com/matlabcentral/answers/151402-why-isn-t-truesize-working-properly))
17,735,526
I'm playing around with some code in a Kobold2D example project (Orthogonal Tile based Game) and I've noticed: ``` @interface TileMapLayer : CCLayer //Map { float tileMapHeightInPixels; //depricated@interface TileMapLayer() } @end ``` in the TileMapLayer.h file, and: ``` @interface TileMapLayer() @property (strong) HUDLayer *hud; @property (strong) CCTMXTiledMap *tileMap; @property (strong) CCTMXLayer *background; @property (strong) CCTMXLayer *foreground; @property (strong) CCTMXLayer *meta; @property (strong) CCTMXLayer *base; @property (strong) CCSprite *player; @property (strong) CCSprite *playerTurret; @property (assign) int money; @end ``` in the TileMapLay.m file. I've always thought that `.h` files hold interfaces and `.m` files store implementations Can someone please explain their purpose (started from the basics, I'm still learning Objective C) and what the difference in purpose between the 2 examples above?
2013/07/18
['https://Stackoverflow.com/questions/17735526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
What you put in a header and implementation file is entirely up to you. They all get concatenated by the preprocessor before compilation anyway. It's convention to put external interfaces that other compilation units might want to use into header files. The person who wrote your example code intends to keep all of those properties defined in the `.m` file private - that is they're intended to not be directly accessed by other code in the system.
Things defined in .h can be used by any .m files as long as the .m includes the .h. But things defined in .m can only be used in current .m file.
17,735,526
I'm playing around with some code in a Kobold2D example project (Orthogonal Tile based Game) and I've noticed: ``` @interface TileMapLayer : CCLayer //Map { float tileMapHeightInPixels; //depricated@interface TileMapLayer() } @end ``` in the TileMapLayer.h file, and: ``` @interface TileMapLayer() @property (strong) HUDLayer *hud; @property (strong) CCTMXTiledMap *tileMap; @property (strong) CCTMXLayer *background; @property (strong) CCTMXLayer *foreground; @property (strong) CCTMXLayer *meta; @property (strong) CCTMXLayer *base; @property (strong) CCSprite *player; @property (strong) CCSprite *playerTurret; @property (assign) int money; @end ``` in the TileMapLay.m file. I've always thought that `.h` files hold interfaces and `.m` files store implementations Can someone please explain their purpose (started from the basics, I'm still learning Objective C) and what the difference in purpose between the 2 examples above?
2013/07/18
['https://Stackoverflow.com/questions/17735526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
First notice that `.m` are Objective-C files (which can have both Objective-C and C) and `.c` are plain C files which can only contain C code. Both employ the `.h` extension for the header. Regarding Objective-C, the `.m` file does `@interface TileMapLayer()` to declare a class *extension*. A class *extension* can add ivars and properties to a Class that was already declared in the `.h` file. An extension is only viewable from within its own `.m` file. It doesn't make much sense to declare an extension inside an `.h` file, but I guess you could if you wanted. Regarding purpose, a recommended practice is declaring the minimum amount of properties needed in the `.h` in order to keep the interface lean and clean. For properties that are only needed inside the class, you can declare them in the extension on the `.m` file. My personal preference is to avoid explicitly declaring and using ivars at all (unless I'm overriding a property setter or getter), because that way on the implementation I can tell at first glance which variables are local to the function or object properties. The overhead is usually negligible and I prefer to code for readability than to prematurely optimize. With the recently introduced auto-synthesized properties this saves a lot of boilerplate code as well. A strategy that I also recommend is thinking carefully which properties should be modifiable from outside the object or not. Declare the non-modifiable properties as `readonly` in the `.h` files. Then, you can re-declare them as `readwrite` in the `.m` *extension* for operations from the object itself. This ensures that you or your colleagues don't commit the mistake and modify a `readonly` property that is not supposed to change from outside the object. In a sense it helps you in keeping the logic of the object inside it. I would try to avoid the trap of declaring everything `readwrite` (the default), because then it usually comes to bite you back later.
Things defined in .h can be used by any .m files as long as the .m includes the .h. But things defined in .m can only be used in current .m file.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. Exercises like over-the-head-squats demands extremely high flexibility. You can highly improve quality of your squats by doing air squats in front of a mirror. You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: <http://www.6-directions.com/> You can just use floor-cloths for sliding exercises. I use to do so. If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.
Training is in essence applying force to a resistance. How that resistance looks like is just limited to your imagination. * The World is your gym (phrase stolen from Ross Enamait) go out and train outside in fresh air, you can do pull-ups, chin-ups, dips on trees or monkey bars on playgrounds, using heavy stones, barrels or kegs for overhead lifting or deadlifts or big logs. Running up hills for conditioning is an challenging task... too. * You are your own Gym (phrase stolen from a title of a bodyweight training program od a farmer navy seal - Mark Lauren) you can do bodyweight exercises in addition or just alone, there are some outstanding programs outhere. I recommend: Never Gymless-Ross Enamait, YAYOG - Mark Lauren or Convict Conditioning by Paul Wade. * Make your own gym: Depending on your Budget and available space for training you could build some of the tools on your own, here is some Information on custom created tools like bulgarian bags, sandbags, gymnastic rings, trx bands and kettle-dumbells. <http://rosstraining.net/forum/viewtopic.php?f=9&t=157&sid=03871eb27b3ff4b3f2230da5c9b07e97> now go do something...
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. Exercises like over-the-head-squats demands extremely high flexibility. You can highly improve quality of your squats by doing air squats in front of a mirror. You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: <http://www.6-directions.com/> You can just use floor-cloths for sliding exercises. I use to do so. If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.
If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. [Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
Training is in essence applying force to a resistance. How that resistance looks like is just limited to your imagination. * The World is your gym (phrase stolen from Ross Enamait) go out and train outside in fresh air, you can do pull-ups, chin-ups, dips on trees or monkey bars on playgrounds, using heavy stones, barrels or kegs for overhead lifting or deadlifts or big logs. Running up hills for conditioning is an challenging task... too. * You are your own Gym (phrase stolen from a title of a bodyweight training program od a farmer navy seal - Mark Lauren) you can do bodyweight exercises in addition or just alone, there are some outstanding programs outhere. I recommend: Never Gymless-Ross Enamait, YAYOG - Mark Lauren or Convict Conditioning by Paul Wade. * Make your own gym: Depending on your Budget and available space for training you could build some of the tools on your own, here is some Information on custom created tools like bulgarian bags, sandbags, gymnastic rings, trx bands and kettle-dumbells. <http://rosstraining.net/forum/viewtopic.php?f=9&t=157&sid=03871eb27b3ff4b3f2230da5c9b07e97> now go do something...
Lifting>family but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. [Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars.
Get a pullup/chinup bar. You can get one for about $20. Buy a couple of parallel bars where you can do dips. If you have a couple of sturdy chairs, they will do. Pullups, chinups, dips, pushups, planks, bodyweight squats are all great exercises that could make up for a very decent routine.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. [Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars.
[Gymnastic Strength Training](https://www.gymnasticbodies.com/) is a perfect option for you in my opinion. It is very well designed program with tons of progressions and requires almost negligible equipment.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. Exercises like over-the-head-squats demands extremely high flexibility. You can highly improve quality of your squats by doing air squats in front of a mirror. You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: <http://www.6-directions.com/> You can just use floor-cloths for sliding exercises. I use to do so. If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.
Get a pullup/chinup bar. You can get one for about $20. Buy a couple of parallel bars where you can do dips. If you have a couple of sturdy chairs, they will do. Pullups, chinups, dips, pushups, planks, bodyweight squats are all great exercises that could make up for a very decent routine.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. Exercises like over-the-head-squats demands extremely high flexibility. You can highly improve quality of your squats by doing air squats in front of a mirror. You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: <http://www.6-directions.com/> You can just use floor-cloths for sliding exercises. I use to do so. If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.
Lifting>family but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
Get a pullup/chinup bar. You can get one for about $20. Buy a couple of parallel bars where you can do dips. If you have a couple of sturdy chairs, they will do. Pullups, chinups, dips, pushups, planks, bodyweight squats are all great exercises that could make up for a very decent routine.
Lifting>family but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine.
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. [Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars.
Training is in essence applying force to a resistance. How that resistance looks like is just limited to your imagination. * The World is your gym (phrase stolen from Ross Enamait) go out and train outside in fresh air, you can do pull-ups, chin-ups, dips on trees or monkey bars on playgrounds, using heavy stones, barrels or kegs for overhead lifting or deadlifts or big logs. Running up hills for conditioning is an challenging task... too. * You are your own Gym (phrase stolen from a title of a bodyweight training program od a farmer navy seal - Mark Lauren) you can do bodyweight exercises in addition or just alone, there are some outstanding programs outhere. I recommend: Never Gymless-Ross Enamait, YAYOG - Mark Lauren or Convict Conditioning by Paul Wade. * Make your own gym: Depending on your Budget and available space for training you could build some of the tools on your own, here is some Information on custom created tools like bulgarian bags, sandbags, gymnastic rings, trx bands and kettle-dumbells. <http://rosstraining.net/forum/viewtopic.php?f=9&t=157&sid=03871eb27b3ff4b3f2230da5c9b07e97> now go do something...
28,699
The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is "one rep" supposed to be twice on the right and twice on the left? I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.
2016/01/19
['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']
[Gymnastic Strength Training](https://www.gymnasticbodies.com/) is a perfect option for you in my opinion. It is very well designed program with tons of progressions and requires almost negligible equipment.
Lifting>family but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine.
25,834,234
I have a `p:datagrid` that contain some offers inside the `p:datagrid` there is a `p:commandLink` that will pass offer and redirect to onther page this is my xhtml ``` <p:dataGrid lazy="true" var="offer" paginatorPosition="bottom" value="#{listCategoriesBean.OfferByCategory()}" columns="1" rows="5" paginator="true" id="OffersList" styleClass="listPage" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" emptyMessage="#{msg['offersEmpty']}" widgetVar="dtWv"> <p:commandLink styleClass="clickAll" action="#{navigationBean.ToMore()}"> <f:setPropertyActionListener value="#{offer}" target="#{listCategoriesBean.offer}" /> <i class="fa fa-plus"></i> </p:commandLink> </p:dataGrid> ``` this is my bean ``` @SessionScoped public class NavigationBean implements Serializable { public String ToMore() { return "/more.xhtml?faces-redirect=true"; } } ``` The problem is when click on the commandLink it only refresh the page
2014/09/14
['https://Stackoverflow.com/questions/25834234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3982495/']
(Copied from Answer, so (c) @naifsami) I Solved the problem by workarround idea by using p:remotecommand outside the table and call the remotecommand from inside the table ``` <p:remoteCommand name="remoteCommandFunctionName" action="#{listCategoriesBean.ToMore()}" /> <p:dataGrid lazy="true" var="offer" paginatorPosition="bottom" value="#{listCategoriesBean.OfferByCategory()}" columns="1" rows="5" paginator="true" id="OffersList" styleClass="listPage" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" emptyMessage="#{msg['offersEmpty']}" > <p:commandLink styleClass="clickAll" type="button" onclick="remoteCommandFunctionName([{name:'n', value:'#{offer.id}'}])" > <i class="fa fa-plus"></i> </p:commandLink> </p:dataGrid> ``` my bean ``` public String ToMore() { String offerid=""; FacesContext context = FacesContext.getCurrentInstance(); Map map = context.getExternalContext().getRequestParameterMap(); offerid=(String) map.get("n"); offer1= newOfferServices.OfferByNumber(Integer.parseInt(offerid)); setOffer(offer1); return "/more.xhtml?faces-redirect=true"; } ```
You should get the desired result by navigating through the outcome attribute. ```html <p:commandLink styleClass="clickAll" action="more.xhtml?faces-redirect=true"> <f:setPropertyActionListener value="#{offer}" target="#{listCategoriesBean.offer}" /> <i class="fa fa-plus"></i> </p:commandLink> ```
68,377,604
Im just beginner in Swift Development. I don't know how to remove the .isSelected when the user choose the other button
2021/07/14
['https://Stackoverflow.com/questions/68377604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15285622/']
Looking at the pattern that you tried, you could match using a capture group for the part after the first curly. ``` \{(\{.*?}}) ``` And replace with ``` {&#8203;$1 ``` See a [regex demo](https://regex101.com/r/XJ9wdP/1) and a [Java demo](https://ideone.com/tdRXau) Example code ``` String regex = "\\{(\\{.*?\\}\\})"; String string = "{{ interface_ID }} THERE SHOU{{interface_ID}}LD BE CODE HERE: {{interface_ID}}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(string); System.out.println(matcher.replaceAll("{&#8203;$1")); ``` Output ``` {&#8203;{ interface_ID }} THERE SHOU{&#8203;{interface_ID}}LD BE CODE HERE: {&#8203;{interface_ID}} ```
``` Pattern CURLY_BRACKETS_PLACEHOLDER = Pattern.compile("\\{\\{(.*?)\\}\\}"); Matcher m = CURLY_BRACKETS_PLACEHOLDER.matcher(htmlString); while(m.find()) { String script = m.group(1); String scriptWithPlaceholder = "{{"+script+"}}"; String replacementToken = "{"+ ZERO_WIDTH_SPACE_CHARACTER +"{"+script+"}}"; htmlString = htmlString.replace(scriptWithPlaceholder, replacementToken); } return htmlString; ```
181,623
Does the first syllable rhyme with “glow” or with “how”? It is no use appealing to the Hindi for “Little Frog” or anything else, since Kipling confessed to making it up of whole cloth, as I discovered after asking a local Hindi speaker who drew a total blank. The question comes down to what sound Kipling meant to suggest by the spelling “ow,” which is hard to figure out, given that homograph pairs like “row” (quarrel vs. line of something) and “bow” (loopy knot or gesture of deference) straddle the difference in question. I know Disney’s film made the first syllable rhyme with “glow,” but I concede to Disney no authority in the matter whatsoever. I used to have access to an LP phonograph disk of Boris Karloff reading aloud, which would be better as authority, but alas I cannot remember how he pronounced the name.
2014/07/01
['https://english.stackexchange.com/questions/181623', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/76878/']
It actually appears that the way it is pronounced may be different. The Name [Mowgli](http://en.m.wikipedia.org/wiki/Mowgli#The_Name_Mowgli): > > In the stories, the name Mowgli is said to mean "frog". Kipling made up the name, and it "does not mean 'frog' in any language other than the language of the forest." > > > Kipling stated that the first syllable of "Mowgli" should rhyme with "cow" and is pronounced this way in Britain, while in America and India it is almost always pronounced to rhyme with "go". > > >
Andrew Leach left a comment linking to a [Kipling Society web page](http://www.kiplingsociety.co.uk/rg_junglebook_names.htm) that says > > *This list of names, their meanings, and pronunciation, was provided by Rudyard Kipling as an Author's Note for the definitive Sussex Edition of his works (Vol. X11, pages 471-8).* > > > [...] > > MOWGLI [...] is a name I made up. It does not mean. ‘frog’ in any language that I know of. It is pronounced *Mowglee* (accent on the *Mow*, which rhymes with 'cow'). > > >
41,160,023
I don't get it why is this not working properly: [Fiddle](https://jsfiddle.net/ze5tsgy9/1/) I just want to show the tax amount but it gets `false` results. ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); $("#tax").val(brutto - netto); }); ```
2016/12/15
['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']
Please try following code : ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function () { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); var brutto1 = $("#brutto").val(); $("#tax").val(brutto1 - netto); ``` }); In your code the value of brutto is not updated in variable after new value (natto \* 1.19), so you gets false result. Thanks...
You need to validate the value of `brutto` element is a number before performing operation. the `+` operator is use to convert input to a number. ``` $(document).on('keyup paste', '#netto', function() { var brutto = +$("#brutto").val() || 1; var netto = +$("#netto").val() || 1; brutto = netto * 1.19; $("#brutto").val(brutto); $("#tax").val(brutto - netto); }); ``` This will also be useful since the element is readonly. [Updated Fiddle](https://jsfiddle.net/satpalsingh/ze5tsgy9/5/)
41,160,023
I don't get it why is this not working properly: [Fiddle](https://jsfiddle.net/ze5tsgy9/1/) I just want to show the tax amount but it gets `false` results. ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); $("#tax").val(brutto - netto); }); ```
2016/12/15
['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']
The problem is that you get the brutto value before filling it, the solution is to get `var brutto` after you calculate `$("#brutto").val(netto * 1.19)`: ```js // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var netto = +$("#netto").val(); $("#brutto").val(netto * 1.19); var brutto = +$("#brutto").val(); $("#tax").val(brutto - netto); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label for="brutto">Brutto</label> <input class="form-control" readonly="readonly" name="brutto" type="text" id="brutto"> </div> <div class="form-group"> <label for="tax">Taxes 19%</label> <input class="form-control" readonly="readonly" name="tax" type="text" id="tax"> </div> <div class="form-group"> <label for="netto">Netto</label> <input class="form-control" name="netto" type="text" id="netto"> </div> ```
You need to validate the value of `brutto` element is a number before performing operation. the `+` operator is use to convert input to a number. ``` $(document).on('keyup paste', '#netto', function() { var brutto = +$("#brutto").val() || 1; var netto = +$("#netto").val() || 1; brutto = netto * 1.19; $("#brutto").val(brutto); $("#tax").val(brutto - netto); }); ``` This will also be useful since the element is readonly. [Updated Fiddle](https://jsfiddle.net/satpalsingh/ze5tsgy9/5/)
41,160,023
I don't get it why is this not working properly: [Fiddle](https://jsfiddle.net/ze5tsgy9/1/) I just want to show the tax amount but it gets `false` results. ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); $("#tax").val(brutto - netto); }); ```
2016/12/15
['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']
Please try following code : ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function () { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); var brutto1 = $("#brutto").val(); $("#tax").val(brutto1 - netto); ``` }); In your code the value of brutto is not updated in variable after new value (natto \* 1.19), so you gets false result. Thanks...
Parse you strings to int, change the event to a input type event: ``` $(document).on('input', '#netto', function () { var brutto = parseInt($("#brutto").val()); var netto = parseInt($("#netto").val()); $("#brutto").val(netto * 1.19); $("#tax").val((netto * 1.19) - netto ); }); ``` better if you go with a input type number so you don't have problems with invalid values <https://jsfiddle.net/ze5tsgy9/6/> or: <https://jsfiddle.net/ze5tsgy9/7/> if you want to get rid of NaN when its empty
41,160,023
I don't get it why is this not working properly: [Fiddle](https://jsfiddle.net/ze5tsgy9/1/) I just want to show the tax amount but it gets `false` results. ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); $("#tax").val(brutto - netto); }); ```
2016/12/15
['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']
The problem is that you get the brutto value before filling it, the solution is to get `var brutto` after you calculate `$("#brutto").val(netto * 1.19)`: ```js // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var netto = +$("#netto").val(); $("#brutto").val(netto * 1.19); var brutto = +$("#brutto").val(); $("#tax").val(brutto - netto); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label for="brutto">Brutto</label> <input class="form-control" readonly="readonly" name="brutto" type="text" id="brutto"> </div> <div class="form-group"> <label for="tax">Taxes 19%</label> <input class="form-control" readonly="readonly" name="tax" type="text" id="tax"> </div> <div class="form-group"> <label for="netto">Netto</label> <input class="form-control" name="netto" type="text" id="netto"> </div> ```
Parse you strings to int, change the event to a input type event: ``` $(document).on('input', '#netto', function () { var brutto = parseInt($("#brutto").val()); var netto = parseInt($("#netto").val()); $("#brutto").val(netto * 1.19); $("#tax").val((netto * 1.19) - netto ); }); ``` better if you go with a input type number so you don't have problems with invalid values <https://jsfiddle.net/ze5tsgy9/6/> or: <https://jsfiddle.net/ze5tsgy9/7/> if you want to get rid of NaN when its empty
41,160,023
I don't get it why is this not working properly: [Fiddle](https://jsfiddle.net/ze5tsgy9/1/) I just want to show the tax amount but it gets `false` results. ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); $("#tax").val(brutto - netto); }); ```
2016/12/15
['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']
The problem is that you get the brutto value before filling it, the solution is to get `var brutto` after you calculate `$("#brutto").val(netto * 1.19)`: ```js // calculate brutto and tax $(document).on('keyup paste', '#netto', function() { var netto = +$("#netto").val(); $("#brutto").val(netto * 1.19); var brutto = +$("#brutto").val(); $("#tax").val(brutto - netto); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label for="brutto">Brutto</label> <input class="form-control" readonly="readonly" name="brutto" type="text" id="brutto"> </div> <div class="form-group"> <label for="tax">Taxes 19%</label> <input class="form-control" readonly="readonly" name="tax" type="text" id="tax"> </div> <div class="form-group"> <label for="netto">Netto</label> <input class="form-control" name="netto" type="text" id="netto"> </div> ```
Please try following code : ``` // calculate brutto and tax $(document).on('keyup paste', '#netto', function () { var brutto = $("#brutto").val(); var netto = $("#netto").val(); $("#brutto").val(netto * 1.19); var brutto1 = $("#brutto").val(); $("#tax").val(brutto1 - netto); ``` }); In your code the value of brutto is not updated in variable after new value (natto \* 1.19), so you gets false result. Thanks...
53,911,308
In order to release my App in the Play Store, I had to change the `TargetSdkVersion` from `23` to `26`. Before I changed it, the App worked perfectly! Now the App crashes on start. I figured out, that the problem was at these two lines: ``` prefs = getSharedPreferences("de.bs.quicknoteblock.Notes", Context.MODE_WORLD_WRITEABLE); editor = prefs.edit(); ``` Now my Question is, how I can use `SharedPreferences` with `Api-Level 26`
2018/12/24
['https://Stackoverflow.com/questions/53911308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10828450/']
`Context.MODE_WORLD_WRITEABLE` is deprecated, replace it with `Context.MODE_PRIVATE`
hi I think your problem is the SharedPreferences code please test this way > > (maybe should change Context.MODE\_WORLD\_WRITEABLE to > Context.MODE\_PRIVATE is work ! ) > > > first please download this source code and add your project , [download](http://ufile.io/hapau) so after add you can use SharedPreferences so esay sample code : ``` // class A --- > save text in SharedPreferences new AppPreferenceTools(context, "Share") .savePreferences("test","simple text"); // class B ---> read text as SharedPreferences String text = new AppPreferenceTools(context, "Share").getName("test",defultSTR); ```
66,720,402
I'm trying to retrieve the most recent article on a blog. My current code below does not output anything. ``` {% for article in blogs['myblog'].articles.last %} {{ article.title }} {% endfor %} ```
2021/03/20
['https://Stackoverflow.com/questions/66720402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13262682/']
You don't need a loop in order to access the last item. ``` {% assign article = blogs['myblog'].articles.last %} ``` This will set `article` to the last item. You can then use it as expected. ``` {{ article.title }} ``` Docs: <https://shopify.dev/docs/themes/liquid/reference/filters/array-filters#last>
It can be done like this using [forloop.last](https://shopify.dev/docs/themes/liquid/reference/objects/for-loops#forloop-last): ``` {% for article in blogs['myblog'].articles %} {% if forloop.last == true %} {{ article.title }} {% endif %} {% endfor %} ``` This assumes that `blogs` is a variable. Otherwise, try replacing `blogs['myblog'].articles` with `blog.articles`.
47,354,108
Could you please advise how ``` sudo su - userb ``` translates into ansible ? More specifically, I would like to login to linux server X as `usera` then become `userb` (with the command above), and then execute all the tasks defined in the playbook as `userb` The following are configuration options in `ansible.cfg`: ``` sudo_user = root #ask_sudo_pass = True #ask_pass = True #remote_user = root #become=True #become_method=sudo #become_user=root #become_ask_pass=False ``` An example task would be: ``` - name: "Create the version directory of app" remote_user: userb file: path="{{ app_dir }}/{{ app_version }}" state=directory owner=userb group=xxx ``` EDIT: please note that no sudo password is provided in order to become `userb` ``` usera@serverX:~> sudo su - userb Last login: Fri Nov 17 15:46:48 CET 2017 on pts/1 -bash-4.2$ ```
2017/11/17
['https://Stackoverflow.com/questions/47354108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4035529/']
I do not believe this is possible without adding some extra state and interfaces to your BlockingQueue. Proof goes something like this. You want to wait until the reading thread is blocked on `pop`. But there is no way to distinguish between that and the thread being about to execute the `pop`. This remains true no matter what you put just before or after the call to `pop` itself. If you really want to fix this with 100% reliability, you need to add some state inside the queue, guarded by the queue's mutex, that means "someone is waiting". The `pop` call then has to update that state just before it atomically releases the mutex and goes to sleep on the internal condition variable. The `push` thread can obtain the mutex and wait until "someone is waiting". To avoid a busy loop here, you will want to use the condition variable again. All of this machinery is nearly as complicated as the queue itself, so maybe you will want to test it, too... This sort of multi-threaded code is where concepts like "code coverage" -- and arguably even unit testing itself -- break down a bit. There are just too many possible interleavings of operations. In practice, I would probably go with your original approach of sleeping.
You can use a `std::condition_variable` to accomplish this. The help page of cppreference.com actually shows a very nice cosumer-producer example which should be exactly what you are looking for: <http://en.cppreference.com/w/cpp/thread/condition_variable> EDIT: Actually the german version of cppreference.com has an even better example :-) <http://de.cppreference.com/w/cpp/thread/condition_variable>
47,354,108
Could you please advise how ``` sudo su - userb ``` translates into ansible ? More specifically, I would like to login to linux server X as `usera` then become `userb` (with the command above), and then execute all the tasks defined in the playbook as `userb` The following are configuration options in `ansible.cfg`: ``` sudo_user = root #ask_sudo_pass = True #ask_pass = True #remote_user = root #become=True #become_method=sudo #become_user=root #become_ask_pass=False ``` An example task would be: ``` - name: "Create the version directory of app" remote_user: userb file: path="{{ app_dir }}/{{ app_version }}" state=directory owner=userb group=xxx ``` EDIT: please note that no sudo password is provided in order to become `userb` ``` usera@serverX:~> sudo su - userb Last login: Fri Nov 17 15:46:48 CET 2017 on pts/1 -bash-4.2$ ```
2017/11/17
['https://Stackoverflow.com/questions/47354108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4035529/']
``` template<class T> struct async_queue { T pop() { auto l = lock(); ++wait_count; cv.wait( l, [&]{ return !data.empty(); } ); --wait_count; auto r = std::move(data.front()); data.pop_front(); return r; } void push(T in) { { auto l = lock(); data.push_back( std::move(in) ); } cv.notify_one(); } void push_many(std::initializer_list<T> in) { { auto l = lock(); for (auto&& x: in) data.push_back( x ); } cv.notify_all(); } std::size_t readers_waiting() { return wait_count; } std::size_t data_waiting() const { auto l = lock(); return data.size(); } private: std::queue<T> data; std::condition_variable cv; mutable std::mutex m; std::atomic<std::size_t> wait_count{0}; auto lock() const { return std::unique_lock<std::mutex>(m); } }; ``` or somesuch. In the push thread, busy wait on `readers_waiting` until it passes 1. At which point you have the lock and are within `cv.wait` before the lock is unlocked. Do a `push`. In theory an infinitely slow reader thread could have gotten into `cv.wait` and still be evaluating the first lambda by the time you call `push`, but an infinitely slow reader thread is no different than a blocked one... This does, however, deal with slow thread startup and the like. Using `readers_waiting` and `data_waiting` for anything other than debugging is usually code smell.
You can use a `std::condition_variable` to accomplish this. The help page of cppreference.com actually shows a very nice cosumer-producer example which should be exactly what you are looking for: <http://en.cppreference.com/w/cpp/thread/condition_variable> EDIT: Actually the german version of cppreference.com has an even better example :-) <http://de.cppreference.com/w/cpp/thread/condition_variable>
51,161,348
I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: ``` [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); ``` I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). I attempted to find a similar function in Python (using numpy) and there does not seem to be any. Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? Thanks for your time and help!
2018/07/03
['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']
There is a library called [CVXOPT](https://scaron.info/blog/quadratic-programming-in-python.html) that has quadratic programming in it. ``` def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): qp_G = .5 * (P + P.T) # make sure P is symmetric qp_a = -q if A is not None: qp_C = -numpy.vstack([A, G]).T qp_b = -numpy.hstack([b, h]) meq = A.shape[0] else: # no equality constraint qp_C = -G.T qp_b = -h meq = 0 return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0] ```
[OSQP](https://osqp.org) is a specialized free QP solver based on ADMM. I have adapted the [OSQP documentation demo](http://osqp.org/docs/examples/demo.html) and the OSQP call in the [qpsolvers repository](https://github.com/stephane-caron/qpsolvers/blob/master/qpsolvers/osqp_.py) for your problem. Note that matrices `H` and `G` are supposed to be sparse in [CSC format](http://www.scipy-lectures.org/advanced/scipy_sparse/csc_matrix.html). Here is the script ``` import numpy as np import scipy.sparse as spa import osqp def quadprog(P, q, G=None, h=None, A=None, b=None, initvals=None, verbose=True): l = -np.inf * np.ones(len(h)) if A is not None: qp_A = spa.vstack([G, A]).tocsc() qp_l = np.hstack([l, b]) qp_u = np.hstack([h, b]) else: # no equality constraint qp_A = G qp_l = l qp_u = h model = osqp.OSQP() model.setup(P=P, q=q, A=qp_A, l=qp_l, u=qp_u, verbose=verbose) if initvals is not None: model.warm_start(x=initvals) results = model.solve() return results.x, results.info.status # Generate problem data n = 2 # Variables H = spa.csc_matrix([[4, 1], [1, 2]]) f = np.array([1, 1]) G = spa.csc_matrix([[1, 0], [0, 1]]) h = np.array([0.7, 0.7]) A = spa.csc_matrix([[1, 1]]) b = np.array([1.]) # Initial point q0 = np.ones(n) x, status = quadprog(H, f, G, h, A, b, initvals=q0, verbose=True) ```
51,161,348
I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: ``` [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); ``` I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). I attempted to find a similar function in Python (using numpy) and there does not seem to be any. Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? Thanks for your time and help!
2018/07/03
['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']
There is a library called [CVXOPT](https://scaron.info/blog/quadratic-programming-in-python.html) that has quadratic programming in it. ``` def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): qp_G = .5 * (P + P.T) # make sure P is symmetric qp_a = -q if A is not None: qp_C = -numpy.vstack([A, G]).T qp_b = -numpy.hstack([b, h]) meq = A.shape[0] else: # no equality constraint qp_C = -G.T qp_b = -h meq = 0 return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0] ```
I will start by mentioning that *quadratic programming* problems are a subset of *convex optimization* problems which are a subset of *optimization* problems. There are multiple python packages which solve quadratic programming problems, notably 1. [cvxopt](https://cvxopt.org/userguide/coneprog.html#quadratic-programming) -- which solves all kinds of *convex optimization* problems (including quadratic programming problems). This is a python version of the previous [cvx MATLAB package](http://cvxr.com/cvx/). 2. [quadprog](https://github.com/rmcgibbo/quadprog) -- this is exclusively for quadratic programming problems but doesn't seem to have much documentation. 3. [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) -- this is a very general minimizer which can solve quadratic programming problems, as well as other *optimization* problems (convex and non-convex). You might also benefit from looking at the answers to [this stackoverflow post](https://stackoverflow.com/questions/17009774/quadratic-program-qp-solver-that-only-depends-on-numpy-scipy) which has more details and references. Note: The code snippet in user1911226' answer appears to come from this blog post: <https://scaron.info/blog/quadratic-programming-in-python.html> which compares some of these quadratic programming packages. I can't comment on their answer, but they claim to be mentioning the cvxopt solution, but the code is actually for the quadprog solution.
51,161,348
I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: ``` [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); ``` I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). I attempted to find a similar function in Python (using numpy) and there does not seem to be any. Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? Thanks for your time and help!
2018/07/03
['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']
There is a library called [CVXOPT](https://scaron.info/blog/quadratic-programming-in-python.html) that has quadratic programming in it. ``` def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): qp_G = .5 * (P + P.T) # make sure P is symmetric qp_a = -q if A is not None: qp_C = -numpy.vstack([A, G]).T qp_b = -numpy.hstack([b, h]) meq = A.shape[0] else: # no equality constraint qp_C = -G.T qp_b = -h meq = 0 return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0] ```
You could use the [`solve_qp`](https://scaron.info/doc/qpsolvers/quadratic-programming.html#qpsolvers.solve_qp) function from [qpsolvers](https://github.com/stephane-caron/qpsolvers). It can be installed, along with a starter kit of open source solvers, by `pip install qpsolvers[open_source_solvers]`. Then you can replace your line with: ```py from qpsolvers import solve_qp solver = "proxqp" # or "osqp", "quadprog", "cvxopt", ... x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) ``` There are many solvers available in Python, each coming with their pros and cons. Make sure you try [different values](https://github.com/stephane-caron/qpsolvers#solvers) for the `solver` keyword argument to find the one that fits your problem best. Here is a standalone example based on your question and the other comments: ```py import numpy as np from qpsolvers import solve_qp H = np.array([[4.0, 1.0], [1.0, 2.0]]) f = np.array([1.0, 1]) G = np.array([[1.0, 0.0], [0.0, 1.0]]) h = np.array([0.7, 0.7]) A = np.array([[1.0, 1.0]]) b = np.array([1.0]) q_0 = np.array([1.0, 1.0]) solver = "cvxopt" # or "osqp", "proxqp", "quadprog", ... options = {"verbose": True} x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) ```
51,161,348
I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: ``` [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); ``` I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). I attempted to find a similar function in Python (using numpy) and there does not seem to be any. Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? Thanks for your time and help!
2018/07/03
['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']
[OSQP](https://osqp.org) is a specialized free QP solver based on ADMM. I have adapted the [OSQP documentation demo](http://osqp.org/docs/examples/demo.html) and the OSQP call in the [qpsolvers repository](https://github.com/stephane-caron/qpsolvers/blob/master/qpsolvers/osqp_.py) for your problem. Note that matrices `H` and `G` are supposed to be sparse in [CSC format](http://www.scipy-lectures.org/advanced/scipy_sparse/csc_matrix.html). Here is the script ``` import numpy as np import scipy.sparse as spa import osqp def quadprog(P, q, G=None, h=None, A=None, b=None, initvals=None, verbose=True): l = -np.inf * np.ones(len(h)) if A is not None: qp_A = spa.vstack([G, A]).tocsc() qp_l = np.hstack([l, b]) qp_u = np.hstack([h, b]) else: # no equality constraint qp_A = G qp_l = l qp_u = h model = osqp.OSQP() model.setup(P=P, q=q, A=qp_A, l=qp_l, u=qp_u, verbose=verbose) if initvals is not None: model.warm_start(x=initvals) results = model.solve() return results.x, results.info.status # Generate problem data n = 2 # Variables H = spa.csc_matrix([[4, 1], [1, 2]]) f = np.array([1, 1]) G = spa.csc_matrix([[1, 0], [0, 1]]) h = np.array([0.7, 0.7]) A = spa.csc_matrix([[1, 1]]) b = np.array([1.]) # Initial point q0 = np.ones(n) x, status = quadprog(H, f, G, h, A, b, initvals=q0, verbose=True) ```
You could use the [`solve_qp`](https://scaron.info/doc/qpsolvers/quadratic-programming.html#qpsolvers.solve_qp) function from [qpsolvers](https://github.com/stephane-caron/qpsolvers). It can be installed, along with a starter kit of open source solvers, by `pip install qpsolvers[open_source_solvers]`. Then you can replace your line with: ```py from qpsolvers import solve_qp solver = "proxqp" # or "osqp", "quadprog", "cvxopt", ... x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) ``` There are many solvers available in Python, each coming with their pros and cons. Make sure you try [different values](https://github.com/stephane-caron/qpsolvers#solvers) for the `solver` keyword argument to find the one that fits your problem best. Here is a standalone example based on your question and the other comments: ```py import numpy as np from qpsolvers import solve_qp H = np.array([[4.0, 1.0], [1.0, 2.0]]) f = np.array([1.0, 1]) G = np.array([[1.0, 0.0], [0.0, 1.0]]) h = np.array([0.7, 0.7]) A = np.array([[1.0, 1.0]]) b = np.array([1.0]) q_0 = np.array([1.0, 1.0]) solver = "cvxopt" # or "osqp", "proxqp", "quadprog", ... options = {"verbose": True} x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) ```
51,161,348
I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: ``` [q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); ``` I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). I attempted to find a similar function in Python (using numpy) and there does not seem to be any. Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? Thanks for your time and help!
2018/07/03
['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']
I will start by mentioning that *quadratic programming* problems are a subset of *convex optimization* problems which are a subset of *optimization* problems. There are multiple python packages which solve quadratic programming problems, notably 1. [cvxopt](https://cvxopt.org/userguide/coneprog.html#quadratic-programming) -- which solves all kinds of *convex optimization* problems (including quadratic programming problems). This is a python version of the previous [cvx MATLAB package](http://cvxr.com/cvx/). 2. [quadprog](https://github.com/rmcgibbo/quadprog) -- this is exclusively for quadratic programming problems but doesn't seem to have much documentation. 3. [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) -- this is a very general minimizer which can solve quadratic programming problems, as well as other *optimization* problems (convex and non-convex). You might also benefit from looking at the answers to [this stackoverflow post](https://stackoverflow.com/questions/17009774/quadratic-program-qp-solver-that-only-depends-on-numpy-scipy) which has more details and references. Note: The code snippet in user1911226' answer appears to come from this blog post: <https://scaron.info/blog/quadratic-programming-in-python.html> which compares some of these quadratic programming packages. I can't comment on their answer, but they claim to be mentioning the cvxopt solution, but the code is actually for the quadprog solution.
You could use the [`solve_qp`](https://scaron.info/doc/qpsolvers/quadratic-programming.html#qpsolvers.solve_qp) function from [qpsolvers](https://github.com/stephane-caron/qpsolvers). It can be installed, along with a starter kit of open source solvers, by `pip install qpsolvers[open_source_solvers]`. Then you can replace your line with: ```py from qpsolvers import solve_qp solver = "proxqp" # or "osqp", "quadprog", "cvxopt", ... x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) ``` There are many solvers available in Python, each coming with their pros and cons. Make sure you try [different values](https://github.com/stephane-caron/qpsolvers#solvers) for the `solver` keyword argument to find the one that fits your problem best. Here is a standalone example based on your question and the other comments: ```py import numpy as np from qpsolvers import solve_qp H = np.array([[4.0, 1.0], [1.0, 2.0]]) f = np.array([1.0, 1]) G = np.array([[1.0, 0.0], [0.0, 1.0]]) h = np.array([0.7, 0.7]) A = np.array([[1.0, 1.0]]) b = np.array([1.0]) q_0 = np.array([1.0, 1.0]) solver = "cvxopt" # or "osqp", "proxqp", "quadprog", ... options = {"verbose": True} x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) ```
3,554,426
I've started using [Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx) in all new code I'm writing, such as in a framework library I'm building to help bootstrap [IoC](http://en.wikipedia.org/wiki/Inversion_of_control), [O/RM](http://en.wikipedia.org/wiki/Object-relational_mapping), etc., in an ASP.NET MVC application. I've written a simple build script for this framework library that looks like the following: ``` @echo off echo. echo Cleaning build output (removing 'obj' and 'bin' folders)... for /f "tokens=*" %%G in ('dir /b /ad /s bin') do rmdir /s /q "%%G" for /f "tokens=*" %%G in ('dir /b /ad /s obj') do rmdir /s /q "%%G" rmdir /s /q build echo. echo Starting the build... call "%VS100COMNTOOLS%\vsvars32.bat" msbuild Integration.build /target:Build echo. echo Done! pause ``` This doesn't work. What I end up with in my `build` folder if I run this is, for whatever reason, assemblies that aren't fully rewritten by `ccrewrite` alongside `.pdb.original`, `.rewritten` and `.csproj.FileListAbsolute.txt` files that litter the output directory. What does work is first building the solution in Visual Studio 2010, commenting out line 3 through 7 in the batch file and running it again. I then end up with properly rewritten assemblies and no `.pdb.original` nor `.rewritten` files. What I've deduced from this is that Visual Studio 2010 somehow triggers the Code Contract rewriter properly so the resulting assemblies from the Visual Studio 2010 build is re-used by the command-line MSBuild call, so what my batch script basically does is just copying files to the `build` directory. Rather useless, in other words. I've read [this](https://stackoverflow.com/questions/1209166/why-is-ccrewrite-exe-not-doing-anything-from-the-command-line), but Jon's problem seems different from mine since `ccrewrite` is obviously doing *something*, but it's just not completing the rewriting for whatever reason. The `Integration.build` file builds the correct configuration (that has Code Contracts enabled in the `.csproj` files) and everything else looks right, it just doesn't work properly. So, I'm wondering: How do I run MSBuild the way Visual Studio 2010 is where `ccrewrite` does what it's supposed to and doesn't litter my output directory with `.rewritten` and `.pdb.original` files? Does anyone have a perfect example of how an MSBuild file doing proper Code Contracts rewriting looks like?
2010/08/24
['https://Stackoverflow.com/questions/3554426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61818/']
If you attach a handler to the MouseLeftButtonDown event on the ListView it will only fire when areas outside of a ListViewItem are clicked. Any clicks inside the items will be handled by the items themselves to drive the ListView's selection behavior. You can make changes to the clickable areas by adjusting the Background ({x:Null} is not clickable, anything else is) and Margin of the ListViewItems by setting an ItemContainerStyle on the ListView. Also make sure that you are not using a null Background on the ListView itself (White is the default, Transparent works too).
`ListBoxItem` control handles clicks on ListBox. You should either: * use `PreviewMouseDown` event on ListBox * Add event handler in code via `myListBox.AddHandler` method See **[How to Attach to MouseDown Event on ListBox](http://www.wpfnewbie.com/2010/07/22/how-to-attach-to-mousedown-event-on-listbox/)** for explanation and code examples.
3,554,426
I've started using [Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx) in all new code I'm writing, such as in a framework library I'm building to help bootstrap [IoC](http://en.wikipedia.org/wiki/Inversion_of_control), [O/RM](http://en.wikipedia.org/wiki/Object-relational_mapping), etc., in an ASP.NET MVC application. I've written a simple build script for this framework library that looks like the following: ``` @echo off echo. echo Cleaning build output (removing 'obj' and 'bin' folders)... for /f "tokens=*" %%G in ('dir /b /ad /s bin') do rmdir /s /q "%%G" for /f "tokens=*" %%G in ('dir /b /ad /s obj') do rmdir /s /q "%%G" rmdir /s /q build echo. echo Starting the build... call "%VS100COMNTOOLS%\vsvars32.bat" msbuild Integration.build /target:Build echo. echo Done! pause ``` This doesn't work. What I end up with in my `build` folder if I run this is, for whatever reason, assemblies that aren't fully rewritten by `ccrewrite` alongside `.pdb.original`, `.rewritten` and `.csproj.FileListAbsolute.txt` files that litter the output directory. What does work is first building the solution in Visual Studio 2010, commenting out line 3 through 7 in the batch file and running it again. I then end up with properly rewritten assemblies and no `.pdb.original` nor `.rewritten` files. What I've deduced from this is that Visual Studio 2010 somehow triggers the Code Contract rewriter properly so the resulting assemblies from the Visual Studio 2010 build is re-used by the command-line MSBuild call, so what my batch script basically does is just copying files to the `build` directory. Rather useless, in other words. I've read [this](https://stackoverflow.com/questions/1209166/why-is-ccrewrite-exe-not-doing-anything-from-the-command-line), but Jon's problem seems different from mine since `ccrewrite` is obviously doing *something*, but it's just not completing the rewriting for whatever reason. The `Integration.build` file builds the correct configuration (that has Code Contracts enabled in the `.csproj` files) and everything else looks right, it just doesn't work properly. So, I'm wondering: How do I run MSBuild the way Visual Studio 2010 is where `ccrewrite` does what it's supposed to and doesn't litter my output directory with `.rewritten` and `.pdb.original` files? Does anyone have a perfect example of how an MSBuild file doing proper Code Contracts rewriting looks like?
2010/08/24
['https://Stackoverflow.com/questions/3554426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61818/']
If you attach a handler to the MouseLeftButtonDown event on the ListView it will only fire when areas outside of a ListViewItem are clicked. Any clicks inside the items will be handled by the items themselves to drive the ListView's selection behavior. You can make changes to the clickable areas by adjusting the Background ({x:Null} is not clickable, anything else is) and Margin of the ListViewItems by setting an ItemContainerStyle on the ListView. Also make sure that you are not using a null Background on the ListView itself (White is the default, Transparent works too).
I found if I had previously single clicked on an item in the listview (and thereby selecting it), then next double clicked on the empty space in the listview the undesired result of having the previously selected item being actioned as if it had been double clicked on (rather then the empty space). To get around this I used the following code (vb.net): ``` Private Sub ListView1_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs) Handles ListView1.MouseLeftButtonDown ListView1.SelectedIndex = -1 End Sub ``` with this code in place double clicking on the empty space de-selects any previously selected items and has the desired effect of nothing appearing to happen for the user when they double click in an empty area.
55,584,078
I would like to report progress from a long running PLINQ query. I can't really find any native LINQ method that allows me to do this (as was [implemented](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-plinq-query) for [cancellation](https://learn.microsoft.com/en-us/dotnet/api/system.linq.parallelenumerable.withcancellation?view=netframework-4.7.2)). I have read [this article](http://blog.functionalfun.net/2008/07/reporting-progress-during-linq-queries.html) that shows a neat extension function for a regular serialized query. I have been testing the behavior using the below code. ```c# var progress = new BehaviorSubject<int>(0); DateTime start = DateTime.Now; progress.Subscribe(x => { Console.WriteLine(x); }); Enumerable.Range(1,1000000) //.WithProgressReporting(i => progress.OnNext(i)) //Beginning Progress .AsParallel() .AsOrdered() //.WithProgressReporting(i => progress.OnNext(i)) //Middle Progress reporting .Select(v => { Thread.Sleep(1); return v * v; }) //.WithProgressReporting(i => progress.OnNext(i)) //End Progress Reporting .ToList(); Console.WriteLine("Completed in: " + (DateTime.Now - start).TotalSeconds + " seconds"); ``` Edit: Reporting progress from the **middle** using the `IEnumerable<T>` extension removes the parallelism. Reporting from the **end** does not report any progress while the parallel calculations are being computed then quickly reports all the progress at the very end. I assume this is progress of compiling of the results from the parallel computation into a list. I originally thought the progress reporting from **beginning** was causing the the LINQ to run unparallelized. After sleeping on this, and reading comments from [Peter Duniho](https://stackoverflow.com/questions/55584078/how-can-i-report-progress-from-a-plinq-query#comment97866126_55584078), I see that it is actually working as parallel, but I am getting so many progress reports that handling so many is causing my test/application to slow significantly. Is there a way that is parallel/thread safe to report progress from a PLINQ in increments that allow a user to know progress is being made without having a significant impact on the method runtime?
2019/04/09
['https://Stackoverflow.com/questions/55584078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7371817/']
This answer might not be as elegant, but it gets the job done. When using PLINQ, there are multiple threads processing your collection, so using those threads to **report** progress results in multiple (and out-of-order) progress reports like 0% 1% 5% 4% 3% etc... Instead, we can use those multiple threads to **update** a shared variable storing the progress. In my example, it's a local variable `completed`. We then spawn another thread using `Task.Run()` to report on that progress variable at 0.5s intervals. Extension class: ``` static class Extensions public static ParallelQuery<T> WithProgressReporting<T>(this ParallelQuery<T> sequence, Action increment) { return sequence.Select(x => { increment?.Invoke(); return x; }); } } ``` Code: ``` static void Main(string[] args) { long completed = 0; Task.Run(() => { while (completed < 100000) { Console.WriteLine((completed * 100 / 100000) + "%"); Thread.Sleep(500); } }); DateTime start = DateTime.Now; var output = Enumerable.Range(1, 100000) .AsParallel() .WithProgressReporting(()=>Interlocked.Increment(ref completed)) .Select(v => { Thread.Sleep(1); return v * v; }) .ToList(); Console.WriteLine("Completed in: " + (DateTime.Now - start).TotalSeconds + " seconds"); Console.ReadKey(); } ```
This extension can be positioned either at the start or at the end of the LINQ query. If positioned at the start will start reporting progress immediately, but will erroneously report 100% before the job is done. If positioned at the end will report accurately the end of the query, but will delay reporting progress until the first item of the source has completed. ``` public static ParallelQuery<TSource> WithProgressReporting<TSource>( this ParallelQuery<TSource> source, long itemsCount, IProgress<double> progress) { int countShared = 0; return source.Select(item => { int countLocal = Interlocked.Increment(ref countShared); progress.Report(countLocal / (double)itemsCount); return item; }); } ``` Usage example: ``` // The Progress captures the current SynchronizationContext at construction. var progress = new Progress<double>(); progress.ProgressChanged += (object sender, double e) => { Console.WriteLine($"Progress: {e:0%}"); }; var numbers = Enumerable.Range(1, 10); var sum = numbers .AsParallel() .WithDegreeOfParallelism(3) .WithMergeOptions(ParallelMergeOptions.NotBuffered) .Select(n => { Thread.Sleep(500); return n; }) // Simulate some heavy computation .WithProgressReporting(10, progress) // <--- the extension method .Sum(); Console.WriteLine($"Sum: {sum}"); ``` Output: [![Query output](https://i.stack.imgur.com/gZjY9.png)](https://i.stack.imgur.com/gZjY9.png) There is some jumping because sometimes the worker threads are preempting each other. The [`System.Progress<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.progress-1?view=netframework-4.7.2) class has the nice feature that invokes the `ProgressChanged` event at the captured context (usually the UI thread), so the UI controls can be updated safely. On the other hand in a Console Application the event is invoked on the ThreadPool, that will probably be fully utilized by the parallel query, so the event will fire with some delay (the ThreadPool spawns new threads every 500 msec). This is the reason I limited the parallelism to 3 in the example, to keep a free thread for the reporting of the progress (I have a quad core machine).
39,831,170
I'm using C# and windows forms, i have a group box with 20 labels in it (10 in the top row and 10 in the bottom row). I want to set Text property of these labels based on their location coordinates in the group box. Y co-ordinate of all labels in same row remains same and only X co-ordinate changes. ``` Example locations: label1.Location is (6,16), label2.Location is (33,16) ... label10.Location is (150,16) label11.Location is (6,43), label12.Location is (33,43) ... label20.Location is (150,43) ``` Now originally the label.Text is set as `label_[int a]_[int b]` where `int a` is a number between 1 and 10 to show its "column" number and `int b` is a either 1 *OR* 2 for its "row" number. Now this all works great but I need 60 group boxes each with 20 labels in it and renaming each one is quite a pain, that's why id like to do it this way. The reason its set out like this is because every "column" gets only 1 number in EITHER the top OR bottom row. Now my 1st question is; Is it possible to set the text property by its location property? 2ndly, can the stackoverflow hive mind think of a better/efficient way to do this? NOTE: i have tried loading the labels into a List to try use a loop but that creates complications with selecting the appropriate label. i'm trying to develop a single method that can be used separately on each groupbox. now while this all makes sense in my mind, i don't immediately see what other information i can provide.
2016/10/03
['https://Stackoverflow.com/questions/39831170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6691757/']
This sounds like a good candidate for a User Control to me. Design a user control with the groupbox and labels. Expose the operations you need externally. Possibly a good moment to set naming conventions to something more meaningful to you. Another way could be to generate the labels from code instead of design time like @Kevin says. Crate a method which takes you groupbox and other values you need. Then set label name and location as you want (look at the designer file).
I guess can try a foreach to GroupBox.Controls,and you can check their names inside this foreach too. example: ``` foreach(Label lbl in groupBox1.Controls { if (lbl.Name.Contains("[int_a]_[int_b]")) { lbl.Text = "Label Text"; } } ``` I guess this gives you a base to what you're needing
957,172
Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: ``` SELECT * FROM ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '%Flood%' ``` My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!
2009/06/05
['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']
Access uses different wildcard patterns. In your case, it will be - LIKE '?Flood?' (replace question mark with asterisk). I don't know formatting codes to apply here so that it shows it correctly. See the link for details - <http://www.techonthenet.com/access/queries/like.php>
Use this sintax in access never fails (this is an example) select \* from customer, adress where customer.id = adress.customerId
957,172
Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: ``` SELECT * FROM ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '%Flood%' ``` My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!
2009/06/05
['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']
You will need some parentheses in addition to changing the wild cards: ``` SELECT * FROM (ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID) INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '*Flood*' ``` Note that the asterisk is used in the Access query window and with DAO, percent is used with ADO.
Use this sintax in access never fails (this is an example) select \* from customer, adress where customer.id = adress.customerId
957,172
Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: ``` SELECT * FROM ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '%Flood%' ``` My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!
2009/06/05
['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']
The syntax error is caused because access uses " instead of ' as the string delimiter. As previously mentioned you will also need to change the % wildcards to \*
Use this sintax in access never fails (this is an example) select \* from customer, adress where customer.id = adress.customerId
957,172
Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: ``` SELECT * FROM ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '%Flood%' ``` My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!
2009/06/05
['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']
You will need some parentheses in addition to changing the wild cards: ``` SELECT * FROM (ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID) INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '*Flood*' ``` Note that the asterisk is used in the Access query window and with DAO, percent is used with ADO.
Access uses different wildcard patterns. In your case, it will be - LIKE '?Flood?' (replace question mark with asterisk). I don't know formatting codes to apply here so that it shows it correctly. See the link for details - <http://www.techonthenet.com/access/queries/like.php>
957,172
Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: ``` SELECT * FROM ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '%Flood%' ``` My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!
2009/06/05
['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']
You will need some parentheses in addition to changing the wild cards: ``` SELECT * FROM (ControlPoint INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID) INNER JOIN Site ON Site.SiteID = Project.SiteID WHERE Project.ProjectName LIKE '*Flood*' ``` Note that the asterisk is used in the Access query window and with DAO, percent is used with ADO.
The syntax error is caused because access uses " instead of ' as the string delimiter. As previously mentioned you will also need to change the % wildcards to \*
32,011,014
Consider the following macro: ``` #define FOO(a,b) (--a)* 8 + (--b); ``` Now ``` int graph[8][8] = { 0 }; int *graph_p = &(graph[0][0]); int *p = graph_p + FOO(2, 3); ``` Why do I get the error: > > IntelliSense: expression must be a modifiable lvalue > > >
2015/08/14
['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']
It's because you are passing an *integer constant* to function-like macro `FOO(a, b)`, that applies pre-increment `--` operator to its arguments. The result of this macro expansion looks as: ``` int *p = graph_p + (--2)* 8 + (--3);; ``` which is illegal in C, as operator requires a *modifiable lvalue* as its operand. Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end: ``` #define FOO(a,b) ((--a)* 8 + (--b)) ```
The line ``` int *p = graph_p + FOO(2, 3); ``` will be replaced at compile time by the defined macro as ``` int *p = graph_p + (--2)* 8 + (--3);; ``` the operand of prefix `--` must be an lvalue. `2` and `3` are integer constants and it can't be an operand of prefix `--` operator.
32,011,014
Consider the following macro: ``` #define FOO(a,b) (--a)* 8 + (--b); ``` Now ``` int graph[8][8] = { 0 }; int *graph_p = &(graph[0][0]); int *p = graph_p + FOO(2, 3); ``` Why do I get the error: > > IntelliSense: expression must be a modifiable lvalue > > >
2015/08/14
['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']
The line ``` int *p = graph_p + FOO(2, 3); ``` will be replaced at compile time by the defined macro as ``` int *p = graph_p + (--2)* 8 + (--3);; ``` the operand of prefix `--` must be an lvalue. `2` and `3` are integer constants and it can't be an operand of prefix `--` operator.
`FOO(2,3)` translates to `(--2)* 8 + (--3)` You can only increment/decrement an lvalue, not a number.
32,011,014
Consider the following macro: ``` #define FOO(a,b) (--a)* 8 + (--b); ``` Now ``` int graph[8][8] = { 0 }; int *graph_p = &(graph[0][0]); int *p = graph_p + FOO(2, 3); ``` Why do I get the error: > > IntelliSense: expression must be a modifiable lvalue > > >
2015/08/14
['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']
The line ``` int *p = graph_p + FOO(2, 3); ``` will be replaced at compile time by the defined macro as ``` int *p = graph_p + (--2)* 8 + (--3);; ``` the operand of prefix `--` must be an lvalue. `2` and `3` are integer constants and it can't be an operand of prefix `--` operator.
Try this: ``` Int * p=(int * )(graph-p+FOO(2,3)); ```
32,011,014
Consider the following macro: ``` #define FOO(a,b) (--a)* 8 + (--b); ``` Now ``` int graph[8][8] = { 0 }; int *graph_p = &(graph[0][0]); int *p = graph_p + FOO(2, 3); ``` Why do I get the error: > > IntelliSense: expression must be a modifiable lvalue > > >
2015/08/14
['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']
It's because you are passing an *integer constant* to function-like macro `FOO(a, b)`, that applies pre-increment `--` operator to its arguments. The result of this macro expansion looks as: ``` int *p = graph_p + (--2)* 8 + (--3);; ``` which is illegal in C, as operator requires a *modifiable lvalue* as its operand. Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end: ``` #define FOO(a,b) ((--a)* 8 + (--b)) ```
`FOO(2,3)` translates to `(--2)* 8 + (--3)` You can only increment/decrement an lvalue, not a number.
32,011,014
Consider the following macro: ``` #define FOO(a,b) (--a)* 8 + (--b); ``` Now ``` int graph[8][8] = { 0 }; int *graph_p = &(graph[0][0]); int *p = graph_p + FOO(2, 3); ``` Why do I get the error: > > IntelliSense: expression must be a modifiable lvalue > > >
2015/08/14
['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']
It's because you are passing an *integer constant* to function-like macro `FOO(a, b)`, that applies pre-increment `--` operator to its arguments. The result of this macro expansion looks as: ``` int *p = graph_p + (--2)* 8 + (--3);; ``` which is illegal in C, as operator requires a *modifiable lvalue* as its operand. Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end: ``` #define FOO(a,b) ((--a)* 8 + (--b)) ```
Try this: ``` Int * p=(int * )(graph-p+FOO(2,3)); ```
51,500,657
Is it possible to get substring from right hand hand(Reverse) direction using `substring()` in JAVA. Example. Suppose `String S="abcdef"`, Can I get Substring "fedc" using `S.substring(S.length()-1,3)` ? If it is not correct, please suggest me how to get Substring from right hand end(Reverse direction)??
2018/07/24
['https://Stackoverflow.com/questions/51500657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10128375/']
You could reverse the string and use `substring`. Unfortunately `String` does not have that, but `StringBuilder` has it e.g. ``` new StringBuilder("abcdef").reverse().toString().substring(0,4); ```
You can reverse the string and find the substring ``` // reverse String s = "abcdef"; StringBuilder builder = new StringBuilder(s); String substring = builder.reverse().substring(0,3); ```
51,500,657
Is it possible to get substring from right hand hand(Reverse) direction using `substring()` in JAVA. Example. Suppose `String S="abcdef"`, Can I get Substring "fedc" using `S.substring(S.length()-1,3)` ? If it is not correct, please suggest me how to get Substring from right hand end(Reverse direction)??
2018/07/24
['https://Stackoverflow.com/questions/51500657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10128375/']
You could reverse the string and use `substring`. Unfortunately `String` does not have that, but `StringBuilder` has it e.g. ``` new StringBuilder("abcdef").reverse().toString().substring(0,4); ```
Java doesn't support extension methods like C# does, so I would build a function for this. This way you can control how much of the reverse substring you want with a parameter. ``` public class StackOverflow { public static void main(String[] args) { String data = "abcdef"; for (int i = 0; i < data.length(); i++) { System.out.println(reverseSubstring(data, i+1)); } } public static String reverseSubstring(String data, int length) { return new StringBuilder(data).reverse().substring(0, length); } } ``` Result: ``` f fe fed fedc fedcb fedcba ``` UPDATE ------ Another approach is to create a wrapper class to String. This way you can call a class method like how you're asking in your question with the example `S.substring(S.length()-1,3)`. This will also allow you to still have all the `String` methods after using the wrapper's `get()` method. String Wrapper -------------- ``` public class MyString { private String theString; public MyString(String s) { theString = s; } public String get() { return theString; } public String reverseSubstring(int length) { return new StringBuilder(theString).reverse().substring(0, length); } } ``` Usage ----- ``` public class StackOverflow { public static void main(String[] args) { MyString data = new MyString("abcdef"); for (int i = 0; i < data.get().length(); i++) { System.out.println(data.reverseSubstring(i+1)); } } } ``` Results: ``` f fe fed fedc fedcb fedcba ```
39,452,720
I created a vagrant box using `vagrant package` , uploaded it and released it. Then I did `vagrant init <username>/<box>` which created a Vagrantfile. I even appended the box version to the Vagrantfile. Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: ``` The box you're attempting to add doesn't support the provider you requested. Please find an alternate box or use an alternate provider. Double-check your requested provider to verify you didn't simply misspell it. If you're adding a box from HashiCorp's Atlas, make sure the box is released. ``` I have given virtualbox as the provider and virtual box works fine with other boxes I use.
2016/09/12
['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']
What I figured was that due to some reason vagrant had got corrupted. So doing a fresh install of vagrant did the trick.
Upgrading vagrant version through installing `.deb` version worked for me (download through vagrant website: <https://www.vagrantup.com/downloads> - choose tab "Debian" and install the package)
39,452,720
I created a vagrant box using `vagrant package` , uploaded it and released it. Then I did `vagrant init <username>/<box>` which created a Vagrantfile. I even appended the box version to the Vagrantfile. Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: ``` The box you're attempting to add doesn't support the provider you requested. Please find an alternate box or use an alternate provider. Double-check your requested provider to verify you didn't simply misspell it. If you're adding a box from HashiCorp's Atlas, make sure the box is released. ``` I have given virtualbox as the provider and virtual box works fine with other boxes I use.
2016/09/12
['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']
What I figured was that due to some reason vagrant had got corrupted. So doing a fresh install of vagrant did the trick.
I suffered for 2 hours but I don't want anyone to suffer ;) 1 - **access the terminal (sudo) and, remove vagrant files** $ rm -rf /opt/vagrant $ rm -f /usr/bin/vagrant 2 - **then install it again as it has probably been corrupted.** $ curl -O <https://releases.hashicorp.com/vagrant/2.2.9/vagrant_2.2.9_x86_64.deb> 3 - **install vagrant** $ sudo apt install ./vagrant\_2.2.9\_x86\_64.deb 4 - **confirm by viewing the installed vagrant version** & vagrant --version *be happy*
39,452,720
I created a vagrant box using `vagrant package` , uploaded it and released it. Then I did `vagrant init <username>/<box>` which created a Vagrantfile. I even appended the box version to the Vagrantfile. Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: ``` The box you're attempting to add doesn't support the provider you requested. Please find an alternate box or use an alternate provider. Double-check your requested provider to verify you didn't simply misspell it. If you're adding a box from HashiCorp's Atlas, make sure the box is released. ``` I have given virtualbox as the provider and virtual box works fine with other boxes I use.
2016/09/12
['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']
Make sure you have virtualbox installed if you are using ubuntu. `sudo apt install virtualbox-qt`
Upgrading vagrant version through installing `.deb` version worked for me (download through vagrant website: <https://www.vagrantup.com/downloads> - choose tab "Debian" and install the package)
39,452,720
I created a vagrant box using `vagrant package` , uploaded it and released it. Then I did `vagrant init <username>/<box>` which created a Vagrantfile. I even appended the box version to the Vagrantfile. Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: ``` The box you're attempting to add doesn't support the provider you requested. Please find an alternate box or use an alternate provider. Double-check your requested provider to verify you didn't simply misspell it. If you're adding a box from HashiCorp's Atlas, make sure the box is released. ``` I have given virtualbox as the provider and virtual box works fine with other boxes I use.
2016/09/12
['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']
Make sure you have virtualbox installed if you are using ubuntu. `sudo apt install virtualbox-qt`
I suffered for 2 hours but I don't want anyone to suffer ;) 1 - **access the terminal (sudo) and, remove vagrant files** $ rm -rf /opt/vagrant $ rm -f /usr/bin/vagrant 2 - **then install it again as it has probably been corrupted.** $ curl -O <https://releases.hashicorp.com/vagrant/2.2.9/vagrant_2.2.9_x86_64.deb> 3 - **install vagrant** $ sudo apt install ./vagrant\_2.2.9\_x86\_64.deb 4 - **confirm by viewing the installed vagrant version** & vagrant --version *be happy*
39,452,720
I created a vagrant box using `vagrant package` , uploaded it and released it. Then I did `vagrant init <username>/<box>` which created a Vagrantfile. I even appended the box version to the Vagrantfile. Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: ``` The box you're attempting to add doesn't support the provider you requested. Please find an alternate box or use an alternate provider. Double-check your requested provider to verify you didn't simply misspell it. If you're adding a box from HashiCorp's Atlas, make sure the box is released. ``` I have given virtualbox as the provider and virtual box works fine with other boxes I use.
2016/09/12
['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']
Upgrading vagrant version through installing `.deb` version worked for me (download through vagrant website: <https://www.vagrantup.com/downloads> - choose tab "Debian" and install the package)
I suffered for 2 hours but I don't want anyone to suffer ;) 1 - **access the terminal (sudo) and, remove vagrant files** $ rm -rf /opt/vagrant $ rm -f /usr/bin/vagrant 2 - **then install it again as it has probably been corrupted.** $ curl -O <https://releases.hashicorp.com/vagrant/2.2.9/vagrant_2.2.9_x86_64.deb> 3 - **install vagrant** $ sudo apt install ./vagrant\_2.2.9\_x86\_64.deb 4 - **confirm by viewing the installed vagrant version** & vagrant --version *be happy*
5,043
I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.
2011/01/21
['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']
On OLED, AMOLED and Super AMOLED screens: [Yes](http://techlogg.com/2010/12/ips-vs-amoled-vs-slcd-smartphone-displays-explained/1877) LCD screens: [No](http://techlogg.com/2010/05/black-vs-white-screen-power-consumption-24-more-monitors-tested/17)
This depends on the screen technology. For instance, (it was said that) Android 2.3 Gingerbread has dark theme since Google's latest flagship device Nexus S uses (Super) AMOLED display which consumes less energy when displaying dark color since AMOLED produces its own light and darker color emits less photons. Contrasts with LCD display which uses a backlight (a fixed number of photons) and the LCD crystals filters those colors it needs. The crystals on an LCD displays though, actually consume slightly less power when displaying white since it takes more power to strain the crystal to block more light. Screen color does not affect the backlighting. There are certain display technologies in TVs that tries to give dynamic backlighting by dimming the screen when displaying darker image. I'm not aware of any device that actually ships with that type of screen though.
5,043
I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.
2011/01/21
['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']
This depends on the screen technology. For instance, (it was said that) Android 2.3 Gingerbread has dark theme since Google's latest flagship device Nexus S uses (Super) AMOLED display which consumes less energy when displaying dark color since AMOLED produces its own light and darker color emits less photons. Contrasts with LCD display which uses a backlight (a fixed number of photons) and the LCD crystals filters those colors it needs. The crystals on an LCD displays though, actually consume slightly less power when displaying white since it takes more power to strain the crystal to block more light. Screen color does not affect the backlighting. There are certain display technologies in TVs that tries to give dynamic backlighting by dimming the screen when displaying darker image. I'm not aware of any device that actually ships with that type of screen though.
If your screen has an older standard lcd then this doesn't help at all. The backlight is still shining behind all those darkened pixels. You just can't see it. If you have oled, amoled, super amoled, LED lcd, or I think even plasma then it does help to darken the screen because the light is generated specifically where it is needed. BTW there are fire fox plugins that reformat whatever page you are on to be dark. I don't remember the names, but I needed it when I was living in a studio apartment with my girlfriend and I was up all night on my computer while she was trying to sleep 20 feet away in the same room.
5,043
I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.
2011/01/21
['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']
On OLED, AMOLED and Super AMOLED screens: [Yes](http://techlogg.com/2010/12/ips-vs-amoled-vs-slcd-smartphone-displays-explained/1877) LCD screens: [No](http://techlogg.com/2010/05/black-vs-white-screen-power-consumption-24-more-monitors-tested/17)
If your screen has an older standard lcd then this doesn't help at all. The backlight is still shining behind all those darkened pixels. You just can't see it. If you have oled, amoled, super amoled, LED lcd, or I think even plasma then it does help to darken the screen because the light is generated specifically where it is needed. BTW there are fire fox plugins that reformat whatever page you are on to be dark. I don't remember the names, but I needed it when I was living in a studio apartment with my girlfriend and I was up all night on my computer while she was trying to sleep 20 feet away in the same room.
5,043
I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.
2011/01/21
['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']
On OLED, AMOLED and Super AMOLED screens: [Yes](http://techlogg.com/2010/12/ips-vs-amoled-vs-slcd-smartphone-displays-explained/1877) LCD screens: [No](http://techlogg.com/2010/05/black-vs-white-screen-power-consumption-24-more-monitors-tested/17)
Hey, I just ran a load of test to figure this out. They are vaguely scientific tests! I figured out that I was saving 20% battery by switching to dark wallpaper and dark themed apps. Have a look through my write up, you should be able to work out the saving on your phone: <http://blog.stevemould.com/phone-battery-save-black-wallpaper/>
5,043
I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.
2011/01/21
['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']
Hey, I just ran a load of test to figure this out. They are vaguely scientific tests! I figured out that I was saving 20% battery by switching to dark wallpaper and dark themed apps. Have a look through my write up, you should be able to work out the saving on your phone: <http://blog.stevemould.com/phone-battery-save-black-wallpaper/>
If your screen has an older standard lcd then this doesn't help at all. The backlight is still shining behind all those darkened pixels. You just can't see it. If you have oled, amoled, super amoled, LED lcd, or I think even plasma then it does help to darken the screen because the light is generated specifically where it is needed. BTW there are fire fox plugins that reformat whatever page you are on to be dark. I don't remember the names, but I needed it when I was living in a studio apartment with my girlfriend and I was up all night on my computer while she was trying to sleep 20 feet away in the same room.
3,475,856
$\int\_{x^2+y^2+z^2\le 2(x+y+z)}(x^2+y^2+z^2)\sin z dxdydz$ Can you give me a hint how to start?
2019/12/14
['https://math.stackexchange.com/questions/3475856', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/653945/']
Let us restate, also introducing notations, so that there is nothing more to prove at the end. > > Given is a triangle $\Delta ABC$. We consider intermediate points $A',A''\in BC$, $B',B''\in CA$, $C',C''\in AB$, so that > $$ > \frac{A'C}{BC} = > \frac{B'A}{CA} = > \frac{C'B}{AB} = > \frac 13= > \frac{BA''}{BC} = > \frac{CB''}{CA} = > \frac{AC''}{AB} > \ . > $$ > The **equidistant** parallels > > > * to $AA'$ through $B,A'',A',C$ (one of them being $AA'$, > * to $BB'$ through $C,B'',B',A$ (one of them being $BB'$, > > > determine the points $X,X';Y,Y';Z,Z';S,T,U$ as in the following figure: > [![The 1:3:3 triangle, net construction](https://i.stack.imgur.com/yRKdy.png)](https://i.stack.imgur.com/yRKdy.png) > We have also drawn the mid points $\alpha$, $\beta$, $\gamma$ of the sides of $\Delta ABC$ as orientation, but we do not need them.(Except for the Bonus.) > > > **1.st Claim:** The following quadrilaterals are congruent parallelograms: > $AZ'US$, > $Z'ZBU$, > $YSTY'$, > $SUX'T$, > $Y'TXC$. > > > **2.nd Claim:** The following segments are parallel: > $$ > AY\ \|\ > ZS\ \|\ > SY'\ \|\ > ZU\ \|\ > UT\ \|\ > TC\ \|\ > BX'\ \|\ > X'X\ \ . > $$ > > > In particular > > > * the points $Z',C'',S,Y'$ (and $\beta$) are colinear, > * the points $Z,C',U,T,C$ are colinear, > * the points $B,X',X$ are colinear, > > > so that we can draw solid lines instead of the dotted lines: > [![The 1:3:3 triangle](https://i.stack.imgur.com/LDDWD.png)](https://i.stack.imgur.com/LDDWD.png) > > > The question in the OP follows now easily from the above construction. (The key word is *equidistant parallels* in all three directions.) **Proof:** The first claim is clear, since we have two directions with three equidistant parallels in each one. The equidistance is insured by the fact that a intersecting line is delimited in equal segments, here explicitly $BA''=A''A'=A'C$ and $CB''=B''B'=B'A$. For the second claim, we use the first one and succesively compare triangles built with one side parallel and congruent to $AZ'$, and an other one parallel and congruent to $AS$. We have for instance $\Delta AZ'S\equiv \Delta SYA$, because $AZ'$ is (via $US$) parallel and congruent to $SY$, adn $AS$ is a common side. This gives $AY\| Z'S$. (Congruence also holds for the two segments.) With a similar argument we add one by one the other segments in the parallel chain. $\square$ --- *Bonus:* $\beta$ is for instance on $SY'$ and in fact its mid point, because it is the mid point of the one diagonal $AC$ in the parallelogram $ATCY$, so also of the other diagonal $YT$, which is also one diagonal in the parallelogram $YSTY'$. --- *Note:* If we start with a lattice defined by two directions, make a choice of points $A,B,C$ as in the picture, and vectorially (for instance) also immediately accept that the "third direction works", there is nothing to be shown. But the question in the OP reduces to exactly this aspect. Also the above proof is easy, the only complicated thing is to make sentences that construct, and fix the known data step by step.
Two things : 1) About the equality of the lengths you are asking for, see the recent question [Proof that each of the three cevians is divided in the ratio $1:3:3$](https://math.stackexchange.com/q/3350495) (with, among the answers, one of mine). 2) About the proportion ($1/7$) of areas : Let $A,a$ be the resp. areas of the big and small (red) triangle. In your second figure, the sum of the areas of the 12 (purple) copies of the initial triangle is $12a$. This sum can be computed in a second manner by recognizing 3 parallelograms (one of them is $ABCD$) whose total area is the double of the area of the big triangle **minus the area of the small triangle**, giving the equation : $$12a=2(A-a)$$ which amounts to : > > $$a=\tfrac17A$$ > > > Remarks : 1) The given figure can be connected to one of the figures one finds in this [reference](https://en.wikipedia.org/wiki/Goldberg%E2%80%93Coxeter_construction). 2) A generalization of the $1/7$ triangle is [Routh theorem](https://en.wikipedia.org/wiki/Routh%27s_theorem).
23,575
Back in the 90's I remember watching a late-night movie on one of the networks. The story took place in an arid, post-apocaliptic future. The plot revolved around a little girl who befriended a cyborg killing machine. The cyborg killing machine spent the movie blasting apart a gang of evil cyborgs to protect her, and it seems like he died in the end. It had an old west or samurai vibe to it, and it seemed pretty good for the timeslot it was in. Any ideas what this film might be?
2012/09/18
['https://scifi.stackexchange.com/questions/23575', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/8590/']
Is it by any chance [Screamers](http://www.imdb.com/title/tt0114367/)? The main character is a human soldier (or mercenary, can't remember exactly). He travels trough an arid, desolated post-apocalyptic planet and saves a little girl from cyborg killing machines, and she follows him 'till the end of the movie, when he dies.
I think it might be the film [Cyborg](http://www.imdb.com/title/tt0097138/). > > Gibson Rickenbacker is a hired fighter living in a plague-ravaged apocalyptic America where a plague has infested most of the United States and the rest of the world. In New York City, Gibson encounters a woman named Pearl Prophet. Pearl reveals to Gibson that she is a cyborg who is carrying vital-information for a group of scientists in Atlanta who are working on a cure to the plague and Pearl hires Gibson to escort her back to Atlanta. But Pearl is kidnapped by "Pirates" a murderous gang led by Fender Tremolo, who wants the cure for themselves and they decide to take Pearl to Atlanta themselves. Gibson, joined by a young woman named Nady Simmons, goes in pursuit of Fender and his gang, as Gibson sets out to rescue Pearl, stop Fender and his gang from reaching Atlanta and defeat Fender who slaughtered Gibson's family. (From IMDB) > > >
23,575
Back in the 90's I remember watching a late-night movie on one of the networks. The story took place in an arid, post-apocaliptic future. The plot revolved around a little girl who befriended a cyborg killing machine. The cyborg killing machine spent the movie blasting apart a gang of evil cyborgs to protect her, and it seems like he died in the end. It had an old west or samurai vibe to it, and it seemed pretty good for the timeslot it was in. Any ideas what this film might be?
2012/09/18
['https://scifi.stackexchange.com/questions/23575', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/8590/']
S. Albano, in case you haven't already found the movie, the one you're looking for is [Knights (1993)](http://www.imdb.com/title/tt0107333/ "Knights (1993)") From [Wikipedia](https://en.wikipedia.org/wiki/Knights_(film)): > > The cyborg Gabriel was created to destroy all other cyborgs. He later rescues Nea by killing the cyborg Simon. Gabriel trains Nea to become a cyborg killer and help him. They continue to kill cyborgs until Gabriel is torn in half by one of his targets and taken to the cyborg camp. Nea follows Jacob and challenges the cyborg leader Job to a fight. Finding Gabriel, she straps him to her back and they battle cyborgs until Gabriel can attach a dead cyborg's legs to himself. They pursue Job, but before they can catch him, the Master Builder captures Nea's brother, taking him to Cyborg City. During a battle, Job tells Gabriel that the cyborg population can't be stopped. Job dies moments later. Gabriel and Nea ride off in search of her brother. > > > **Trailer**
Is it by any chance [Screamers](http://www.imdb.com/title/tt0114367/)? The main character is a human soldier (or mercenary, can't remember exactly). He travels trough an arid, desolated post-apocalyptic planet and saves a little girl from cyborg killing machines, and she follows him 'till the end of the movie, when he dies.
23,575
Back in the 90's I remember watching a late-night movie on one of the networks. The story took place in an arid, post-apocaliptic future. The plot revolved around a little girl who befriended a cyborg killing machine. The cyborg killing machine spent the movie blasting apart a gang of evil cyborgs to protect her, and it seems like he died in the end. It had an old west or samurai vibe to it, and it seemed pretty good for the timeslot it was in. Any ideas what this film might be?
2012/09/18
['https://scifi.stackexchange.com/questions/23575', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/8590/']
S. Albano, in case you haven't already found the movie, the one you're looking for is [Knights (1993)](http://www.imdb.com/title/tt0107333/ "Knights (1993)") From [Wikipedia](https://en.wikipedia.org/wiki/Knights_(film)): > > The cyborg Gabriel was created to destroy all other cyborgs. He later rescues Nea by killing the cyborg Simon. Gabriel trains Nea to become a cyborg killer and help him. They continue to kill cyborgs until Gabriel is torn in half by one of his targets and taken to the cyborg camp. Nea follows Jacob and challenges the cyborg leader Job to a fight. Finding Gabriel, she straps him to her back and they battle cyborgs until Gabriel can attach a dead cyborg's legs to himself. They pursue Job, but before they can catch him, the Master Builder captures Nea's brother, taking him to Cyborg City. During a battle, Job tells Gabriel that the cyborg population can't be stopped. Job dies moments later. Gabriel and Nea ride off in search of her brother. > > > **Trailer**
I think it might be the film [Cyborg](http://www.imdb.com/title/tt0097138/). > > Gibson Rickenbacker is a hired fighter living in a plague-ravaged apocalyptic America where a plague has infested most of the United States and the rest of the world. In New York City, Gibson encounters a woman named Pearl Prophet. Pearl reveals to Gibson that she is a cyborg who is carrying vital-information for a group of scientists in Atlanta who are working on a cure to the plague and Pearl hires Gibson to escort her back to Atlanta. But Pearl is kidnapped by "Pirates" a murderous gang led by Fender Tremolo, who wants the cure for themselves and they decide to take Pearl to Atlanta themselves. Gibson, joined by a young woman named Nady Simmons, goes in pursuit of Fender and his gang, as Gibson sets out to rescue Pearl, stop Fender and his gang from reaching Atlanta and defeat Fender who slaughtered Gibson's family. (From IMDB) > > >
10,908,070
I have a dataset with minute by minute GPS coordinates recorded by a persons cellphone. I.e. the dataset has 1440 rows with LON/LAT values. Based on the data I would like a point estimate (lon/lat value) of where the participants home is. Let's assume that home is the single location where they spend most of their time in a given 24h interval. Furthermore, the GPS sensor most of the time has quite high accuracy, however sometimes it is completely off resulting in gigantic outliers. I think the best way to go about this is to treat it as a point process and use 2D density estimation to find the peak. Is there a native way to do this in R? I looked into kde2d (MASS) but this didn't really seem to do the trick. Kde2d creates a 25x25 grid of the data range with density values. However, in my data, the person can easily travel 100 miles or more per day, so these blocks are generally too large of an estimate. I could narrow them down and use a much larger grid but I am sure there must be a better way to get a point estimate.
2012/06/06
['https://Stackoverflow.com/questions/10908070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318752/']
There are "time spent" functions in the `trip` package (I'm the author). You can create objects from the track data that understand the underlying track process over time, and simply process the points assuming straight line segments between fixes. If "home" is where the largest value pixel is, i.e. when you break up all the segments based on the time duration and sum them into cells, then it's easy to find it. A "time spent" grid from the `tripGrid` function is a `SpatialGridDataFrame` with the standard `sp` package classes, and a trip object can be composed of one or many tracks. Using `rgdal` you can easily transform coordinates to an appropriate map projection if lon/lat is not appropriate for your extent, but it makes no difference to the grid/time-spent calculation of line segments. There is a simple `speedfilter` to remove fixes that imply movement that is too fast, but that is very simplistic and can introduce new problems, in general updating or filtering tracks for unlikely movement can be very complicated. (In my experience a basic time spent gridding gets you as good an estimate as many sophisticated models that just open up new complications). The filter works with Cartesian or long/lat coordinates, using tools in `sp` to calculate distances (long/lat is reliable, whereas a poor map projection choice can introduce problems - over short distances like humans on land it's probably no big deal). (The function `tripGrid` calculates the exact components of the straight line segments using `pixellate.psp`, but that detail is hidden in the implementation). In terms of data preparation, `trip` is strict about a sensible sequence of times and will prevent you from creating an object if the data have duplicates, are out of order, etc. There is an example of reading data from a text file in `?trip`, and a very simple example with (really) dummy data is: ``` library(trip) d <- data.frame(x = 1:10, y = rnorm(10), tms = Sys.time() + 1:10, id = gl(1, 5)) coordinates(d) <- ~x+y tr <- trip(d, c("tms", "id")) g <- tripGrid(tr) pt <- coordinates(g)[which.max(g$z), ] image(g, col = c("transparent", heat.colors(16))) lines(tr, col = "black") points(pt[1], pt[2], pch = "+", cex = 2) ``` That dummy track has no overlapping regions, but it shows that finding the max point in "time spent" is simple enough.
How about using the location that minimises the sum squared distance to all the events? This might be close to the supremum of any kernel smoothing if my brain is working right. If your data comprises two clusters (home and work) then I think the location will be in the biggest cluster rather than between them. Its not the same as the simple mean of the x and y coordinates. For an uncertainty on that, jitter your data by whatever your positional uncertainty is (would be great if you had that value from the GPS, otherwise guess - 50 metres?) and recompute. Do that 100 times, do a kernel smoothing of those locations and find the 95% contour. Not rigorous, and I need to experiment with this minimum distance/kernel supremum thing...
10,908,070
I have a dataset with minute by minute GPS coordinates recorded by a persons cellphone. I.e. the dataset has 1440 rows with LON/LAT values. Based on the data I would like a point estimate (lon/lat value) of where the participants home is. Let's assume that home is the single location where they spend most of their time in a given 24h interval. Furthermore, the GPS sensor most of the time has quite high accuracy, however sometimes it is completely off resulting in gigantic outliers. I think the best way to go about this is to treat it as a point process and use 2D density estimation to find the peak. Is there a native way to do this in R? I looked into kde2d (MASS) but this didn't really seem to do the trick. Kde2d creates a 25x25 grid of the data range with density values. However, in my data, the person can easily travel 100 miles or more per day, so these blocks are generally too large of an estimate. I could narrow them down and use a much larger grid but I am sure there must be a better way to get a point estimate.
2012/06/06
['https://Stackoverflow.com/questions/10908070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318752/']
There are "time spent" functions in the `trip` package (I'm the author). You can create objects from the track data that understand the underlying track process over time, and simply process the points assuming straight line segments between fixes. If "home" is where the largest value pixel is, i.e. when you break up all the segments based on the time duration and sum them into cells, then it's easy to find it. A "time spent" grid from the `tripGrid` function is a `SpatialGridDataFrame` with the standard `sp` package classes, and a trip object can be composed of one or many tracks. Using `rgdal` you can easily transform coordinates to an appropriate map projection if lon/lat is not appropriate for your extent, but it makes no difference to the grid/time-spent calculation of line segments. There is a simple `speedfilter` to remove fixes that imply movement that is too fast, but that is very simplistic and can introduce new problems, in general updating or filtering tracks for unlikely movement can be very complicated. (In my experience a basic time spent gridding gets you as good an estimate as many sophisticated models that just open up new complications). The filter works with Cartesian or long/lat coordinates, using tools in `sp` to calculate distances (long/lat is reliable, whereas a poor map projection choice can introduce problems - over short distances like humans on land it's probably no big deal). (The function `tripGrid` calculates the exact components of the straight line segments using `pixellate.psp`, but that detail is hidden in the implementation). In terms of data preparation, `trip` is strict about a sensible sequence of times and will prevent you from creating an object if the data have duplicates, are out of order, etc. There is an example of reading data from a text file in `?trip`, and a very simple example with (really) dummy data is: ``` library(trip) d <- data.frame(x = 1:10, y = rnorm(10), tms = Sys.time() + 1:10, id = gl(1, 5)) coordinates(d) <- ~x+y tr <- trip(d, c("tms", "id")) g <- tripGrid(tr) pt <- coordinates(g)[which.max(g$z), ] image(g, col = c("transparent", heat.colors(16))) lines(tr, col = "black") points(pt[1], pt[2], pch = "+", cex = 2) ``` That dummy track has no overlapping regions, but it shows that finding the max point in "time spent" is simple enough.
In response to spacedman - I am pretty sure least squares won't work. Least squares is best known for bowing to the demands of outliers, without much weighting to things that are "nearby". This is the opposite of what is desired. The bisquare estimator would probably work better, in my opinion - but I have never used it. I think it also requires some tuning. It's more or less like a least squares estimator for a certain distance from 0, and then the weighting is constant beyond that. So once a point becomes an outlier, it's penalty is constant. We don't want outliers to weigh more and more and more as we move away from them, we would rather weigh them constant, and let the optimization focus on better fitting the things in the vicinity of the cluster.
10,908,070
I have a dataset with minute by minute GPS coordinates recorded by a persons cellphone. I.e. the dataset has 1440 rows with LON/LAT values. Based on the data I would like a point estimate (lon/lat value) of where the participants home is. Let's assume that home is the single location where they spend most of their time in a given 24h interval. Furthermore, the GPS sensor most of the time has quite high accuracy, however sometimes it is completely off resulting in gigantic outliers. I think the best way to go about this is to treat it as a point process and use 2D density estimation to find the peak. Is there a native way to do this in R? I looked into kde2d (MASS) but this didn't really seem to do the trick. Kde2d creates a 25x25 grid of the data range with density values. However, in my data, the person can easily travel 100 miles or more per day, so these blocks are generally too large of an estimate. I could narrow them down and use a much larger grid but I am sure there must be a better way to get a point estimate.
2012/06/06
['https://Stackoverflow.com/questions/10908070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318752/']
How about using the location that minimises the sum squared distance to all the events? This might be close to the supremum of any kernel smoothing if my brain is working right. If your data comprises two clusters (home and work) then I think the location will be in the biggest cluster rather than between them. Its not the same as the simple mean of the x and y coordinates. For an uncertainty on that, jitter your data by whatever your positional uncertainty is (would be great if you had that value from the GPS, otherwise guess - 50 metres?) and recompute. Do that 100 times, do a kernel smoothing of those locations and find the 95% contour. Not rigorous, and I need to experiment with this minimum distance/kernel supremum thing...
In response to spacedman - I am pretty sure least squares won't work. Least squares is best known for bowing to the demands of outliers, without much weighting to things that are "nearby". This is the opposite of what is desired. The bisquare estimator would probably work better, in my opinion - but I have never used it. I think it also requires some tuning. It's more or less like a least squares estimator for a certain distance from 0, and then the weighting is constant beyond that. So once a point becomes an outlier, it's penalty is constant. We don't want outliers to weigh more and more and more as we move away from them, we would rather weigh them constant, and let the optimization focus on better fitting the things in the vicinity of the cluster.
13,075
I played a game today where I feel that I had a nice positional advantage (the computer supports my opinion) but I only managed to draw it in the end. This is the position that I consider to be critical: ``` [fen "2bq1r2/1r1np1kp/pp4p1/2pP1pP1/2P1NQ2/3B3P/PP3P2/R3R1K1 w - - 0 1"] ``` I am playing White. Here Black played has just played ...f5 and my following moves were Ng3 and h4 (after Rf7). I still had some advantage at that point according to the computer but I lost it a couple of moves later after some inaccuracies. **What plan should I have followed? What are White ideas to win in this position?**
2015/12/13
['https://chess.stackexchange.com/questions/13075', 'https://chess.stackexchange.com', 'https://chess.stackexchange.com/users/8751/']
Black is very weak on the black squares, on the e file, his e pawn is very weak and his knight and bishop are short of good squares because of his cramped position. You should try and get your knight to f4 and double your rooks on the e file. I would start with Nc3. This also helps against Black's obvious plan to undermine your center and give himself more space with b5. You may need to play a4 at some stage to control b5 but your immediate priority should be to double on the e file. Once you control the e file you want to either win his e pawn or invade on the e file. At the same time your queen can exert more control over black squares in his position, either from h6 or maybe along the long diagonal from b2 or c3.
You should try for a breakthrough on the h file. You will eventually play h5, but you might want to move your king to g2 and double rooks on the file before you push the pawn. Your pieces have better lateral mobility than Black's, which is why you should be thinking of moving your rooks to one end of the board, and finding a way to break through.
13,075
I played a game today where I feel that I had a nice positional advantage (the computer supports my opinion) but I only managed to draw it in the end. This is the position that I consider to be critical: ``` [fen "2bq1r2/1r1np1kp/pp4p1/2pP1pP1/2P1NQ2/3B3P/PP3P2/R3R1K1 w - - 0 1"] ``` I am playing White. Here Black played has just played ...f5 and my following moves were Ng3 and h4 (after Rf7). I still had some advantage at that point according to the computer but I lost it a couple of moves later after some inaccuracies. **What plan should I have followed? What are White ideas to win in this position?**
2015/12/13
['https://chess.stackexchange.com/questions/13075', 'https://chess.stackexchange.com', 'https://chess.stackexchange.com/users/8751/']
Black is very weak on the black squares, on the e file, his e pawn is very weak and his knight and bishop are short of good squares because of his cramped position. You should try and get your knight to f4 and double your rooks on the e file. I would start with Nc3. This also helps against Black's obvious plan to undermine your center and give himself more space with b5. You may need to play a4 at some stage to control b5 but your immediate priority should be to double on the e file. Once you control the e file you want to either win his e pawn or invade on the e file. At the same time your queen can exert more control over black squares in his position, either from h6 or maybe along the long diagonal from b2 or c3.
As stated, White is clearly better here, but it's hard to say if White can force a win in the long run against best play. I like the idea with Nc3 in Brian Towers response a lot, but I'm not sure the idea outlined in that answer is enough to win by itself. I think that you should combine different ideas. As suggested, working on the h-file is not something to scoff at. Combine a pawn march to h6 with a well-timed Qc3, and Black is completely tied down. Use pressure on the e-file to restrict Black even further. Play a4 at the right time to prevent counterplay; or play a3 followed by b4 to break up Black's pawn structure on the queenside! As long as a black pawn is on e7, it will be very difficult to coordinate Black's pieces to deal with the resulting pressure. The more I look at it, the more I like the a3-b4 idea. It's hard to see how Black copes with the pressure. Black may be forced to give up the e7 pawn for nothing.
13,075
I played a game today where I feel that I had a nice positional advantage (the computer supports my opinion) but I only managed to draw it in the end. This is the position that I consider to be critical: ``` [fen "2bq1r2/1r1np1kp/pp4p1/2pP1pP1/2P1NQ2/3B3P/PP3P2/R3R1K1 w - - 0 1"] ``` I am playing White. Here Black played has just played ...f5 and my following moves were Ng3 and h4 (after Rf7). I still had some advantage at that point according to the computer but I lost it a couple of moves later after some inaccuracies. **What plan should I have followed? What are White ideas to win in this position?**
2015/12/13
['https://chess.stackexchange.com/questions/13075', 'https://chess.stackexchange.com', 'https://chess.stackexchange.com/users/8751/']
As stated, White is clearly better here, but it's hard to say if White can force a win in the long run against best play. I like the idea with Nc3 in Brian Towers response a lot, but I'm not sure the idea outlined in that answer is enough to win by itself. I think that you should combine different ideas. As suggested, working on the h-file is not something to scoff at. Combine a pawn march to h6 with a well-timed Qc3, and Black is completely tied down. Use pressure on the e-file to restrict Black even further. Play a4 at the right time to prevent counterplay; or play a3 followed by b4 to break up Black's pawn structure on the queenside! As long as a black pawn is on e7, it will be very difficult to coordinate Black's pieces to deal with the resulting pressure. The more I look at it, the more I like the a3-b4 idea. It's hard to see how Black copes with the pressure. Black may be forced to give up the e7 pawn for nothing.
You should try for a breakthrough on the h file. You will eventually play h5, but you might want to move your king to g2 and double rooks on the file before you push the pawn. Your pieces have better lateral mobility than Black's, which is why you should be thinking of moving your rooks to one end of the board, and finding a way to break through.
7,486,389
Is there any way to call one class's ArrayList onto another class? In class A ArrayList is there, I need to use that ArrayList in class B, Class A is having `AsyncTask` in that I have the Arraylist so I need that in side AsynTask's Arraylist in another class. In class A: ``` public Class A{ public class HomeTask extends AsyncTask<Void,Void,Bundle> { onPreexecute(){} doInbackground(){} postexecute(){} Arraylist joblist(); //------------ My data is here; } } ``` second class: ``` Class B { // I need to use that arraylist here } ```
2011/09/20
['https://Stackoverflow.com/questions/7486389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/954839/']
If you set the language in a view, the error messages will be printed in the selected language: ``` from django.utils.translation import activate activate('de') ```
if you use \_ in your form messages the message will be displayed in the right lang! but if you want to check which lang is running in the template you can use: ``` {% if LANGUAGE_CODE != "ch" %} {% endif %} ``` for more info about using \_ in your form, check this out: <https://docs.djangoproject.com/en/1.3/ref/forms/validation/#form-subclasses-and-modifying-field-errors>
7,486,389
Is there any way to call one class's ArrayList onto another class? In class A ArrayList is there, I need to use that ArrayList in class B, Class A is having `AsyncTask` in that I have the Arraylist so I need that in side AsynTask's Arraylist in another class. In class A: ``` public Class A{ public class HomeTask extends AsyncTask<Void,Void,Bundle> { onPreexecute(){} doInbackground(){} postexecute(){} Arraylist joblist(); //------------ My data is here; } } ``` second class: ``` Class B { // I need to use that arraylist here } ```
2011/09/20
['https://Stackoverflow.com/questions/7486389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/954839/']
**Some quick explanation first:** Your form field errors come from ``` raise forms.ValidationError(_("My Error Message")) ``` In Django (possibly in other places also), it is common to see this: ``` from django.utils.translation import ugettext_lazy as _ ``` This turns the `_` into a `ugettext_lazy`, i.e. the code above is REALLY: ``` raise forms.ValidationError(ugettext_lazy("My Error Message")) ``` but to avoid typing ugettext\_lazy (or your translation function) over and over again, we simply map it to `_`. **Answer to your question** Finally, to answer your question on whether the errors can be shown in Chinese (or other languages). This depends on whether the validation error message is passed into django.utils.translation.ugettext. In the example above, the "My Error Message" would be displayed in Chinese translated if the user's LANGUAGE\_CODE is zh-tw or zh-cn. Below is an example where there would be no translation: ``` raise forms.ValidationError("My Error Message") ``` I highly recommend reading: <https://docs.djangoproject.com/en/1.3/topics/i18n/internationalization/> as there is additional work you will need to do to get the translations to show up properly.
if you use \_ in your form messages the message will be displayed in the right lang! but if you want to check which lang is running in the template you can use: ``` {% if LANGUAGE_CODE != "ch" %} {% endif %} ``` for more info about using \_ in your form, check this out: <https://docs.djangoproject.com/en/1.3/ref/forms/validation/#form-subclasses-and-modifying-field-errors>
5,081,853
A client has asked me to connect to their SVN server to upload (sync) my file changes rather than use FTP. I simply want to connect to the SVN server. Every tutorial I read has something to do with installing SVN server on my local machine - I don't want to install a server, I want to connect to one, pull down the files, replace with my changes, and push them back up. Can someone tell me how to do this? Or is there are very very very basic tutorial out there that explains how? I had never used SVN before this. I'm using Ubuntu 10. Thanks, Chris
2011/02/22
['https://Stackoverflow.com/questions/5081853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/628815/']
Basically you need to install subversion first: ``` sudo apt-get install subversion ``` Then you need to checkout the SVN repository, add your files and commit; that looks similar to this: ``` svn co http://some.url/to/the/repository cd repository-folder cp ../files/from/otherfolder . svn add the/new/files svn commit ```
I'd suggest reading through <http://svnbook.red-bean.com/nightly/en/svn.tour.importing.html> and the next 4-5 pages of that chapter/section to get a good primer on using SVN as a client. You want to check out a working copy to your local machine: `svn checkout <http://host.example.com/svn/repo/trunk> my-working-copy` This will let you modify files on your local machine, and commit them back up to the repository. Make sure to svn update before you svn commit!
5,873,516
I don't get it. I usually install third party software into */usr/local* so libraries are installed into /usr/local/lib and never had problems linking to these libraries. But now it suddenly no longer works: ``` $ gcc -lkaytils -o test test.c /usr/bin/ld.gold.real: error: cannot find -lkaytils /usr/bin/ld.gold.real: /tmp/ccXwCkYk.o: in function main:test.c(.text+0x15): error: undefined reference to 'strCreate' collect2: ld returned 1 exit status ``` When I add the parameter `-L/usr/local/lib` than it works but I never had to use this before. Header files in */usr/local/include* are found without adding `-I/usr/local/include`. I'm using Debian GNU/Linux 6 (Squeeze) which has an entry for */usr/local/lib* in */etc/ld.so.conf.d/libc.conf* by default and the ldconfig cache knows the library I'm trying to use: ``` k@vincent:~$ ldconfig -p | grep kaytils libkaytils.so.0 (libc6,x86-64) => /usr/local/lib/libkaytils.so.0 libkaytils.so (libc6,x86-64) => /usr/local/lib/libkaytils.so ``` So what the heck is going on here? Where can I check which library paths are searched by gcc by default? Maybe something is wrong there.
2011/05/03
['https://Stackoverflow.com/questions/5873516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274473/']
gcc -print-search-dirs will tell you what path the compiler checks. /usr/local/lib is simply not among them, so your compile time linker (in this case the new gold ld from binutils) doesn't find the library while the dynamic one (ld-linux.so which reads the cache written by ldconfig) does. Presumably the builds you've done previously added -L/usr/local/lib as necessary in their makefiles (usually done by a ./configure script), or you installed binaries.
This is probably an issue of environment variables - you have something set that's including /usr/local/include but not /usr/local/lib From the GCC mapage on environment variables ``` CPATH specifies a list of directories to be searched as if speci‐ fied with -I, but after any paths given with -I options on the com‐ mand line. This environment variable is used regardless of which language is being preprocessed. ``` and ``` The value of LIBRARY_PATH is a colon-separated list of directories, much like PATH. When configured as a native compiler, GCC tries the directories thus specified when searching for special linker files, if it can’t find them using GCC_EXEC_PREFIX. Linking using GCC also uses these directories when searching for ordinary libraries for the -l option (but directories specified with -L come first). ``` try "printenv" to see what you have set
55,464,578
Consider the following code: ``` struct A { virtual A& operator+=(const A& other) noexcept = 0; }; void foo_inner(int *p) noexcept { *p += *p; } void foo_virtual_inner(A *p) noexcept { *p += *p; } void foo(int *p) noexcept { return foo_inner(p); } struct Aint : public A { int i; A& operator+=(const A& other) noexcept override final { // No devirtualization of foo_virtual with: i += dynamic_cast<const Aint&>(other).i; // ... nor with: // i += reinterpret_cast<const Aint&>(other).i; return *this; } }; void foo_virtual(Aint *p) noexcept { return foo_virtual_inner(p); } ``` As far as I can tell, both `foo()` and `foo_virtual()` should compile to the same object code. The compiler has all the information it needs to de-virtualize the call to `operator+=` in `foo_virtual_inner()`, when it's called from `foo_virtual`. But - [neither GCC 8.3, nor MSVC 19.10, nor clang 8 do this](https://godbolt.org/z/l0vdFG). Naturally I used the maximum optimization flag (`-O3` or `/Ox`). Why? Is this a bug, or am I missing something? --- clang 8 output: ``` foo(int*): # @foo(int*) shl dword ptr [rdi] ret foo_virtual(Aint*): # @foo_virtual(Aint*) mov rax, qword ptr [rdi] mov rax, qword ptr [rax] mov rsi, rdi jmp rax # TAILCALL ``` GCC 8.3 output: ``` foo(int*): sal DWORD PTR [rdi] ret foo_virtual(Aint*): mov rax, QWORD PTR [rdi] mov rax, QWORD PTR [rax] cmp rax, OFFSET FLAT:Aint::operator+=(A const&) jne .L19 push rbx xor ecx, ecx mov edx, OFFSET FLAT:typeinfo for Aint mov esi, OFFSET FLAT:typeinfo for A mov rbx, rdi call __dynamic_cast test rax, rax je .L20 mov eax, DWORD PTR [rax+8] add DWORD PTR [rbx+8], eax pop rbx ret .L19: mov rsi, rdi jmp rax foo_virtual(Aint*) [clone .cold.1]: .L20: call __cxa_bad_cast ``` MSVC 19.10 output: ``` p$ = 8 void foo(int * __ptr64) PROC ; foo mov eax, DWORD PTR [rcx] add eax, eax mov DWORD PTR [rcx], eax ret 0 void foo(int * __ptr64) ENDP ; foo p$ = 8 void foo_virtual(Aint * __ptr64) PROC ; foo_virtual mov rax, QWORD PTR [rcx] mov rdx, rcx rex_jmp QWORD PTR [rax] void foo_virtual(Aint * __ptr64) ENDP ``` PS - What's the explanation for all of that typeinfo business in the compiled code under GCC?
2019/04/01
['https://Stackoverflow.com/questions/55464578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593077/']
GCC guesses that Aint \*p points to instance of Aint \*p (but does not think this is guaranteed to happen) and therefore it devirtualises speculatively the call to operator+= and the typeinfo checking is an inlined copy of it. -fno-devirtualize-speculatively leads to same code as Clang and MSVC produces. ``` _Z11foo_virtualP4Aint: .LFB4: .cfi_startproc movq (%rdi), %rax movq %rdi, %rsi movq (%rax), %rax jmp *%rax ```
Following @JanHubicka's answer, I've filed a bug against GCC: <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89924> and it's being worked on (!).
55,464,578
Consider the following code: ``` struct A { virtual A& operator+=(const A& other) noexcept = 0; }; void foo_inner(int *p) noexcept { *p += *p; } void foo_virtual_inner(A *p) noexcept { *p += *p; } void foo(int *p) noexcept { return foo_inner(p); } struct Aint : public A { int i; A& operator+=(const A& other) noexcept override final { // No devirtualization of foo_virtual with: i += dynamic_cast<const Aint&>(other).i; // ... nor with: // i += reinterpret_cast<const Aint&>(other).i; return *this; } }; void foo_virtual(Aint *p) noexcept { return foo_virtual_inner(p); } ``` As far as I can tell, both `foo()` and `foo_virtual()` should compile to the same object code. The compiler has all the information it needs to de-virtualize the call to `operator+=` in `foo_virtual_inner()`, when it's called from `foo_virtual`. But - [neither GCC 8.3, nor MSVC 19.10, nor clang 8 do this](https://godbolt.org/z/l0vdFG). Naturally I used the maximum optimization flag (`-O3` or `/Ox`). Why? Is this a bug, or am I missing something? --- clang 8 output: ``` foo(int*): # @foo(int*) shl dword ptr [rdi] ret foo_virtual(Aint*): # @foo_virtual(Aint*) mov rax, qword ptr [rdi] mov rax, qword ptr [rax] mov rsi, rdi jmp rax # TAILCALL ``` GCC 8.3 output: ``` foo(int*): sal DWORD PTR [rdi] ret foo_virtual(Aint*): mov rax, QWORD PTR [rdi] mov rax, QWORD PTR [rax] cmp rax, OFFSET FLAT:Aint::operator+=(A const&) jne .L19 push rbx xor ecx, ecx mov edx, OFFSET FLAT:typeinfo for Aint mov esi, OFFSET FLAT:typeinfo for A mov rbx, rdi call __dynamic_cast test rax, rax je .L20 mov eax, DWORD PTR [rax+8] add DWORD PTR [rbx+8], eax pop rbx ret .L19: mov rsi, rdi jmp rax foo_virtual(Aint*) [clone .cold.1]: .L20: call __cxa_bad_cast ``` MSVC 19.10 output: ``` p$ = 8 void foo(int * __ptr64) PROC ; foo mov eax, DWORD PTR [rcx] add eax, eax mov DWORD PTR [rcx], eax ret 0 void foo(int * __ptr64) ENDP ; foo p$ = 8 void foo_virtual(Aint * __ptr64) PROC ; foo_virtual mov rax, QWORD PTR [rcx] mov rdx, rcx rex_jmp QWORD PTR [rax] void foo_virtual(Aint * __ptr64) ENDP ``` PS - What's the explanation for all of that typeinfo business in the compiled code under GCC?
2019/04/01
['https://Stackoverflow.com/questions/55464578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593077/']
GCC guesses that Aint \*p points to instance of Aint \*p (but does not think this is guaranteed to happen) and therefore it devirtualises speculatively the call to operator+= and the typeinfo checking is an inlined copy of it. -fno-devirtualize-speculatively leads to same code as Clang and MSVC produces. ``` _Z11foo_virtualP4Aint: .LFB4: .cfi_startproc movq (%rdi), %rax movq %rdi, %rsi movq (%rax), %rax jmp *%rax ```
The compiler can't assume that an Aint\* actually points to an Aint object until it sees some operation that would have undefined semantics otherwise, like referring to one of its non-static members. Otherwise it could be the result of reinterpret\_cast from some other pointer type waiting to be reinterpret\_casted back to that type. It seems to me that the standard conversion to A\* should be such an operation, but AFAICT the standard doesn't currently say that. Wording to that effect would need to consider converting to a non-virtual base of an object under construction, which is deliberately allowed.
55,464,578
Consider the following code: ``` struct A { virtual A& operator+=(const A& other) noexcept = 0; }; void foo_inner(int *p) noexcept { *p += *p; } void foo_virtual_inner(A *p) noexcept { *p += *p; } void foo(int *p) noexcept { return foo_inner(p); } struct Aint : public A { int i; A& operator+=(const A& other) noexcept override final { // No devirtualization of foo_virtual with: i += dynamic_cast<const Aint&>(other).i; // ... nor with: // i += reinterpret_cast<const Aint&>(other).i; return *this; } }; void foo_virtual(Aint *p) noexcept { return foo_virtual_inner(p); } ``` As far as I can tell, both `foo()` and `foo_virtual()` should compile to the same object code. The compiler has all the information it needs to de-virtualize the call to `operator+=` in `foo_virtual_inner()`, when it's called from `foo_virtual`. But - [neither GCC 8.3, nor MSVC 19.10, nor clang 8 do this](https://godbolt.org/z/l0vdFG). Naturally I used the maximum optimization flag (`-O3` or `/Ox`). Why? Is this a bug, or am I missing something? --- clang 8 output: ``` foo(int*): # @foo(int*) shl dword ptr [rdi] ret foo_virtual(Aint*): # @foo_virtual(Aint*) mov rax, qword ptr [rdi] mov rax, qword ptr [rax] mov rsi, rdi jmp rax # TAILCALL ``` GCC 8.3 output: ``` foo(int*): sal DWORD PTR [rdi] ret foo_virtual(Aint*): mov rax, QWORD PTR [rdi] mov rax, QWORD PTR [rax] cmp rax, OFFSET FLAT:Aint::operator+=(A const&) jne .L19 push rbx xor ecx, ecx mov edx, OFFSET FLAT:typeinfo for Aint mov esi, OFFSET FLAT:typeinfo for A mov rbx, rdi call __dynamic_cast test rax, rax je .L20 mov eax, DWORD PTR [rax+8] add DWORD PTR [rbx+8], eax pop rbx ret .L19: mov rsi, rdi jmp rax foo_virtual(Aint*) [clone .cold.1]: .L20: call __cxa_bad_cast ``` MSVC 19.10 output: ``` p$ = 8 void foo(int * __ptr64) PROC ; foo mov eax, DWORD PTR [rcx] add eax, eax mov DWORD PTR [rcx], eax ret 0 void foo(int * __ptr64) ENDP ; foo p$ = 8 void foo_virtual(Aint * __ptr64) PROC ; foo_virtual mov rax, QWORD PTR [rcx] mov rdx, rcx rex_jmp QWORD PTR [rax] void foo_virtual(Aint * __ptr64) ENDP ``` PS - What's the explanation for all of that typeinfo business in the compiled code under GCC?
2019/04/01
['https://Stackoverflow.com/questions/55464578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593077/']
Following @JanHubicka's answer, I've filed a bug against GCC: <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89924> and it's being worked on (!).
The compiler can't assume that an Aint\* actually points to an Aint object until it sees some operation that would have undefined semantics otherwise, like referring to one of its non-static members. Otherwise it could be the result of reinterpret\_cast from some other pointer type waiting to be reinterpret\_casted back to that type. It seems to me that the standard conversion to A\* should be such an operation, but AFAICT the standard doesn't currently say that. Wording to that effect would need to consider converting to a non-virtual base of an object under construction, which is deliberately allowed.
53,561,760
I feel dumb as it seems so easy. But I am stuck with this one: I built a scraper which gets me the titles of jobs. Works great but it includes the h1 tags. E.g. it saves the title of a job as: "<*h1>Marketing Manager<*/h1>" I do not know why he does not just take the value within the h1 tag. But secondly, I just tried to strip the tags away by stripping the first 4 and last 5 characters of the title (title(4..-5). Unfortunately no function like strip seems to work (the error tells me its some weird nokogiri class that cannot be stripped). So here is my code, hopefully someone knows a smart solution for my problem: ``` company_career_urls.each do |url| puts "gets job url" # get the specific job url html_file = open(url).read html_doc = Nokogiri::HTML(html_file) i = 0 Vacancy.where(:companyname => "Lillydoo").destroy_all html_doc.search('.job-list-button a').each do |element| i = i+1 if i > 7 else job_url = element.attribute('href').value puts job_url #get the job name and description html_file = open(job_url).read html_doc = Nokogiri::HTML(html_file) job_description = html_doc.search('.inner ul') job_title = html_doc.search('.job-detail-desc h1') #this line seems to be the problem # job_title = job_title_html[4..-6] puts job_title resource_type = "image" type = "upload" version = 1234567890 public_id = "wv7l1o6xwimtfvx2oxdw" format = "jpg" signature = Cloudinary::Utils.api_sign_request({:public_id=>public_id, :version=>version}, Cloudinary.config.api_secret) photo = "#{resource_type}/#{type}/v#{version}/#{public_id}.#{format}##{signature}" vacancy = Vacancy.create(title: job_title, companyname: 'Lillydoo', jobdescription: job_description, photo: photo) end end ```
2018/11/30
['https://Stackoverflow.com/questions/53561760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10075876/']
This gives you a bunch of elements: ``` job_title = html_doc.search('.job-detail-desc h1') ``` This gives you the text of the first one: ``` job_title = html_doc.at('.job-detail-desc h1').text ```
For HTML, a rule of thumb is that documents have `html` and `body` tags, and fragments usually do not. Try to use the `DocumentFragment` class because the text is not a valid HTML or XML document. ``` html_doc = Nokogiri::HTML::DocumentFragment.parse(html_file) ```
53,561,760
I feel dumb as it seems so easy. But I am stuck with this one: I built a scraper which gets me the titles of jobs. Works great but it includes the h1 tags. E.g. it saves the title of a job as: "<*h1>Marketing Manager<*/h1>" I do not know why he does not just take the value within the h1 tag. But secondly, I just tried to strip the tags away by stripping the first 4 and last 5 characters of the title (title(4..-5). Unfortunately no function like strip seems to work (the error tells me its some weird nokogiri class that cannot be stripped). So here is my code, hopefully someone knows a smart solution for my problem: ``` company_career_urls.each do |url| puts "gets job url" # get the specific job url html_file = open(url).read html_doc = Nokogiri::HTML(html_file) i = 0 Vacancy.where(:companyname => "Lillydoo").destroy_all html_doc.search('.job-list-button a').each do |element| i = i+1 if i > 7 else job_url = element.attribute('href').value puts job_url #get the job name and description html_file = open(job_url).read html_doc = Nokogiri::HTML(html_file) job_description = html_doc.search('.inner ul') job_title = html_doc.search('.job-detail-desc h1') #this line seems to be the problem # job_title = job_title_html[4..-6] puts job_title resource_type = "image" type = "upload" version = 1234567890 public_id = "wv7l1o6xwimtfvx2oxdw" format = "jpg" signature = Cloudinary::Utils.api_sign_request({:public_id=>public_id, :version=>version}, Cloudinary.config.api_secret) photo = "#{resource_type}/#{type}/v#{version}/#{public_id}.#{format}##{signature}" vacancy = Vacancy.create(title: job_title, companyname: 'Lillydoo', jobdescription: job_description, photo: photo) end end ```
2018/11/30
['https://Stackoverflow.com/questions/53561760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10075876/']
The issue you're having is that `job_title` is not a simple string; it's a set of node object(s) that match the search. When you print it with `puts`, Ruby is calling `#to_s` on the node set and outputting the "HTML source" of all the nodes. What you need to do is to isolate the node you want an then extract its text content using `#content` (or `#text`). Here's an example: ``` require 'nokogiri' CONTENT = <<'EOT' <html> <body> <h1>Test Heading</h1> </body> </html> EOT html_doc = Nokogiri::HTML(CONTENT) # this returns a set of all matching nodes nodes = html_doc.css('h1') puts nodes.class # --> "Nokogiri::XML::NodeSet" puts nodes # --> "<h1>Test Heading<h1>" # if you know you will only have one, use at_css node = html_doc.at_css('h1') puts node.class # --> "Nokogiri::XML::Element" puts node # --> "<h1>Test Heading</h1>" # to get just the text content inside the node puts node.content # --> "Test Heading" ``` See <https://www.nokogiri.org/tutorials/searching_a_xml_html_document.html>
For HTML, a rule of thumb is that documents have `html` and `body` tags, and fragments usually do not. Try to use the `DocumentFragment` class because the text is not a valid HTML or XML document. ``` html_doc = Nokogiri::HTML::DocumentFragment.parse(html_file) ```
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
Key should be unique in hash map or Dictionary (C#). This case while inserting key itself need to combine name and drink. Giving the solution in C# here. Hope it helps. ``` public class Person { public string Name { get; set; } public string Drink { get; set; } } class Program { static void Main(string[] args) { List<Person> persons = new List<Person>(); persons.Add(new Person() { Name = "Steve", Drink = "Tea" }); persons.Add(new Person() { Name = "Bell", Drink = "Milk" }); persons.Add(new Person() { Name = "Bell", Drink = "Milk" }); persons.Add(new Person() { Name = "Bell", Drink = "Milk" }); persons.Add(new Person() { Name = "Steve", Drink = "Milk" }); Dictionary<string, int> output = new Dictionary<string, int>(); foreach(var p in persons) { string key = p.Name + ":" + p.Drink; if(output.ContainsKey(key)) { output[key]++; } else { output.Add(key,1); } } foreach(var k in output) { string[] split = k.Key.Split(':'); Console.WriteLine(string.Format("{0} {1} {2}", split[0],split[1],k.Value.ToString())); } } } ```
First I would recommend you to take care of your namings. What is really the key in your case is an order not a person (since Steve cola and Steve wine is different you shouldn't name it as person). After that: containsKey will use the hashcode method which will be inherited from the Object class if you don't override it in your class. The Object class's hashcode probably will provide different hashcode for your instances so you should override it in your class e.g. you can create an acceptable hashcode method if you concat the name and beverage (which is your unique identifier for an order) and invoke a hashcode method on that string.
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
You are making a mistake by storing `Person` Object as a Key. You must store the person name, a String as Key and it will work fine. ``` Map<String, Integer> map = new HashMap<>(); for (Person p : persons) { if (map.containsKey(p.getName())) { map.put(p.getName(), map.get(p)+1); } else { map.put(p.getName(),1); } } ```
You have to override equals and hashCode method in Person class. Below is the sample code: ``` class Person { private String name; private String drink; public Person(String name, String drink) { super(); this.name = name; this.drink = drink; } @Override public int hashCode() { return this.getName().hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Person)) { return false; } Person person = (Person) obj; return person.getName().equals(this.name); } ....getters and setters ....toString method } ``` After this, if you try to run your code it will work for sure for me output for below code was ``` Map<Person, Integer> map = new HashMap<>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } for(Map.Entry<Person, Integer> person : map.entrySet()){ System.out.println(person.getKey()+" "+person.getValue()); } ``` Output: ``` Person [name=Steve, drink=wine] 2 Person [name=Ben, drink=cola] 3 Person [name=Frank, drink=wine] 2 ``` Hope it will help you.
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
Overwrite hashcode and equals method in your Person class
You are making a mistake by storing `Person` Object as a Key. You must store the person name, a String as Key and it will work fine. ``` Map<String, Integer> map = new HashMap<>(); for (Person p : persons) { if (map.containsKey(p.getName())) { map.put(p.getName(), map.get(p)+1); } else { map.put(p.getName(),1); } } ```
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
If you can use Java 8 streams here is one clever solution : ``` List<Person> people = Arrays.asList(new Person("Steve", "wine"), new Person("Steve", "cola"), new Person("Ben", "cola"), new Person("Ben", "cola"), new Person("Steve", "wine"), new Person("Steve", "wine")); Map<Person, Long> map = people.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); ``` **Edit :** To decrease the code you can import the methods statically like this: ``` import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.counting; import static java.util.function.Function.identity; ``` and then the code look like this: ``` Map<Person, Long> map = people .stream() .collect(groupingBy(identity(), counting())); ```
Overwrite hashcode and equals method in your Person class
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
Overwrite hashcode and equals method in your Person class
You have to override equals and hashCode method in Person class. Below is the sample code: ``` class Person { private String name; private String drink; public Person(String name, String drink) { super(); this.name = name; this.drink = drink; } @Override public int hashCode() { return this.getName().hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Person)) { return false; } Person person = (Person) obj; return person.getName().equals(this.name); } ....getters and setters ....toString method } ``` After this, if you try to run your code it will work for sure for me output for below code was ``` Map<Person, Integer> map = new HashMap<>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } for(Map.Entry<Person, Integer> person : map.entrySet()){ System.out.println(person.getKey()+" "+person.getValue()); } ``` Output: ``` Person [name=Steve, drink=wine] 2 Person [name=Ben, drink=cola] 3 Person [name=Frank, drink=wine] 2 ``` Hope it will help you.
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
Overwrite hashcode and equals method in your Person class
Key should be unique in hash map or Dictionary (C#). This case while inserting key itself need to combine name and drink. Giving the solution in C# here. Hope it helps. ``` public class Person { public string Name { get; set; } public string Drink { get; set; } } class Program { static void Main(string[] args) { List<Person> persons = new List<Person>(); persons.Add(new Person() { Name = "Steve", Drink = "Tea" }); persons.Add(new Person() { Name = "Bell", Drink = "Milk" }); persons.Add(new Person() { Name = "Bell", Drink = "Milk" }); persons.Add(new Person() { Name = "Bell", Drink = "Milk" }); persons.Add(new Person() { Name = "Steve", Drink = "Milk" }); Dictionary<string, int> output = new Dictionary<string, int>(); foreach(var p in persons) { string key = p.Name + ":" + p.Drink; if(output.ContainsKey(key)) { output[key]++; } else { output.Add(key,1); } } foreach(var k in output) { string[] split = k.Key.Split(':'); Console.WriteLine(string.Format("{0} {1} {2}", split[0],split[1],k.Value.ToString())); } } } ```
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
If you can use Java 8 streams here is one clever solution : ``` List<Person> people = Arrays.asList(new Person("Steve", "wine"), new Person("Steve", "cola"), new Person("Ben", "cola"), new Person("Ben", "cola"), new Person("Steve", "wine"), new Person("Steve", "wine")); Map<Person, Long> map = people.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); ``` **Edit :** To decrease the code you can import the methods statically like this: ``` import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.counting; import static java.util.function.Function.identity; ``` and then the code look like this: ``` Map<Person, Long> map = people .stream() .collect(groupingBy(identity(), counting())); ```
First I would recommend you to take care of your namings. What is really the key in your case is an order not a person (since Steve cola and Steve wine is different you shouldn't name it as person). After that: containsKey will use the hashcode method which will be inherited from the Object class if you don't override it in your class. The Object class's hashcode probably will provide different hashcode for your instances so you should override it in your class e.g. you can create an acceptable hashcode method if you concat the name and beverage (which is your unique identifier for an order) and invoke a hashcode method on that string.
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
You are making a mistake by storing `Person` Object as a Key. You must store the person name, a String as Key and it will work fine. ``` Map<String, Integer> map = new HashMap<>(); for (Person p : persons) { if (map.containsKey(p.getName())) { map.put(p.getName(), map.get(p)+1); } else { map.put(p.getName(),1); } } ```
Overriding **equals** and **hascode** method in your **Person** class is the solution for your problem. assuming you have Person class with parameter **name** and **drink** , then you could use some IDE like eclipse to generate hashcode and equals method for you see below code: ``` public class Person { private String name; private String drink; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDrink() { return drink; } public void setDrink(String drink) { this.drink = drink; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((drink == null) ? 0 : drink.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (drink == null) { if (other.drink != null) return false; } else if (!drink.equals(other.drink)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } ```
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
You have to override equals and hashCode method in Person class. Below is the sample code: ``` class Person { private String name; private String drink; public Person(String name, String drink) { super(); this.name = name; this.drink = drink; } @Override public int hashCode() { return this.getName().hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Person)) { return false; } Person person = (Person) obj; return person.getName().equals(this.name); } ....getters and setters ....toString method } ``` After this, if you try to run your code it will work for sure for me output for below code was ``` Map<Person, Integer> map = new HashMap<>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } for(Map.Entry<Person, Integer> person : map.entrySet()){ System.out.println(person.getKey()+" "+person.getValue()); } ``` Output: ``` Person [name=Steve, drink=wine] 2 Person [name=Ben, drink=cola] 3 Person [name=Frank, drink=wine] 2 ``` Hope it will help you.
First I would recommend you to take care of your namings. What is really the key in your case is an order not a person (since Steve cola and Steve wine is different you shouldn't name it as person). After that: containsKey will use the hashcode method which will be inherited from the Object class if you don't override it in your class. The Object class's hashcode probably will provide different hashcode for your instances so you should override it in your class e.g. you can create an acceptable hashcode method if you concat the name and beverage (which is your unique identifier for an order) and invoke a hashcode method on that string.
46,169,229
I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): ``` Steve wine Steve cola Ben cola Frank wine Ben cola Ben cola Frank wine ``` In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: ``` Steve wine 1 Steve cola 1 Ben cola 3 Frank wine 2 ``` My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. ``` Map<Person, Integer> map = new HashMap<Person, Integer>(); for (Person p : persons) { if (map.containsKey(p)) { map.put(p, map.get(p)+1); } else { map.put(p,1); } } ``` It doesn't work. It just returns me the result like this: ``` Steve wine 1 Steve cola 1 Ben cola 1 Frank wine 1 Ben cola 1 Ben cola 1 Frank wine 1 ``` So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!
2017/09/12
['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']
Overwrite hashcode and equals method in your Person class
``` int count = Collections.frequency("your collection", "Your Value"); ``` I meant to say like that: ``` ArrayList<String> list = new ArrayList<>(); list.add("Steve wine"); list.add("Steve cola"); list.add("Ben cola"); list.add("Frank wine"); list.add("Ben cola"); list.add("Ben cola"); list.add("Frank wine"); System.out.println(Collections.frequency(list, "Steve wine")); System.out.println(Collections.frequency(list, "Ben cola")); ```