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
|
---|---|---|---|---|---|
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | Here are some GIS developer blogs (python included):
[Another GIS Blog](http://anothergisblog.blogspot.com/feeds/posts/default)
[ArcGIS & Python](http://arcgisandpython.blogspot.com/feeds/posts/default)
[Dave Bouwman](http://blog.davebouwman.com/feed/)
[Café Python](http://arcpy.wordpress.com/feed/)
[CGarrad](http://blog.cgarrard.com/feeds/posts/default)
[Dll Shepherd.Net](http://www.dllshepherd.net/feeds/posts/default)
[GIS Solved](http://gissolved.blogspot.com/feeds/posts/default)
[Guerilla GIS](http://www.redtrails.com/blog/?feed=rss2)
[Nerd tips for things you probably won't use](http://justinberke.blogspot.com/feeds/posts/default)
[Node Dangles](http://nodedangles.wordpress.com/feed/) | A few more GIS developer blogs:
<http://www.spatiallyadjusted.com/>
<http://wiki.gis.com/wiki/index.php/List_of_GIS-related_Blogs> |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | and here are the new ones for Python 2.7:
<http://arcpy.wordpress.com/>
<http://docs.python.org/tutorial/> | This guy has some great stuff on the ESRI Javascript API. Not sure what kind of development you're doing, but if it's JS, this is a must read!
<http://odoe.net/blog/> |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | To read relevant Open Source GIS blogs in an integrated way, visit <http://planet.osgeo.org/>
It aggregates more than 120 blogs, among them many developers' blogs (Tip: use j/k keys to navigate easily). | This guy has some great stuff on the ESRI Javascript API. Not sure what kind of development you're doing, but if it's JS, this is a must read!
<http://odoe.net/blog/> |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | To read relevant Open Source GIS blogs in an integrated way, visit <http://planet.osgeo.org/>
It aggregates more than 120 blogs, among them many developers' blogs (Tip: use j/k keys to navigate easily). | Not always GIS/Map related, but still interesting nonetheless. It's written by a few developers at the New York Times and focuses more on design and prototyping of interactive maps and graphics, and not necessarily GIS applications. Seeing their processes has been really helpful to me. They also use R a lot for spatial stuff, which is cool.
[Chartsnthings](http://chartsnthings.tumblr.com/) |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | Few from my side, mostly out of ESRI world:
* [CARTODB](http://blog.cartodb.com/)
* [MapBox](http://developmentseed.org/blog/mapbox/)
* [OPENGEO](http://blog.opengeo.org/)
* [Linfiniti Geo Blog](http://linfiniti.com/)
* [Smathermather's Weblog](http://smathermather.wordpress.com/)
* [GISTUTOR](http://www.gistutor.com/)
* [Open Source Computing and GIS in the UK](http://www.archaeogeek.com/)
* [Google Geo Developers](http://googlegeodevelopers.blogspot.ch/) | This guy has some great stuff on the ESRI Javascript API. Not sure what kind of development you're doing, but if it's JS, this is a must read!
<http://odoe.net/blog/> |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | Not always GIS/Map related, but still interesting nonetheless. It's written by a few developers at the New York Times and focuses more on design and prototyping of interactive maps and graphics, and not necessarily GIS applications. Seeing their processes has been really helpful to me. They also use R a lot for spatial stuff, which is cool.
[Chartsnthings](http://chartsnthings.tumblr.com/) | This guy has some great stuff on the ESRI Javascript API. Not sure what kind of development you're doing, but if it's JS, this is a must read!
<http://odoe.net/blog/> |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | Few from my side, mostly out of ESRI world:
* [CARTODB](http://blog.cartodb.com/)
* [MapBox](http://developmentseed.org/blog/mapbox/)
* [OPENGEO](http://blog.opengeo.org/)
* [Linfiniti Geo Blog](http://linfiniti.com/)
* [Smathermather's Weblog](http://smathermather.wordpress.com/)
* [GISTUTOR](http://www.gistutor.com/)
* [Open Source Computing and GIS in the UK](http://www.archaeogeek.com/)
* [Google Geo Developers](http://googlegeodevelopers.blogspot.ch/) | A few more GIS developer blogs:
<http://www.spatiallyadjusted.com/>
<http://wiki.gis.com/wiki/index.php/List_of_GIS-related_Blogs> |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | Here are some GIS developer blogs (python included):
[Another GIS Blog](http://anothergisblog.blogspot.com/feeds/posts/default)
[ArcGIS & Python](http://arcgisandpython.blogspot.com/feeds/posts/default)
[Dave Bouwman](http://blog.davebouwman.com/feed/)
[Café Python](http://arcpy.wordpress.com/feed/)
[CGarrad](http://blog.cgarrard.com/feeds/posts/default)
[Dll Shepherd.Net](http://www.dllshepherd.net/feeds/posts/default)
[GIS Solved](http://gissolved.blogspot.com/feeds/posts/default)
[Guerilla GIS](http://www.redtrails.com/blog/?feed=rss2)
[Nerd tips for things you probably won't use](http://justinberke.blogspot.com/feeds/posts/default)
[Node Dangles](http://nodedangles.wordpress.com/feed/) | To read relevant Open Source GIS blogs in an integrated way, visit <http://planet.osgeo.org/>
It aggregates more than 120 blogs, among them many developers' blogs (Tip: use j/k keys to navigate easily). |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | A few more GIS developer blogs:
<http://www.spatiallyadjusted.com/>
<http://wiki.gis.com/wiki/index.php/List_of_GIS-related_Blogs> | This guy has some great stuff on the ESRI Javascript API. Not sure what kind of development you're doing, but if it's JS, this is a must read!
<http://odoe.net/blog/> |
32,293 | I'm looking for recommendations for GIS blogs ... specifically GIS *developer* blogs. I'm less interested in the geography than in how apps are put together.
I'd like to keep up with ESRI ArcGIS as well as open source tools.
Which blogs are you fine people reading? | 2012/08/27 | ['https://gis.stackexchange.com/questions/32293', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/9795/'] | Here are some GIS developer blogs (python included):
[Another GIS Blog](http://anothergisblog.blogspot.com/feeds/posts/default)
[ArcGIS & Python](http://arcgisandpython.blogspot.com/feeds/posts/default)
[Dave Bouwman](http://blog.davebouwman.com/feed/)
[Café Python](http://arcpy.wordpress.com/feed/)
[CGarrad](http://blog.cgarrard.com/feeds/posts/default)
[Dll Shepherd.Net](http://www.dllshepherd.net/feeds/posts/default)
[GIS Solved](http://gissolved.blogspot.com/feeds/posts/default)
[Guerilla GIS](http://www.redtrails.com/blog/?feed=rss2)
[Nerd tips for things you probably won't use](http://justinberke.blogspot.com/feeds/posts/default)
[Node Dangles](http://nodedangles.wordpress.com/feed/) | This guy has some great stuff on the ESRI Javascript API. Not sure what kind of development you're doing, but if it's JS, this is a must read!
<http://odoe.net/blog/> |
40,102,145 | How can I add a menu-icon when I scale a page down below 769px?
I added a button a one page site that I am developing in order to display the menu on mobile devices.
Used this in jquery:
```
if($(window).width() < 769){
$('html').append('<i class="fa fa-bars menu-icon" aria-hidden="true"></i>');
}
```
The menu shows up if initially start the site with a window of size below 769px..but if I load the page on a big screen and try to resize the window to a width below 769,the menu-icon does not show up immediately.Instead I have to refresh the page for it to appear.
Thanks in advance | 2016/10/18 | ['https://Stackoverflow.com/questions/40102145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6354757/'] | Because the script you run just runs once... on page load I guess. Why would it react on resizing the window? You dont specify that in your script.
Its far easier to just add the icon in the original html and display/ hide it with [css media queries](https://developer.mozilla.org/de/docs/Web/CSS/Media_Queries/Using_media_queries):
```
.menu-icon { display: none; }
@media (max-width: 768px) {
.menu-icon { display: block; }
}
```
Its also possible to [detect mobile devices via css](https://stackoverflow.com/questions/14942081/detect-if-a-browser-in-a-mobile-device-ios-android-phone-tablet-is-used), not just based on the window width. | You have to put your code inside `$(window).resize()` like follows so that whenever page size gets modified; the handler will get invoked and you can run your logic accordingly:
```
$('html').append('<i class="fa fa-bars menu-icon" aria-hidden="true"></i>'); //append the icon to html
$("i.fa-bars.menu-icon").hide(); //hide it initially
$(window).resize(function() {
if($(window).width() < 769){
$("i.fa-bars.menu-icon").show(); //show it on mobile view
}
else
{
$("i.fa-bars.menu-icon").hide(); //hide it on bigger screen
}
}).trigger('resize');//firing the resize immediately
``` |
55,231,329 | So I am using lua and splitting a string by spaces to write a sort of sub-language. And I am trying to have it not split anything inside parenthesis, I am already at the stage where I can detect whether there is parenthesis. But I want to reverse the gmatching of the string inside the parenthesis as I want to preserve the string contained within.
```
local function split(strng)
local __s={}
local all_included={}
local flag_table={}
local uncompiled={}
local flagged=false
local flagnum=0
local c=0
for i in string.gmatch(strng,'%S+') do
c=c+1
table.insert(all_included,i)
if(flagged==false)then
if(string.find(i,'%('or'%['or'%{'))then
flagged=true
flag_table[tostring(c)]=1
table.insert(uncompiled,i)
print'flagged'
else
table.insert(__s,i)
end
elseif(flagged==true)then
table.insert(uncompiled,i)
if(string.find(i,'%)' or '%]' or '%}'))then
flagged=false
local __=''
for i=1,#uncompiled do
__=__ .. uncompiled[i]
end
table.insert(__s,__)
print'unflagged'
end
end
end
return __s;
end
```
This is my splitting code | 2019/03/18 | ['https://Stackoverflow.com/questions/55231329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7307551/'] | I would just not use `gmatch` for this at all.
```
local input = " this is a string (containg some (well, many) annoying) parentheses and should be split. The string contains double spaces. What should be done? And what about trailing spaces? "
local pos = 1
local words = {}
local last_start = pos
while pos <= #input do
local char = string.byte(input, pos)
if char == string.byte(" ") then
table.insert(words, string.sub(input, last_start, pos - 1))
last_start = pos + 1
elseif char == string.byte("(") then
local depth = 1
while depth ~= 0 and pos + 1 < #input do
local char = string.byte(input, pos + 1)
if char == string.byte(")") then
depth = depth - 1
elseif char == string.byte("(") then
depth = depth + 1
end
pos = pos + 1
end
end
pos = pos + 1
end
table.insert(words, string.sub(input, last_start))
for k, v in pairs(words) do
print(k, "'" .. v .. "'")
end
```
Output:
```
1 ''
2 'this'
3 'is'
4 'a'
5 'string'
6 '(containg some (well, many) annoying)'
7 'parentheses'
8 'and'
9 'should'
10 'be'
11 'split.'
12 'The'
13 'string'
14 'contains'
15 ''
16 'double'
17 ''
18 ''
19 'spaces.'
20 'What'
21 'should'
22 'be'
23 'done?'
24 'And'
25 'what'
26 'about'
27 'trailing'
28 'spaces?'
29 ''
```
Thinking about trailing spaces and other such problems is left as an exercise for the reader. I tried to highlight some of the possible problems with the example that I used. Also, I only looked at one kind of parenthesis since I do not want to think how `this (string} should be ]parsed`.
Oh and if nested parenthesis are not a concerned: Most of the code above can be replaced with a call to `string.find(input, ")", pos, true)` to find the closing parenthesis.
Please note that you cannot `or` or `and` patterns as attempted in your code.
`"%(" or "%["` equals `"%("`
Lua will interpret that expression left to right. `"%(` is a true value Lua will reduce the expression to `"%("`, which logically is the same as the full expression.
So `string.find(i,'%('or'%['or'%{')` will only find `(`'s in `i`. | As a similar but slightly different approach to Uli's answer, I would first split by parentheses. Then you can split the the ***odd***-numbered fields on whitespace:
```
split = require("split") -- https://luarocks.org/modules/telemachus/split
split__by_parentheses = function(input)
local fields = {}
local level = 0
local field = ""
for i = 1, #input do
local char = input:sub(i, i)
if char == "(" then
if level == 0 then
-- add non-parenthesized field to list
fields[#fields+1] = field
field = ""
end
level = level + 1
end
field = field .. char
if char == ")" then
level = level - 1
assert(level >= 0, 'Mismatched parentheses')
if level == 0 then
-- add parenthesized field to list
fields[#fields+1] = field
field = ""
end
end
end
assert(level == 0, 'Mismatched parentheses')
fields[#fields+1] = field
return fields
end
input = " this is a string (containg some (well, many) annoying) parentheses and should be split. The string contains double spaces. What should be done? And what about trailing spaces? "
fields = split__by_parentheses(input)
for i, field in ipairs(fields) do
print(("%d\t'%s'"):format(i, field))
if i % 2 == 1 then
for j, word in ipairs(split.split(field)) do
print(("\t%d\t%s"):format(j, word))
end
end
end
```
outputs
```
1 ' this is a string '
1
2 this
3 is
4 a
5 string
6
2 '(containg some (well, many) annoying)'
3 ' parentheses and should be split. The string contains double spaces. What should be done? And what about trailing spaces? '
1
2 parentheses
3 and
4 should
5 be
6 split.
7 The
8 string
9 contains
10 double
11 spaces.
12 What
13 should
14 be
15 done?
16 And
17 what
18 about
19 trailing
20 spaces?
21
``` |
13,308,555 | May i know, how to open an ios application, on tapping on notification.
Or when we swipe an icon (in case when iphone is locked.) of notification?
Can anyone please help me out here? | 2012/11/09 | ['https://Stackoverflow.com/questions/13308555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232153/'] | It's automatically open the app. Apple do the stuff for us. We don't need to code anything for open the app. | On pressing the local notification, app launches automatically. |
13,308,555 | May i know, how to open an ios application, on tapping on notification.
Or when we swipe an icon (in case when iphone is locked.) of notification?
Can anyone please help me out here? | 2012/11/09 | ['https://Stackoverflow.com/questions/13308555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232153/'] | The OS handles the behavior when tapping the notification as it comes in. Doesn't matter if it is sent by a 3rd party or not, if it is going through APNS, it will open the application and inside `applicationDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions` :
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (launchOptions != nil) {
// Launched from push notification
NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
}
}
```
If the app happens to be already open when the notification comes in the OS will fire the delegate method:
```
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Do something
}
``` | It's automatically open the app. Apple do the stuff for us. We don't need to code anything for open the app. |
13,308,555 | May i know, how to open an ios application, on tapping on notification.
Or when we swipe an icon (in case when iphone is locked.) of notification?
Can anyone please help me out here? | 2012/11/09 | ['https://Stackoverflow.com/questions/13308555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232153/'] | It's automatically open the app. Apple do the stuff for us. We don't need to code anything for open the app. | The app is opened automatically, but the last view controller you were in. So in order to open you desired view controller just implement application:didReceiveRemoteNotification:
Further explanation [here](http://developer.apple.com/library/ios/documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/application%3adidReceiveRemoteNotification%3a). |
13,308,555 | May i know, how to open an ios application, on tapping on notification.
Or when we swipe an icon (in case when iphone is locked.) of notification?
Can anyone please help me out here? | 2012/11/09 | ['https://Stackoverflow.com/questions/13308555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232153/'] | The OS handles the behavior when tapping the notification as it comes in. Doesn't matter if it is sent by a 3rd party or not, if it is going through APNS, it will open the application and inside `applicationDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions` :
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (launchOptions != nil) {
// Launched from push notification
NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
}
}
```
If the app happens to be already open when the notification comes in the OS will fire the delegate method:
```
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Do something
}
``` | On pressing the local notification, app launches automatically. |
13,308,555 | May i know, how to open an ios application, on tapping on notification.
Or when we swipe an icon (in case when iphone is locked.) of notification?
Can anyone please help me out here? | 2012/11/09 | ['https://Stackoverflow.com/questions/13308555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232153/'] | The OS handles the behavior when tapping the notification as it comes in. Doesn't matter if it is sent by a 3rd party or not, if it is going through APNS, it will open the application and inside `applicationDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions` :
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (launchOptions != nil) {
// Launched from push notification
NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
}
}
```
If the app happens to be already open when the notification comes in the OS will fire the delegate method:
```
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Do something
}
``` | The app is opened automatically, but the last view controller you were in. So in order to open you desired view controller just implement application:didReceiveRemoteNotification:
Further explanation [here](http://developer.apple.com/library/ios/documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/application%3adidReceiveRemoteNotification%3a). |
64,256,903 | I'm new in CodeIgniter in general. I have a view layout, on which I have navigation menu bar in it. I want to populate the dropdown menu with categories I've saved in database.
Here's snippet of my layout (View\layouts\frontend.php):
```
<nav class="navbar navbar-expand-md sticky-top">
<div class="collapse navbar-collapse flex-column " id="navbar">
<!-- Brand bar -->
<a class="navbar-brand ml-3" href="#">
<span class="">Test Site</span>
</a>
<!-- Internal links Menu navbar -->
<ul class="navbar-nav justify-content-center w-100 px-3">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">News</a>
<a class="dropdown-item" href="#">Event</a>
<a class="dropdown-item" href="#">Announcement</a>
</div>
</li>
</ul>
</nav>
```
Now, I understand that on every views that Extends that layout, I can just do query on controller and return the view with data. Here's what I've done so far and it works.
Home Controller:
```
use App\Models\CategoryModel;
class Home extends BaseController
{
public function index()
{
$categoryModel = new CategoryModel();
$data['categories'] = $categoryModel->orderBy('id', 'ASC')->findAll();
return view('frontend/home_page', $data);
}
}
```
Part of layout:
```
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<?php if ($categories) : ?>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($categories as $category) : ?>
<a class="dropdown-item" href="#"><?php echo $category['name'] ?></a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</li>
```
But it looks like I have to do that on all controllers' functions that renders my views that use my layout (frontend.php).
What I want to ask is, is there a possibility to just make a function/class/something to call so it's only done one time? What is the best practice in this situation? | 2020/10/08 | ['https://Stackoverflow.com/questions/64256903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14378974/'] | I'd recommend using different classes over inline css.
```css
.heading {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}
.heading.morning {
color: green;
}
.heading.afternoon {
color: purple;
}
.heading.night {
color: blue;
}
```
```
if (currentTime < 12 && currentTime >= 0) {
ReactDOM.render(
<div>
<h1 className="heading morning">Good Morning</h1>
</div>,
root
);
} else if (currentTime >= 12 && currentTime <= 18) {
ReactDOM.render(
<div>
<h1 className="heading afternoon">Good Afternoon</h1>
</div>,
root
);
} else {
ReactDOM.render(
<div>
<h1 className="heading night">Good Evening</h1>
</div>,
root
);
}
``` | You can do it in different ways, one of them is below:
JS file
```
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const root = document.getElementById("root");
const curretnTime = new Date().getHours();
if (curretnTime < 12 && curretnTime >= 0) {
ReactDOM.render(
<div className="morning">
<h1>Good Morning</h1>
</div>,
root
);
} else if (curretnTime >= 12 && curretnTime <= 18) {
ReactDOM.render(
<div>
<h1>Good Afternoon</h1>
</div>,
root
);
} else {
ReactDOM.render(
<div className="evening">
<h1>Good Evening</h1>
</div>,
root
);
}
```
CSS file
```
h1 {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}
.morning {
color: green;
}
.evening {
color: blue;
}
``` |
64,256,903 | I'm new in CodeIgniter in general. I have a view layout, on which I have navigation menu bar in it. I want to populate the dropdown menu with categories I've saved in database.
Here's snippet of my layout (View\layouts\frontend.php):
```
<nav class="navbar navbar-expand-md sticky-top">
<div class="collapse navbar-collapse flex-column " id="navbar">
<!-- Brand bar -->
<a class="navbar-brand ml-3" href="#">
<span class="">Test Site</span>
</a>
<!-- Internal links Menu navbar -->
<ul class="navbar-nav justify-content-center w-100 px-3">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">News</a>
<a class="dropdown-item" href="#">Event</a>
<a class="dropdown-item" href="#">Announcement</a>
</div>
</li>
</ul>
</nav>
```
Now, I understand that on every views that Extends that layout, I can just do query on controller and return the view with data. Here's what I've done so far and it works.
Home Controller:
```
use App\Models\CategoryModel;
class Home extends BaseController
{
public function index()
{
$categoryModel = new CategoryModel();
$data['categories'] = $categoryModel->orderBy('id', 'ASC')->findAll();
return view('frontend/home_page', $data);
}
}
```
Part of layout:
```
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<?php if ($categories) : ?>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($categories as $category) : ?>
<a class="dropdown-item" href="#"><?php echo $category['name'] ?></a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</li>
```
But it looks like I have to do that on all controllers' functions that renders my views that use my layout (frontend.php).
What I want to ask is, is there a possibility to just make a function/class/something to call so it's only done one time? What is the best practice in this situation? | 2020/10/08 | ['https://Stackoverflow.com/questions/64256903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14378974/'] | I'd recommend using different classes over inline css.
```css
.heading {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}
.heading.morning {
color: green;
}
.heading.afternoon {
color: purple;
}
.heading.night {
color: blue;
}
```
```
if (currentTime < 12 && currentTime >= 0) {
ReactDOM.render(
<div>
<h1 className="heading morning">Good Morning</h1>
</div>,
root
);
} else if (currentTime >= 12 && currentTime <= 18) {
ReactDOM.render(
<div>
<h1 className="heading afternoon">Good Afternoon</h1>
</div>,
root
);
} else {
ReactDOM.render(
<div>
<h1 className="heading night">Good Evening</h1>
</div>,
root
);
}
``` | I think that you are not using inline-css - `To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.`. But that is just "definition".
Anyway, what are you doing is not correct. You should create a component (see: <https://reactjs.org/docs/react-component.html>) where you will have logic for the change of color (see: <https://reactjs.org/docs/faq-state.html#what-does-setstate-do> - you can save the color in `state`). Then you can add the `componentDidMount` method and there you can add `setInterval` - so you can basically set "every X hour I will change the color". |
64,256,903 | I'm new in CodeIgniter in general. I have a view layout, on which I have navigation menu bar in it. I want to populate the dropdown menu with categories I've saved in database.
Here's snippet of my layout (View\layouts\frontend.php):
```
<nav class="navbar navbar-expand-md sticky-top">
<div class="collapse navbar-collapse flex-column " id="navbar">
<!-- Brand bar -->
<a class="navbar-brand ml-3" href="#">
<span class="">Test Site</span>
</a>
<!-- Internal links Menu navbar -->
<ul class="navbar-nav justify-content-center w-100 px-3">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">News</a>
<a class="dropdown-item" href="#">Event</a>
<a class="dropdown-item" href="#">Announcement</a>
</div>
</li>
</ul>
</nav>
```
Now, I understand that on every views that Extends that layout, I can just do query on controller and return the view with data. Here's what I've done so far and it works.
Home Controller:
```
use App\Models\CategoryModel;
class Home extends BaseController
{
public function index()
{
$categoryModel = new CategoryModel();
$data['categories'] = $categoryModel->orderBy('id', 'ASC')->findAll();
return view('frontend/home_page', $data);
}
}
```
Part of layout:
```
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<?php if ($categories) : ?>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($categories as $category) : ?>
<a class="dropdown-item" href="#"><?php echo $category['name'] ?></a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</li>
```
But it looks like I have to do that on all controllers' functions that renders my views that use my layout (frontend.php).
What I want to ask is, is there a possibility to just make a function/class/something to call so it's only done one time? What is the best practice in this situation? | 2020/10/08 | ['https://Stackoverflow.com/questions/64256903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14378974/'] | You should use inline styles, like:
```
import React from "react";
import ReactDOM from "react-dom";
const root = document.getElementById("root");
const curretnTime = new Date().getHours();
let timeOfDay = 'evening'; // not used
let timeOfDayColor = 'blue';
let timeOfDayMessage = 'Good Evening';
if (curretnTime < 12 && curretnTime >= 0) {
timeOfDay = 'morning';
timeOfDayColor = 'green';
timeOfDayMessage = 'Good Morning';
} else if (curretnTime >= 12 && curretnTime <= 18) {
timeOfDay = 'afternoon';
timeOfDayColor = 'purple';
timeOfDayMessage = 'Good Afternoon';
}
ReactDOM.render(
<div>
<h1 className="heading" style={{backgroundColor: timeOfDayColor}} >{timeOfDayMessage}</h1>
</div>,
root
);
```
The `style={{backgroundColor: timeOfDayColor}}` is your inline style that overrides the CSS style : <https://www.w3schools.com/react/react_css.asp>
However, **you should really use components** and not have all the code in the ReactDOM.render method. Maybe try a react tutorial first: <https://reactjs.org/tutorial/tutorial.html> | I'd recommend using different classes over inline css.
```css
.heading {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}
.heading.morning {
color: green;
}
.heading.afternoon {
color: purple;
}
.heading.night {
color: blue;
}
```
```
if (currentTime < 12 && currentTime >= 0) {
ReactDOM.render(
<div>
<h1 className="heading morning">Good Morning</h1>
</div>,
root
);
} else if (currentTime >= 12 && currentTime <= 18) {
ReactDOM.render(
<div>
<h1 className="heading afternoon">Good Afternoon</h1>
</div>,
root
);
} else {
ReactDOM.render(
<div>
<h1 className="heading night">Good Evening</h1>
</div>,
root
);
}
``` |
64,256,903 | I'm new in CodeIgniter in general. I have a view layout, on which I have navigation menu bar in it. I want to populate the dropdown menu with categories I've saved in database.
Here's snippet of my layout (View\layouts\frontend.php):
```
<nav class="navbar navbar-expand-md sticky-top">
<div class="collapse navbar-collapse flex-column " id="navbar">
<!-- Brand bar -->
<a class="navbar-brand ml-3" href="#">
<span class="">Test Site</span>
</a>
<!-- Internal links Menu navbar -->
<ul class="navbar-nav justify-content-center w-100 px-3">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">News</a>
<a class="dropdown-item" href="#">Event</a>
<a class="dropdown-item" href="#">Announcement</a>
</div>
</li>
</ul>
</nav>
```
Now, I understand that on every views that Extends that layout, I can just do query on controller and return the view with data. Here's what I've done so far and it works.
Home Controller:
```
use App\Models\CategoryModel;
class Home extends BaseController
{
public function index()
{
$categoryModel = new CategoryModel();
$data['categories'] = $categoryModel->orderBy('id', 'ASC')->findAll();
return view('frontend/home_page', $data);
}
}
```
Part of layout:
```
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<?php if ($categories) : ?>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($categories as $category) : ?>
<a class="dropdown-item" href="#"><?php echo $category['name'] ?></a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</li>
```
But it looks like I have to do that on all controllers' functions that renders my views that use my layout (frontend.php).
What I want to ask is, is there a possibility to just make a function/class/something to call so it's only done one time? What is the best practice in this situation? | 2020/10/08 | ['https://Stackoverflow.com/questions/64256903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14378974/'] | I'd recommend using different classes over inline css.
```css
.heading {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}
.heading.morning {
color: green;
}
.heading.afternoon {
color: purple;
}
.heading.night {
color: blue;
}
```
```
if (currentTime < 12 && currentTime >= 0) {
ReactDOM.render(
<div>
<h1 className="heading morning">Good Morning</h1>
</div>,
root
);
} else if (currentTime >= 12 && currentTime <= 18) {
ReactDOM.render(
<div>
<h1 className="heading afternoon">Good Afternoon</h1>
</div>,
root
);
} else {
ReactDOM.render(
<div>
<h1 className="heading night">Good Evening</h1>
</div>,
root
);
}
``` | You could do this:
```js
import React from 'react';
import ReactDOM from 'react-dom';
const time = new Date().getHours();
let greeting;
let color = {};
if (time <= 12) {
greeting = 'Good morning';
color.color = 'red';
} else if (time > 12 && time <= 18) {
greeting = 'Good afternoon';
color.color = 'green';
} else {
greeting = 'Good night';
color.color = 'blue';
}
ReactDOM.render(
<h1 className="heading" style={color}>
{greeting}
</h1>,
document.getElementById('root')
);
``` |
64,256,903 | I'm new in CodeIgniter in general. I have a view layout, on which I have navigation menu bar in it. I want to populate the dropdown menu with categories I've saved in database.
Here's snippet of my layout (View\layouts\frontend.php):
```
<nav class="navbar navbar-expand-md sticky-top">
<div class="collapse navbar-collapse flex-column " id="navbar">
<!-- Brand bar -->
<a class="navbar-brand ml-3" href="#">
<span class="">Test Site</span>
</a>
<!-- Internal links Menu navbar -->
<ul class="navbar-nav justify-content-center w-100 px-3">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">News</a>
<a class="dropdown-item" href="#">Event</a>
<a class="dropdown-item" href="#">Announcement</a>
</div>
</li>
</ul>
</nav>
```
Now, I understand that on every views that Extends that layout, I can just do query on controller and return the view with data. Here's what I've done so far and it works.
Home Controller:
```
use App\Models\CategoryModel;
class Home extends BaseController
{
public function index()
{
$categoryModel = new CategoryModel();
$data['categories'] = $categoryModel->orderBy('id', 'ASC')->findAll();
return view('frontend/home_page', $data);
}
}
```
Part of layout:
```
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<?php if ($categories) : ?>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($categories as $category) : ?>
<a class="dropdown-item" href="#"><?php echo $category['name'] ?></a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</li>
```
But it looks like I have to do that on all controllers' functions that renders my views that use my layout (frontend.php).
What I want to ask is, is there a possibility to just make a function/class/something to call so it's only done one time? What is the best practice in this situation? | 2020/10/08 | ['https://Stackoverflow.com/questions/64256903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14378974/'] | You should use inline styles, like:
```
import React from "react";
import ReactDOM from "react-dom";
const root = document.getElementById("root");
const curretnTime = new Date().getHours();
let timeOfDay = 'evening'; // not used
let timeOfDayColor = 'blue';
let timeOfDayMessage = 'Good Evening';
if (curretnTime < 12 && curretnTime >= 0) {
timeOfDay = 'morning';
timeOfDayColor = 'green';
timeOfDayMessage = 'Good Morning';
} else if (curretnTime >= 12 && curretnTime <= 18) {
timeOfDay = 'afternoon';
timeOfDayColor = 'purple';
timeOfDayMessage = 'Good Afternoon';
}
ReactDOM.render(
<div>
<h1 className="heading" style={{backgroundColor: timeOfDayColor}} >{timeOfDayMessage}</h1>
</div>,
root
);
```
The `style={{backgroundColor: timeOfDayColor}}` is your inline style that overrides the CSS style : <https://www.w3schools.com/react/react_css.asp>
However, **you should really use components** and not have all the code in the ReactDOM.render method. Maybe try a react tutorial first: <https://reactjs.org/tutorial/tutorial.html> | You can do it in different ways, one of them is below:
JS file
```
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const root = document.getElementById("root");
const curretnTime = new Date().getHours();
if (curretnTime < 12 && curretnTime >= 0) {
ReactDOM.render(
<div className="morning">
<h1>Good Morning</h1>
</div>,
root
);
} else if (curretnTime >= 12 && curretnTime <= 18) {
ReactDOM.render(
<div>
<h1>Good Afternoon</h1>
</div>,
root
);
} else {
ReactDOM.render(
<div className="evening">
<h1>Good Evening</h1>
</div>,
root
);
}
```
CSS file
```
h1 {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}
.morning {
color: green;
}
.evening {
color: blue;
}
``` |
64,256,903 | I'm new in CodeIgniter in general. I have a view layout, on which I have navigation menu bar in it. I want to populate the dropdown menu with categories I've saved in database.
Here's snippet of my layout (View\layouts\frontend.php):
```
<nav class="navbar navbar-expand-md sticky-top">
<div class="collapse navbar-collapse flex-column " id="navbar">
<!-- Brand bar -->
<a class="navbar-brand ml-3" href="#">
<span class="">Test Site</span>
</a>
<!-- Internal links Menu navbar -->
<ul class="navbar-nav justify-content-center w-100 px-3">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">News</a>
<a class="dropdown-item" href="#">Event</a>
<a class="dropdown-item" href="#">Announcement</a>
</div>
</li>
</ul>
</nav>
```
Now, I understand that on every views that Extends that layout, I can just do query on controller and return the view with data. Here's what I've done so far and it works.
Home Controller:
```
use App\Models\CategoryModel;
class Home extends BaseController
{
public function index()
{
$categoryModel = new CategoryModel();
$data['categories'] = $categoryModel->orderBy('id', 'ASC')->findAll();
return view('frontend/home_page', $data);
}
}
```
Part of layout:
```
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<?php if ($categories) : ?>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($categories as $category) : ?>
<a class="dropdown-item" href="#"><?php echo $category['name'] ?></a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</li>
```
But it looks like I have to do that on all controllers' functions that renders my views that use my layout (frontend.php).
What I want to ask is, is there a possibility to just make a function/class/something to call so it's only done one time? What is the best practice in this situation? | 2020/10/08 | ['https://Stackoverflow.com/questions/64256903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14378974/'] | You should use inline styles, like:
```
import React from "react";
import ReactDOM from "react-dom";
const root = document.getElementById("root");
const curretnTime = new Date().getHours();
let timeOfDay = 'evening'; // not used
let timeOfDayColor = 'blue';
let timeOfDayMessage = 'Good Evening';
if (curretnTime < 12 && curretnTime >= 0) {
timeOfDay = 'morning';
timeOfDayColor = 'green';
timeOfDayMessage = 'Good Morning';
} else if (curretnTime >= 12 && curretnTime <= 18) {
timeOfDay = 'afternoon';
timeOfDayColor = 'purple';
timeOfDayMessage = 'Good Afternoon';
}
ReactDOM.render(
<div>
<h1 className="heading" style={{backgroundColor: timeOfDayColor}} >{timeOfDayMessage}</h1>
</div>,
root
);
```
The `style={{backgroundColor: timeOfDayColor}}` is your inline style that overrides the CSS style : <https://www.w3schools.com/react/react_css.asp>
However, **you should really use components** and not have all the code in the ReactDOM.render method. Maybe try a react tutorial first: <https://reactjs.org/tutorial/tutorial.html> | I think that you are not using inline-css - `To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.`. But that is just "definition".
Anyway, what are you doing is not correct. You should create a component (see: <https://reactjs.org/docs/react-component.html>) where you will have logic for the change of color (see: <https://reactjs.org/docs/faq-state.html#what-does-setstate-do> - you can save the color in `state`). Then you can add the `componentDidMount` method and there you can add `setInterval` - so you can basically set "every X hour I will change the color". |
64,256,903 | I'm new in CodeIgniter in general. I have a view layout, on which I have navigation menu bar in it. I want to populate the dropdown menu with categories I've saved in database.
Here's snippet of my layout (View\layouts\frontend.php):
```
<nav class="navbar navbar-expand-md sticky-top">
<div class="collapse navbar-collapse flex-column " id="navbar">
<!-- Brand bar -->
<a class="navbar-brand ml-3" href="#">
<span class="">Test Site</span>
</a>
<!-- Internal links Menu navbar -->
<ul class="navbar-nav justify-content-center w-100 px-3">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">News</a>
<a class="dropdown-item" href="#">Event</a>
<a class="dropdown-item" href="#">Announcement</a>
</div>
</li>
</ul>
</nav>
```
Now, I understand that on every views that Extends that layout, I can just do query on controller and return the view with data. Here's what I've done so far and it works.
Home Controller:
```
use App\Models\CategoryModel;
class Home extends BaseController
{
public function index()
{
$categoryModel = new CategoryModel();
$data['categories'] = $categoryModel->orderBy('id', 'ASC')->findAll();
return view('frontend/home_page', $data);
}
}
```
Part of layout:
```
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Categories
</a>
<?php if ($categories) : ?>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<?php foreach ($categories as $category) : ?>
<a class="dropdown-item" href="#"><?php echo $category['name'] ?></a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</li>
```
But it looks like I have to do that on all controllers' functions that renders my views that use my layout (frontend.php).
What I want to ask is, is there a possibility to just make a function/class/something to call so it's only done one time? What is the best practice in this situation? | 2020/10/08 | ['https://Stackoverflow.com/questions/64256903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14378974/'] | You should use inline styles, like:
```
import React from "react";
import ReactDOM from "react-dom";
const root = document.getElementById("root");
const curretnTime = new Date().getHours();
let timeOfDay = 'evening'; // not used
let timeOfDayColor = 'blue';
let timeOfDayMessage = 'Good Evening';
if (curretnTime < 12 && curretnTime >= 0) {
timeOfDay = 'morning';
timeOfDayColor = 'green';
timeOfDayMessage = 'Good Morning';
} else if (curretnTime >= 12 && curretnTime <= 18) {
timeOfDay = 'afternoon';
timeOfDayColor = 'purple';
timeOfDayMessage = 'Good Afternoon';
}
ReactDOM.render(
<div>
<h1 className="heading" style={{backgroundColor: timeOfDayColor}} >{timeOfDayMessage}</h1>
</div>,
root
);
```
The `style={{backgroundColor: timeOfDayColor}}` is your inline style that overrides the CSS style : <https://www.w3schools.com/react/react_css.asp>
However, **you should really use components** and not have all the code in the ReactDOM.render method. Maybe try a react tutorial first: <https://reactjs.org/tutorial/tutorial.html> | You could do this:
```js
import React from 'react';
import ReactDOM from 'react-dom';
const time = new Date().getHours();
let greeting;
let color = {};
if (time <= 12) {
greeting = 'Good morning';
color.color = 'red';
} else if (time > 12 && time <= 18) {
greeting = 'Good afternoon';
color.color = 'green';
} else {
greeting = 'Good night';
color.color = 'blue';
}
ReactDOM.render(
<h1 className="heading" style={color}>
{greeting}
</h1>,
document.getElementById('root')
);
``` |
21,604,653 | I tried to modify my gruntfile but am getting a ton of errors about my indentation. Is whitespace always important for gruntfiles? What's the best way to fix these errors, counting whitespaces?
```
$ grunt
Running "newer:jshint" (newer) task
Running "newer:jshint:all" (newer) task
Running "jshint:all" (jshint) task
Gruntfile.js
line 33 col 11 Expected 'options' to have an indentation at 9 instead at 11.
line 36 col 7 Expected '}' to have an indentation at 9 instead at 7.
line 37 col 7 Expected 'js' to have an indentation at 9 instead at 7.
line 38 col 9 Expected 'files' to have an indentation at 11 instead at 9.
line 39 col 9 Expected 'tasks' to have an indentation at 11 instead at 9.
line 40 col 9 Expected 'options' to have an indentation at 11 instead at 9.
line 41 col 11 Expected 'livereload' to have an indentation at 13 instead at 11.
line 42 col 9 Expected '}' to have an indentation at 11 instead at 9.
line 43 col 7 Expected '}' to have an indentation at 9 instead at 7.
line 43 col 9 Trailing whitespace.
line 44 col 7 Expected 'compass' to have an indentation at 9 instead at 7.
line 45 col 9 Expected 'files' to have an indentation at 11 instead at 9.
line 46 col 9 Expected 'tasks' to have an indentation at 11 instead at 9.
line 47 col 7 Expected '}' to have an indentation at 9 instead at 7.
line 48 col 7 Expected 'gruntfile' to have an indentation at 9 instead at 7.
line 49 col 9 Expected 'files' to have an indentation at 11 instead at 9.
line 50 col 7 Expected '}' to have an indentation at 9 instead at 7.
line 51 col 7 Expected 'livereload' to have an indentation at 9 instead at 7.
line 52 col 9 Expected 'options' to have an indentation at 11 instead at 9.
line 53 col 11 Expected 'livereload' to have an indentation at 13 instead at 11.
line 54 col 9 Expected '}' to have an indentation at 11 instead at 9.
line 55 col 9 Expected 'files' to have an indentation at 11 instead at 9.
line 56 col 11 Expected '<%= yeoman.app %>/{,*/}*.html' to have an indentation at 13 instead at 11.
line 57 col 11 Expected '.tmp/styles/{,*/}*.css' to have an indentation at 13 instead at 11.
line 58 col 11 Expected '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' to have an indentation at 13 instead at 11.
line 59 col 9 Expected ']' to have an indentation at 11 instead at 9.
line 60 col 7 Expected '}' to have an indentation at 9 instead at 7.
line 61 col 5 Expected '}' to have an indentation at 7 instead at 5.
line 64 col 5 Expected 'connect' to have an indentation at 7 instead at 5.
line 65 col 7 Expected 'options' to have an indentation at 9 instead at 7.
line 66 col 9 Expected 'port' to have an indentation at 11 instead at 9.
line 68 col 9 Expected 'hostname' to have an indentation at 11 instead at 9.
line 69 col 9 Expected 'livereload' to have an indentation at 11 instead at 9.
line 70 col 7 Expected '}' to have an indentation at 9 instead at 7.
line 71 col 7 Expected 'livereload' to have an indentation at 9 instead at 7.
line 72 col 9 Expected 'options' to have an indentation at 11 instead at 9.
line 73 col 11 Expected 'open' to have an indentation at 13 instead at 11.
line 74 col 11 Expected 'base' to have an indentation at 13 instead at 11.
line 75 col 13 Expected '.tmp' to have an indentation at 15 instead at 13.
line 76 col 13 Expected '<%= yeoman.app %>' to have an indentation at 15 instead at 13.
line 77 col 11 Expected ']' to have an indentation at 13 instead at 11.
line 78 col 9 Expected '}' to have an indentation at 11 instead at 9.
line 79 col 7 Expected '}' to have an indentation at 9 instead at 7.
line 80 col 7 Expected 'test' to have an indentation at 9 instead at 7.
line 81 col 9 Expected 'options' to have an indentation at 11 instead at 9.
line 82 col 11 Expected 'port' to have an indentation at 13 instead at 11.
line 83 col 11 Expected 'base' to have an indentation at 13 instead at 11.
line 84 col 13 Expected '.tmp' to have an indentation at 15 instead at 13.
line 85 col 13 Expected 'test' to have an indentation at 15 instead at 13.
line 86 col 13 Expected '<%= yeoman.app %>' to have an indentation at 15 instead at 13.
line 86 col 13 Too many errors. (21% scanned).
✖ 51 problems
Warning: Task "jshint:all" failed. Use --force to continue.
``` | 2014/02/06 | ['https://Stackoverflow.com/questions/21604653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2031033/'] | Comment out the 'indent' property in the .jshintrc file, or perhaps in the package.json. Doing a global find on the word 'indent' should get you there.
I find white space really adds to the readability of code, particularly JS. So much so, that I don't know that it should be linted at all, particularly since it has no affect on how the JS is executed. | You may be getting the indent errors from 'lint'.
If you have an 'eslintrc' file you can remove the following line
from the rules key value pairs
' indent: [2, 2, {"SwitchCase": 1}],' |
8,980,329 | I am trying to build a little tool using google maps API. I thought With the use of the distanceMartrix api I could actually do this with just html/javascript
```
$.get("http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC&destinations=San+Francisco|Victoria+BC&sensor=false", function(data){
alert("Hello world");
});
```
the above code fails to success on the alert. I can get it to alert before the function and I have jquery commands before this which all perform fine. So what is going wrong in this incredibly simple statement? (im guessing its something stupid because im tired!!) | 2012/01/23 | ['https://Stackoverflow.com/questions/8980329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369765/'] | looks like you need to include google maps v3 js library via tag `script` and then use this service <http://code.google.com/apis/maps/documentation/javascript/reference.html#DistanceMatrixService>
there will be somethnmg like this
```
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type=text/javascript">
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [...], //array of origins
destinations: [...], //aray of destionations
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status){
if(status==google.maps.DistanceMatrixStatus.OK)
{
alert('ok')
}
});
}
</script>
```
`
**UPD:**
I have some trobles with formatting code, but I hope you guess what I mean. | Since you are making an "AJAX" request from a different domain than your script it needs to be a JSONP request instead of just a JSON request. JSONP requires a callback in your script that receives the data and processes it. Many APIs will serve up a JSONP request if you just append `&callback=?` to the end of the URL. jQuery will take care of the rest, making it go to the success callback.
I'm guessing that is it. |
8,980,329 | I am trying to build a little tool using google maps API. I thought With the use of the distanceMartrix api I could actually do this with just html/javascript
```
$.get("http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC&destinations=San+Francisco|Victoria+BC&sensor=false", function(data){
alert("Hello world");
});
```
the above code fails to success on the alert. I can get it to alert before the function and I have jquery commands before this which all perform fine. So what is going wrong in this incredibly simple statement? (im guessing its something stupid because im tired!!) | 2012/01/23 | ['https://Stackoverflow.com/questions/8980329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369765/'] | looks like you need to include google maps v3 js library via tag `script` and then use this service <http://code.google.com/apis/maps/documentation/javascript/reference.html#DistanceMatrixService>
there will be somethnmg like this
```
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type=text/javascript">
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [...], //array of origins
destinations: [...], //aray of destionations
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status){
if(status==google.maps.DistanceMatrixStatus.OK)
{
alert('ok')
}
});
}
</script>
```
`
**UPD:**
I have some trobles with formatting code, but I hope you guess what I mean. | Google Maps API requires basic authentication (you have to pay for >25k requests a day). Loading their library does it automatically, but loading it via Google would do. |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | You need to understand the concept of Bitmap and memory
>
> Let’s say you want to display an image on your screen that you just took with your camera. The total memory needed for this is calculated with the following formula: memory\_needed\_in\_bytes = 4 \* image\_width \* image\_height;
>
>
> Why 4? Well, the most common / recommended bitmap configuration is ARGB\_8888. That means that for each pixel we draw, we need to keep 8 bits (1 byte) for the alpha, the red, the greed and the blue channel in memory, in order to properly display it. There are alternatives, like the RGB\_565 configuration that requires half the memory than ARGB\_8888, but loses the transparency and the color precision (while maybe adding a green tint).
>
>
> Let’s assume you have a brand new device with full HD screen and 12 MP camera. The picture you just took is 4000x3000 pixels large and the total memory needed to display it is: 4 bytes \* 4000 \* 3000 = 48 MB
>
>
> 48 megabytes of your RAM just for a single image!? That’s a lot!
>
>
> Now let’s take the screen resolution into consideration. You are trying to show a 4000x3000 image on a screen that has 1920x1080 pixels, in worst case scenario (displaying the image full screen) you shouldn’t allocate more than 4 \* 1920 \* 1080 = 8.3 MB of memory.
>
>
> Always follow the Android programming tips for displaying bitmaps efficiently:
>
>
> Measure the view you’re showing your images in.
> Scale / crop the large image accordingly.
> Show only what can be displayed.
>
>
> | The exception thrown is known as `OutOfMemoryError`. The error occurs when (obviously) you run out of memory! Here is the documentation for it:
>
> Thrown when a request for memory is made that can not be satisfied using the available platform resources. Such a request may be made by both the running application or by an internal function of the VM.
>
>
>
More information here:
<http://developer.android.com/reference/java/lang/OutOfMemoryError.html>
So, you should allocate more memory to your emulator. But I think the main reason is your app uses too much memory. Did you use a super big image? |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | The exception thrown is known as `OutOfMemoryError`. The error occurs when (obviously) you run out of memory! Here is the documentation for it:
>
> Thrown when a request for memory is made that can not be satisfied using the available platform resources. Such a request may be made by both the running application or by an internal function of the VM.
>
>
>
More information here:
<http://developer.android.com/reference/java/lang/OutOfMemoryError.html>
So, you should allocate more memory to your emulator. But I think the main reason is your app uses too much memory. Did you use a super big image? | add this ligne to your manifest file:
```
android:largeHeap="true"
``` |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | The exception thrown is known as `OutOfMemoryError`. The error occurs when (obviously) you run out of memory! Here is the documentation for it:
>
> Thrown when a request for memory is made that can not be satisfied using the available platform resources. Such a request may be made by both the running application or by an internal function of the VM.
>
>
>
More information here:
<http://developer.android.com/reference/java/lang/OutOfMemoryError.html>
So, you should allocate more memory to your emulator. But I think the main reason is your app uses too much memory. Did you use a super big image? | if you are using RXJAVA and are only observing the "Single" type of observable than this is prone to happen where you are emitting large number of images or data set of any kind:
try using toFlowable before .subscribe
<https://medium.com/@gabrieldemattosleon/fundamentals-of-rxjava-with-kotlin-for-absolute-beginners-3d811350b701> |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | You need to understand the concept of Bitmap and memory
>
> Let’s say you want to display an image on your screen that you just took with your camera. The total memory needed for this is calculated with the following formula: memory\_needed\_in\_bytes = 4 \* image\_width \* image\_height;
>
>
> Why 4? Well, the most common / recommended bitmap configuration is ARGB\_8888. That means that for each pixel we draw, we need to keep 8 bits (1 byte) for the alpha, the red, the greed and the blue channel in memory, in order to properly display it. There are alternatives, like the RGB\_565 configuration that requires half the memory than ARGB\_8888, but loses the transparency and the color precision (while maybe adding a green tint).
>
>
> Let’s assume you have a brand new device with full HD screen and 12 MP camera. The picture you just took is 4000x3000 pixels large and the total memory needed to display it is: 4 bytes \* 4000 \* 3000 = 48 MB
>
>
> 48 megabytes of your RAM just for a single image!? That’s a lot!
>
>
> Now let’s take the screen resolution into consideration. You are trying to show a 4000x3000 image on a screen that has 1920x1080 pixels, in worst case scenario (displaying the image full screen) you shouldn’t allocate more than 4 \* 1920 \* 1080 = 8.3 MB of memory.
>
>
> Always follow the Android programming tips for displaying bitmaps efficiently:
>
>
> Measure the view you’re showing your images in.
> Scale / crop the large image accordingly.
> Show only what can be displayed.
>
>
> | add this ligne to your manifest file:
```
android:largeHeap="true"
``` |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | You need to understand the concept of Bitmap and memory
>
> Let’s say you want to display an image on your screen that you just took with your camera. The total memory needed for this is calculated with the following formula: memory\_needed\_in\_bytes = 4 \* image\_width \* image\_height;
>
>
> Why 4? Well, the most common / recommended bitmap configuration is ARGB\_8888. That means that for each pixel we draw, we need to keep 8 bits (1 byte) for the alpha, the red, the greed and the blue channel in memory, in order to properly display it. There are alternatives, like the RGB\_565 configuration that requires half the memory than ARGB\_8888, but loses the transparency and the color precision (while maybe adding a green tint).
>
>
> Let’s assume you have a brand new device with full HD screen and 12 MP camera. The picture you just took is 4000x3000 pixels large and the total memory needed to display it is: 4 bytes \* 4000 \* 3000 = 48 MB
>
>
> 48 megabytes of your RAM just for a single image!? That’s a lot!
>
>
> Now let’s take the screen resolution into consideration. You are trying to show a 4000x3000 image on a screen that has 1920x1080 pixels, in worst case scenario (displaying the image full screen) you shouldn’t allocate more than 4 \* 1920 \* 1080 = 8.3 MB of memory.
>
>
> Always follow the Android programming tips for displaying bitmaps efficiently:
>
>
> Measure the view you’re showing your images in.
> Scale / crop the large image accordingly.
> Show only what can be displayed.
>
>
> | >
> android:largeHeap="true"
>
>
>
You shouldn't use this, this is not a fix for the problem, this is a temporary problem fix. What this do is increase the memory of the emulator/phone, it will work but eventually it will crash again because you did not fix the memory problem |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | You need to understand the concept of Bitmap and memory
>
> Let’s say you want to display an image on your screen that you just took with your camera. The total memory needed for this is calculated with the following formula: memory\_needed\_in\_bytes = 4 \* image\_width \* image\_height;
>
>
> Why 4? Well, the most common / recommended bitmap configuration is ARGB\_8888. That means that for each pixel we draw, we need to keep 8 bits (1 byte) for the alpha, the red, the greed and the blue channel in memory, in order to properly display it. There are alternatives, like the RGB\_565 configuration that requires half the memory than ARGB\_8888, but loses the transparency and the color precision (while maybe adding a green tint).
>
>
> Let’s assume you have a brand new device with full HD screen and 12 MP camera. The picture you just took is 4000x3000 pixels large and the total memory needed to display it is: 4 bytes \* 4000 \* 3000 = 48 MB
>
>
> 48 megabytes of your RAM just for a single image!? That’s a lot!
>
>
> Now let’s take the screen resolution into consideration. You are trying to show a 4000x3000 image on a screen that has 1920x1080 pixels, in worst case scenario (displaying the image full screen) you shouldn’t allocate more than 4 \* 1920 \* 1080 = 8.3 MB of memory.
>
>
> Always follow the Android programming tips for displaying bitmaps efficiently:
>
>
> Measure the view you’re showing your images in.
> Scale / crop the large image accordingly.
> Show only what can be displayed.
>
>
> | if you are using RXJAVA and are only observing the "Single" type of observable than this is prone to happen where you are emitting large number of images or data set of any kind:
try using toFlowable before .subscribe
<https://medium.com/@gabrieldemattosleon/fundamentals-of-rxjava-with-kotlin-for-absolute-beginners-3d811350b701> |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | >
> android:largeHeap="true"
>
>
>
You shouldn't use this, this is not a fix for the problem, this is a temporary problem fix. What this do is increase the memory of the emulator/phone, it will work but eventually it will crash again because you did not fix the memory problem | add this ligne to your manifest file:
```
android:largeHeap="true"
``` |
33,864,168 | ```
11-23 10:38:04.430 2095-2095/? I/art: Not late-enabling -Xcheck:jni (already on)
11-23 10:38:04.430 2095-2095/? I/art: Late-enabling JIT
11-23 10:38:04.433 2095-2095/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-23 10:38:04.830 2095-2095/com.example.somanshusrivastava.carpiko W/System: ClassLoader referenced unknown path: /data/app/com.example.somanshusrivastava.carpiko-2/lib/x86
11-23 10:38:05.697 2095-2106/com.example.somanshusrivastava.carpiko I/art: Background partial concurrent mark sweep GC freed 96(3KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.581ms total 140.616ms
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.812 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.827 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 79(11KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 5.901ms total 13.614ms
11-23 10:38:05.836 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.850 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 23(1008B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 2.153ms total 10.247ms
11-23 10:38:05.853 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.867 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 15(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.431ms total 13.789ms
11-23 10:38:05.868 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.869 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.881 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.407ms total 11.758ms
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.882 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.892 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc sticky concurrent mark sweep GC freed 3(608B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.389ms total 8.964ms
11-23 10:38:05.894 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.903 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.387ms total 8.867ms
11-23 10:38:05.904 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.916 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.416ms total 10.922ms
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Forcing collection of SoftReferences for 49MB allocation
11-23 10:38:05.917 2095-2095/com.example.somanshusrivastava.carpiko I/art: Starting a blocking GC Alloc
11-23 10:38:05.928 2095-2095/com.example.somanshusrivastava.carpiko I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 7% free, 50MB/54MB, paused 1.350ms total 10.018ms
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko W/art: Throwing OutOfMemoryError "Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM"
11-23 10:38:05.929 2095-2095/com.example.somanshusrivastava.carpiko D/skia: --- allocation failed for scaled bitmap
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko D/AndroidRuntime: Shutting down VM
11-23 10:38:05.930 2095-2095/com.example.somanshusrivastava.carpiko E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.somanshusrivastava.carpiko, PID: 2095
java.lang.OutOfMemoryError: Failed to allocate a 51750048 byte allocation with 4194304 free bytes and 13MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1080)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2635)
at android.content.res.Resources.loadDrawable(Resources.java:2540)
at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
at android.widget.ImageView.(ImageView.java:152)
at android.widget.ImageView.(ImageView.java:140)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.somanshusrivastava.carpiko.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-23 10:38:07.560 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 13.233ms
11-23 10:38:09.537 2095-2102/com.example.somanshusrivastava.carpiko W/art: Suspending all threads took: 9.664ms
11-23 10:38:11.140 2095-2095/? I/Process: Sending signal. PID: 2095 SIG: 9
```
Whenever I try to run the *AVD*, my app unexpectedly closes and this is the error I get. This is the logcat that is generated. It is showing a FatalException and a MemoryException. Is it an AVD error or code error? Please help. | 2015/11/23 | ['https://Stackoverflow.com/questions/33864168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1947616/'] | >
> android:largeHeap="true"
>
>
>
You shouldn't use this, this is not a fix for the problem, this is a temporary problem fix. What this do is increase the memory of the emulator/phone, it will work but eventually it will crash again because you did not fix the memory problem | if you are using RXJAVA and are only observing the "Single" type of observable than this is prone to happen where you are emitting large number of images or data set of any kind:
try using toFlowable before .subscribe
<https://medium.com/@gabrieldemattosleon/fundamentals-of-rxjava-with-kotlin-for-absolute-beginners-3d811350b701> |
49,316,050 | I'm beginning on Jenkins in my work place. We use semantic versioning with Teamcity and I want to implement the same on Jenkins. My problem appears when I store the artifacts in builds folder ($JENKINS\_HOME/jobs/$JOB\_NAME/builds/$BUILD\_NUMBER) because Jenkins use only the build\_number to create the folder for build so when I have to reset de Build\_number the future artifacts will be stored in the folder of previous builds.
>
> For example:
>
>
> *I have build 1.3.1\_develop.1 stored, when I reset Build\_Number the next build should be 1.3.2\_develop.1 and it should be stored in the
> folder 1 of build 1.3.1\_develop.1*
>
>
>
My question is if someone could explain me how to deal with automatic semantic versioning on jenkins because we reset the build number we increase the mayor, minor and patch number.
Jenkins Version: 2.89.4
Jobs--> We use jobs to compile Vuejs for front and to deploy back with python (If this helps)
Thanks for any help. | 2018/03/16 | ['https://Stackoverflow.com/questions/49316050', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9498712/'] | First thing I notice is you are not using semantic versioning correctly. `1.3.1_develop.1` should be `1.3.1-develop+1`. Build metadata should always be preceded by the plus '+' symbol and is not factored into the SemVer sort order.
Second, build number is never "reset", it might roll-over eventually, but it should never be reset. A build number that does not indicate the machine performing the build is also generally useless unless there can only ever be one.
Basically, there's no concept of a build number in semantic versioning. The standard specifies the syntax for build meta data, but is completely neutral on what might be included. Build numbers are generally useless at the level of semantic versioning. They have their uses for preventing directory collisions in CI build systems and even provide a unique identifier for some product lines (Windows for instance), particularly where semantic versioning is not in use (Windows again).
I recommend using a SHA-1 or better hash of the build inputs (Git commit Id for instance) in the build meta tag in addition to any build counter, and use that for your output directory name. You can still use a monotonic counter on your prerelease tags as well, but you would have to create a build output directory name that includes the entire semver string in order to maintain uniqueness.
Third, your build machine is the worst place to archive your build artifacts! Build automation can and does go horribly wrong from time to time. Your build system should not have access to your archive of build artifacts. When your build and initial smoke testing is completed, it should signal a process running on a completely different machine to move the artifacts off the build machine to a more secure location. No process running on the build system should have write access to your archive of build artifacts. | There is a tool `GitVersion` which does what you want and it can be integrated with Jenkins or other CI providers.
<https://gitversion.net/docs/reference/build-servers/jenkins> |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | I found that the best option is to use `+ theme(legend.title = element_blank())` as user "gkcn" noted.
For me (on 03/26/15) using the previously suggested `labs(fill="")` and `scale_fill_discrete("")` remove one title, only to add in another legend, which is not useful. | @pascal 's solution in a [comment](https://stackoverflow.com/questions/6022898/how-can-i-remove-the-legend-title-in-ggplot2#comment41208703_6023078) to set the `name` argument of a scale function, such as `scale_fill_discrete`, to `NULL`, is the best option for me. It allows removing the title together with the blank space that would remain if you used `""`, while at the same time allowing the user to selectively remove titles, which is not possible with the `theme(legend.title = element_blank())` approach.
Since it is buried in a comment, I am posting it as an answer to potentially increase its visibility, with kudos to @pascal.
TL;DR (for the copy-pasters):
`scale_fill_discrete(name = NULL)` |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | You can modify the legend title by passing it as the first parameter to a scale. For example:
```
ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +
geom_bar(position="dodge") +
theme(legend.position="top", legend.direction="horizontal") +
scale_fill_discrete("")
```
There is also a shortcut for this, i.e. `labs(fill="")`
Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using `opts(legend.direction="horizontal")`.
![enter image description here](https://i.stack.imgur.com/VOdR7.png) | You can use `labs`:
```
p + labs(fill="")
```
![plot example](https://i.stack.imgur.com/HSGJr.png) |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | I found that the best option is to use `+ theme(legend.title = element_blank())` as user "gkcn" noted.
For me (on 03/26/15) using the previously suggested `labs(fill="")` and `scale_fill_discrete("")` remove one title, only to add in another legend, which is not useful. | The only way worked for me was using `legend.title = theme_blank()` and I think it is the most convenient variant in comparison to `labs(fill="")` and `scale_fill_discrete("")`, which also could be useful in some cases.
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(
legend.position="top",
legend.direction="horizontal",
legend.title = theme_blank()
)
```
P.S. There are more useful options in [documentation](https://github.com/hadley/ggplot2/wiki/Legend-Attributes). |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | You can modify the legend title by passing it as the first parameter to a scale. For example:
```
ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +
geom_bar(position="dodge") +
theme(legend.position="top", legend.direction="horizontal") +
scale_fill_discrete("")
```
There is also a shortcut for this, i.e. `labs(fill="")`
Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using `opts(legend.direction="horizontal")`.
![enter image description here](https://i.stack.imgur.com/VOdR7.png) | @pascal 's solution in a [comment](https://stackoverflow.com/questions/6022898/how-can-i-remove-the-legend-title-in-ggplot2#comment41208703_6023078) to set the `name` argument of a scale function, such as `scale_fill_discrete`, to `NULL`, is the best option for me. It allows removing the title together with the blank space that would remain if you used `""`, while at the same time allowing the user to selectively remove titles, which is not possible with the `theme(legend.title = element_blank())` approach.
Since it is buried in a comment, I am posting it as an answer to potentially increase its visibility, with kudos to @pascal.
TL;DR (for the copy-pasters):
`scale_fill_discrete(name = NULL)` |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | The only way worked for me was using `legend.title = theme_blank()` and I think it is the most convenient variant in comparison to `labs(fill="")` and `scale_fill_discrete("")`, which also could be useful in some cases.
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(
legend.position="top",
legend.direction="horizontal",
legend.title = theme_blank()
)
```
P.S. There are more useful options in [documentation](https://github.com/hadley/ggplot2/wiki/Legend-Attributes). | @pascal 's solution in a [comment](https://stackoverflow.com/questions/6022898/how-can-i-remove-the-legend-title-in-ggplot2#comment41208703_6023078) to set the `name` argument of a scale function, such as `scale_fill_discrete`, to `NULL`, is the best option for me. It allows removing the title together with the blank space that would remain if you used `""`, while at the same time allowing the user to selectively remove titles, which is not possible with the `theme(legend.title = element_blank())` approach.
Since it is buried in a comment, I am posting it as an answer to potentially increase its visibility, with kudos to @pascal.
TL;DR (for the copy-pasters):
`scale_fill_discrete(name = NULL)` |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | You can modify the legend title by passing it as the first parameter to a scale. For example:
```
ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +
geom_bar(position="dodge") +
theme(legend.position="top", legend.direction="horizontal") +
scale_fill_discrete("")
```
There is also a shortcut for this, i.e. `labs(fill="")`
Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using `opts(legend.direction="horizontal")`.
![enter image description here](https://i.stack.imgur.com/VOdR7.png) | You've got two good options already, so here's another using `scale_fill_manual()`. Note this also lets you specify the colors of the bars easily:
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
```
If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:
```
ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
theme(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
``` |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | You can use `labs`:
```
p + labs(fill="")
```
![plot example](https://i.stack.imgur.com/HSGJr.png) | You've got two good options already, so here's another using `scale_fill_manual()`. Note this also lets you specify the colors of the bars easily:
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
```
If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:
```
ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
theme(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
``` |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | I found that the best option is to use `+ theme(legend.title = element_blank())` as user "gkcn" noted.
For me (on 03/26/15) using the previously suggested `labs(fill="")` and `scale_fill_discrete("")` remove one title, only to add in another legend, which is not useful. | You've got two good options already, so here's another using `scale_fill_manual()`. Note this also lets you specify the colors of the bars easily:
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
```
If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:
```
ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
theme(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
``` |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | The only way worked for me was using `legend.title = theme_blank()` and I think it is the most convenient variant in comparison to `labs(fill="")` and `scale_fill_discrete("")`, which also could be useful in some cases.
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(
legend.position="top",
legend.direction="horizontal",
legend.title = theme_blank()
)
```
P.S. There are more useful options in [documentation](https://github.com/hadley/ggplot2/wiki/Legend-Attributes). | You've got two good options already, so here's another using `scale_fill_manual()`. Note this also lets you specify the colors of the bars easily:
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
```
If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:
```
ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
theme(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
``` |
6,022,898 | I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
```
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
```
I make a simple bar plot:
```
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
```
My question is: is there a way to remove the title ('Type') from the legend?
Thanks! | 2011/05/16 | ['https://Stackoverflow.com/questions/6022898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745027/'] | You can modify the legend title by passing it as the first parameter to a scale. For example:
```
ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +
geom_bar(position="dodge") +
theme(legend.position="top", legend.direction="horizontal") +
scale_fill_discrete("")
```
There is also a shortcut for this, i.e. `labs(fill="")`
Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using `opts(legend.direction="horizontal")`.
![enter image description here](https://i.stack.imgur.com/VOdR7.png) | The only way worked for me was using `legend.title = theme_blank()` and I think it is the most convenient variant in comparison to `labs(fill="")` and `scale_fill_discrete("")`, which also could be useful in some cases.
```
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(
legend.position="top",
legend.direction="horizontal",
legend.title = theme_blank()
)
```
P.S. There are more useful options in [documentation](https://github.com/hadley/ggplot2/wiki/Legend-Attributes). |
3,503,714 | I am looking through the solution of integrating: $$\int\_{}^{} \frac{x^4+1}{x^3+1} dx$$
I understand it but for the following part:
[![enter image description here](https://i.stack.imgur.com/oaGcE.png)](https://i.stack.imgur.com/oaGcE.png)
My problem is limited to the first and penultimate column. I would very much appreciate it if someone could explain to me these, especially the penultimate one.
EDIT 0: Clarification
I have a problem with this line:
[![enter image description here](https://i.stack.imgur.com/fc2Py.png)](https://i.stack.imgur.com/fc2Py.png)
How do I get those thetas?
My main problem is with this part:
[![enter image description here](https://i.stack.imgur.com/83dBw.png)](https://i.stack.imgur.com/83dBw.png)
Why 1 = ..., -1 = ... and 0 = ...? | 2020/01/10 | ['https://math.stackexchange.com/questions/3503714', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/398496/'] | An introduction to partial fractions.
If we have two fraction and we want to add them together, $\frac {a}{b} + \frac {c}{d} = \frac {ad + bc}{bd}$
We can do the same thing, with rational polynomials.
$ \frac {1}{x} - \frac {1}{x+1} = \frac{x+1}{(x)(x+1)} - \frac {x}{x(x+1)} = \frac {x+1-x}{x(x+1)} = \frac {1}{x(x+1)}$
Supposing you had $\frac {1}{x(x+1)}$ How do you break it into partial fractions?
We already know the solution, but how do you find it if you didn't know?
We know that the denominators are factors of the denominator of the original expression.
So we "guess" that it might look something like this:
$\frac {1}{x(x+1)} = \frac {a}{x} + \frac {b}{x+1}$
Solve for $a,b$
Multiply both sides by $(x)(x+1)$
$\frac {1}{x(x+1)}(x)(x+1) = \frac {a}{x}(x)(x+1) + \frac {b}{x+1}(x)(x+1)\\
1 = a(x+1) + bx\\
1 = ax + a + bx\\
1 = (a+b)x + a$
We have an $x$ term on the right and no $x$ term on the left, we might do something like this to create an x term on the left without changing the value of the expression.
$0x + 1 = (a+b)x + a$
If the LHS equals the RHS, then the coefficient of the x terms must be equal. The constant terms must also be equal.
$0x = (a+b)x\\
1 = a$
There was no reason to carry the $x$ along and we could have cut straight to
$0 = a+b\\
1 =a$
One more increase in difficulty.
Suppose we have.
$\frac {1}{x(x^2+1)}$
When we break it into partial fractions, we should assume that the degree of the numerator in each term is one less than the degree of the denominator. That is:
$\frac {1}{x(x^2+1)} = \frac {a}{x} + \frac {bx + c}{x^2 + 1}$
Then we multiply both sides by $(x)(x^2+1)$ as we did before, and set corresponding coefficients equal to each other.
$\frac {1}{x(x^2+1)}(x)(x^2+1) = \frac {a}{x}(x)(x^2+1) + \frac {bx + c}{x^2 + 1}(x)(x^2+1)\\
1 = a(x^2 + 1) + (bx+c) x\\
1 = ax^2 + a + bx^2+ cx\
0x^2 + 0x + 1 = (a+b) x^2 + cx + a\\
0 = a+b\\
0 = c\\
1 = a$
This is exactly what was done in the problem above
$\frac {1-x}{(x+1)(x^2-x+1)}$
We want the numerators to be of one degree less than each term's denominator.
$\frac {1-x}{(x+1)(x^2-x+1)} = \frac {a}{x-1} + \frac {bx + c}{x^2 - x + 1}$
Multiply through by $(x^3 + 1)$ or $(x+1)(x^2 - x + 1)$ if you prefer.
$\frac {1-x}{(x+1)(x^2-x+1)}(x+1)(x^2 - x + 1) = \frac {a}{x+1}(x+1)(x^2 - x + 1) + \frac {bx + c}{x^2 - x + 1}(x+1)(x^2 - x + 1)\\
1-x = a(x^2 - x + 1)+ (bx + c)(x+1)\\
1-x = ax^2 - ax + a + bx^2 + bx + cx + c\\
0x^2 - x + 1 = (a+b)x^2 + (-a+b+c)x + (a+c)\\
0 = a+b\\
-1 = -a+b+c \\
1 = a+c$
I hope this clears things up. | Solution of integral will be by partial fraction method
$$I=\int (x+\frac{1-x}{x^3+1})dx$$
$$I = \frac{x^2}{2}+\int (\frac{1-x}{(x+1)(x^2-x+1)})dx$$
Where you can solve for
$$I\_1=\int (\frac{1-x}{(x+1)(x^2-x+1)})dx$$
Using partial fraction like done here
<https://www.mathsdiscussion.com/discussion-forum/topic/indefinite-integral/?part=1#postid-77>
$$I=\frac{x^2}{2}-\frac{1}{3}ln(\frac{x^2-x+1}{(x+1)^2})+C$$
Problem what you say in your solution is when let
$$\frac{1-x}{(x+1)(x^2-x+1)}=\frac{a}{x+1}+\frac{bx+c}{x^2-x+1}$$
Multiplying both sides by $(x+1)(x^2-x+1)$ we ge
$$1-x=a(x^2-x+1)+(bx+c)(x+1)$$
Now comparing coefficients of $x^2$ , x and constant terms on both sides we get
$$ $$
Coefficient of$x^2$ on both sides 0=a+b
$$. $$
Coefficient of x on both sides -1=-a+b+c
$$. $$
Constant terms on both sides 1=a+c
$$ $$ This how we get those 3 equations |
52,559,052 | Can someone please check why it isn't removing exact character (`ind`) from the string?
When I execute below, the char `'<'` at position 17 is not removed, I see it's removing `'2'`, also I tried with `ind - 2` to remove `'<'` but it doesn't work for the next special character.
Please note that I need to use the below code to remove special chars.
```
static void Main(string[] args)
{
string path = "<X><A>this is AA<123 w<o<r<d</A></X>";
int xx = 0;
bool bFlg = true;
XmlDocument x = new XmlDocument();
while (bFlg)
{
try
{
xx++;
x.LoadXml(path);
bFlg = false;
}
catch (Exception ee)
{
//"Name cannot begin with the '1' character, hexadecimal value 0x31. Line 1, position 18."
string toBeSearched = "position";
int ix = ee.Message.IndexOf(toBeSearched);
if (ix != -1)
{
var pos = ee.Message.Substring(ix + toBeSearched.Length);
pos = Regex.Replace(pos, @"[^\d]", "");
path = path.Remove(Convert.ToInt32(pos), 1);
bFlg = true;
}
else
throw new Exception(ee.Message);
if (xx > 20)
break;
}
}
}
``` | 2018/09/28 | ['https://Stackoverflow.com/questions/52559052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7991976/'] | It's a little bit messy.. but given your current test case, it works.
```
string path = "<X><A>this is AA<123 w<o<r<d</A></X>";
int pathLength = path.Length;
List<int> positons = new List<int>();
for (int itr = 0; itr < pathLength; itr++) {
if (path[itr] == '<') {
for (int pointer = itr + 1; pointer < pathLength; pointer++) {
if (path[pointer] == '<') {
positons.Add(itr);
break;
} else if (path[pointer] == '>') {
break;
}
}
}
}
int offset = 0;
foreach(var pos in positons) {
path = path.Remove(pos - offset, 1);
offset++;
}
``` | If the path is always enclosed within the same tags (since this was not specified, I'm not sure), it can be as simple as removing the leading and trailing tags:
```
const string LeadingTags = "<X><A>";
const string TrailingTags = "</A></X>";
string path = "<X><A>this is AA<123 w<o<r<d</A></X>";
int length = path.Length - LeadingTags.Length - TrailingTags.Length;
string value = path.Substring(LeadingTags.Length, length);
Console.WriteLine(value);
```
Prints the correct value:
>
> this is AA<123 w<o<r<d
>
>
> |
36,802,272 | I am attempting to pass a string into a method and based on what string is passed in, either instantiate BasicHttpBinding or WSHttpBinding. The following if statement is in my code.
```
if(bindingObject == "basic")
{System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();}
else
{System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();
```
This code gives me the error
>
> The name 'binding' does not exist in the current context
>
>
>
From my research it seems I have to use a common base class between the two service models if I want to use the variable named *binding* no matter which ServiceModel I need to use.
My question is, what is the common base class that would work? Or is there a way to do this. The closest I have found is System.ServiceModel.Channels.Binding but then I get the error such as
>
> does not contain a definition for 'MaxBufferPoolSize' and no extension method 'MaxBufferPoolSize' accepting a first argument of tyep 'System.ServiceModel.Channels.Binding' could be found
>
>
> | 2016/04/22 | ['https://Stackoverflow.com/questions/36802272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3150921/'] | First: both `BasicHttpBinding` and `BasicHttpBinding` need to either derive from the same base class or implement the same [interface](https://msdn.microsoft.com/en-us/library/87d83y5b.aspx)
If you're using visual studio, you can put a cursor over the types and press `f12` to see what types they derive from and what interfaces they implement. The type that is appropriate to use depends on what you want to do with them.
According to documentation for [BasicHttpBinding](https://msdn.microsoft.com/en-us/library/system.servicemodel.basichttpbinding%28v=vs.110%29.aspx) and [WSHttpBinding](https://msdn.microsoft.com/en-us/library/system.servicemodel.wshttpbinding%28v=vs.110%29.aspx), the common base class seems to be `System.ServiceModel.Channels.Binding`,
**You should use `f12` to check anyway, because there's probably an interface in there that defines the members that you need to use.**
Second, You have to declare it outside the context of your if statement
```
System.ServiceModel.Channels.Binding binding;
if(bindingObject == "basic")
{
binding = ...
}
else
{
binding = ...
}
``` | You could use wither the Binding base class or the IBindingRuntimePreferences interface, if that provides access to the functionality you need.
```
//System.ServiceModel.Channels.Binding binding;
System.ServiceModel.Channels.IBindingRuntimePreferences binding;
if(bindingObject == "basic")
binding = new System.ServiceModel.BasicHttpBinding();}
else
binding = new System.ServiceModel.WSHttpBinding();
``` |
36,802,272 | I am attempting to pass a string into a method and based on what string is passed in, either instantiate BasicHttpBinding or WSHttpBinding. The following if statement is in my code.
```
if(bindingObject == "basic")
{System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();}
else
{System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();
```
This code gives me the error
>
> The name 'binding' does not exist in the current context
>
>
>
From my research it seems I have to use a common base class between the two service models if I want to use the variable named *binding* no matter which ServiceModel I need to use.
My question is, what is the common base class that would work? Or is there a way to do this. The closest I have found is System.ServiceModel.Channels.Binding but then I get the error such as
>
> does not contain a definition for 'MaxBufferPoolSize' and no extension method 'MaxBufferPoolSize' accepting a first argument of tyep 'System.ServiceModel.Channels.Binding' could be found
>
>
> | 2016/04/22 | ['https://Stackoverflow.com/questions/36802272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3150921/'] | First: both `BasicHttpBinding` and `BasicHttpBinding` need to either derive from the same base class or implement the same [interface](https://msdn.microsoft.com/en-us/library/87d83y5b.aspx)
If you're using visual studio, you can put a cursor over the types and press `f12` to see what types they derive from and what interfaces they implement. The type that is appropriate to use depends on what you want to do with them.
According to documentation for [BasicHttpBinding](https://msdn.microsoft.com/en-us/library/system.servicemodel.basichttpbinding%28v=vs.110%29.aspx) and [WSHttpBinding](https://msdn.microsoft.com/en-us/library/system.servicemodel.wshttpbinding%28v=vs.110%29.aspx), the common base class seems to be `System.ServiceModel.Channels.Binding`,
**You should use `f12` to check anyway, because there's probably an interface in there that defines the members that you need to use.**
Second, You have to declare it outside the context of your if statement
```
System.ServiceModel.Channels.Binding binding;
if(bindingObject == "basic")
{
binding = ...
}
else
{
binding = ...
}
``` | It's perfect use case for dynamic keyword
```
dynamic binding;
if (bindingObject == "basic")
{
binding = new System.ServiceModel.BasicHttpBinding();
}
else
{
binding = new System.ServiceModel.WSHttpBinding();
}
```
Then you can access the following
```
binding.MaxBufferPoolSize = 10;
``` |
36,802,272 | I am attempting to pass a string into a method and based on what string is passed in, either instantiate BasicHttpBinding or WSHttpBinding. The following if statement is in my code.
```
if(bindingObject == "basic")
{System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();}
else
{System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();
```
This code gives me the error
>
> The name 'binding' does not exist in the current context
>
>
>
From my research it seems I have to use a common base class between the two service models if I want to use the variable named *binding* no matter which ServiceModel I need to use.
My question is, what is the common base class that would work? Or is there a way to do this. The closest I have found is System.ServiceModel.Channels.Binding but then I get the error such as
>
> does not contain a definition for 'MaxBufferPoolSize' and no extension method 'MaxBufferPoolSize' accepting a first argument of tyep 'System.ServiceModel.Channels.Binding' could be found
>
>
> | 2016/04/22 | ['https://Stackoverflow.com/questions/36802272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3150921/'] | The problem you're facing is because of scoping of local variables. According to C# specs for scoping from MSDN,
>
> Scopes can be nested, and an inner scope may redeclare the meaning of a name from an outer scope (this does not, however, remove the restriction imposed by §1.20 that within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block).
>
>
>
Another from spec for identifiers scoping,
>
> For each occurrence of a given identifier as a simple-name in an expression or declarator, within the local variable declaration space, immediately enclosing block, or switch-block of that occurrence, every other occurrence of the same identifier as a simple-name in an expression or declarator within the immediately enclosing block or switch-block must refer to the same entity. This rule ensures that the meaning of a name is always the same within a given block, switch block, for-, foreach- or using-statement, or anonymous function.
>
>
>
Now moving to the error you're facing:
`BasicHttpBinding` is derived from HttpBindingBase which derived from `Binding` and implement `IBindingRuntimePreferences`.
`WSHttpBinding` is dervied from WSHttpBindingBase which derived from `Binding` and implement `IBindingRuntimePreferences`.
But the property `MaxBufferPoolSize` resides in HttpBindingBase and WsHttpBindingBase and not in their common parent `Binding` or `IBindingRuntimePreferences`. Which means you can not use a common class to represent these bindings. Rather you should use `dynamic` as type which would bind the types at runtime instead of compile time.
```
Public dynamic GetBinding(string bindingObject)
{
if (bindingObject == "basic")
{
binding = new System.ServiceModel.BasicHttpBinding();
}
else
{
binding = new System.ServiceModel.WSHttpBinding();
}
return binding;
}
``` | You could use wither the Binding base class or the IBindingRuntimePreferences interface, if that provides access to the functionality you need.
```
//System.ServiceModel.Channels.Binding binding;
System.ServiceModel.Channels.IBindingRuntimePreferences binding;
if(bindingObject == "basic")
binding = new System.ServiceModel.BasicHttpBinding();}
else
binding = new System.ServiceModel.WSHttpBinding();
``` |
36,802,272 | I am attempting to pass a string into a method and based on what string is passed in, either instantiate BasicHttpBinding or WSHttpBinding. The following if statement is in my code.
```
if(bindingObject == "basic")
{System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();}
else
{System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();
```
This code gives me the error
>
> The name 'binding' does not exist in the current context
>
>
>
From my research it seems I have to use a common base class between the two service models if I want to use the variable named *binding* no matter which ServiceModel I need to use.
My question is, what is the common base class that would work? Or is there a way to do this. The closest I have found is System.ServiceModel.Channels.Binding but then I get the error such as
>
> does not contain a definition for 'MaxBufferPoolSize' and no extension method 'MaxBufferPoolSize' accepting a first argument of tyep 'System.ServiceModel.Channels.Binding' could be found
>
>
> | 2016/04/22 | ['https://Stackoverflow.com/questions/36802272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3150921/'] | The problem you're facing is because of scoping of local variables. According to C# specs for scoping from MSDN,
>
> Scopes can be nested, and an inner scope may redeclare the meaning of a name from an outer scope (this does not, however, remove the restriction imposed by §1.20 that within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block).
>
>
>
Another from spec for identifiers scoping,
>
> For each occurrence of a given identifier as a simple-name in an expression or declarator, within the local variable declaration space, immediately enclosing block, or switch-block of that occurrence, every other occurrence of the same identifier as a simple-name in an expression or declarator within the immediately enclosing block or switch-block must refer to the same entity. This rule ensures that the meaning of a name is always the same within a given block, switch block, for-, foreach- or using-statement, or anonymous function.
>
>
>
Now moving to the error you're facing:
`BasicHttpBinding` is derived from HttpBindingBase which derived from `Binding` and implement `IBindingRuntimePreferences`.
`WSHttpBinding` is dervied from WSHttpBindingBase which derived from `Binding` and implement `IBindingRuntimePreferences`.
But the property `MaxBufferPoolSize` resides in HttpBindingBase and WsHttpBindingBase and not in their common parent `Binding` or `IBindingRuntimePreferences`. Which means you can not use a common class to represent these bindings. Rather you should use `dynamic` as type which would bind the types at runtime instead of compile time.
```
Public dynamic GetBinding(string bindingObject)
{
if (bindingObject == "basic")
{
binding = new System.ServiceModel.BasicHttpBinding();
}
else
{
binding = new System.ServiceModel.WSHttpBinding();
}
return binding;
}
``` | It's perfect use case for dynamic keyword
```
dynamic binding;
if (bindingObject == "basic")
{
binding = new System.ServiceModel.BasicHttpBinding();
}
else
{
binding = new System.ServiceModel.WSHttpBinding();
}
```
Then you can access the following
```
binding.MaxBufferPoolSize = 10;
``` |
700,963 | **THE GEAR:**
* Midtower running Ubuntu 14.04 for the host
* An HP t610 Thin Client running a stripped-down embedded copy of Windows 7 and VMWare. Note that the client factory resets with every boot.
* DAC is a Behringer U-Control UCA202 which outputs the host's audio via USB on the client to my hi-fi.
**CURRENTLY USING:**
I tried NoMachine but it has a few key problems:
NoMachine fails to detect any display devices half the time I connect, so I'm stuck with 320 x 240 default resolution.
It [lacks support for client USB devices when connecting to Ubuntu 14.04](https://www.nomachine.com/TR11L04682). As I use a USB DAC for this music workstation it rules the service out as an option.
**SO FAR I'VE EXPLORED:**
NoMachine - (see above)
TightVNC - miserable performance; best for remote viewing only with no input devices
RealVNC - sluggish refresh rate at all quality settings. No USB sound support
VMWare - not avail. for Windows
Vinagre - not avail. for Windows
Remmina - not avail. for Windows
KRDC - not avail. for Windows
Are there any viable solutions to pair an Ubuntu host with a Windows 7 client with remote USB support? | 2015/11/21 | ['https://askubuntu.com/questions/700963', 'https://askubuntu.com', 'https://askubuntu.com/users/474069/'] | There are only executable versions of Concorde and Linkern, not less, not more.
Compile your own version:
```
mkdir -p ~/src
cd ~/src
wget http://www.math.uwaterloo.ca/tsp/concorde/downloads/codes/src/co031219.tgz
tar xf co031219.tgz
cd co031219
./configure
make
```
There is no rule to install (`make install`). All needed binaries are in subfolders of the source folder:
>
> This builds the concorde library (concorde.a), header file
> (concorde.h), and several executable programs, including:
>
>
>
> ```
> TSP/concorde the TSP solver
> LINKERN/linkern the Lin-Kernighan TSP heuristic
> EDGEGEN/edgegen generates edge sets
> FMATCH/fmatch solves fractional 2-matching problems
>
> ```
>
> NOTE that to build the concorde TSP solver (for the exact solution of
> TSPs), you must specify an LP solver in the configure step (either
> QSopt for CPLEX).
>
>
> A short help menu for each of the executable codes can be obtained by
> executing the code without any option, for example "concorde". A
> typical way to run the concorde solver is to use: "concorde
> myprob.tsp" where myprob.tsp is a TSP instance in TSPLIB format. To
> test the concorde solver run "concorde -s 99 -k 100" (this should
> generate and solve a random geometric TSP on 100 points).#
>
>
>
[Source](http://www.math.uwaterloo.ca/tsp/concorde/DOC/README.html) | The instructions by @A.B. above are correct, but they do not include a description of how to install an LP solver. An LP solver is necessary to solve the TSP exactly using concorde.
To install an LP solver on Ubuntu, download the BETA version of qsopt from here: <http://www.math.uwaterloo.ca/~bico/qsopt/beta/index.html> (all the files listed under **Red Hat Linux, gcc 3.4.3 (AMD 64-bit)**) and put them in a directory on your machine. Then go to the unzipped concorde folder and run `./configure --with-qsopt=<full path to qsopt files>` making sure NOT to include a trailing / after the full path.
Next just run `make`. After that, cd into TSP and try running `./concorde -s 99 -k 100`
Good luck! |
224,144 | Trying to enable PHP in 10.6.6 server and it keeps loading the php text (I can see the php code on my .php file).
I've enabled the php5 module in server admin (and verified that it's in the httpd.conf).. anything else I can try?
![alt text](https://i.stack.imgur.com/hYzVF.png)
I also blew away the current httpd.conf and started again, no luck.... | 2011/01/19 | ['https://serverfault.com/questions/224144', 'https://serverfault.com', 'https://serverfault.com/users/31400/'] | You also need to make sure that the config for executing php code is in place
```
AddHandler php5-script .php
AddType text/html .php
``` | Don't forget to clean your browser cache or try with another browser. |
224,144 | Trying to enable PHP in 10.6.6 server and it keeps loading the php text (I can see the php code on my .php file).
I've enabled the php5 module in server admin (and verified that it's in the httpd.conf).. anything else I can try?
![alt text](https://i.stack.imgur.com/hYzVF.png)
I also blew away the current httpd.conf and started again, no luck.... | 2011/01/19 | ['https://serverfault.com/questions/224144', 'https://serverfault.com', 'https://serverfault.com/users/31400/'] | Turns out I was using php short tags and didn't have it turned on in the php.ini:
```
; This directive determines whether or not PHP will recognize code between
; <? and ?> tags as PHP source which should be processed as such. It's been
; recommended for several years that you not use the short tag "short cut" and
; instead to use the full <?php and ?> tag combination. With the wide spread use
; of XML and use of these tags by other languages, the server can become easily
; confused and end up parsing the wrong code in the wrong context. But because
; this short cut has been a feature for such a long time, it's currently still
; supported for backwards compatibility, but we recommend you don't use them.
; Default Value: On
; Development Value: Off
; Production Value: Off
; http://php.net/short-open-tag
short_open_tag = On
``` | Don't forget to clean your browser cache or try with another browser. |
3,346,305 | How can I configure PHP to send all outgoing mail to my own account so that I can test a business application without actually sending mails to unsuspecting businesses, such as "Congratulations, you have a new account. You will be billed for $xxx" ? | 2010/07/27 | ['https://Stackoverflow.com/questions/3346305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270511/'] | Rather than configuring PHP, a generalized solution would be to stand up a dummy SMTP server.
See [this question](https://stackoverflow.com/questions/1006650). | So you already wrote the application and it uses live email addresses, and now you want to test it? Did you use a centralized function for mail or are there tons of mail() calls all over the code? Sorry but you're going to have to change every mail() call. Do yourself a favor and replace them all with your own function, and then handle test/live functionality in that one location. |
3,346,305 | How can I configure PHP to send all outgoing mail to my own account so that I can test a business application without actually sending mails to unsuspecting businesses, such as "Congratulations, you have a new account. You will be billed for $xxx" ? | 2010/07/27 | ['https://Stackoverflow.com/questions/3346305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270511/'] | Rather than configuring PHP, a generalized solution would be to stand up a dummy SMTP server.
See [this question](https://stackoverflow.com/questions/1006650). | You can redirect all port 25 traffic on the server running PHP to a mailserver/port which delivers all mail to you.
This is the only 100% foolproof method of which I know. |
3,346,305 | How can I configure PHP to send all outgoing mail to my own account so that I can test a business application without actually sending mails to unsuspecting businesses, such as "Congratulations, you have a new account. You will be billed for $xxx" ? | 2010/07/27 | ['https://Stackoverflow.com/questions/3346305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270511/'] | Rather than configuring PHP, a generalized solution would be to stand up a dummy SMTP server.
See [this question](https://stackoverflow.com/questions/1006650). | You could create a Google Apps account (or use your dummy server), create a catch-all email account and have it sent to the domain. All you would have to do is look at the catch-all account. |
3,346,305 | How can I configure PHP to send all outgoing mail to my own account so that I can test a business application without actually sending mails to unsuspecting businesses, such as "Congratulations, you have a new account. You will be billed for $xxx" ? | 2010/07/27 | ['https://Stackoverflow.com/questions/3346305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270511/'] | Rather than configuring PHP, a generalized solution would be to stand up a dummy SMTP server.
See [this question](https://stackoverflow.com/questions/1006650). | I found this site: <http://dummysmtp.com/>.
My server is running qmail, so I edited the contents of /var/qmail/control/smtproutes like so:
>
> :smtp.dummysmtp.com *username* *password*
>
>
>
It worked when I sent a simple mail with PHP mail(), but later I found that mail is still getting out to other people. I had to crawl into the bowels of the code and found this:
```
/* Choose the mailer */
switch($this->Mailer) {
case 'sendmail':
$result = $this->SendmailSend($header, $body);
break;
case 'smtp':
$result = $this->SmtpSend($header, $body);
break;
case 'mail':
$result = $this->MailSend($header, $body);
break;
default:
$result = $this->MailSend($header, $body);
break;
//$this->SetError($this->Mailer . $this->Lang('mailer_not_supported'));
//$result = false;
//break;
}
```
So I had to make sure that each option was configured to send its mail to dummysmtp.com. Once I got that figured out, it all worked. |
3,346,305 | How can I configure PHP to send all outgoing mail to my own account so that I can test a business application without actually sending mails to unsuspecting businesses, such as "Congratulations, you have a new account. You will be billed for $xxx" ? | 2010/07/27 | ['https://Stackoverflow.com/questions/3346305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270511/'] | I found this site: <http://dummysmtp.com/>.
My server is running qmail, so I edited the contents of /var/qmail/control/smtproutes like so:
>
> :smtp.dummysmtp.com *username* *password*
>
>
>
It worked when I sent a simple mail with PHP mail(), but later I found that mail is still getting out to other people. I had to crawl into the bowels of the code and found this:
```
/* Choose the mailer */
switch($this->Mailer) {
case 'sendmail':
$result = $this->SendmailSend($header, $body);
break;
case 'smtp':
$result = $this->SmtpSend($header, $body);
break;
case 'mail':
$result = $this->MailSend($header, $body);
break;
default:
$result = $this->MailSend($header, $body);
break;
//$this->SetError($this->Mailer . $this->Lang('mailer_not_supported'));
//$result = false;
//break;
}
```
So I had to make sure that each option was configured to send its mail to dummysmtp.com. Once I got that figured out, it all worked. | So you already wrote the application and it uses live email addresses, and now you want to test it? Did you use a centralized function for mail or are there tons of mail() calls all over the code? Sorry but you're going to have to change every mail() call. Do yourself a favor and replace them all with your own function, and then handle test/live functionality in that one location. |
3,346,305 | How can I configure PHP to send all outgoing mail to my own account so that I can test a business application without actually sending mails to unsuspecting businesses, such as "Congratulations, you have a new account. You will be billed for $xxx" ? | 2010/07/27 | ['https://Stackoverflow.com/questions/3346305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270511/'] | I found this site: <http://dummysmtp.com/>.
My server is running qmail, so I edited the contents of /var/qmail/control/smtproutes like so:
>
> :smtp.dummysmtp.com *username* *password*
>
>
>
It worked when I sent a simple mail with PHP mail(), but later I found that mail is still getting out to other people. I had to crawl into the bowels of the code and found this:
```
/* Choose the mailer */
switch($this->Mailer) {
case 'sendmail':
$result = $this->SendmailSend($header, $body);
break;
case 'smtp':
$result = $this->SmtpSend($header, $body);
break;
case 'mail':
$result = $this->MailSend($header, $body);
break;
default:
$result = $this->MailSend($header, $body);
break;
//$this->SetError($this->Mailer . $this->Lang('mailer_not_supported'));
//$result = false;
//break;
}
```
So I had to make sure that each option was configured to send its mail to dummysmtp.com. Once I got that figured out, it all worked. | You can redirect all port 25 traffic on the server running PHP to a mailserver/port which delivers all mail to you.
This is the only 100% foolproof method of which I know. |
3,346,305 | How can I configure PHP to send all outgoing mail to my own account so that I can test a business application without actually sending mails to unsuspecting businesses, such as "Congratulations, you have a new account. You will be billed for $xxx" ? | 2010/07/27 | ['https://Stackoverflow.com/questions/3346305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270511/'] | I found this site: <http://dummysmtp.com/>.
My server is running qmail, so I edited the contents of /var/qmail/control/smtproutes like so:
>
> :smtp.dummysmtp.com *username* *password*
>
>
>
It worked when I sent a simple mail with PHP mail(), but later I found that mail is still getting out to other people. I had to crawl into the bowels of the code and found this:
```
/* Choose the mailer */
switch($this->Mailer) {
case 'sendmail':
$result = $this->SendmailSend($header, $body);
break;
case 'smtp':
$result = $this->SmtpSend($header, $body);
break;
case 'mail':
$result = $this->MailSend($header, $body);
break;
default:
$result = $this->MailSend($header, $body);
break;
//$this->SetError($this->Mailer . $this->Lang('mailer_not_supported'));
//$result = false;
//break;
}
```
So I had to make sure that each option was configured to send its mail to dummysmtp.com. Once I got that figured out, it all worked. | You could create a Google Apps account (or use your dummy server), create a catch-all email account and have it sent to the domain. All you would have to do is look at the catch-all account. |
23,809 | I used platformio IDE
I did "platformio lib install 1101"
(<http://platformio.org/lib/show/1101/ESP8266wifi>),
I installed this: <http://platformio.org/lib/show/549/WebSockets> (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:
>
> fatal error: ESP8266WiFi.h: No such file or directory fatal error:
>
>
> ESP8266WiFiMulti.h: No such file or directory fatal error:
>
>
> ESP8266Webserver.h: No such file or directory
>
>
> | 2016/05/03 | ['https://arduino.stackexchange.com/questions/23809', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/20742/'] | Have you overridden `lib_dir` in `platformio.ini`? If yes, please remove it. | Make sure **ESP8266WiFi.h**, **ESP8266WiFiMulti.h**, **ESP8266Webserver.h** files are located in the same directory where your \*.uno file present. |
23,809 | I used platformio IDE
I did "platformio lib install 1101"
(<http://platformio.org/lib/show/1101/ESP8266wifi>),
I installed this: <http://platformio.org/lib/show/549/WebSockets> (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:
>
> fatal error: ESP8266WiFi.h: No such file or directory fatal error:
>
>
> ESP8266WiFiMulti.h: No such file or directory fatal error:
>
>
> ESP8266Webserver.h: No such file or directory
>
>
> | 2016/05/03 | ['https://arduino.stackexchange.com/questions/23809', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/20742/'] | While Bhushan Patil's answer should work, it would still make future projects tedious. Instead you can add the header files to the hardware library, and use them at will, with the `#include <library>` syntax every other library uses in C/C++.
The PlatformIO IDE has a config file you can modify that tells the IDE where to look for libraries. You could read this file, and determine where to put your header files, such that PlatformIO could find them, or add a location to look for header files in. See this page from the PlatformIO documentation:
<http://docs.platformio.org/en/latest/projectconf.html>
Beyond that, you could also use the absolute path for the header file (library) you are trying to use, by doing something like
```
#include "/home/user/path/to/user/library.h"
``` | Make sure **ESP8266WiFi.h**, **ESP8266WiFiMulti.h**, **ESP8266Webserver.h** files are located in the same directory where your \*.uno file present. |
23,809 | I used platformio IDE
I did "platformio lib install 1101"
(<http://platformio.org/lib/show/1101/ESP8266wifi>),
I installed this: <http://platformio.org/lib/show/549/WebSockets> (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:
>
> fatal error: ESP8266WiFi.h: No such file or directory fatal error:
>
>
> ESP8266WiFiMulti.h: No such file or directory fatal error:
>
>
> ESP8266Webserver.h: No such file or directory
>
>
> | 2016/05/03 | ['https://arduino.stackexchange.com/questions/23809', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/20742/'] | Make sure **ESP8266WiFi.h**, **ESP8266WiFiMulti.h**, **ESP8266Webserver.h** files are located in the same directory where your \*.uno file present. | Note the different capitalization: ESP8266**w**i**f**i vs ESP8266**W**i**F**i. Confusing as it may be, these are actually two completely different libraries.
[ekstrand/ESP8266wifi](https://github.com/ekstrand/ESP8266wifi) is a library that is to be used when you are controlling an ESP8266 running the AT firmware over a serial connection from another microcontroller board such as a more traditional Arduino. The code does not run on the ESP8266.
ESP8266WiFi is a library bundled with the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/readme.rst). It is used for controlling the WiFi functionality of the ESP8266 when you are directly programming the ESP8266.
The WebSocket sketch you were attempting to compile was written for use with the latter library. The WebSockets library can not be used with the ekstrand/ESP8266wifi library or generally any configuration that uses the ESP8266 as a WiFi module running the AT firmware. |
23,809 | I used platformio IDE
I did "platformio lib install 1101"
(<http://platformio.org/lib/show/1101/ESP8266wifi>),
I installed this: <http://platformio.org/lib/show/549/WebSockets> (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:
>
> fatal error: ESP8266WiFi.h: No such file or directory fatal error:
>
>
> ESP8266WiFiMulti.h: No such file or directory fatal error:
>
>
> ESP8266Webserver.h: No such file or directory
>
>
> | 2016/05/03 | ['https://arduino.stackexchange.com/questions/23809', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/20742/'] | Have you overridden `lib_dir` in `platformio.ini`? If yes, please remove it. | Note the different capitalization: ESP8266**w**i**f**i vs ESP8266**W**i**F**i. Confusing as it may be, these are actually two completely different libraries.
[ekstrand/ESP8266wifi](https://github.com/ekstrand/ESP8266wifi) is a library that is to be used when you are controlling an ESP8266 running the AT firmware over a serial connection from another microcontroller board such as a more traditional Arduino. The code does not run on the ESP8266.
ESP8266WiFi is a library bundled with the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/readme.rst). It is used for controlling the WiFi functionality of the ESP8266 when you are directly programming the ESP8266.
The WebSocket sketch you were attempting to compile was written for use with the latter library. The WebSockets library can not be used with the ekstrand/ESP8266wifi library or generally any configuration that uses the ESP8266 as a WiFi module running the AT firmware. |
23,809 | I used platformio IDE
I did "platformio lib install 1101"
(<http://platformio.org/lib/show/1101/ESP8266wifi>),
I installed this: <http://platformio.org/lib/show/549/WebSockets> (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:
>
> fatal error: ESP8266WiFi.h: No such file or directory fatal error:
>
>
> ESP8266WiFiMulti.h: No such file or directory fatal error:
>
>
> ESP8266Webserver.h: No such file or directory
>
>
> | 2016/05/03 | ['https://arduino.stackexchange.com/questions/23809', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/20742/'] | While Bhushan Patil's answer should work, it would still make future projects tedious. Instead you can add the header files to the hardware library, and use them at will, with the `#include <library>` syntax every other library uses in C/C++.
The PlatformIO IDE has a config file you can modify that tells the IDE where to look for libraries. You could read this file, and determine where to put your header files, such that PlatformIO could find them, or add a location to look for header files in. See this page from the PlatformIO documentation:
<http://docs.platformio.org/en/latest/projectconf.html>
Beyond that, you could also use the absolute path for the header file (library) you are trying to use, by doing something like
```
#include "/home/user/path/to/user/library.h"
``` | Note the different capitalization: ESP8266**w**i**f**i vs ESP8266**W**i**F**i. Confusing as it may be, these are actually two completely different libraries.
[ekstrand/ESP8266wifi](https://github.com/ekstrand/ESP8266wifi) is a library that is to be used when you are controlling an ESP8266 running the AT firmware over a serial connection from another microcontroller board such as a more traditional Arduino. The code does not run on the ESP8266.
ESP8266WiFi is a library bundled with the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/readme.rst). It is used for controlling the WiFi functionality of the ESP8266 when you are directly programming the ESP8266.
The WebSocket sketch you were attempting to compile was written for use with the latter library. The WebSockets library can not be used with the ekstrand/ESP8266wifi library or generally any configuration that uses the ESP8266 as a WiFi module running the AT firmware. |
17,439 | Will they be able to walk-through it? If so, will they successfully cross over to the land of the dead, since they [can't normally](https://scifi.stackexchange.com/questions/9992/could-ghosts-in-harry-potter-move-on)? | 2012/05/29 | ['https://scifi.stackexchange.com/questions/17439', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/6385/'] | As I understand it, in the HP universe, Ghosts are not really the 'souls' of those they resemble -- they are more of an imprint of the consciousness that is left behind when some die. Similar to what is captured in Paintings and Photographs, actually.
Nick explained it in OotP:
>
> “Wizards can leave an imprint of themselves upon the earth, to walk palely where their living selves once trod,” said Nick miserably. “But very few wizards choose that path.”
>
>
> ...
>
>
> “I was afraid of death,” said Nick softly. “I chose to remain behind. I sometimes wonder whether I oughtn’t to have… well, that is neither here nor there… in fact, I am neither here nor there…” He gave a small sad chuckle. “I know nothing of the secrets of death, Harry, for I chose my feeble imitation of life instead. I believe learned wizards study the matter in the Department of Mysteries—”
>
>
>
Snape had a similar comment:
>
> A ghost, as I trust that you are all aware by now, is the imprint of a departed soul left upon the earth... and of course, as Potter so wisely tells us, transparent.
>
>
>
I read this as an indication it's closest to an echo or a shadow of a soul, not an actual one; in each case, they use the term 'imprint.'
The [Harry Potter wiki](http://harrypotter.wikia.com/wiki/Ghost) has this comment:
>
> As ghosts are imprints of souls of the said deceased wizards and witches, they are unable to move beyond the [veil](http://harrypotter.wikia.com/wiki/Veil), and are forever trapped in the world of living as intangible beings.
>
>
>
However, the canon status of it is questionable; it does seem consistent, though.
My **guess** (and that's all it is) would be that a ghost would either not be able to pass it, or would be destroyed; I have no canon backup, tho. Possibly you are right; their true 'self' is held to earth until the ghost passes on - if that is the case, then passing through the arch would allow them to pass on, although how much link the ghost has to the actual soul (assuming there is one) is also never stated.
Souls and the afterlife being of such core relevance to many religions, I think it's no accident that JKR left some of this ambiguous, the same way she mostly dodged religion showing up in the books. (Major Holidays are present.. but they have their secular aspects, and we never really see religious details.)
I hate giving a 'There's no answer, and short of [WOG](http://tvtropes.org/pmwiki/pmwiki.php/Main/WordOfGod), we aren't supposed to be able to conclude one', but I think that's exactly the case here. I'll be delighted if someone can come with a JKR quote to refute that, tho. :) | >
> Ghosts are transparent, moving, talking and thinking versions of wizards and witches who wished, for whatever reason, to remain on earth.
>
>
> *Tales of Beedle the Bard* - page 70 - Bloomsbury - *Babbity Rabbity and the Cackling Stump*
>
>
>
**[KHW](https://scifi.stackexchange.com/users/2292/khw)** also mentions what Snape and Nearly Headless Nick say about the properties of ghosts.
Respectfully, though, I can find no ***canon*** source that addresses whether a ghost can go through the Veil or, if so, what would happen to them. We know more about the Love Room in the Department of Mysteries than we do about the Death Room. Aside from what we learn in *Order of the Phoenix*, **I can't pinpoint a *canon* reference to the Death Room or the Veil, or a J.K. Rowling interview that discusses it or whether ghosts even *can* go through the Veil.** As always *please* correct me if I am wrong.
So I think we've established what a ghost is, but even to make a thoughtful speculative answer is difficult because while we know about ghosts, **we do not know what happens behind the Veil.** Well, 1) at least some people who have seen death can hear muttering voices of the dead behind the Veil and 2) some of the newly dead *can* slip behind the Veil once their life force leaves them (like Sirius); I don't *think* a spirit of a deceased individual becomes a ghost until they reject "moving on".
If I were to make my own speculative observation, based on J.K. Rowling's encouragement to her fans to interpret the King's Cross chapter in a way that feels comfortable, I would imagine perhaps she ***might*** feel the same about the Veil -- that it's open to interpretation. But that's still not a canonical answer. I don't think this question is truly answerable without more information from J.K. Rowling about the Veil. |
56,925,079 | So I am trying to use SDK java for my web page development. I have html file that show my map. What I would like to do is to get my data from Smartsheet and convert these data to points on the map.
I figure maybe java SDK is the file that I would be downloading, so I took the following step to download the java SDK
1. Install brew
2. install maven using command
brew install maven
3. follow steps in <https://github.com/smartsheet-platform/smartsheet-java-sdk#install-by-compiling-directly-from-source> to install sdk.
when I install the sdk, I got the following error in my terminal:
```
[ERROR] Source option 6 is no longer supported. Use 7 or later.
[ERROR] Target option 6 is no longer supported. Use 7 or later.
```
I am not sure what this means, how am I able to fix the problem?
I tried downloading the python sdk, and it works. I would like to incorporate the code to my web page (.js file) and I am not sure how it works.
any helps / recommendations would be appreciated. | 2019/07/07 | ['https://Stackoverflow.com/questions/56925079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11420526/'] | I would say your requirement "Germany for German users, Canada for Canadian users" is not possible.
If you take a look at the local availability of AAD B2C you will find that it's a "non-regional" service:
<https://azure.microsoft.com/en-us/global-infrastructure/services/?products=active-directory-b2c>
The "country or region" option that you can select when you create a new B2C tenant is not equal to data residency. There is a "mapping" between the option which you choose in the drop-down and the data residency. You can check this mapping here:
<https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-tenant-type>
Right now, there are two possible data residencies: the USA and Europe. Considering this limitation, you should evaluate whether you still want to have multiple B2C tenants.
In case you decide that you still need "local" data residency (hello GDPR) you should be aware that besides the login information you probably also have application data saved in databases. One approach for this scenario is to duplicate your deployment (App Gateway / Web App / Databases / Caches) into two regions (one for the US data residency and one for the EU residency ). You can use Azure Traffic Manager as a DNS load balancer and route your customers depending on their location to the desired region. You should check out <https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/n-tier/multi-region-sql-server>. Then you can, for example, deploy your MVC CORE application into two different Azure Web Applications. One of them using your US AAD B2C tenant and the other one the EU AAD B2C tenant. | You may determine the user's location directly in your application using the method of your choice, be it a user preference setting in the app, IP geomapping service, browser location or some other magic. Then in your app you can simply use the endpoint of one B2C tenant for German users and the endpoint of the another B2C tenant if the user is in Canada.
A similar approach should probably be used for the user data, as noted by @wlami. His approach is infrastructure-centric, mine is app-centric and gives you control on the user location detection mechanism. |
35,748,064 | ```
class foo {
foo();
unique_ptr<T, (void *)(T*)> ptr;
};
foo::foo() {
bool x = some operation;
if (!x) throw;
ptr = unique_ptr<T, (void *)(T*)>(new T(x), deleter);
}
```
This code does not compile because the unique pointer and its deleter get initialized with null (as I don't initialize it in the initializer list). I can't initialize it in the list because it's dependent on the variable `x` as shown above. How can I solve this deadlock? | 2016/03/02 | ['https://Stackoverflow.com/questions/35748064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4558644/'] | Try this:
```
foo()
: ptr(nullptr, deleter)
{
if (!some operation) { throw AppropriateException(); }
ptr.reset(new T(true));
}
``` | working example of using a generator and custom deleter:
```
#include <iostream>
#include <memory>
#include <vector>
struct bar {};
struct bar_deleter {
void operator()(bar* p) const noexcept {
try {
if (p) {
std::cout << "deleting p" << std::endl;
}
else {
std::cout << "not deleting p" << std::endl;
}
}
catch(...) {
}
}
};
bool some_condition()
{
static int counter = 0;
return (counter++ % 2) == 0;
}
struct foo {
using ptr_type = std::unique_ptr<bar, bar_deleter>;
foo()
: ptr(bar_generator())
{}
static ptr_type bar_generator() {
if (some_condition()) {
std::cout << "creating bar" << std::endl;
return { new bar, bar_deleter{} };
}
else {
std::cout << "not creating bar" << std::endl;
return { nullptr, bar_deleter{} };
}
}
ptr_type ptr;
};
int main()
{
using namespace std;
auto v = std::vector<foo>(10);
return 0;
}
```
expected results:
```
creating bar
not creating bar
creating bar
not creating bar
creating bar
not creating bar
creating bar
not creating bar
creating bar
not creating bar
deleting p
deleting p
deleting p
deleting p
deleting p
``` |
35,748,064 | ```
class foo {
foo();
unique_ptr<T, (void *)(T*)> ptr;
};
foo::foo() {
bool x = some operation;
if (!x) throw;
ptr = unique_ptr<T, (void *)(T*)>(new T(x), deleter);
}
```
This code does not compile because the unique pointer and its deleter get initialized with null (as I don't initialize it in the initializer list). I can't initialize it in the list because it's dependent on the variable `x` as shown above. How can I solve this deadlock? | 2016/03/02 | ['https://Stackoverflow.com/questions/35748064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4558644/'] | One solution would be to add a static function that determines what `x` should be and then return it to the constructor of the `unique_ptr` in the member initialization list
```
foo() : ptr(construct_t(), deleter) {}
static T* construct_t()
{
bool x = some operation;
if(!x) throw;
return new T(x);
}
``` | working example of using a generator and custom deleter:
```
#include <iostream>
#include <memory>
#include <vector>
struct bar {};
struct bar_deleter {
void operator()(bar* p) const noexcept {
try {
if (p) {
std::cout << "deleting p" << std::endl;
}
else {
std::cout << "not deleting p" << std::endl;
}
}
catch(...) {
}
}
};
bool some_condition()
{
static int counter = 0;
return (counter++ % 2) == 0;
}
struct foo {
using ptr_type = std::unique_ptr<bar, bar_deleter>;
foo()
: ptr(bar_generator())
{}
static ptr_type bar_generator() {
if (some_condition()) {
std::cout << "creating bar" << std::endl;
return { new bar, bar_deleter{} };
}
else {
std::cout << "not creating bar" << std::endl;
return { nullptr, bar_deleter{} };
}
}
ptr_type ptr;
};
int main()
{
using namespace std;
auto v = std::vector<foo>(10);
return 0;
}
```
expected results:
```
creating bar
not creating bar
creating bar
not creating bar
creating bar
not creating bar
creating bar
not creating bar
creating bar
not creating bar
deleting p
deleting p
deleting p
deleting p
deleting p
``` |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | When Atlantis was sinking, the residents knew about it only slightly in advance. Being sensible people, they rushed into their basements and shut the doors. One atlantis had sunk, they dug between the basements to form a network of underwater/underground rooms. They somehow figured out how to get air down there (and how to build airlocks), and decided there was no reason for them to move. Over the past thousand years, the sea gradually destroyed all of the buildings.
If you know what to look for the doors aren't hard to find, but the lack of above-sea-floor structures make it almost impossible to locate on sonar. | In an old short story I wrote years ago (but never published because my writing was *meh*), I figured that Atlantis was sitting on the top of a volcanic island and during an earthquake, the city that had overdevelopped to the point of weakening the soil, fell into a nearby oceanic trench upside-down. The city remained mainly intact, but the city acting like a plug at the top of a bottleneck, the citizens never could escape to the surface again.
Here is a pic of what I mean (sorry for the language in the image, I was on the version of [this wikipedia](https://en.wikipedia.org/wiki/Abyssal_plain) article when I took it):
[![enter image description here](https://i.stack.imgur.com/By0i9.png)](https://i.stack.imgur.com/By0i9.png)
Thus making the city undetectable by any means without resorting to magic. |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | Reasonably, an underwater city would not particularly look like the cities we are familiar with and would not be recognized as a settlement unless someone goes and looks at with Mark II Eyeball.
They would have no interest in roads. So there would be no easily discernible grid. Transport and travel would then happen above the buildings using some sort of flotation devices and draft animals. Always available "water transport" beats roads.
In modern times these would probably be replaced by vehicles. If the atlanteans can breathe down there no hard, acoustically reflective pressurized hull is needed, so making the vehicles stealthy should not be particularly hard.
With no need for roads and vastly reduced level of fire hazards buildings would be built wall-to-wall. Bulk transport within the city could be then handled by connecting the buildings. If you have horizontal channels or rings with one-way traffic you can make the water move and cargo transport becomes a matter of putting stuff into the channel and taking them out from it. Speed would be limited, but a system like this could have very large cargo capacity.
The system might work well enough that there is no need to transport cargo over the city. At that point you'd have lots of small ventilation holes and closed (sharks not welcome) vehicle hatches.
If the buildings of the city were of roughly same height this would look like a featureless plain to sonar as long as the atlanteans do not use metal construction on top.
The city would then only be visible at the edges where the buildings rise above their surroundings. This would probably be fairly simple to hide by just letting detritus from the construction accumulate against the walls. Additionally there is no real need to make the buildings that high. The good economics of water transport and lack of city walls would allow the city to spread and significant part of the height of the buildings might be below the level of the surface. I think it would blend naturally unless someone specifically looks.
So even without particular effort to hide from sonar, a realistic underwater city might be entirely invisible to sonar by virtue of being entirely different. No tech beyond neolithic (city building) required. | When Atlantis was sinking, the residents knew about it only slightly in advance. Being sensible people, they rushed into their basements and shut the doors. One atlantis had sunk, they dug between the basements to form a network of underwater/underground rooms. They somehow figured out how to get air down there (and how to build airlocks), and decided there was no reason for them to move. Over the past thousand years, the sea gradually destroyed all of the buildings.
If you know what to look for the doors aren't hard to find, but the lack of above-sea-floor structures make it almost impossible to locate on sonar. |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | When Atlantis was sinking, the residents knew about it only slightly in advance. Being sensible people, they rushed into their basements and shut the doors. One atlantis had sunk, they dug between the basements to form a network of underwater/underground rooms. They somehow figured out how to get air down there (and how to build airlocks), and decided there was no reason for them to move. Over the past thousand years, the sea gradually destroyed all of the buildings.
If you know what to look for the doors aren't hard to find, but the lack of above-sea-floor structures make it almost impossible to locate on sonar. | If the Atlanteans wanted to be invisible to radar they could use materials similar to the rubber like tiles used on submarines. If they needed a particularly primitive version of this then large amounts of organic matter, especially seaweed of the sort with the flotation air sacs, would be useful in deflecting and absorbing sonar if strung out above their city. |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | >
> Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar?
>
>
>
You **already** need magic or very advanced technology to justify a city existing **underwater**. However, given that Atlanteans somehow either have or don't need air...
* Once submerged, the city might have just decayed away - it wasn't built of stone but of unbaked clay bricks or organic matter. The Atlanteans now live in smaller structures that sonar can't resolve.
* The submersion was slow enough that those Atlanteans as didn't want to simply relocate, and saw the futility of building taller and taller structures above ground, built instead deeper and stronger abodes below what is now the sea floor.
* They might have their city covered, naturally or artificially, with a sound-reflecting layer that mimics the sea-floor (for insulating purposes, for example: several thermal insulators are also good sound insulators). They might not even be aware of this effect, unless informed by friendly cetaceans (if they were, could we say they did this on *porpoise*?)
Atlanteans still can hit ships with colossal bubbles of methane, that have the same effect on a ship as a torpedo (they make the supporting water underneath disappear, so that the ship's weight cracks the vessel in the middle). Additionally, a delayed fuse can turn the bubble into a fuel-air bomb, capable of taking down a plane if it flies low enough.
The problem, possibly requiring magic, is now *how they know that there are ships and even planes above*, and where very exactly they are and how fast they're going - it takes time for a methane torpedo to hit. | In an old short story I wrote years ago (but never published because my writing was *meh*), I figured that Atlantis was sitting on the top of a volcanic island and during an earthquake, the city that had overdevelopped to the point of weakening the soil, fell into a nearby oceanic trench upside-down. The city remained mainly intact, but the city acting like a plug at the top of a bottleneck, the citizens never could escape to the surface again.
Here is a pic of what I mean (sorry for the language in the image, I was on the version of [this wikipedia](https://en.wikipedia.org/wiki/Abyssal_plain) article when I took it):
[![enter image description here](https://i.stack.imgur.com/By0i9.png)](https://i.stack.imgur.com/By0i9.png)
Thus making the city undetectable by any means without resorting to magic. |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | Reasonably, an underwater city would not particularly look like the cities we are familiar with and would not be recognized as a settlement unless someone goes and looks at with Mark II Eyeball.
They would have no interest in roads. So there would be no easily discernible grid. Transport and travel would then happen above the buildings using some sort of flotation devices and draft animals. Always available "water transport" beats roads.
In modern times these would probably be replaced by vehicles. If the atlanteans can breathe down there no hard, acoustically reflective pressurized hull is needed, so making the vehicles stealthy should not be particularly hard.
With no need for roads and vastly reduced level of fire hazards buildings would be built wall-to-wall. Bulk transport within the city could be then handled by connecting the buildings. If you have horizontal channels or rings with one-way traffic you can make the water move and cargo transport becomes a matter of putting stuff into the channel and taking them out from it. Speed would be limited, but a system like this could have very large cargo capacity.
The system might work well enough that there is no need to transport cargo over the city. At that point you'd have lots of small ventilation holes and closed (sharks not welcome) vehicle hatches.
If the buildings of the city were of roughly same height this would look like a featureless plain to sonar as long as the atlanteans do not use metal construction on top.
The city would then only be visible at the edges where the buildings rise above their surroundings. This would probably be fairly simple to hide by just letting detritus from the construction accumulate against the walls. Additionally there is no real need to make the buildings that high. The good economics of water transport and lack of city walls would allow the city to spread and significant part of the height of the buildings might be below the level of the surface. I think it would blend naturally unless someone specifically looks.
So even without particular effort to hide from sonar, a realistic underwater city might be entirely invisible to sonar by virtue of being entirely different. No tech beyond neolithic (city building) required. | In an old short story I wrote years ago (but never published because my writing was *meh*), I figured that Atlantis was sitting on the top of a volcanic island and during an earthquake, the city that had overdevelopped to the point of weakening the soil, fell into a nearby oceanic trench upside-down. The city remained mainly intact, but the city acting like a plug at the top of a bottleneck, the citizens never could escape to the surface again.
Here is a pic of what I mean (sorry for the language in the image, I was on the version of [this wikipedia](https://en.wikipedia.org/wiki/Abyssal_plain) article when I took it):
[![enter image description here](https://i.stack.imgur.com/By0i9.png)](https://i.stack.imgur.com/By0i9.png)
Thus making the city undetectable by any means without resorting to magic. |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | Reasonably, an underwater city would not particularly look like the cities we are familiar with and would not be recognized as a settlement unless someone goes and looks at with Mark II Eyeball.
They would have no interest in roads. So there would be no easily discernible grid. Transport and travel would then happen above the buildings using some sort of flotation devices and draft animals. Always available "water transport" beats roads.
In modern times these would probably be replaced by vehicles. If the atlanteans can breathe down there no hard, acoustically reflective pressurized hull is needed, so making the vehicles stealthy should not be particularly hard.
With no need for roads and vastly reduced level of fire hazards buildings would be built wall-to-wall. Bulk transport within the city could be then handled by connecting the buildings. If you have horizontal channels or rings with one-way traffic you can make the water move and cargo transport becomes a matter of putting stuff into the channel and taking them out from it. Speed would be limited, but a system like this could have very large cargo capacity.
The system might work well enough that there is no need to transport cargo over the city. At that point you'd have lots of small ventilation holes and closed (sharks not welcome) vehicle hatches.
If the buildings of the city were of roughly same height this would look like a featureless plain to sonar as long as the atlanteans do not use metal construction on top.
The city would then only be visible at the edges where the buildings rise above their surroundings. This would probably be fairly simple to hide by just letting detritus from the construction accumulate against the walls. Additionally there is no real need to make the buildings that high. The good economics of water transport and lack of city walls would allow the city to spread and significant part of the height of the buildings might be below the level of the surface. I think it would blend naturally unless someone specifically looks.
So even without particular effort to hide from sonar, a realistic underwater city might be entirely invisible to sonar by virtue of being entirely different. No tech beyond neolithic (city building) required. | >
> Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar?
>
>
>
You **already** need magic or very advanced technology to justify a city existing **underwater**. However, given that Atlanteans somehow either have or don't need air...
* Once submerged, the city might have just decayed away - it wasn't built of stone but of unbaked clay bricks or organic matter. The Atlanteans now live in smaller structures that sonar can't resolve.
* The submersion was slow enough that those Atlanteans as didn't want to simply relocate, and saw the futility of building taller and taller structures above ground, built instead deeper and stronger abodes below what is now the sea floor.
* They might have their city covered, naturally or artificially, with a sound-reflecting layer that mimics the sea-floor (for insulating purposes, for example: several thermal insulators are also good sound insulators). They might not even be aware of this effect, unless informed by friendly cetaceans (if they were, could we say they did this on *porpoise*?)
Atlanteans still can hit ships with colossal bubbles of methane, that have the same effect on a ship as a torpedo (they make the supporting water underneath disappear, so that the ship's weight cracks the vessel in the middle). Additionally, a delayed fuse can turn the bubble into a fuel-air bomb, capable of taking down a plane if it flies low enough.
The problem, possibly requiring magic, is now *how they know that there are ships and even planes above*, and where very exactly they are and how fast they're going - it takes time for a methane torpedo to hit. |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | >
> Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar?
>
>
>
You **already** need magic or very advanced technology to justify a city existing **underwater**. However, given that Atlanteans somehow either have or don't need air...
* Once submerged, the city might have just decayed away - it wasn't built of stone but of unbaked clay bricks or organic matter. The Atlanteans now live in smaller structures that sonar can't resolve.
* The submersion was slow enough that those Atlanteans as didn't want to simply relocate, and saw the futility of building taller and taller structures above ground, built instead deeper and stronger abodes below what is now the sea floor.
* They might have their city covered, naturally or artificially, with a sound-reflecting layer that mimics the sea-floor (for insulating purposes, for example: several thermal insulators are also good sound insulators). They might not even be aware of this effect, unless informed by friendly cetaceans (if they were, could we say they did this on *porpoise*?)
Atlanteans still can hit ships with colossal bubbles of methane, that have the same effect on a ship as a torpedo (they make the supporting water underneath disappear, so that the ship's weight cracks the vessel in the middle). Additionally, a delayed fuse can turn the bubble into a fuel-air bomb, capable of taking down a plane if it flies low enough.
The problem, possibly requiring magic, is now *how they know that there are ships and even planes above*, and where very exactly they are and how fast they're going - it takes time for a methane torpedo to hit. | If the Atlanteans wanted to be invisible to radar they could use materials similar to the rubber like tiles used on submarines. If they needed a particularly primitive version of this then large amounts of organic matter, especially seaweed of the sort with the flotation air sacs, would be useful in deflecting and absorbing sonar if strung out above their city. |
94,839 | It is still a myth as far as our modern civilization is concerned, Atlantis located somewhere within the devil's triangle and it's inhabitants had struck down many planes and vessels daring to disturb the peace. Without resorting to magic how can Atlantis disappear from the sonar? (Answer with most primitive tech wins.) | 2017/10/14 | ['https://worldbuilding.stackexchange.com/questions/94839', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/8400/'] | Reasonably, an underwater city would not particularly look like the cities we are familiar with and would not be recognized as a settlement unless someone goes and looks at with Mark II Eyeball.
They would have no interest in roads. So there would be no easily discernible grid. Transport and travel would then happen above the buildings using some sort of flotation devices and draft animals. Always available "water transport" beats roads.
In modern times these would probably be replaced by vehicles. If the atlanteans can breathe down there no hard, acoustically reflective pressurized hull is needed, so making the vehicles stealthy should not be particularly hard.
With no need for roads and vastly reduced level of fire hazards buildings would be built wall-to-wall. Bulk transport within the city could be then handled by connecting the buildings. If you have horizontal channels or rings with one-way traffic you can make the water move and cargo transport becomes a matter of putting stuff into the channel and taking them out from it. Speed would be limited, but a system like this could have very large cargo capacity.
The system might work well enough that there is no need to transport cargo over the city. At that point you'd have lots of small ventilation holes and closed (sharks not welcome) vehicle hatches.
If the buildings of the city were of roughly same height this would look like a featureless plain to sonar as long as the atlanteans do not use metal construction on top.
The city would then only be visible at the edges where the buildings rise above their surroundings. This would probably be fairly simple to hide by just letting detritus from the construction accumulate against the walls. Additionally there is no real need to make the buildings that high. The good economics of water transport and lack of city walls would allow the city to spread and significant part of the height of the buildings might be below the level of the surface. I think it would blend naturally unless someone specifically looks.
So even without particular effort to hide from sonar, a realistic underwater city might be entirely invisible to sonar by virtue of being entirely different. No tech beyond neolithic (city building) required. | If the Atlanteans wanted to be invisible to radar they could use materials similar to the rubber like tiles used on submarines. If they needed a particularly primitive version of this then large amounts of organic matter, especially seaweed of the sort with the flotation air sacs, would be useful in deflecting and absorbing sonar if strung out above their city. |
63,856,249 | I'm trying to identify CSS color values in strings. Not only hex, but rgb and hsl as well, I've found these throughout different stack posts:
```js
const hexRegex = /#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/
const hslRegex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g
const rgbRegex = /rgba?\(((25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*?){2}(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,?\s*([01]\.?\d*?)?\)/
```
The **rgbRegex** is able to match `rgb()` colors as well as `rgba()` colors, while the **hexRegex** can match solid colors `#000` and `#000000` but it will not match colors with alpha values like `#0000` and `#00000000`. Similarly, the **hslRegex** can match `hsl()` but not `hsla()`.
Is there a way to write the **hexRegex** and the **hslRegex** such that they also match colors with alpha values?
It would also be great if the **hslRegex** could parse out the individual hue, saturation and lightness (and alpha) values when using the JavaScript `.match()` method, which is what the **rgbRegex** does. | 2020/09/12 | ['https://Stackoverflow.com/questions/63856249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1104148/'] | You can use the following regular expressions. Note that the regular expressions make use of the `i` flag to match any lowercase and uppercase variants. These have full support for the formats outlined in [Mozilla's documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value) (I'm too lazy to go through all of the CSSWG docs).
### Hex
`#RGB[A]` or `#RRGGBB[AA]`
[See regex in use here](https://regex101.com/r/RS3uAs/2)
```
#[a-f\d]{3}(?:[a-f\d]?|(?:[a-f\d]{3}(?:[a-f\d]{2})?)?)\b
```
### HSL
`hsl[a](H, S, L[, A])` or `hsl[a](H S L[ / A])`
[See regex in use here](https://regex101.com/r/RS3uAs/7)
```
hsla?\((?:(-?\d+(?:deg|g?rad|turn)?),\s*((?:\d{1,2}|100)%),\s*((?:\d{1,2}|100)%)(?:,\s*((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?|(-?\d+(?:deg|g?rad|turn)?)\s+((?:\d{1,2}|100)%)\s+((?:\d{1,2}|100)%)(?:\s+((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?)\)
```
If your language permits regex recursion (this is shorter):
```
hsla?\((?:(-?\d+(?:deg|g?rad|turn)?),\s*((?:\d{1,2}|100)%),\s*((?2))(?:,\s*((?2)|0(?:\.\d+)?|1))?|(-?\d+(?:deg|g?rad|turn)?)\s+((?2))\s+((?2))(?:\s+((?2)|0(?:\.\d+)?|1))?)\)
```
### RBG
`rgb[a](R, G, B[, A])` or `rgb[a](R G B[ / A])`
```
rgba?\((?:(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%),\s*(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%),\s*(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%)(?:,\s*((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?|(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%)\s+(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%)\s+(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%)(?:\s+((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?)\)
```
If your language permits regex recursion (this is shorter):
```
rgba?\((?:(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%),\s*((?1)),\s*((?1))(?:,\s*((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?|(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,2}|100)%)\s+((?1))\s+((?1))(?:\s+((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?)\)
```
[See regex in use here](https://regex101.com/r/RS3uAs/6) | You can add another `(,\s*[\d.]*)?` right before the closing bracket which makes the alpha value optional.
```
const hslReges = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*[\d.]*)?\)/g
``` |
3,446,203 | For constants $\alpha$, $\beta$, and $\gamma$ with $0<\alpha<\beta<\gamma$, define a sequence by $a\_1 = \gamma$ and $$a\_{n+1}=\frac{a\_{n}^2+\alpha\beta}{\alpha+\beta}$$
I am fairly sure that this sequence diverges to $+\infty$, but how can I prove it? I thought it might be something like showing by induction that $a\_n > n$ for all $n$, but that turns out to be not necessarily true (e.g. for $n=1$). And $a\_n \geq n-1$ is true for $n=1$ but the inductive step doesn't work out. Any suggestions would be much appreciated. | 2019/11/22 | ['https://math.stackexchange.com/questions/3446203', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/554727/'] | The actual definition of a presentation is that $\left< G\mid R\right>$ stands for the quotient of the free group over the set $G$ quotiented by the normal closure of the set $R$.
The rough definition is that elements of the resulting group are going to be words in the alphabet $G$, subject to the relations present in $R$ (any element of $R$ is set to equal the identity). | >
> for example $1$ and $2$ are thus terms without an equal sign in $\Bbb Z/3$ how are they equal to the group identity?
>
>
>
They're not since they're neither relations nor relators. |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | I made this function for me using the previous answers.
Maybe it is useful to someone here =)
```
utmzone <- function(lon,lat) {
## Special Cases for Norway & Svalbard
if (lat > 55 & lat < 64 & lon > 2 & lon < 6){
band <- 32
} else {
if (lat > 71 & lon >= 6 & lon < 9){
band <- 31
} else {
if (lat > 71 & lon >= 9 & lon < 12){
band <- 33
} else {
if (lat > 71 & lon >= 18 & lon < 21){
band <- 33
} else {
if (lat > 71 & lon >= 21 & lon < 24){
band <- 35
} else {
if (lat > 71 & lon >= 30 & lon < 33){
band <- 35
} else {
## Rest of the world
if (lon >= -180 & lon <= 180){
band <- (floor((lon + 180)/6) %% 60) + 1
} else {
band <- "something is wrong"
}}}}}}}
return(band)
}
utmzone(-43,-22)
#[1] 23
``` | So I had this problem today, that I needed to find the UTM zone from lat/long for points all over the globe. The trouble is that there's all these curly edge cases like Svalbard, Norway, and the poles:[![UTM curly edge cases](https://i.stack.imgur.com/Rhj62.jpg)](https://i.stack.imgur.com/Rhj62.jpg) (shown in red on this map) which will catch you out if you assume it's all regular!
Here's my R function to find UTM zones from lat/long pairs, with tests at the end for all of the curly edge cases.
```r
require(tidyverse)
require(purrr)
require(testthat)
find_one_utm_zone <- function(longitude, latitude) {
# Special zones for Svalbard
if (latitude >= 72.0 && latitude <= 84.0 ) {
if (longitude >= 0.0 && longitude < 9.0)
return("31X");
if (longitude >= 9.0 && longitude < 21.0)
return("33X")
if (longitude >= 21.0 && longitude < 33.0)
return("35X")
if (longitude >= 33.0 && longitude < 42.0)
return("37X")
}
# Special zones for Norway
if (latitude >= 56.0 && latitude < 64.0 ) {
if (longitude >= 0.0 && longitude < 3.0)
return("31V");
if (longitude >= 3.0 && longitude < 12.0)
return("32V")
}
# North + South Poles
if (latitude > 84.0){
if ((longitude+180)%%360-180 < 0) {return("Y")}
if ((longitude+180)%%360-180 > 0) {return("Z")}
} else if (latitude < -80.0){
if ((longitude+180)%%360-180 < 0) {return("A")}
if ((longitude+180)%%360-180 > 0) {return("B")}
}
# Everything in the middle
if ( (latitude>-80.0) && (latitude<=84.0) ){
mid_zones <- LETTERS[c(3:8,10:14,16:24)] # C to X, skip I and O
utm_letter <- mid_zones[ min(floor( (latitude + 80) / 8 )+1 , 20) ]
utm_number <- (floor( (longitude + 180) / 6 ) %% 60) + 1 # modulo in case longitude is 0 to 360 instead of -180 to 180
utm_zone <- paste0(utm_number, utm_letter)
return(utm_zone)
} else {
stop("lat long not valid (or something else broke)")
}
}
find_utm_zone <- function(lon, lat){
purrr::map2_chr(.x = lon, .y = lat, .f = find_one_utm_zone)
}
```
Example of use
```r
locs <-
tibble(lon = c(-100,30,150, 4, 7, 22, 0, 12, -34, -20),
lat = c(-45, 85, 12, 57, 81, 83, 5, -81, 85, 83),
desired_utm_zone = c("14G","Z","56P", "32V" ,"31X","35X","31N", "B","Y","27X"))
locs2 <-
locs %>%
mutate(utm_zone = find_utm_zone(lon = lon,lat = lat))
```
Test that it worked:
```r
testthat::expect_equal(locs2$utm_zone, locs2$desired_utm_zone)
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | **Edit:** For (non-R) code that works for *all* non-polar areas on earth, see [here](https://gis.stackexchange.com/questions/13291/is-there-a-simple-way-to-compute-the-utm-zone-from-a-lat-long-point) or [here](http://www.igorexchange.com/node/927).
---
Unless you are dealing with data from a couple of exceptional areas ([Svalbard and parts of Norway](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system#Exceptions)), this is a simple enough calculation that you might as well just do it yourself in R. Here is [Wikipedia's description](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system) of how longitude relates to UTM Zone number:
>
> The UTM system divides the surface of Earth between 80°S and 84°N latitude into 60 zones, each 6° of longitude in width. Zone 1 covers longitude 180° to 174° W; zone numbering increases eastward to zone 60 that covers longitude 174 to 180 East.
>
>
>
So, assuming that in your data longitudes to the west of the [Prime Meridian](http://en.wikipedia.org/wiki/Prime_Meridian) are encoded as running from -180 to 0 degrees, here's an R-code version of the above:
```
long2UTM <- function(long) {
(floor((long + 180)/6) %% 60) + 1
}
# Trying it out for San Francisco, clearly in UTM Zone 10
# in the figure in the Wikipedia article linked above
SFlong <- -122.4192
long2UTM(SFlong)
# [1] 10
```
That expression could obviously be simplified a bit, but I think in this form the logic underlying its construction is most clear. The `%% 60` bit is in there just in case some of your longitudes are greater than 180 or less than -180. | So I had this problem today, that I needed to find the UTM zone from lat/long for points all over the globe. The trouble is that there's all these curly edge cases like Svalbard, Norway, and the poles:[![UTM curly edge cases](https://i.stack.imgur.com/Rhj62.jpg)](https://i.stack.imgur.com/Rhj62.jpg) (shown in red on this map) which will catch you out if you assume it's all regular!
Here's my R function to find UTM zones from lat/long pairs, with tests at the end for all of the curly edge cases.
```r
require(tidyverse)
require(purrr)
require(testthat)
find_one_utm_zone <- function(longitude, latitude) {
# Special zones for Svalbard
if (latitude >= 72.0 && latitude <= 84.0 ) {
if (longitude >= 0.0 && longitude < 9.0)
return("31X");
if (longitude >= 9.0 && longitude < 21.0)
return("33X")
if (longitude >= 21.0 && longitude < 33.0)
return("35X")
if (longitude >= 33.0 && longitude < 42.0)
return("37X")
}
# Special zones for Norway
if (latitude >= 56.0 && latitude < 64.0 ) {
if (longitude >= 0.0 && longitude < 3.0)
return("31V");
if (longitude >= 3.0 && longitude < 12.0)
return("32V")
}
# North + South Poles
if (latitude > 84.0){
if ((longitude+180)%%360-180 < 0) {return("Y")}
if ((longitude+180)%%360-180 > 0) {return("Z")}
} else if (latitude < -80.0){
if ((longitude+180)%%360-180 < 0) {return("A")}
if ((longitude+180)%%360-180 > 0) {return("B")}
}
# Everything in the middle
if ( (latitude>-80.0) && (latitude<=84.0) ){
mid_zones <- LETTERS[c(3:8,10:14,16:24)] # C to X, skip I and O
utm_letter <- mid_zones[ min(floor( (latitude + 80) / 8 )+1 , 20) ]
utm_number <- (floor( (longitude + 180) / 6 ) %% 60) + 1 # modulo in case longitude is 0 to 360 instead of -180 to 180
utm_zone <- paste0(utm_number, utm_letter)
return(utm_zone)
} else {
stop("lat long not valid (or something else broke)")
}
}
find_utm_zone <- function(lon, lat){
purrr::map2_chr(.x = lon, .y = lat, .f = find_one_utm_zone)
}
```
Example of use
```r
locs <-
tibble(lon = c(-100,30,150, 4, 7, 22, 0, 12, -34, -20),
lat = c(-45, 85, 12, 57, 81, 83, 5, -81, 85, 83),
desired_utm_zone = c("14G","Z","56P", "32V" ,"31X","35X","31N", "B","Y","27X"))
locs2 <-
locs %>%
mutate(utm_zone = find_utm_zone(lon = lon,lat = lat))
```
Test that it worked:
```r
testthat::expect_equal(locs2$utm_zone, locs2$desired_utm_zone)
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | I made this function for me using the previous answers.
Maybe it is useful to someone here =)
```
utmzone <- function(lon,lat) {
## Special Cases for Norway & Svalbard
if (lat > 55 & lat < 64 & lon > 2 & lon < 6){
band <- 32
} else {
if (lat > 71 & lon >= 6 & lon < 9){
band <- 31
} else {
if (lat > 71 & lon >= 9 & lon < 12){
band <- 33
} else {
if (lat > 71 & lon >= 18 & lon < 21){
band <- 33
} else {
if (lat > 71 & lon >= 21 & lon < 24){
band <- 35
} else {
if (lat > 71 & lon >= 30 & lon < 33){
band <- 35
} else {
## Rest of the world
if (lon >= -180 & lon <= 180){
band <- (floor((lon + 180)/6) %% 60) + 1
} else {
band <- "something is wrong"
}}}}}}}
return(band)
}
utmzone(-43,-22)
#[1] 23
``` | Version for TypeScript, based on [Luiz Bondis summary](https://stackoverflow.com/a/65329856/189673):
```js
export function utmZoneFromLatLng(lat: number, lon: number) {
// Special Cases for Norway & Svalbard
if (lat > 55 && lat < 64 && lon > 2 && lon < 6) {
return 32;
}
if (lat > 71 && lon >= 6 && lon < 9) {
return 31;
}
if (lat > 71 && ((lon >= 9 && lon < 12) || (lon >= 18 && lon < 21))) {
return 33;
}
if (lat > 71 && ((lon >= 21 && lon < 24) || (lon >= 30 && lon < 33))) {
return 35;
}
// Rest of the world
if (lon >= -180 && lon <= 180) {
return (Math.floor((lon + 180) / 6) % 60) + 1;
}
throw new Error(`utmZoneFromLatLng: Cannot figure out UTM zone from give Lat: ${lat}, Lng: ${lon}`);
}
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | **Edit:** For (non-R) code that works for *all* non-polar areas on earth, see [here](https://gis.stackexchange.com/questions/13291/is-there-a-simple-way-to-compute-the-utm-zone-from-a-lat-long-point) or [here](http://www.igorexchange.com/node/927).
---
Unless you are dealing with data from a couple of exceptional areas ([Svalbard and parts of Norway](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system#Exceptions)), this is a simple enough calculation that you might as well just do it yourself in R. Here is [Wikipedia's description](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system) of how longitude relates to UTM Zone number:
>
> The UTM system divides the surface of Earth between 80°S and 84°N latitude into 60 zones, each 6° of longitude in width. Zone 1 covers longitude 180° to 174° W; zone numbering increases eastward to zone 60 that covers longitude 174 to 180 East.
>
>
>
So, assuming that in your data longitudes to the west of the [Prime Meridian](http://en.wikipedia.org/wiki/Prime_Meridian) are encoded as running from -180 to 0 degrees, here's an R-code version of the above:
```
long2UTM <- function(long) {
(floor((long + 180)/6) %% 60) + 1
}
# Trying it out for San Francisco, clearly in UTM Zone 10
# in the figure in the Wikipedia article linked above
SFlong <- -122.4192
long2UTM(SFlong)
# [1] 10
```
That expression could obviously be simplified a bit, but I think in this form the logic underlying its construction is most clear. The `%% 60` bit is in there just in case some of your longitudes are greater than 180 or less than -180. | Version for TypeScript, based on [Luiz Bondis summary](https://stackoverflow.com/a/65329856/189673):
```js
export function utmZoneFromLatLng(lat: number, lon: number) {
// Special Cases for Norway & Svalbard
if (lat > 55 && lat < 64 && lon > 2 && lon < 6) {
return 32;
}
if (lat > 71 && lon >= 6 && lon < 9) {
return 31;
}
if (lat > 71 && ((lon >= 9 && lon < 12) || (lon >= 18 && lon < 21))) {
return 33;
}
if (lat > 71 && ((lon >= 21 && lon < 24) || (lon >= 30 && lon < 33))) {
return 35;
}
// Rest of the world
if (lon >= -180 && lon <= 180) {
return (Math.floor((lon + 180) / 6) % 60) + 1;
}
throw new Error(`utmZoneFromLatLng: Cannot figure out UTM zone from give Lat: ${lat}, Lng: ${lon}`);
}
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | I don't know r-code but I suppose this PL/SQL code can help you with the exceptions:
```
UTMZone := Trunc((lon - Zone0WestMeridian) / d);
--Special Cases for Norway & Svalbard
CASE
WHEN (lat > 55) AND (UTMZone = 31) AND (lat < 64) AND (lon > 2) THEN UTMZone := 32;
WHEN (lat > 71) AND (UTMZone = 32) AND (lon < 9) THEN UTMZone := 31;
WHEN (lat > 71) AND (UTMZone = 32) AND (lon > 8) THEN UTMZone := 33;
WHEN (lat > 71) AND (UTMZone = 34) AND (lon < 21) THEN UTMZone := 33;
WHEN (lat > 71) AND (UTMZone = 34) AND (lon > 20) THEN UTMZone := 35;
WHEN (lat > 71) AND (UTMZone = 36) AND (lon < 33) THEN UTMZone := 35;
WHEN (lat > 71) AND (UTMZone = 36) AND (lon > 32) THEN UTMZone := 37;
ELSE UTMZone := UTMZone;
END CASE;
``` | Version for TypeScript, based on [Luiz Bondis summary](https://stackoverflow.com/a/65329856/189673):
```js
export function utmZoneFromLatLng(lat: number, lon: number) {
// Special Cases for Norway & Svalbard
if (lat > 55 && lat < 64 && lon > 2 && lon < 6) {
return 32;
}
if (lat > 71 && lon >= 6 && lon < 9) {
return 31;
}
if (lat > 71 && ((lon >= 9 && lon < 12) || (lon >= 18 && lon < 21))) {
return 33;
}
if (lat > 71 && ((lon >= 21 && lon < 24) || (lon >= 30 && lon < 33))) {
return 35;
}
// Rest of the world
if (lon >= -180 && lon <= 180) {
return (Math.floor((lon + 180) / 6) % 60) + 1;
}
throw new Error(`utmZoneFromLatLng: Cannot figure out UTM zone from give Lat: ${lat}, Lng: ${lon}`);
}
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | I made this function for me using the previous answers.
Maybe it is useful to someone here =)
```
utmzone <- function(lon,lat) {
## Special Cases for Norway & Svalbard
if (lat > 55 & lat < 64 & lon > 2 & lon < 6){
band <- 32
} else {
if (lat > 71 & lon >= 6 & lon < 9){
band <- 31
} else {
if (lat > 71 & lon >= 9 & lon < 12){
band <- 33
} else {
if (lat > 71 & lon >= 18 & lon < 21){
band <- 33
} else {
if (lat > 71 & lon >= 21 & lon < 24){
band <- 35
} else {
if (lat > 71 & lon >= 30 & lon < 33){
band <- 35
} else {
## Rest of the world
if (lon >= -180 & lon <= 180){
band <- (floor((lon + 180)/6) %% 60) + 1
} else {
band <- "something is wrong"
}}}}}}}
return(band)
}
utmzone(-43,-22)
#[1] 23
``` | Python version:
```
def get_utm_fromLatLon(lat, lon):
#Special Cases for Norway and Svalbard
if (lat > 55 and lat < 64 and lon > 2 and lon < 6):
return 32
elif (lat > 71 and lon >= 6 and lon < 9):
return 31
elif (lat > 71 and ((lon >= 9 and lon < 12) or (lon >= 18 and lon < 21))):
return 33
elif (lat > 71 and ((lon >= 21 and lon < 24) or (lon >= 30 and lon < 33))):
return 35
# Rest of the world
elif (lon >= -180 and lon <= 180):
return (math.floor((lon + 180) / 6) % 60) + 1
else:
raise ValueError('Cannot figure out UTM zone from given Lat: {0}, Lon: {1}.'.format(lat, lon))
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | So I had this problem today, that I needed to find the UTM zone from lat/long for points all over the globe. The trouble is that there's all these curly edge cases like Svalbard, Norway, and the poles:[![UTM curly edge cases](https://i.stack.imgur.com/Rhj62.jpg)](https://i.stack.imgur.com/Rhj62.jpg) (shown in red on this map) which will catch you out if you assume it's all regular!
Here's my R function to find UTM zones from lat/long pairs, with tests at the end for all of the curly edge cases.
```r
require(tidyverse)
require(purrr)
require(testthat)
find_one_utm_zone <- function(longitude, latitude) {
# Special zones for Svalbard
if (latitude >= 72.0 && latitude <= 84.0 ) {
if (longitude >= 0.0 && longitude < 9.0)
return("31X");
if (longitude >= 9.0 && longitude < 21.0)
return("33X")
if (longitude >= 21.0 && longitude < 33.0)
return("35X")
if (longitude >= 33.0 && longitude < 42.0)
return("37X")
}
# Special zones for Norway
if (latitude >= 56.0 && latitude < 64.0 ) {
if (longitude >= 0.0 && longitude < 3.0)
return("31V");
if (longitude >= 3.0 && longitude < 12.0)
return("32V")
}
# North + South Poles
if (latitude > 84.0){
if ((longitude+180)%%360-180 < 0) {return("Y")}
if ((longitude+180)%%360-180 > 0) {return("Z")}
} else if (latitude < -80.0){
if ((longitude+180)%%360-180 < 0) {return("A")}
if ((longitude+180)%%360-180 > 0) {return("B")}
}
# Everything in the middle
if ( (latitude>-80.0) && (latitude<=84.0) ){
mid_zones <- LETTERS[c(3:8,10:14,16:24)] # C to X, skip I and O
utm_letter <- mid_zones[ min(floor( (latitude + 80) / 8 )+1 , 20) ]
utm_number <- (floor( (longitude + 180) / 6 ) %% 60) + 1 # modulo in case longitude is 0 to 360 instead of -180 to 180
utm_zone <- paste0(utm_number, utm_letter)
return(utm_zone)
} else {
stop("lat long not valid (or something else broke)")
}
}
find_utm_zone <- function(lon, lat){
purrr::map2_chr(.x = lon, .y = lat, .f = find_one_utm_zone)
}
```
Example of use
```r
locs <-
tibble(lon = c(-100,30,150, 4, 7, 22, 0, 12, -34, -20),
lat = c(-45, 85, 12, 57, 81, 83, 5, -81, 85, 83),
desired_utm_zone = c("14G","Z","56P", "32V" ,"31X","35X","31N", "B","Y","27X"))
locs2 <-
locs %>%
mutate(utm_zone = find_utm_zone(lon = lon,lat = lat))
```
Test that it worked:
```r
testthat::expect_equal(locs2$utm_zone, locs2$desired_utm_zone)
``` | Python version:
```
def get_utm_fromLatLon(lat, lon):
#Special Cases for Norway and Svalbard
if (lat > 55 and lat < 64 and lon > 2 and lon < 6):
return 32
elif (lat > 71 and lon >= 6 and lon < 9):
return 31
elif (lat > 71 and ((lon >= 9 and lon < 12) or (lon >= 18 and lon < 21))):
return 33
elif (lat > 71 and ((lon >= 21 and lon < 24) or (lon >= 30 and lon < 33))):
return 35
# Rest of the world
elif (lon >= -180 and lon <= 180):
return (math.floor((lon + 180) / 6) % 60) + 1
else:
raise ValueError('Cannot figure out UTM zone from given Lat: {0}, Lon: {1}.'.format(lat, lon))
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | **Edit:** For (non-R) code that works for *all* non-polar areas on earth, see [here](https://gis.stackexchange.com/questions/13291/is-there-a-simple-way-to-compute-the-utm-zone-from-a-lat-long-point) or [here](http://www.igorexchange.com/node/927).
---
Unless you are dealing with data from a couple of exceptional areas ([Svalbard and parts of Norway](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system#Exceptions)), this is a simple enough calculation that you might as well just do it yourself in R. Here is [Wikipedia's description](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system) of how longitude relates to UTM Zone number:
>
> The UTM system divides the surface of Earth between 80°S and 84°N latitude into 60 zones, each 6° of longitude in width. Zone 1 covers longitude 180° to 174° W; zone numbering increases eastward to zone 60 that covers longitude 174 to 180 East.
>
>
>
So, assuming that in your data longitudes to the west of the [Prime Meridian](http://en.wikipedia.org/wiki/Prime_Meridian) are encoded as running from -180 to 0 degrees, here's an R-code version of the above:
```
long2UTM <- function(long) {
(floor((long + 180)/6) %% 60) + 1
}
# Trying it out for San Francisco, clearly in UTM Zone 10
# in the figure in the Wikipedia article linked above
SFlong <- -122.4192
long2UTM(SFlong)
# [1] 10
```
That expression could obviously be simplified a bit, but I think in this form the logic underlying its construction is most clear. The `%% 60` bit is in there just in case some of your longitudes are greater than 180 or less than -180. | I made this function for me using the previous answers.
Maybe it is useful to someone here =)
```
utmzone <- function(lon,lat) {
## Special Cases for Norway & Svalbard
if (lat > 55 & lat < 64 & lon > 2 & lon < 6){
band <- 32
} else {
if (lat > 71 & lon >= 6 & lon < 9){
band <- 31
} else {
if (lat > 71 & lon >= 9 & lon < 12){
band <- 33
} else {
if (lat > 71 & lon >= 18 & lon < 21){
band <- 33
} else {
if (lat > 71 & lon >= 21 & lon < 24){
band <- 35
} else {
if (lat > 71 & lon >= 30 & lon < 33){
band <- 35
} else {
## Rest of the world
if (lon >= -180 & lon <= 180){
band <- (floor((lon + 180)/6) %% 60) + 1
} else {
band <- "something is wrong"
}}}}}}}
return(band)
}
utmzone(-43,-22)
#[1] 23
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | **Edit:** For (non-R) code that works for *all* non-polar areas on earth, see [here](https://gis.stackexchange.com/questions/13291/is-there-a-simple-way-to-compute-the-utm-zone-from-a-lat-long-point) or [here](http://www.igorexchange.com/node/927).
---
Unless you are dealing with data from a couple of exceptional areas ([Svalbard and parts of Norway](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system#Exceptions)), this is a simple enough calculation that you might as well just do it yourself in R. Here is [Wikipedia's description](http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system) of how longitude relates to UTM Zone number:
>
> The UTM system divides the surface of Earth between 80°S and 84°N latitude into 60 zones, each 6° of longitude in width. Zone 1 covers longitude 180° to 174° W; zone numbering increases eastward to zone 60 that covers longitude 174 to 180 East.
>
>
>
So, assuming that in your data longitudes to the west of the [Prime Meridian](http://en.wikipedia.org/wiki/Prime_Meridian) are encoded as running from -180 to 0 degrees, here's an R-code version of the above:
```
long2UTM <- function(long) {
(floor((long + 180)/6) %% 60) + 1
}
# Trying it out for San Francisco, clearly in UTM Zone 10
# in the figure in the Wikipedia article linked above
SFlong <- -122.4192
long2UTM(SFlong)
# [1] 10
```
That expression could obviously be simplified a bit, but I think in this form the logic underlying its construction is most clear. The `%% 60` bit is in there just in case some of your longitudes are greater than 180 or less than -180. | I don't know r-code but I suppose this PL/SQL code can help you with the exceptions:
```
UTMZone := Trunc((lon - Zone0WestMeridian) / d);
--Special Cases for Norway & Svalbard
CASE
WHEN (lat > 55) AND (UTMZone = 31) AND (lat < 64) AND (lon > 2) THEN UTMZone := 32;
WHEN (lat > 71) AND (UTMZone = 32) AND (lon < 9) THEN UTMZone := 31;
WHEN (lat > 71) AND (UTMZone = 32) AND (lon > 8) THEN UTMZone := 33;
WHEN (lat > 71) AND (UTMZone = 34) AND (lon < 21) THEN UTMZone := 33;
WHEN (lat > 71) AND (UTMZone = 34) AND (lon > 20) THEN UTMZone := 35;
WHEN (lat > 71) AND (UTMZone = 36) AND (lon < 33) THEN UTMZone := 35;
WHEN (lat > 71) AND (UTMZone = 36) AND (lon > 32) THEN UTMZone := 37;
ELSE UTMZone := UTMZone;
END CASE;
``` |
9,186,496 | I'm writing a program which expects a number of lat/long points, and I convert them internally to UTM in order to do some calculations in metres.
The range of the lat/long points themselves is quite small -- about 200m x 200m. They can be relied on almost always to be within a single UTM zone (unless you get unlucky and are across the border of a zone).
However, the zone that the lat/longs are in is unrestricted. One day the program might be run for people in Australia (and oh, how many zones does even a single state lie across, and how much pain has that caused me already...), and another day for people in Mexico.
My question is -- is there a way to determine which zone a particular long/lat is in so that it may be fed into a conversion library (I currently use proj4 and also the R package `rgdal`).
My language is R, but the answer doesn't have to be -- maybe it's just a simple calculation, or maybe I can embed a system call to the `proj` exectuable.
cheers. | 2012/02/08 | ['https://Stackoverflow.com/questions/9186496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913184/'] | I don't know r-code but I suppose this PL/SQL code can help you with the exceptions:
```
UTMZone := Trunc((lon - Zone0WestMeridian) / d);
--Special Cases for Norway & Svalbard
CASE
WHEN (lat > 55) AND (UTMZone = 31) AND (lat < 64) AND (lon > 2) THEN UTMZone := 32;
WHEN (lat > 71) AND (UTMZone = 32) AND (lon < 9) THEN UTMZone := 31;
WHEN (lat > 71) AND (UTMZone = 32) AND (lon > 8) THEN UTMZone := 33;
WHEN (lat > 71) AND (UTMZone = 34) AND (lon < 21) THEN UTMZone := 33;
WHEN (lat > 71) AND (UTMZone = 34) AND (lon > 20) THEN UTMZone := 35;
WHEN (lat > 71) AND (UTMZone = 36) AND (lon < 33) THEN UTMZone := 35;
WHEN (lat > 71) AND (UTMZone = 36) AND (lon > 32) THEN UTMZone := 37;
ELSE UTMZone := UTMZone;
END CASE;
``` | Python version:
```
def get_utm_fromLatLon(lat, lon):
#Special Cases for Norway and Svalbard
if (lat > 55 and lat < 64 and lon > 2 and lon < 6):
return 32
elif (lat > 71 and lon >= 6 and lon < 9):
return 31
elif (lat > 71 and ((lon >= 9 and lon < 12) or (lon >= 18 and lon < 21))):
return 33
elif (lat > 71 and ((lon >= 21 and lon < 24) or (lon >= 30 and lon < 33))):
return 35
# Rest of the world
elif (lon >= -180 and lon <= 180):
return (math.floor((lon + 180) / 6) % 60) + 1
else:
raise ValueError('Cannot figure out UTM zone from given Lat: {0}, Lon: {1}.'.format(lat, lon))
``` |
13,735,783 | I have a youtube player with custom HTML controls and would like to add a button to turn on/off closed caption and to toggle the language. Anyone have experience with using either the JS or iframe API to do this? I know that appending cc\_load\_policy=1 to the url will force the captions to display, but I am using custom controls and would like to add a toggle button. I tried using the loadVideoByUrl method and appending the cc parameter, but that doesn't work doesn't seem to work.
I was also only able to get the player to show captions in the user's default language with the iframe method, not the swf object method. Swf object always defaults to English. If anyone has any insights to this as well, please let me know! | 2012/12/06 | ['https://Stackoverflow.com/questions/13735783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1879911/'] | I have not found this anywhere in their api docs, but with your youtube player object you should be able to do:
```
player.loadModule("captions"); //Works for html5 ignored by AS3
player.loadModule("cc"); //Works for AS3 ignored by html5
```
to turn it off:
```
player.unloadModule("captions"); //Works for html5 ignored by AS3
player.unloadModule("cc"); //Works for AS3 ignored by html5
```
to change which language if the module is loaded:
```
player.setOption("captions", "track", {"languageCode": "es"}); //Works for html5 ignored by AS3
player.setOption("cc", "track", {"languageCode": "es"}); //Works for AS3 ignored by html5
``` | Unfortunately, we don't have full API support over captions right now. You can add yourself to this external feature request to be notified when this changes: <https://code.google.com/p/gdata-issues/issues/detail?id=444>
(Despite the age of that feature request, there are people actively looking on adding support.) |
13,735,783 | I have a youtube player with custom HTML controls and would like to add a button to turn on/off closed caption and to toggle the language. Anyone have experience with using either the JS or iframe API to do this? I know that appending cc\_load\_policy=1 to the url will force the captions to display, but I am using custom controls and would like to add a toggle button. I tried using the loadVideoByUrl method and appending the cc parameter, but that doesn't work doesn't seem to work.
I was also only able to get the player to show captions in the user's default language with the iframe method, not the swf object method. Swf object always defaults to English. If anyone has any insights to this as well, please let me know! | 2012/12/06 | ['https://Stackoverflow.com/questions/13735783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1879911/'] | I have not found this anywhere in their api docs, but with your youtube player object you should be able to do:
```
player.loadModule("captions"); //Works for html5 ignored by AS3
player.loadModule("cc"); //Works for AS3 ignored by html5
```
to turn it off:
```
player.unloadModule("captions"); //Works for html5 ignored by AS3
player.unloadModule("cc"); //Works for AS3 ignored by html5
```
to change which language if the module is loaded:
```
player.setOption("captions", "track", {"languageCode": "es"}); //Works for html5 ignored by AS3
player.setOption("cc", "track", {"languageCode": "es"}); //Works for AS3 ignored by html5
``` | ```js
function onPlayerStateChange(event)
{
try
{
player.unloadModule("captions");
player.unloadModule("cc");
}
catch (exception)
{
LoggerUtil.logError("Error when trying to unloadModule youtube captions: " + exception);
}
// The rest of your function
}
```
Thanks **James Irwin** those two lines worked for me when testing on android 4.4.2 and android 6.0.1
```
player.unloadModule("captions");
player.unloadModule("cc");
```
You should put this two lines inside the `onPlayerStateChange` function. |
24,876 | Crossposted from [MO](https://mathoverflow.net/questions/171493/polynomial-problems-in-graph-classes-defined-by-forbidden-induced-cyclic-subgrap).
Let $C$ be a graph class defined by a finite
number of forbidden induced subgraphs, all
of which are cyclic (contain at least one cycle).
>
> Are there NP-hard graph problems that can be solved in
> polynomial time for $C$ other than Clique and Clique
> cover?
>
>
>
If I remember correctly, this is impossible for
independent set (unless $P=NP$).
Search in graphclasses.org didn't find any.
A class for which Clique and Clique cover are
polynomial is [C5,C6,X164,X165,sunlet4,triangle-free](http://graphclasses.org/classes/gc_1022.html)
**Edit**
Negative for IS and Domination is in [this paper](http://www.sciencedirect.com/science/article/pii/S0304397505008327). Page 2, the graphs $S\_{i,j,k}$. | 2014/06/13 | ['https://cstheory.stackexchange.com/questions/24876', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/22348/'] | I think there is a number of hard problems that become easy for triangle-free graphs; especially those deal directly with triangles such as Partition Into Triangles (Does G have a partition into triangles?). Other less trivial examples include:
* Stable Cutset Problem (Does G have an independent set S such that G-S is disconnected?). See: *On stable sutsets in graphs,* Discrete Applied Math. 105 (2000) 39-50.
* Intersection Graph Basis (Is G the intersection graph of subsets of a k-element ground set?). See: Problem [GT59] in: Garey & Johnson, *Computers and Intractability: A Guide to the Theory of NP-Completeness.* | From the comment above: in [Stefan Kratsch, Pascal Schweitzer, Graph Isomorphism for Graph Classes Characterized by two Forbidden Induced Subgraphs](http://arxiv.org/abs/1208.0142): GI is polynomial time (trivially) solvable for $(K\_s,I\_t)\text{-free}$ graphs, but also (less trivially) for $(K\_s,K\_{1,t})\text{-free}$ graphs.
**EDIT**: as noted in the comment, $K\_{1,t}$ doesn't contain a cycle (I read the introduction of the paper too quickly).
After thinking a little bit about it, it seems easy to prove the following (original?):
**NEGATIVE RESULT:** *for every finite set $\{H\_1,...H\_k\}$ in which every $H\_i$ contains a cycle, the problem of graph isomorphism (GI) restricted to the class $\mathcal{C}$ of $(H\_1,...,H\_k)\text{-free}$ graphs is GI-complete.*
*Proof:* Fixed a class of $(H\_1,...,H\_k)\text{-free}$ graphs in which each $H\_i$ contains a cycle, and given $G\_1,G\_2$, let $r$ be the length of the longest cycle of the $H\_i$s. Replace each edge $(u,v)$ of $G\_1,G\_2$ with a path of length $l = \lceil r/3 \rceil$ adding $l$ new nodes $(u,p\_1,p\_2,...,p\_l,v)$ (see figure below). By construction the new graphs $G'\_1, G'\_2$ are $(H\_1,...,H\_k)\text{-free}$ indeed the possible shortest cycles are those formed by a triangle that must have length $3\lceil r/3 \rceil + 3 > r$; and it is easy to prove that they are isomorphic if and only if the original $G\_1,G\_2$ are isomorphic.
![enter image description here](https://i.stack.imgur.com/IoPq3.png)
**Figure**: a graph $G\_1$ on the left, and the equivalent $(H\_1,...,H\_k)\text{-free}$ graph $G'\_1$ on the right (suppose that the longest cycle of the $H\_i$ has length $r=15$, so every edge of $G\_1$ is replaced with a path of length $l = 5$.
We can also extend the negative result to Hamiltonian cycle NPC problem, indeed it is an immediate corollary to the following (original?):
**Theorem**: for any $k \geq 3$, the Hamiltonian cycle problem remains NP-complete even if we the graph $G$ does not contain cycles of length $\leq k$.
*Proof* We know that the Hamiltonian cycle problem is NPC even on a planar directed graph $G$ with each node $v$ satisfying: $outdeg(v) + indeg(v) \leq 3$ (Papdimitriou and Vazirani, On Two Geometric Problems Related to the Travelling Salesman Problem).
We can transform the graph $G$ to an undirectde graph $G'$ simply adding a node on the incoming edge of nodes $v$ that have $indeg(v )=1$, and to the outgoing edge of nodes $v$ that have $indeg(v)=2$.
Then we can replace the nodes of $G'$ with the gadget in the figure below. It is easy to see that there are only two valid traversals (*zigzags*) that visit each node of the gadget exactly once (red and green paths in the figure): the gadgets cannot be traversed from top-to-bottom, otherwise the horizontal (incoming or outgoing) path would be cut out.
Furthermore we can place enough nodes on the vertical/horizontal segments of the gadgets, and extend the number of its zigzags, to ensure that no cycle of length $\geq k$ is possible in the gadget or in a triangle of 3 gadgets linked together. This assures that if the resulting graph $G''$ has an Hamiltonian cycle, then the original graph $G$ has also an Hamiltonian cycle (the converse is immediate by construction of the gadget).
![enter image description here](https://i.stack.imgur.com/uw6oT.png)
**Corollary:** Hamiltonian cycle and path problems remain NP-complete even if restricted to $(H\_1,...,H\_k)\text{-free}$ graphs, where every $H\_i$ contains a cycle. |
24,876 | Crossposted from [MO](https://mathoverflow.net/questions/171493/polynomial-problems-in-graph-classes-defined-by-forbidden-induced-cyclic-subgrap).
Let $C$ be a graph class defined by a finite
number of forbidden induced subgraphs, all
of which are cyclic (contain at least one cycle).
>
> Are there NP-hard graph problems that can be solved in
> polynomial time for $C$ other than Clique and Clique
> cover?
>
>
>
If I remember correctly, this is impossible for
independent set (unless $P=NP$).
Search in graphclasses.org didn't find any.
A class for which Clique and Clique cover are
polynomial is [C5,C6,X164,X165,sunlet4,triangle-free](http://graphclasses.org/classes/gc_1022.html)
**Edit**
Negative for IS and Domination is in [this paper](http://www.sciencedirect.com/science/article/pii/S0304397505008327). Page 2, the graphs $S\_{i,j,k}$. | 2014/06/13 | ['https://cstheory.stackexchange.com/questions/24876', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/22348/'] | Here are some additional examples to Mon Tag's answer :
* The Disconnected Cutset problem (Does $G$ admit a set of vertices $S$ such that $G-S$ and the subgraph of $G$ induced by $S$ are disconnected) is NP-complete (see [here](http://dx.doi.org/10.1007/978-3-642-23786-7_43)). It is easy to see that this problem is polynomially solvable for triangle-free graphs (hence also the Stable Cutset problem as mentioned by Mon Tag).
* Recognizing triangular line graphs is NP-complete (see [here](http://www.sciencedirect.com/science/article/pii/S0012365X11005449)), It is also
easy to see that this problem becomes polynomially for triangle-free input graphs.
* Computing the maximum connected matching is hard (see [here](http://www.discuss.wmie.uz.zgora.pl/gt/index.php?doi=10.7151/dmgt.1206).
A matching is connected if, for any pair of the matching edges, there is another edge of the graph incident to both of them).
It can be proved that this problem is polynomially solvable for $(C\_3, C\_4, C\_5)$-free graphs. | From the comment above: in [Stefan Kratsch, Pascal Schweitzer, Graph Isomorphism for Graph Classes Characterized by two Forbidden Induced Subgraphs](http://arxiv.org/abs/1208.0142): GI is polynomial time (trivially) solvable for $(K\_s,I\_t)\text{-free}$ graphs, but also (less trivially) for $(K\_s,K\_{1,t})\text{-free}$ graphs.
**EDIT**: as noted in the comment, $K\_{1,t}$ doesn't contain a cycle (I read the introduction of the paper too quickly).
After thinking a little bit about it, it seems easy to prove the following (original?):
**NEGATIVE RESULT:** *for every finite set $\{H\_1,...H\_k\}$ in which every $H\_i$ contains a cycle, the problem of graph isomorphism (GI) restricted to the class $\mathcal{C}$ of $(H\_1,...,H\_k)\text{-free}$ graphs is GI-complete.*
*Proof:* Fixed a class of $(H\_1,...,H\_k)\text{-free}$ graphs in which each $H\_i$ contains a cycle, and given $G\_1,G\_2$, let $r$ be the length of the longest cycle of the $H\_i$s. Replace each edge $(u,v)$ of $G\_1,G\_2$ with a path of length $l = \lceil r/3 \rceil$ adding $l$ new nodes $(u,p\_1,p\_2,...,p\_l,v)$ (see figure below). By construction the new graphs $G'\_1, G'\_2$ are $(H\_1,...,H\_k)\text{-free}$ indeed the possible shortest cycles are those formed by a triangle that must have length $3\lceil r/3 \rceil + 3 > r$; and it is easy to prove that they are isomorphic if and only if the original $G\_1,G\_2$ are isomorphic.
![enter image description here](https://i.stack.imgur.com/IoPq3.png)
**Figure**: a graph $G\_1$ on the left, and the equivalent $(H\_1,...,H\_k)\text{-free}$ graph $G'\_1$ on the right (suppose that the longest cycle of the $H\_i$ has length $r=15$, so every edge of $G\_1$ is replaced with a path of length $l = 5$.
We can also extend the negative result to Hamiltonian cycle NPC problem, indeed it is an immediate corollary to the following (original?):
**Theorem**: for any $k \geq 3$, the Hamiltonian cycle problem remains NP-complete even if we the graph $G$ does not contain cycles of length $\leq k$.
*Proof* We know that the Hamiltonian cycle problem is NPC even on a planar directed graph $G$ with each node $v$ satisfying: $outdeg(v) + indeg(v) \leq 3$ (Papdimitriou and Vazirani, On Two Geometric Problems Related to the Travelling Salesman Problem).
We can transform the graph $G$ to an undirectde graph $G'$ simply adding a node on the incoming edge of nodes $v$ that have $indeg(v )=1$, and to the outgoing edge of nodes $v$ that have $indeg(v)=2$.
Then we can replace the nodes of $G'$ with the gadget in the figure below. It is easy to see that there are only two valid traversals (*zigzags*) that visit each node of the gadget exactly once (red and green paths in the figure): the gadgets cannot be traversed from top-to-bottom, otherwise the horizontal (incoming or outgoing) path would be cut out.
Furthermore we can place enough nodes on the vertical/horizontal segments of the gadgets, and extend the number of its zigzags, to ensure that no cycle of length $\geq k$ is possible in the gadget or in a triangle of 3 gadgets linked together. This assures that if the resulting graph $G''$ has an Hamiltonian cycle, then the original graph $G$ has also an Hamiltonian cycle (the converse is immediate by construction of the gadget).
![enter image description here](https://i.stack.imgur.com/uw6oT.png)
**Corollary:** Hamiltonian cycle and path problems remain NP-complete even if restricted to $(H\_1,...,H\_k)\text{-free}$ graphs, where every $H\_i$ contains a cycle. |
24,876 | Crossposted from [MO](https://mathoverflow.net/questions/171493/polynomial-problems-in-graph-classes-defined-by-forbidden-induced-cyclic-subgrap).
Let $C$ be a graph class defined by a finite
number of forbidden induced subgraphs, all
of which are cyclic (contain at least one cycle).
>
> Are there NP-hard graph problems that can be solved in
> polynomial time for $C$ other than Clique and Clique
> cover?
>
>
>
If I remember correctly, this is impossible for
independent set (unless $P=NP$).
Search in graphclasses.org didn't find any.
A class for which Clique and Clique cover are
polynomial is [C5,C6,X164,X165,sunlet4,triangle-free](http://graphclasses.org/classes/gc_1022.html)
**Edit**
Negative for IS and Domination is in [this paper](http://www.sciencedirect.com/science/article/pii/S0304397505008327). Page 2, the graphs $S\_{i,j,k}$. | 2014/06/13 | ['https://cstheory.stackexchange.com/questions/24876', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/22348/'] | From the comment above: in [Stefan Kratsch, Pascal Schweitzer, Graph Isomorphism for Graph Classes Characterized by two Forbidden Induced Subgraphs](http://arxiv.org/abs/1208.0142): GI is polynomial time (trivially) solvable for $(K\_s,I\_t)\text{-free}$ graphs, but also (less trivially) for $(K\_s,K\_{1,t})\text{-free}$ graphs.
**EDIT**: as noted in the comment, $K\_{1,t}$ doesn't contain a cycle (I read the introduction of the paper too quickly).
After thinking a little bit about it, it seems easy to prove the following (original?):
**NEGATIVE RESULT:** *for every finite set $\{H\_1,...H\_k\}$ in which every $H\_i$ contains a cycle, the problem of graph isomorphism (GI) restricted to the class $\mathcal{C}$ of $(H\_1,...,H\_k)\text{-free}$ graphs is GI-complete.*
*Proof:* Fixed a class of $(H\_1,...,H\_k)\text{-free}$ graphs in which each $H\_i$ contains a cycle, and given $G\_1,G\_2$, let $r$ be the length of the longest cycle of the $H\_i$s. Replace each edge $(u,v)$ of $G\_1,G\_2$ with a path of length $l = \lceil r/3 \rceil$ adding $l$ new nodes $(u,p\_1,p\_2,...,p\_l,v)$ (see figure below). By construction the new graphs $G'\_1, G'\_2$ are $(H\_1,...,H\_k)\text{-free}$ indeed the possible shortest cycles are those formed by a triangle that must have length $3\lceil r/3 \rceil + 3 > r$; and it is easy to prove that they are isomorphic if and only if the original $G\_1,G\_2$ are isomorphic.
![enter image description here](https://i.stack.imgur.com/IoPq3.png)
**Figure**: a graph $G\_1$ on the left, and the equivalent $(H\_1,...,H\_k)\text{-free}$ graph $G'\_1$ on the right (suppose that the longest cycle of the $H\_i$ has length $r=15$, so every edge of $G\_1$ is replaced with a path of length $l = 5$.
We can also extend the negative result to Hamiltonian cycle NPC problem, indeed it is an immediate corollary to the following (original?):
**Theorem**: for any $k \geq 3$, the Hamiltonian cycle problem remains NP-complete even if we the graph $G$ does not contain cycles of length $\leq k$.
*Proof* We know that the Hamiltonian cycle problem is NPC even on a planar directed graph $G$ with each node $v$ satisfying: $outdeg(v) + indeg(v) \leq 3$ (Papdimitriou and Vazirani, On Two Geometric Problems Related to the Travelling Salesman Problem).
We can transform the graph $G$ to an undirectde graph $G'$ simply adding a node on the incoming edge of nodes $v$ that have $indeg(v )=1$, and to the outgoing edge of nodes $v$ that have $indeg(v)=2$.
Then we can replace the nodes of $G'$ with the gadget in the figure below. It is easy to see that there are only two valid traversals (*zigzags*) that visit each node of the gadget exactly once (red and green paths in the figure): the gadgets cannot be traversed from top-to-bottom, otherwise the horizontal (incoming or outgoing) path would be cut out.
Furthermore we can place enough nodes on the vertical/horizontal segments of the gadgets, and extend the number of its zigzags, to ensure that no cycle of length $\geq k$ is possible in the gadget or in a triangle of 3 gadgets linked together. This assures that if the resulting graph $G''$ has an Hamiltonian cycle, then the original graph $G$ has also an Hamiltonian cycle (the converse is immediate by construction of the gadget).
![enter image description here](https://i.stack.imgur.com/uw6oT.png)
**Corollary:** Hamiltonian cycle and path problems remain NP-complete even if restricted to $(H\_1,...,H\_k)\text{-free}$ graphs, where every $H\_i$ contains a cycle. | MAX-CUT remains NP-complete.
**Lemma 3.2** simple max-cut is NP-complete in the following two classes of graphs:
graphs not containing cycles of length at most $k$, for every $k \ge 3$.
They are subdividing an edge twice.
From "MAX-CUT and containment relations in graphs, Marcin Kaminski" |
24,876 | Crossposted from [MO](https://mathoverflow.net/questions/171493/polynomial-problems-in-graph-classes-defined-by-forbidden-induced-cyclic-subgrap).
Let $C$ be a graph class defined by a finite
number of forbidden induced subgraphs, all
of which are cyclic (contain at least one cycle).
>
> Are there NP-hard graph problems that can be solved in
> polynomial time for $C$ other than Clique and Clique
> cover?
>
>
>
If I remember correctly, this is impossible for
independent set (unless $P=NP$).
Search in graphclasses.org didn't find any.
A class for which Clique and Clique cover are
polynomial is [C5,C6,X164,X165,sunlet4,triangle-free](http://graphclasses.org/classes/gc_1022.html)
**Edit**
Negative for IS and Domination is in [this paper](http://www.sciencedirect.com/science/article/pii/S0304397505008327). Page 2, the graphs $S\_{i,j,k}$. | 2014/06/13 | ['https://cstheory.stackexchange.com/questions/24876', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/22348/'] | I think there is a number of hard problems that become easy for triangle-free graphs; especially those deal directly with triangles such as Partition Into Triangles (Does G have a partition into triangles?). Other less trivial examples include:
* Stable Cutset Problem (Does G have an independent set S such that G-S is disconnected?). See: *On stable sutsets in graphs,* Discrete Applied Math. 105 (2000) 39-50.
* Intersection Graph Basis (Is G the intersection graph of subsets of a k-element ground set?). See: Problem [GT59] in: Garey & Johnson, *Computers and Intractability: A Guide to the Theory of NP-Completeness.* | MAX-CUT remains NP-complete.
**Lemma 3.2** simple max-cut is NP-complete in the following two classes of graphs:
graphs not containing cycles of length at most $k$, for every $k \ge 3$.
They are subdividing an edge twice.
From "MAX-CUT and containment relations in graphs, Marcin Kaminski" |
24,876 | Crossposted from [MO](https://mathoverflow.net/questions/171493/polynomial-problems-in-graph-classes-defined-by-forbidden-induced-cyclic-subgrap).
Let $C$ be a graph class defined by a finite
number of forbidden induced subgraphs, all
of which are cyclic (contain at least one cycle).
>
> Are there NP-hard graph problems that can be solved in
> polynomial time for $C$ other than Clique and Clique
> cover?
>
>
>
If I remember correctly, this is impossible for
independent set (unless $P=NP$).
Search in graphclasses.org didn't find any.
A class for which Clique and Clique cover are
polynomial is [C5,C6,X164,X165,sunlet4,triangle-free](http://graphclasses.org/classes/gc_1022.html)
**Edit**
Negative for IS and Domination is in [this paper](http://www.sciencedirect.com/science/article/pii/S0304397505008327). Page 2, the graphs $S\_{i,j,k}$. | 2014/06/13 | ['https://cstheory.stackexchange.com/questions/24876', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/22348/'] | Here are some additional examples to Mon Tag's answer :
* The Disconnected Cutset problem (Does $G$ admit a set of vertices $S$ such that $G-S$ and the subgraph of $G$ induced by $S$ are disconnected) is NP-complete (see [here](http://dx.doi.org/10.1007/978-3-642-23786-7_43)). It is easy to see that this problem is polynomially solvable for triangle-free graphs (hence also the Stable Cutset problem as mentioned by Mon Tag).
* Recognizing triangular line graphs is NP-complete (see [here](http://www.sciencedirect.com/science/article/pii/S0012365X11005449)), It is also
easy to see that this problem becomes polynomially for triangle-free input graphs.
* Computing the maximum connected matching is hard (see [here](http://www.discuss.wmie.uz.zgora.pl/gt/index.php?doi=10.7151/dmgt.1206).
A matching is connected if, for any pair of the matching edges, there is another edge of the graph incident to both of them).
It can be proved that this problem is polynomially solvable for $(C\_3, C\_4, C\_5)$-free graphs. | MAX-CUT remains NP-complete.
**Lemma 3.2** simple max-cut is NP-complete in the following two classes of graphs:
graphs not containing cycles of length at most $k$, for every $k \ge 3$.
They are subdividing an edge twice.
From "MAX-CUT and containment relations in graphs, Marcin Kaminski" |
21,020,187 | From [this Spring documentation](http://docs.spring.io/spring/docs/3.2.6.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-autowire) I know that when I use @Bean, the default is already equivalent to:
@Bean(autowire = Autowire.NO)
>
> (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
>
>
>
I am just trying to understand what this means for me. If my system is 100% Java Config **and has no XML configuration**, then from what I can tell, when I use @Bean, the 'Autowire.no' has no impact whatsoever.
**EDIT**
By "no impact" I mean that other @Autowired references to this bean ARE autowired (in other Java Config classes). I suspect that is because with Java Config there is no explicit 'ref element' defined, so this (default) setting has no effect.
Example:
First Config:
```
package a.b.c;
@Configuration
public class AlphaConfig {
@Bean(autowire = Autowire.NO)
public AlphaBeanType alphaBean() {
return new AlphaBeanType();
}
}
```
Then in second config:
```
package d.e.f;
import a.b.c.AlphaBeanType;
@Configuration
public class AnotherConfig {
@Autowire
private AlphaBeanType alphaBeanType;
@Bean
. . .
}
```
What I see is that 'alphaBeanType' is always autowired in the second config class - which seems to be in conflict with the documentation - hence my question.
**end edit**
Of course, I can't quite tell from the documentation! Does anyone know for sure? | 2014/01/09 | ['https://Stackoverflow.com/questions/21020187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1538856/'] | The `autowire` element of the `@Bean` annotation (as well as the `autowire` attribute of the `bean` element in xml-based config) determines the autowiring status of the **bean's own properties** and has no relation to how a bean which is marked with the `@Bean` annotation will be injected into other beans.
On the other hand the `@Autowired` annotation explicitly
>
> marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
>
>
>
So in your case the `@Bean` annotation declared on the `alphaBean` method with the default `Autowire.NO` mode disables automatic (that is implicit) injection of the properties (if any) of the `AlphaBeanType` bean. While the `@Autowired` annotation indicates that an `AlphaBeanType` bean should be injected into `AnotherConfig` configuration object. | That is what the spring documentation says though right? the default is NO. So, even if you do explicitly specify it it shouldnt have any impact. Also, when you do specify a bean, what you did mention of it being Autowire.No is correct. so it shouldnt have any impact. |
21,020,187 | From [this Spring documentation](http://docs.spring.io/spring/docs/3.2.6.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-autowire) I know that when I use @Bean, the default is already equivalent to:
@Bean(autowire = Autowire.NO)
>
> (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
>
>
>
I am just trying to understand what this means for me. If my system is 100% Java Config **and has no XML configuration**, then from what I can tell, when I use @Bean, the 'Autowire.no' has no impact whatsoever.
**EDIT**
By "no impact" I mean that other @Autowired references to this bean ARE autowired (in other Java Config classes). I suspect that is because with Java Config there is no explicit 'ref element' defined, so this (default) setting has no effect.
Example:
First Config:
```
package a.b.c;
@Configuration
public class AlphaConfig {
@Bean(autowire = Autowire.NO)
public AlphaBeanType alphaBean() {
return new AlphaBeanType();
}
}
```
Then in second config:
```
package d.e.f;
import a.b.c.AlphaBeanType;
@Configuration
public class AnotherConfig {
@Autowire
private AlphaBeanType alphaBeanType;
@Bean
. . .
}
```
What I see is that 'alphaBeanType' is always autowired in the second config class - which seems to be in conflict with the documentation - hence my question.
**end edit**
Of course, I can't quite tell from the documentation! Does anyone know for sure? | 2014/01/09 | ['https://Stackoverflow.com/questions/21020187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1538856/'] | Setting `Autowire.NO` does not mean that the bean cannot be injected in other beans via `@Autowire`. `@Autowire` works by default by type, and can also work by name using `@Qualifier`.
So if your bean has the right type or name, it will get inject in other beans, that's normal.
`Autowire.NO` means something like:
>
> Don't inject the properties of **THIS** bean being declared with `@Bean` neither by type or by name. If the bean properties are not set in the `@Bean` method code, leave them unfilled.
>
>
>
This a code example of how this works, let's define two beans:
```
public class MyBeanTwo {
public MyBeanTwo() {
System.out.println(">>> MY Bean 2 created!");
}
}
public class MyBean {
private MyBeanTwo myBeanTwo;
public MyBean() {
System.out.println(">>>MyBean created !!");
}
public void setMyBeanTwo(MyBeanTwo myBeanTwo) {
System.out.println(">>> Injecting MyBeanTwo INTO MyBeanOne !!!");
this.myBeanTwo = myBeanTwo;
}
}
```
And some configuration:
```
@Configuration
public class SimpleConfigOne {
@Bean
public MyBean createMyBean() {
return new MyBean();
}
@Bean
public MyBeanTwo createMyBeanTwo() {
return new MyBeanTwo();
}
}
```
With this configuration, the startup of this application gives this log:
```
>>>MyBean created !!
>>> MY Bean 2 created!
```
Meaning one instance of each bean was created, but `MyBean` did NOT get injected with `MyBeanTwo`, even tough a bean with the correct type existed.
By declaring `MyBean` like this:
```
@Bean(autowire = Autowire.BY_TYPE)
public MyBean createMyBean() {
return new MyBean();
}
```
`MyBeanOne` is now eligible to have it's properties set via autowiring by type.
The startup log becomes:
```
>>>MyBean created !!
>>> MY Bean 2 created!
>>> Injecting MyBeanTwo INTO MyBeanOne !!!
```
This shows that `MyBean` had `MyBeanTwo` injected by type via a by type injection.
**Reason why Autowire.NO is the default:**
Usually we don't want to autowire the properties of beans created with `@Bean`. What we usually do is set the properties explicitly via code for readability, as a form of documentation and to make sure the property is set with the correct value. | That is what the spring documentation says though right? the default is NO. So, even if you do explicitly specify it it shouldnt have any impact. Also, when you do specify a bean, what you did mention of it being Autowire.No is correct. so it shouldnt have any impact. |