text:
## Saturday, August 16, 2014

### Shortest distance to a geometry in a specified direction using Python

Looking at this map, I wondered how to calculate which geometry in a set is the closest to a point in a given direction.
Usually, the problem is finding the closest geometry in general, which is easy using the distance function, but I couldn't find a solution for this other.

So I put me this problem: Which is the closest country that I have at each direction, knowing my geographical coordinates?
All the source code is, as usual, at GitHub

### The algorithm

The main idea is:
1. Create an infinite line from the point towards the desired direction.
2. Calculate the difference geometry between the  line and each polygon
1. If the polygon and the line actually intersect, the result will be a multi-line. The first line length of the multi-line is the distance we are looking for
So this would be the initial situation:
And the distance to the polygon 1 would be calculated as:
The main problem is how to calculate the difference between the two geometries, but fortunately, shapely comes with this function, so coding it is not so difficult:
from shapely.geometry import Polygon
from shapely.geometry import LineString
from math import cos
from math import sin
from math import pi

def closest_polygon(x, y, angle, polygons, dist = 10000):

angle = angle * pi / 180.0
line = LineString([(x, y), (x + dist * sin(angle), y + dist * cos(angle))])

dist_min = None
closest_polygon = None
for i in range(len(polygons)):
difference = line.difference(polygons[i])
if difference.geom_type == 'MultiLineString':
dist = list(difference.geoms)[0].length
if dist_min is None or dist_min > dist:
dist_min = dist
closest_polygon = i

return {'closest_polygon': closest_polygon, 'distance': dist_min}

if __name__ == '__main__':

polygons = []
polygons.append(Polygon([(4, 2), (4, 4), (6, 4), (6, 2)]))
polygons.append(Polygon([(7, 2), (7, 4), (9, 4), (9, 2)]))

print closest_polygon(3, 3, 90, polygons)
• The main section creates the two squares using shapely
• The closest_polygon function calculates the closest polygon and its distance:
• A LineString to the desired direction is calculated. The dist is in the units used by the polygons. An infinite line isn't possible, so the distance must be larger than the further
• For each of the polygons to analyze, the difference is calculated using the shapely difference method
• Then, if the line and the polygon intersect (and the line is long enough), a MultilineString will be the result of the difference operation. The first String in the MultilineString is the one that connects our point with the polygon. Its length is the distance we are looking for
 The example schema, drawn with the script draw_closest.py

### Calculating the closest country in each direction

After getting the formula for calculating the closest polygon, the next step would be using it for something. So:
Which country do I have in all directions?
To create the script, some things have to be considered:
1. The projection should be azimuthal equidistant so the distances can be compared in all the directions from the given point
2. I've used the BaseMap library to draw the maps. I find it a bit tricky to use, but the code will be shorter
The script is used this way:

usage: closest_country.py [-h] [-n num_angles] [-o out_file] [-wf zoom_factor]
lon lat

Creates a map with the closest country in each direction

positional arguments:
lon              The point longitude
lat              The point latitude

optional arguments:
-h, --help       show this help message and exit
-n num_angles    Number of angles
-o out_file      Out file. If present, saves the file instead of showing it
-wf zoom_factor  The width factor. Use it to zoom in and out. Use > 1 to
draw a bigger area, and <1 for a smaller one. By default is
1

For example:
python closest_country.py -n 100 -wf 2.0 5 41
The code has some functions, but the main one is draw_map:
def draw_map(self, num_angles = 360, width_factor = 1.0):

#Create the map, with no countries
self.map = Basemap(projection='aeqd',
lat_0=self.center_lat,lon_0=self.center_lon,resolution =None)
#Iterate over all the angles:
results = {}
distances = []
for num in range(num_angles):
angle = num * 360./num_angles
closest, dist = self.closest_polygon(angle)
if closest is not None:
distances.append(dist)
if (self.names[closest] in results) == False:
results[self.names[closest]] = []

results[self.names[closest]].append(angle)

#The map zoom is calculated here,
#taking the 90% of the distances to be drawn by default
width = width_factor * sorted(distances)[
int(-1 * round(len(distances)/10.))]

#Create the figure so a legend can be added
plt.close()
fig = plt.figure()
cmap = plt.get_cmap('Paired')

self.map = Basemap(projection='aeqd', width=width, height=width,
lat_0=self.center_lat,lon_0=self.center_lon,resolution =None)

#Fill background.
self.map.drawmapboundary(fill_color='aqua')

#Draw parallels and meridians to give some references
self.map.drawparallels(range(-80, 100, 20))
self.map.drawmeridians(range(-180, 200, 20))

#Draw a black dot at the center.
xpt, ypt = self.map(self.center_lon, self.center_lat)
self.map.plot([xpt],[ypt],'ko')

#Draw the sectors
for i in range(len(results.keys())):
for angle in results[results.keys()[i]]:
anglerad = float(angle) * pi / 180.0
anglerad2 = float(angle + 360./num_angles) * pi / 180.0
polygon = Polygon([(xpt, ypt), (xpt + width * sin(anglerad), ypt + width * cos(anglerad)), (xpt + width * sin(anglerad2), ypt + width * cos(anglerad2))])
patch2b = PolygonPatch(polygon, fc=cmap(float(i)/(len(results) - 1)), ec=cmap(float(i)/(len(results) - 1)), alpha=1., zorder=1)

#Draw the countries
for polygon in self.polygons:
patch2b = PolygonPatch(polygon, fc='#555555', ec='#787878', alpha=1., zorder=2)

#Draw the legend
cmap = self.cmap_discretize(cmap, len(results.keys()))
mappable = cm.ScalarMappable(cmap=cmap)
mappable.set_array([])
mappable.set_clim(0, len(results))
colorbar = plt.colorbar(mappable, ticks= [x + 0.5 for x in range(len(results.keys()))])
colorbar.ax.set_yticklabels(results.keys())

plt.title('Closest country')

• The first steps are used to calculate  the closest country in each direction, storing the result in a dict. The distance is calculated using the closest_polygon method, explained in the previous section..
• The actual map size is then calculated, taking the distance where the 90% of the polygons will appear. The width_factor can change this, because some times the result is not pretty enough. Some times has to much zoom and some, too few. Note that the aeqd i.e., Azimuthal Equidistant projection is used, since is the one that makes the distances in all directions comparable.
• Next steps are to actually drawing the map
• The sectors (the colors indicating the closest country) are drawn using the Descartes library and it's PolygonPatch
• The legend needs to change the color map to a discrete color map. I used a function called cmap_discretize, found here, to do it
• The legend is created using the examples found in this cookbook
Some outputs:

### Next steps: What's across the ocean

Well, my original idea was creating a map like this one, showing the closest country when you are at the beach. Given a point and a direction (east or west in the example), calculating the country is easy, and doing it for each point in the coast is easy too. The problem is that doing it automatic is far more difficult, since you have to know the best direction (not easy in many places like islands), which countries to take as the origin, etc.
An other good thing would be doing the same, but with d3js, since  the point position could become interactive. I found some libraries like shapely.js or  jsts, but I think that they still don't implement the difference operation that we need.

A LinkedIn discussion that gave me some ideas

How to install Basemap (you can use a virtual environment to test it without installing it in the whole system). Be sure to have pip installed, and the python-dev package in case you are using Ubuntu. Some distributions have Basemap as a system package too.
How to create an Azimuthal equidistant map with Basemap - The Azimuthal Equidistant projection
Some simple and useful Basemap examples
Advanced Basemap tricks that helped me to add the legend and much more
How to discretize a color map
Descartes: Drawing polygons in Matplotlib

## Monday, July 7, 2014

### Using the D3 trail layout to draw the Hayian tracks

I wrote many examples (1, 2, 3 and 4) and some entries in the blog (1 and 2) showing how to draw animated paths on a map using the D3 library.
But since then, Benjamin Schmidt wrote a D3 layout, called trail layout, that simplifies a lot doing this kind of stuff.
Since the layout is new, and hasn't got many examples (actually, two made by the author), I'll try to show how to work with it.

### The trail layout

How does the trail layout work? The author defines it as:
This is a layout function for creating paths in D3 where (unlike the native d3.svg.line() element) you need to apply specific aesthetics to each element of the line.
Basically, the input is a set of points, and the layout takes them and creates separate segments to join them. This segments can be either line or d SVG elements.

#### Let's see the simplest example:

var width = 600,
height = 500;

var points = [{"x":0,"y":0}, {"x":200,"y":200}, {"x":0,"y":400}, {"x":200,"y":100}];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);

var trail = d3.layout.trail().coordType('xy');

var trail_layout = trail.data(points).layout();

paths = svg.selectAll("line").data(trail_layout);

paths.enter()
.append('line')
.style("stroke-width",3)
.style("stroke","black")
.attr("x1",function(d) {return d.x1})
.attr("y1",function(d) {return d.y1})
.attr("y2",function(d) {return d.y2})
.attr("x2",function(d) {return d.x2})

• In this case, the points are defined as an array of objects with the x and y properties. If the x and y are named this way, the layout takes them directly. If they are called for instance lon and lat, the layout must be told how to get them.
• Line 10 creates the SVG
• Line 14 initializes the layout. In this case, the layout is using the coordType xy, which means that as a result will give the initial and end point for each segment, convenient for drawing SVG line elements. The other option is using the coordinates value, which is convenient for drawing d elements, as we will see later.
•  Line 15 is where the data is set and the layout is retrieved
• The last step is where the lines are actually drawn.
• For each data element, the line svg is added
• The styles are applied
• The extremes of the line are set using the attributes x1, y1, x2, y2

#### How to use coordinates as the coordType:

The following example created the trail as a set of SVG line elements, but the trail layout has an option for creating it as a set of SVG d elements (paths).
You can see the example here. The data, in this case, is the Hayian track. As you can see, it's quite similar as the former example, with the following differences:
• Since in this case we are using geographical coordinates, a projection must be set, and also a d3.geo.path to convert the data into x and y positions, as usual when drawing d3 maps
• When initializing the trail layout, coordinates must be set as the coordType.
• Since the data elements do not store the positions with the name x and y, the layout has to be told how the retrieve them using the positioner:
.positioner(function(d) {return [d.lon, d.lat];})
• When drawing the trail, a path element is appended instead the line element, and the d attribute is set with the path  function defined above.

### Creating the map with the trail

Once the basic usage of the trail layout is known, let's reproduce the Hayian path example (simplified for better understanding):

.map {
fill: none;
stroke: #777;
stroke-opacity: .5;
stroke-width: .5px;
}

.land {
fill: #999;
}

.boundary {
fill: none;
stroke: #fff;
stroke-width: .5px;
}

var width = 600,
height = 500;

var projection = d3.geo.mercator()
.scale(5*(width + 1) / 2 / Math.PI)
.translate([width / 2, height / 2])
.rotate([-125, -15, 0])
.precision(.1);

var path = d3.geo.path()
.projection(projection);

d3.json("/mbostock/raw/4090846/world-50m.json", function(error, world) {
d3.json("track.json", function(error, track) {

var color_scale = d3.scale.quantile().domain([1, 5]).range(colorbrewer.YlOrRd[5]);

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);

var trail = d3.layout.trail()
.positioner(function(d) {return projection([d.lon,d.lat]);})
.coordType('xy');

var trail_layout = trail.data(track).layout();

svg.insert("path", ".map")
.datum(topojson.feature(world, world.objects.land))
.attr("class", "land")
.attr("d", path);

svg.insert("path", ".map")
.datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
.attr("class", "boundary")
.attr("d", path);

var hayan_trail = svg.selectAll("d").data(trail_layout);

hayan_trail.enter()
.append('line')
.attr("x1",function(d) {return d.x1})
.attr("x2",function(d) {return d.x1})
.attr("y1",function(d) {return d.y1})
.attr("y2",function(d) {return d.y1})
.attr("class","line")
.style("stroke-width",4)
.attr("stroke", function(d){return color_scale(d.class);})
.transition()
.ease("linear")
.delay(function(d,i) {return i*500})
.duration(500)
.attr("x2",function(d) {return d.x2})
.attr("y2",function(d) {return d.y2})
;

});
});

• The map creation is as usual (explained here)
• Lines 49 to 51 create the trail layout as in the former example
• Line 67 creates the trail, but with some differences:
• the beginning and the end of the line are the same point at the beginning, so the line is not drawn at this moment (lines 69 to 72)
• The stroke colour is defined as a function of the typhoon class using the colour scale (line 75)
• A transition is defined to create the effect of the line drawing slowly
• The ease is defined as linear, important in this case where we join a transition for each segment.
• The delay is set to draw one segment after the other. The time (500 ms) must be the same as the one set at duration
• Finally, the changed values are x2 and y2, that is, the final point of the line, which are changed to their actual values
• The complete example, with the typhoon icon and the date is also available
It's possible to use paths instead of lines to draw the map, as in the first version. The whole code is here, but the main changes are in the last section:
hayan_trail.enter()
.append('path')
.attr("d", path)
.style("stroke-width",7)
.attr("stroke", function(d){return color_scale(d.class);})
.style('stroke-dasharray', function(d) {
var node = d3.select(this).node();
if (node.hasAttribute("d")){
var l = d3.select(this).node().getTotalLength();
return l + 'px, ' + l + 'px';
}
})
.style('stroke-dashoffset', function(d) {
var node = d3.select(this).node();
if (node.hasAttribute("d"))
return d3.select(this).node().getTotalLength() + 'px';
})
.transition()
.delay(function(d,i) {return i*1000})
.duration(1000)
.ease("linear")
.style('stroke-dashoffset', function(d) {
return '0px';
});
• The strategy here is to change the stroke-dasharray  and stroke-dashoffset style values as in this example, and changing it later so the effect takes place.
• At the beginning, both values are the same length as the path. This way, the path doesn't appear. The length is calculated using the JavaScript function getTotalLength
• After the transition, the stroke-offset value will be 0, and the path is fully drawn

### Conclusion

I recommend using the trail layout instead of the method from my old posts. It's much cleaner, fast, easy, and let's changing each segment separately.
The only problem I find is that when the stroke width gets thicker, the angles of every segment make strange effects, because the union between them doesn't exist.

This didn't happen with the old method. I can't imagine how to avoid this using lines, but using the coordinates option could be solved transforming the straight lines for curved lines.

## Wednesday, April 16, 2014

### D3 map Styling tutorial IV: Drawing gradient paths

After creating the last D3js example, I was unsatisfied with the color of the path. It changed with the typhoon class at every moment, but it wasn't possible to see the class at every position. When I saw this example by Mike Bostock, I found the solution.

### Understanding the gradient along a stroke example

First, how to adapt the Mike Bostock's Gradient Along Stroke example to a map.
The map is drawn using the example Simple path on a map, from this post. The only change is that the dashed path is changed with the gradient.
You can see the result here.
The differences from drawing a simple path start at the line 100:
var line = d3.svg.line()
.interpolate("cardinal")
.x(function(d) { return projection([d.lon, d.lat])[0]; })
.y(function(d) { return projection([d.lon, d.lat])[1]; });

svg.selectAll("path")
.enter().append("path")
.style("fill", function(d) { return color(d.t); })
.style("stroke", function(d) { return color(d.t); })
.attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], trackWidth); });

•  The line definition remains the same. From every element it gets, it takes the lat and lon attributes, projecting them, and assigning them to the x and y path properties
• A color function is defined at line 41, which will interpolate the color value from green to red:
var color = d3.interpolateLab("#008000", "#c83a22");
• The data is not the line(track) directly, as in the former example, but passed through the functinos sample and quad.
• The sample function assigns a property t with values between 0 and 1, which is used to get the color at every point.
• Finally, the function lineJoin is used to draw a polygon for the sampled area.
The functions used in the Mike Bostock's example aren't explained, I'll try to do it a little:
• sample takes a line (the data applied to a line function), and iterates with the precision parameter as increment along the string, creating an array with all the calculated points.
• quad takes the points calculated by the sample function and returns an array with the adjacent points (i-1, i, i+1, i+2).
• lineJoin takes the four points generated by quad, and draws the polygon, with the help of lineItersect and perp functions.

### Drawing the typhoon track with the colors according to the typhoon class

The final example draws the typhoon path changing smoothly the color according to the typhoon class.
The animation of the path, and the rotating icon are explained in the third part of the tutorial. In this case, the way to animate the path will change.
For each position of the typhoon, a gradient path is drawn, because the gradient is always between two colors. So the part of the code that changes is:
      //Draw the path, only when i > 0 in otder to have two points
if (i>0){
color0 = color_scale(track[i-1].class);
color1 = color_scale(track[i].class);

var activatedTrack = new Array();

activatedTrack.push(track[i-1]);
activatedTrack.push(track[i]);

var color = d3.interpolateLab(color0, color1);
path_g.selectAll("path"+i)
.enter().append("path")
.style("fill", function(d) { return color(d.t);})
.style("stroke", function(d) { return color(d.t); })
.attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], trackWidth); });
}

i = i + 1;
if (i==track.length)
clearInterval(animation)

• Inside the animation interval (line 145), the gradient path is create for each position (starting with the second one to have two points)
• The two colors are taken from the point information
• An array with the two points is created, with the name activatedTrack. I tried using more points, but the result is very similar.
• The color interpolation is calculated (line 172)
• The gradient colored path is created (line 173). Note that the name is path+i, to make different paths each iteration, and not to overwrite them. The method is the same as the one used in the first section.
Besides, an invisible path with all the positions is created, so the typhoon icon can be moved as it was in the third part of the tutorial.

## Monday, March 31, 2014

### Slides for the workshop "Introduction to Python for geospatial uses"

Last 26th, 27th and 28th of March, the 8as Jornadas SIG Libre were held in Girona, where I had the opportunity to give a workshop about Python for geospatial uses.

The slides in Spanish:
http://rveciana.github.io/introduccion-python-geoespacial

The Slides in English:
http://rveciana.github.io/introduccion-python-geoespacial/index_en.html

The example files in both languages:
https://github.com/rveciana/introduccion-python-geoespacial

The meeting was awesome, if you have the opportunity and understand Spanish, come next year!

## Monday, March 24, 2014

### Shaded relief images using GDAL python

After showing how to colour a DEM file, classifying it, and calculating its isobands, this post shows how to create a shaded relief image from it.
 The resulting image
A shaded relief image simulates the shadow thrown upon a relief map. This shadow is usually blended with some colouring, related to the altitude, a terrain classification, etc.
The shadow is usually drawn considering that the sun is at 315 degrees of azimuth and 45 degrees over the horizon, which never happens at the north hemisphere. This values avoid strange perceptions, such as seeing the mountain tops as the bottom of a valley.

In this example, the script calculates the hillshade image, a coloured image, and blends them into the shaded relief image.

As usual, all the code, plus the sample DEM file, can be found at GitHub.

I didn't know how to create a shaded relief image using numpy. Eric Gayer helped me with some samples, and I found some other information here.
The script is:
"""
Creates a shaded relief file from a DEM.
"""

from osgeo import gdal
from numpy import pi
from numpy import arctan
from numpy import arctan2
from numpy import sin
from numpy import cos
from numpy import sqrt
from numpy import zeros
from numpy import uint8
import matplotlib.pyplot as plt

slope = pi/2. - arctan(sqrt(x*x + y*y))
aspect = arctan2(-x, y)

ds = gdal.Open('w001001.tiff')
band = ds.GetRasterBand(1)

plt.imshow(hs_array,cmap='Greys')
plt.show()

• The script draws the image using matplotlib, to make it easy
• The hillshade function starts calculating the gradient for the x and y directions using the numpy.gradient function. The result are two matrices of the same size than the original, one for each direction.
• From the gradient, the aspect and slope can be calculated. The aspect will give the mountain orientation, which will be illuminated depending on the azimuth angle. The slopewill change the illumination depending on the altitude angle.
• Finally, the hillshade is calculated.

The shaded relief image is calculated using the algorithm explained in the post Colorize PNG from a raster file and the hillshade.
As in the coloring post, the image is read by blocks to improve the performance, because it uses a lot of arrays, and doing it at once with a big image can take a lot of resources.
I will coment the code block by block, to make it easier. The full code is here.

The main function, called shaded_relief, is the most important, and calls the different algorithms:
def shaded_relief(in_file, raster_band, color_file, out_file_name,
azimuth=315, angle_altitude=45):
'''
The main function. Reads the input image block by block to improve the performance, and calculates the shaded relief image
'''

if exists(in_file) is False:
raise Exception('[Errno 2] No such file or directory: \'' + in_file + '\'')

if dataset == None:
raise Exception("Unable to read the data file")

band = dataset.GetRasterBand(raster_band)

block_sizes = band.GetBlockSize()
x_block_size = block_sizes[0]
y_block_size = block_sizes[1]

#If the block y size is 1, as in a GeoTIFF image, the gradient can't be calculated,
#so more than one block is used. In this case, using8 lines gives a similar
#result as taking the whole array.
if y_block_size < 8:
y_block_size = 8

xsize = band.XSize
ysize = band.YSize

max_value = band.GetMaximum()
min_value = band.GetMinimum()

#Adding an extra value to avoid problems with the last & first entry
if sorted(color_table.keys())[0] > min_value:
color_table[min_value - 1] = color_table[sorted(color_table.keys())[0]]

if sorted(color_table.keys())[-1] < max_value:
color_table[max_value + 1] = color_table[sorted(color_table.keys())[-1]]
#Preparing the color table
classification_values = color_table.keys()
classification_values.sort()

max_value = band.GetMaximum()
min_value = band.GetMinimum()

if max_value == None or min_value == None:
stats = band.GetStatistics(0, 1)
max_value = stats[1]
min_value = stats[0]

out_array = zeros((3, ysize, xsize), 'uint8')

#The iteration over the blocks starts here
for i in range(0, ysize, y_block_size):
if i + y_block_size < ysize:
rows = y_block_size
else:
rows = ysize - i

for j in range(0, xsize, x_block_size):
if j + x_block_size < xsize:
cols = x_block_size
else:
cols = xsize - j

dem_array = band.ReadAsArray(j, i, cols, rows)

angle_altitude)

rgb_array = values2rgba(dem_array, color_table,
classification_values, max_value, min_value)

hsv_array = rgb_to_hsv(rgb_array[:, :, 0],
rgb_array[:, :, 1], rgb_array[:, :, 2])

hsv_array[1], hs_array] )

#Saving the image using the PIL library
im = fromarray(transpose(out_array, (1,2,0)), mode='RGB')
im.save(out_file_name)
• After opening the file, at line 20 comes the first interesting point. If the image is read block by block, some times the blocks will have only one line, as in the GeoTIFF images. With this situation, the y gradient won't be calculated, so the hillshade function will fail. I've seen that taking only two lines gives coarse results, and with lines the result is more or less the same as taking the whole array. The performance won't be as good as using only one block, but works faster anyway.
• Lines 32 to 51 read the color table and file maximim and minumum. This has to be outside the values2rgba function, since is needed only once.
• Lines 54 to 66 control the block reading. For each iteration, a small array will be read (line 67). This is what will be processed. The result will be written in the output array defined at line 52, that has the final size.
• Now the calculations start:
• At line 69, the hillshade is calculated
• At line 72, the color array is calculated
• At line 75, the color array is changed from rgb values to hsv.
• At line 78, the value (the v in hsv) is changed to the hillshade value. This will blend both images. I took the idea from this post.
• Then the image is transformed to rgb again (line 81) and written into the output array (line 83)
• Finally, the array is transformed to a png image using the PIL library. The numpy.transpose function is used to re-order the matrix, since the original values are with the shape (3, height, width), and the Image.fromarray function needs (height, width, 3). An other way to do this is using scipy.misc.imsave (that would need scipy installed just for that), or the Image.merge function.

The colouring funcion is taken from the post  Colorize PNG from a raster file, but modifying it so the colors are only continuous, since the discrete option doesn't give nice results in this case:
def values2rgba(array, color_table, classification_values, max_value, min_value):
'''
This function calculates a the color of an array given a color table.
The color is interpolated from the color table values.
'''
rgba = zeros((array.shape[0], array.shape[1], 4), dtype = uint8)

for k in range(len(classification_values) - 1):
if classification_values[k] < max_value and (classification_values[k + 1] > min_value ):
mask = logical_and(array >= classification_values[k], array < classification_values[k + 1])

v0 = float(classification_values[k])
v1 = float(classification_values[k + 1])

rgba[:,:,0] = rgba[:,:,0] + mask * (color_table[classification_values[k]][0] + (array - v0)*(color_table[classification_values[k + 1]][0] - color_table[classification_values[k]][0])/(v1-v0) )
rgba[:,:,1] = rgba[:,:,1] + mask * (color_table[classification_values[k]][1] + (array - v0)*(color_table[classification_values[k + 1]][1] - color_table[classification_values[k]][1])/(v1-v0) )
rgba[:,:,2] = rgba[:,:,2] + mask * (color_table[classification_values[k]][2] + (array - v0)*(color_table[classification_values[k + 1]][2] - color_table[classification_values[k]][2])/(v1-v0) )
rgba[:,:,3] = rgba[:,:,3] + mask * (color_table[classification_values[k]][3] + (array - v0)*(color_table[classification_values[k + 1]][3] - color_table[classification_values[k]][3])/(v1-v0) )
return rgba

The hillshade function is the same explained at the first point
The functions rgb_to_hsv and hsv_to_rgb are taken from this post, and change the image mode from rgb to hsv and hsv to rgb.


text:
• Li Xia

Articles written in Bulletin of Materials Science

• Luminescence properties of YAG:Nd3+ nano-sized ceramic powders via co-microemulsion and microwave heating

Nano-sized ceramic powders with weaker aggregation of Nd3+-doped yttrium aluminum garnet (YAG:Nd3+) were synthesized via co-microemulsion and microwave heating. This method provides a limited small space in a micelle for the formation of nano-sized precursors. It also requires a very short heating time, thus reducing energy consumption in comparison with conventional solid-state sintering processes. As a result, small-sized particles with narrow size distribution, weaker aggregation and high purity were obtained. Powder X-ray diffraction results revealed that the structure of pure YAG:Nd3+ nanoparticles was cubic garnet. Transmission electron microscopy results indicated that the synthesized particles were almost spherical with average diameters of 40 and 80 nm. The luminescent properties of YAG:Nd3+ were investigated through PL. Under excitation at 488 nm, YAG:Nd3+ nanosized ceramic powders showed main emission bands of 1045–1080 nm because of ${}^{4}F_{3/2} \rightarrow 4I_{11/2}$ transitions that are identical to those observed for a single YAG:Nd3+ crystal.

• Bulletin of Materials Science

Current Issue
Volume 42 | Issue 6
December 2019

• Editorial Note on Continuous Article Publication

Posted on July 25, 2019

format: plain


text:
It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

It is a long established fact that a reader will be distracted by the.

Halo Kak, perlu bantuan Mister ?


text:
# Finding a median in a union of sets given as sorted arrays [duplicate]

This question already has an answer here:

You are given $k$ sorted arrays $A_1, A_2, ..., A_k$, each containing $n$ elements.

How fast can you compute the median of $A_1 \cup A_2 \cup ... \cup A_k$ ?

I have a solution running in $\Theta(k\log k\log n)$, but this seems rather inefficient if $k=\Omega(2^\frac{n}{\log n})$, as we can always ignore the order, think of it as a unsorted array of $nk$ elements, and solve it in $O(nk)$ time.

Assuming $k=\omega(1)$ (hence the fact the arrays are sorted give us some information), is there a sub-linear median finding algorithm (regardless of the ratio between $k$ and $n$)?

Assuming $k=\text{poly}( n)$, can we beat $O(k\log k\log n)$?

Can we prove a lower bound for the problem (maybe $\Omega(k\log n)$?)?


text:
# Math Help - Fundamental Theorem of Calculus

1. ## Fundamental Theorem of Calculus

can you guys help me with this:

Use FTC to find the derivative of h(u) = $\int^{2u}_{0} cos^5t\,dt$, justifying your reasoning.

would this be correct:
$\frac{d}{du}\int^{2u}_{0} cos^5t\,dt$ n=2u
$(\frac{d}{dn} \int^{n}_{0} cos^5t\,dt)*(\frac{dn}{du})$
$(cos^5(n))*\frac{dn}{du})$
$cos^5(2u)*\frac{d(2u)}{du}$
$2cos^5(2u)$

any truth to this?

2. yes that is correct.


text:
# Problem: a) For the two vectors A?  and B?  in the figure (Figure 1) , find the scalar product A?B? b) Find the magnitude of the vector product AxB

###### FREE Expert Solution

Scalar product:

$\overline{){\mathbf{A}}{\mathbf{•}}{\mathbf{B}}{\mathbf{=}}{\mathbf{A}}{\mathbf{B}}{\mathbf{c}}{\mathbf{o}}{\mathbf{s}}{\mathbf{\theta }}}$

Cross product:

Magnitude:

$\overline{)|\stackrel{⇀}{\mathbit{A}}|{=}\sqrt{{{\mathbit{A}}_{\mathbit{x}}}^{2}+{{\mathbit{A}}_{\mathbit{y}}}^{2}+{{\mathbit{A}}_{\mathbit{z}}}^{2}}}$

a)

The angle between A and B = (180 - 70.0°) + 30.0° = 140.0°

87% (155 ratings)
###### Problem Details

a) For the two vectors A?  and B?  in the figure (Figure 1) , find the scalar product A?B

b) Find the magnitude of the vector product AxB


text:
# Using Tau Polarization for Charged Higgs Boson and SUSY Searches at LHC

The $\tau$ polarization can be easily measured at LHC in the 1-prong hadronic $\tau$ decay channel by measuring what fraction of the $\tau$-jet momentum is carried by the charged track. A simple cut requiring this fraction to be 0.8 retains most of the polarization of $\tau=$+1 $\tau$-jet signal while suppressing the polarization of $\tau=$-1 $\tau$-jet background and practically eliminating the fake $\tau$ background. This can be utilized to extract the charged Higgs signal. It can be also utilized to extract the SUSY signal in the stau NLSP region, and in particular the stau co-annihilaton region.

Author: Monoranjan Guchait; D. P. Roy

Source: https://archive.org/


text:
# C++ AI Coordinate movement

This topic is 2526 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am currently working on programming a basic text based wizard game. I have my movements working for coordinates (north = x+1, east = y+1 etc.) and I am just wondering how you could code it so that the AI moves randomly on coordinates in close proximity to you. The idea is that after moving around for a bit you will land on the same coordinates as your opponent and enter a battle.

Thanks
Chris

##### Share on other sites

I am currently working on programming a basic text based wizard game. I have my movements working for coordinates (north = x+1, east = y+1 etc.) and I am just wondering how you could code it so that the AI moves randomly on coordinates in close proximity to you. The idea is that after moving around for a bit you will land on the same coordinates as your opponent and enter a battle.

Thanks
Chris

Do you mean the enemy should be aware of the player's position when its moving so that it keeps being inside a specific proximity of the player?

##### Share on other sites
Yeah, that would be quite helpful. I want it so that it doesn't take ages to find the enemy, but it isn't just first move = fight.

Thanks
Chris

##### Share on other sites
here is some pseudo code that came to my mind right now:

 vec2d dist = distVec(player, enemy) if (dist.x > MAX_DIST) enemy.x-- // depending on what u want else if (dist.x < -MAX>DIST) enem.x++ if (dist.y > MAX_DIST) enemy.y-- else if (dist.y < - MAX_DIST) enemy.y++

that should keep the enemy within a certain range to the player.. if u want the enemy to chase u, u can do the following pseudocode:

 if (enemy.x < player.x) enemy.x++ etc..

than the enemy goes terminator style after u..

hope to have helped u, it took a while to get your problem ^^ (and i am still not sure if that was what u wanted to know :-)

1. 1
2. 2
Rutin
21
3. 3
4. 4
frob
17
5. 5

• 9
• 33
• 13
• 13
• 10
• ### Forum Statistics

• Total Topics
632582
• Total Posts
3007207

×

## Important Information

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!


text:
# Daily Archives: March 11, 2010

## Not a Random Walk

Euler appeared, advanced toward Diderot, and in a tone of perfect conviction announced, “Sir, $\frac{a+b^n}{z}=x$, hence God exists—reply!”.

One is tempted to be amazed how often such arguments are made about serious issues. But it shouldn’t be such a surprise when one considers how often people are taken in by such sophistry. If you can’t persuade them with logic, dazzle them with bullshit.

## Update, and a good post by the Rabett

I’ve almost completed the first draft of the paper about the analysis of GHCN data. I intend to send it to Professor Rabett for his opinion before submitting it; I hope he’s willing to offer his valuable advice.

I’d also like to direct readers to a worthwhile post by the Rabett; he’s becoming my favorite climate-science blogger.


text:
# Very popular answer deleted [closed]

A number of answers for the question Proper Use cases for Android UserManager.isAGoat() were deleted, such as this one by casperOne. (I'm not sure who is responsible for the deletions of the other answers which where popular and I feel should have stayed)

I feel that this is an inappropriate action for the moderator to have taken. A moderator may disagree with a post, but it is not grounds for deletion. That is what the up/down vote is for.

Why was this (and other more popular) posts deleted, and is that an appropriate action for a moderator to take?

-

## closed as not constructive by phwd, jonsca, McCannot, Bo Persson, Toon KrijtheNov 14 '12 at 20:03

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

I hope you're feeling better. Also, whoa, deleted post with a score of 148. –  BoltClock's a Unicorn Nov 14 '12 at 18:48
If it helps, there are currently 16 deleted answers. 2 self-deleted, the rest deleted by 4 different moderators. (2 of which are actually employees) –  Mysticial Nov 14 '12 at 18:48
Since when are tabloid-type speculations on-topic on Stack Overflow? That answer you point out isn't more than that. –  Mat Nov 14 '12 at 18:57
BTW, you believe that I'm abusing my moderator (no quotes, I am a moderator) status. From the votes on this meta post, it seems there are those that don't entirely agree with that statement. –  casperOne Nov 14 '12 at 19:31
I have edited the post to attempt to avoid closure as "not constructive". If you feel that the edit is not in line with your underlying question, please edit the post accordingly. I feel that there is a valid question here, but the use of a few "harsh" words were not constructive. –  Servy Nov 14 '12 at 19:42
were you arguing that all the other deletions were justified and that only the one by casperOne was problematic? The edit by @Servy seems to suggest so and I'm not entirely sure that is what you intended to say. –  Bart Nov 14 '12 at 19:47
Reddit kids. Pah. –  John Dibling Nov 14 '12 at 19:52
@Bart I agree it's not 100% clear. I assumed that "not sure who is responsible for the other deletions of answers that where just fine" meant that he didn't have a problem with the deletion of the other answers to this question. I assumed that the plural references to answers being incorrectly deleted was that he felt this is a more broad problem happening in other questions besides this one, and that this is one example. I essentially changed it to be specific-question. –  Servy Nov 14 '12 at 19:53
@Servy Yeah, the OP might have meant that. It's not a big deal, so let's wait for some feedback/confirmation there. :) –  Bart Nov 14 '12 at 19:55
I linked to my answer in that question because I cannot see the other deleted answers. I have a problem with so many HIGHLY voted answers, which had no issues (answered the question) where deleted. Mine was deleted; its the only 'deleted' answer I could see. Not a mod. Edit: -13 for this question so far. Mods are up tight today. –  PenguinCoder Nov 14 '12 at 19:55
@PenguinCoder Could you drop the non-constructive attitude? -13 might easily be caused by simple user disagreement. No mods need to be involved there. We tried to edit your question into something a bit more constructive. It's always better to try to somewhat neutrally address a problem. Even if you're terribly upset. It will get you a far better response. –  Bart Nov 14 '12 at 20:02
@bart I attempt previously, and on the question stated/referenced in my above question to 'play nice'. I did nothing wrong and was polite at that time. Strike the last sentence from the above comment, but my issue still lies with moderators (or high rep users who 50 pts doesn't matter to them) abusing certain privileges they've gained. That frustration crosses over into text, although doesn't change the point of what I am trying to say. –  PenguinCoder Nov 14 '12 at 20:05
@PenguinCoder I just find it a shame that your point (which you might have) possibly gets drowned in downvotes and close votes when a simple change of tone might have (partially) prevented it. But of course I can only speculate on the reason for those votes. –  Bart Nov 14 '12 at 20:17

The question in question is currently headlining on multiple social link sharing sites. The actions of the moderators seem to be in line with making the discussion constructive and in line with the actual question being asked.

Many of the deleted answers did not actually attempt to answer the question about what the function does and how it should be used, even the ones speculating about the relationship between Android goats and Chrome goats. (Honestly, IMO, the top-rated one about that speculation is OK, especially given the source code citation...)

-
Man, 63k views in 10 hours... Is that a new record? –  Mysticial Nov 14 '12 at 18:56
I agree that the top-rated answer should not have been deleted. Showing that it's a reference to an existing joke is the strongest way to prove that it is meant as a joke. That's more informative than the top non-deleted answer, which tries to rationalize a use for it, even though it's probably not meant to be used. (edit: I've raised a flag.) –  Jeremy Banks Nov 14 '12 at 19:13
@JeremyBanks The question, however, is not "what is the meaning behind this joke" (which is off topic, btw) it is "what are valid use cases for this" which the top voted answer does not answer and therefore, "Not An Answer" and deleted as such. –  casperOne Nov 14 '12 at 19:24
@casperOne If "doesn't answer the exact question" is now criteria for deletion, I have quite a backlog of old answers for you to delete. I don't think people would respond favourably, however. –  Jeremy Banks Nov 14 '12 at 19:25
@casperOne: Convert to comm— oh wait, 500 character limit. –  BoltClock's a Unicorn Nov 14 '12 at 19:26
@casperOne Not to disagree with you, but your argument seems to run counter to policy that "no it's not possible" is a valid answer. Here the question is, "what are the ...". The answer is, "there are none". –  Mysticial Nov 14 '12 at 19:26
Wait wait wait wait, did you add an extra sentence to this post to make it an answer? I'm not entirely sure putting words in other people's mouths is the best idea... I'd have prompted the user with a comment instead at most. –  BoltClock's a Unicorn Nov 14 '12 at 19:29
@Mysticial The question is not "is this possible" the question is "when should I use this". As you see from the currently undeleted top rated answer, it attempts to show a valid use case. –  casperOne Nov 14 '12 at 19:29
@Mysticial: I disagree on this count. The top-voted deleted answer doesn't even talk about Android or the method in question. It's doesn't say "there are no use cases" or anything else than say it probably has something to do with an easter egg on another Google product. –  Mat Nov 14 '12 at 19:30
@casperOne That seems to go against the "mods don't judge the technical accuracy of an answer" kind of flag rejections. Which, as you know, are often discussed here by users who are surprised that an obviously wrong answer is not handled by mods... –  Bart Nov 14 '12 at 19:32
@Mat Fair enough. But when I read it, "there are no use cases" was implied. Perhaps it could have been made more clear. –  Mysticial Nov 14 '12 at 19:34
@Bart The mod is not making any critique of whether the response is correct or not. The answer may be correct or it might not be. Regardless of whether or not it's correct, it doesn't even attempt to answer the question, so it's validity is entirely irrelevant. –  Servy Nov 14 '12 at 19:36
@casperOne Quote: Telling the history or the reasoning behind why a joke was made isn't useful or helpful. I utterly, 100% completely, disagree with you. The difference is; I can't delete your incorrect answer or comment with wanton disregard. –  PenguinCoder Nov 14 '12 at 19:53
@PenguinCoder I'm not sure what your point is. In my answer, I at least answered your question. Here's the thing, if you have issue with that answer then you should also be taking the issue up with the other moderators, users, and SE employees that have deleted other answers that say the same exact thing as the deleted answer you've pointed out. This wasn't a personal bias against the question or answer, it's following what was clearly done before on that question to make the entire post live up to Stack Overflow's quality guidelines. –  casperOne Nov 14 '12 at 19:55
@PenguinCoder Again, not sure what the purpose of your last comment is. We're trying to keep the question constructive, you've come to meta in an unconstructive way and are lobbing accusations around which usually doesn't help with the collective goal of increasing quality on the site. –  casperOne Nov 14 '12 at 20:03

The answer that you reference does not answer the question. The question, at a fundamental level is:

What are proper use cases for X?

The top voted answer you refer to says:

X is visible here and Y, related to X is visible here

That said, anything that doesn't answer the question as asked will be deleted (as a number of other moderators, people who answered the question, and SE employees have already done).

It's the only way to keep the question remotely constructive and on topic for the site.

If you really want to know ideas as to why the API is named that and accept those answers, then it makes the question off topic for Stack Overflow.

Also, to the argument and the existing flags on the answer saying it is a joke and this is the reason for the joke, there's nothing in the actual question (or any revision of the question) indicating that the person didn't know it was a joke.

If anything, the question itself indicates that they know it's a joke, given that they're asking for valid uses of the API.

-
It was not immediately obvious to me whether this is a joke name for a useful method, or a joke method with no use. The post giving a contrived use misses the point (a "proper" use case) completely. Elaborating on the "yes, it's a joke" point is more useful as an answer, insofar as anything relating to that question is useful. –  McCannot Nov 14 '12 at 19:48
@McCannot From the initial revision "Does anyone know how and when should this be used?". Because it's a joke doesn't mean it shouldn't be used. If there's a legitimate use for it, then we'd like to see it. If there's not, then we'd like to see it (but it's very difficult to prove that point, of course, but we wouldn't delete it if it tried very hard to elaborate as to why that's their position). But that answer doesn't even give one of those positions. It simply says "this was a joke and why". –  casperOne Nov 14 '12 at 19:53
On the contrary, being a joke is an excellent reason to not use a method. And I don't dispute the utility of the deleted answer, I dispute that it was less useful than the remaining high-voted answer or, for that matter, the question. I should note that, as a card-carrying member of the No Fun Allowed Club I've already voted to close the question and would be happy to see it deleted as well. –  McCannot Nov 14 '12 at 19:58
@McCannot If the answer stated that belief that it's a joke and it should not be used, then it would not have been deleted. However, that's not the case and doing so now would be a destructive edit. If you really want to see that, then @ the user and ask him to edit his question to reflect his position (if it is his position) and then we can undelete it. It's not that I don't trust the editing of SO right now, but at this point, there are too many cooks in the kitchen on this, might as well let the original chef handle the recipe and then take it from there. –  casperOne Nov 14 '12 at 20:01
It really, really stretches the limits of plausibility to see "it's a joke" as not implying "it has no practical use". If we accept your premise that the questioner knows the method is a joke, then there's nothing useful to answer and the whole question should be NARQ'd with extreme prejudice. Unfortunately I'm out of delete votes today and now the question has been re-opened anyway. Sigh. –  McCannot Nov 14 '12 at 20:49
@McCannot Why is saying "I know this wasn't meant to have any practical usage, but I was wondering if there are practical usages" implausible? There are practical uses for impractical things all the time. There's no reason that it can't be that way in code either, and the third highest voted answer (as of this writing) is an attempt to answer the question legitimately. –  casperOne Nov 14 '12 at 20:58


text:
# crossVal: Cross validation of different prediction models In synbreed: Framework for the Analysis of Genomic Prediction Data using R

## Description

Function for the application of the cross validation procedure on prediction models with fixed and random effects. Covariance matrices must be committed to the function and variance components can be committed or reestimated with ASReml or the BLR function.

## Usage

 1 2 3 4 crossVal(gpData, trait=1, cov.matrix = NULL, k = 2, Rep = 1, Seed = NULL, sampling = c("random", "within popStruc", "across popStruc","commit"), TS=NULL,ES=NULL, varComp = NULL, popStruc = NULL, VC.est = c("commit", "ASReml","BRR","BL"),verbose=FALSE,...)

## Arguments

 gpData Object of class gpData trait numeric or character. The name or number of the trait in the gpData object to be used as trait. cov.matrix list including covariance matrices for the random effects. Size and order of rows and columns should be equal to rownames of y. If no covariance is given, an identity matrix and marker genotypes are used for a marker regression. In general, a covariance matrix should be non-singular and positive definite to be invertible, if this is not the case, a constant of 1e-5 is added to the diagonal elements of the covariance matrix. k numeric. Number of folds for k-fold cross validation, thus k should be in [2,nrow(y)] (default=2). Rep numeric. Number of replications (default = 1). Seed numeric. Number for set.seed() to make results reproducable. sampling Different sampling strategies can be "random", "within popStruc" or "across popStruc". If sampling is "commit" test sets have to specified in TS (see Details). TS A (optional) list of vectors with IDs for the test set in each fold within a list of replications, same layout as output for id.TS . ES A (optional) list of IDs for the estimation set in each fold within each replication. varComp A vector of variance components for the random effects, which has to be specified if VC.est="commit". The first variance components should be the same order as the given covariance matrices, the last given variance component is for the residuals. popStruc Vector of length nrow(y) assigning individuals to a population structure. If no popStruc is defined, family information of gpData is used. Only required for options sampling="within popStruc" or sampling="across popStruc" VC.est Should variance components be reestimated with "ASReml" or with Bayesian Ridge Regression "BRR" or Bayesian Lasso "BL" of the BLR package within the estimation set of each fold in the cross validation? If VC.est="commit", the variance components have to be defined in varComp. For ASReml, ASReml software has to be installed on the system. verbose Logical. Whether output shows replications and folds. ... further arguments to be used by the genomic prediction models, i.e. prior values and MCMC options for the BLR function (see BLR).

## Details

In cross validation the data set is splitted into an estimation (ES) and a test set (TS). The effects are estimated with the ES and used to predict observations in the TS. For sampling into ES and TS, k-fold cross validation is applied, where the data set is splitted into k subsets and k-1 comprising the ES and 1 is the TS, repeated for each subset.

To account for the family structure (Albrecht et al. 2011), sampling can be defined as:

random

Does not account for family structure, random sampling within the complete data set

within popStruc

Accounts for within population structure information, e.g. each family is splitted into k subsets

across popStruc

Accounts for across population structure information, e.g. ES and TS contains a set of complete families

The following mixed model equation is used for VC.est="commit":

y=Xb+Zu+e

with

u=N(0,Gsigma2u)

gives the mixed model equations

(X'X,X'Z,Z'X,ZZ+GIsigma2e/sigma2u)(b,u)=(X'y,Z'y)

## Value

An object of class list with following items:

 bu  Estimated fixed and random effects of each fold within each replication. n.DS Size of the data set (ES+TS) in each fold. y.TS Predicted values of all test sets within each replication. n.TS Size of the test set in each fold. id.TS List of IDs of each test sets within a list of each replication. PredAbi Predictive ability of each fold within each replication calculated as correlation coefficient r(y_{TS},\hat y_{TS}). rankCor Spearman's rank correlation of each fold within each replication calculated between y_{TS} and \hat y_{TS}. mse Mean squared error of each fold within each replication calculated between y_{TS} and \hat y_{TS}. bias Regression coefficients of a regression of the observed values on the predicted values in the TS. A regression coefficient < 1 implies inflation of predicted values, and a coefficient of > 1 deflation of predicted values. m10 Mean of observed values for the 10% best predicted of each replication. The k test sets are pooled within each replication. k Number of folds Rep Replications sampling Sampling method Seed Seed for set.seed() rep.seed Calculated seeds for each replication nr.ranEff Number of random effects VC.est.method Method for the variance components (committed or reestimated with ASReml/BRR/BL)

Theresa Albrecht

## References

Albrecht T, Wimmer V, Auinger HJ, Erbe M, Knaak C, Ouzunova M, Simianer H, Schoen CC (2011) Genome-based prediction of testcross values in maize. Theor Appl Genet 123:339-350

Mosier CI (1951) I. Problems and design of cross-validation 1. Educ Psychol Measurement 11:5-11

Crossa J, de los Campos G, Perez P, Gianola D, Burgueno J, et al. (2010) Prediction of genetic values of quantitative traits in plant breeding using pedigree and molecular markers, Genetics 186:713-724

Gustavo de los Campos and Paulino Perez Rodriguez, (2010). BLR: Bayesian Linear Regression. R package version 1.2. http://CRAN.R-project.org/package=BLR

summary.cvData
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 # loading the maize data set ## Not run: library(synbreedData) data(maize) maize2 <- codeGeno(maize) U <- kin(maize2,ret="realized") # cross validation cv.maize <- crossVal(maize2,cov.matrix=list(U),k=5,Rep=1, Seed=123,sampling="random",varComp=c(26.5282,48.5785),VC.est="commit") cv.maize2 <- crossVal(maize2,k=5,Rep=1, Seed=123,sampling="random",varComp=c(0.0704447,48.5785),VC.est="commit") # comparing results, both are equal! cv.maize$PredAbi cv.maize2$PredAbi summary(cv.maize) summary(cv.maize2) ## End(Not run)


text:
# CSS Box Model

All elements on a web page are interpreted by the browser as residing “inside” of a box. This is called the box model.

The box model of the following factors:

• Dimensions of an element’s box
• Borders of an element’s box
• Paddings of an element’s box
• Margins of an element’s box

The box model comprises the set of properties that define parts of an element that take up space on a web page. Those properties are:

1. width and height of the content area, which define how much horizontal and vertical space is reserved for the content area of the box. This area may or may not include padding and borders. Browser can determine width and height automatically.
2. padding: the amount of space between the content area and the border. It is generally opaque and hides anything that it overlays.
3. border surrounding content area and padding.
4. margin: the amount of space (transparent area) between the border and the outside edge of the element.

Finally, the display property determines how the browser lays out the element relative to its neighbors.

+---------------------------------+
|             Margin              |
|  +---------------------------+  |
|  |          Border           |  |
|  |  +---------------------+  |  |
|  |  |       Padding       |  |  |
|  |  |  +---------------+  |  |  |
|  |  |  |               |+ |  |  |
|  |  |  |    Content    ||-|--|--|-- Height
|  |  |  |               |+ |  |  |
|  |  |  +---------------+  |  |  |
|  |  |   +-------------+   |  |  |
|  |  |          |          |  |  |
|  |  +---------------------+  |  |
|  |             |             |  |
|  +---------------------------+  |
|                |                |
+---------------------------------+
|
|
Width

## Center an Element

To center an element, one can use margin: 0 auto;. This will set the top and bottom margin to 0 pixels and adjust the left and right margins until the element is centered within its containing element.

To center an element, the width of the element must be set. If not set, the width of the element will be set to the full width of the containing element.

It is also not possible to center an element that takes up the full width of the page since the width change because of display and browser window size.

## Margin Collapse

Top and bottom margins, also called vertical margins, collapse, while top and bottom padding does not.

In other words, two elements right next to each other with horizontal margins will see their margins add up to make a total margin. Two elements right one above the other with vertical margins, however, will have their larger of the two vertical margins sets the margin.

## Difference Between visibility and display

There are two ways to remove an object from the page with CSS: display: none and visibility: hidden. The former will completely remove the element from the web page. The later will make the element not visible but will keep the space reserved for it.

In both case, the element will be visible in the source code.


text:
# When are these two definitions of “monomorphism” equivalent?

I am new to category theory so I apologize if this is a silly question.

We say that $f : X \rightarrow Y$ is a mono iff for all $g,g' : W \rightarrow X$ it holds that $f \circ g = f \circ g' \Rightarrow g=g'$.

Now define that $f : X \rightarrow Y$ is a mono* iff for all $h : X \rightarrow Z$ there exists $h' : Y \rightarrow Z$ such that $h' \circ f = h$.

Is there any connection between these two definitions? My intuition says that, at least in $\mathsf{Set}$, they're equivalent; but, I could be completely wrong.

-

The first one is the standard definition. The second one is the definition of a split monomorphism. Indeed, take $h = \textrm{id}_X$, then your definition implies there is $h' : Y \to X$ such that $h' \circ f = \textrm{id}_X$; conversely, if there is $r : Y \to X$ such that $r \circ f = \textrm{id}_X$, then for any $h : X \to Z$, for $h' = h \circ r$, we have $h' \circ f = h \circ r \circ f = h$.
In particular, the two definitions are not equivalent even in $\textbf{Set}$: the unique map $\emptyset \to Y$ is always injective but splits if and only if $Y = \emptyset$. It is, however, true in the category of vector spaces over a field.


text:
# InterPore2018 New Orleans

14-17 May 2018
New Orleans
US/Central timezone

## Experimental and simulation research on the influence of temperature on the porous and thermal properties of sandstone

16 May 2018, 18:30
15m
New Orleans

#### New Orleans

Poster MS 1.24: Pore structure characterization and micro-scale effect on fluid flow in unconventional reservoir

### Speaker

Ms Haiyuan Yang (China University of Petroleum (East China))

### Description

In the process of thermal recovery and the underground storage of nuclear waste, the porosity and permeability of rock will change significantly from thermal stress. In this paper, a sandstone sample was subjected to heating, porosity examination, permeability measurements and CT scanning. Based on digital core technology, permeability and thermal conduction simulations were performed. The results show that due to the discontinuity character of thermal cracking, as the temperature increases, the permeability of sandstone increases with fluctuations, resulting in a final value that is higher than the initial value. The permeability of the pore network model is fit to the experimental permeability, whereas the fractal model exhibits a closed relationship with the pore throat diameter. The thermal conductivity simulation shows that due to the porosity’s changing with the temperature, the thermal conductivity coefficient exhibits an opposite fluctuating change.


text:
# American Institute of Mathematical Sciences

October  2001, 7(4): 781-786. doi: 10.3934/dcds.2001.7.781

## Topological sequence entropy of $\omega$–limit sets of interval maps

 1 Department of Applied Mathematics and Statistics, Technical University of Cartagena, Cartagena (Murcia), Spain

Received  November 2000 Revised  April 2001 Published  July 2001

Let $S$ be an increasing sequence of positive integers and let $\omega$ be an $\omega$–limit set of a continuous interval map $f$. We prove that $h_S(f|\omega) = 0$ if $h(f) = 0$, where $h_S(f)$ denotes the topological sequence entropy of $f$.
Citation: José S. Cánovas. Topological sequence entropy of $\omega$–limit sets of interval maps. Discrete & Continuous Dynamical Systems - A, 2001, 7 (4) : 781-786. doi: 10.3934/dcds.2001.7.781
 [1] Ghassen Askri. Li-Yorke chaos for dendrite maps with zero topological entropy and ω-limit sets. Discrete & Continuous Dynamical Systems - A, 2017, 37 (6) : 2957-2976. doi: 10.3934/dcds.2017127 [2] Bruce Kitchens, Michał Misiurewicz. Omega-limit sets for spiral maps. Discrete & Continuous Dynamical Systems - A, 2010, 27 (2) : 787-798. doi: 10.3934/dcds.2010.27.787 [3] Silvére Gangloff, Alonso Herrera, Cristobal Rojas, Mathieu Sablik. Computability of topological entropy: From general systems to transformations on Cantor sets and the interval. Discrete & Continuous Dynamical Systems - A, 2020, 40 (7) : 4259-4286. doi: 10.3934/dcds.2020180 [4] Jakub Šotola. Relationship between Li-Yorke chaos and positive topological sequence entropy in nonautonomous dynamical systems. Discrete & Continuous Dynamical Systems - A, 2018, 38 (10) : 5119-5128. doi: 10.3934/dcds.2018225 [5] José Ginés Espín Buendía, Víctor Jiménez Lopéz. A topological characterization of the $\omega$-limit sets of analytic vector fields on open subsets of the sphere. Discrete & Continuous Dynamical Systems - B, 2019, 24 (3) : 1143-1173. doi: 10.3934/dcdsb.2019010 [6] Carlos Arnoldo Morales, M. J. Pacifico. Lyapunov stability of $\omega$-limit sets. Discrete & Continuous Dynamical Systems - A, 2002, 8 (3) : 671-674. doi: 10.3934/dcds.2002.8.671 [7] Steven M. Pederson. Non-turning Poincaré map and homoclinic tangencies in interval maps with non-constant topological entropy. Conference Publications, 2001, 2001 (Special) : 295-302. doi: 10.3934/proc.2001.2001.295 [8] Christopher Cleveland. Rotation sets for unimodal maps of the interval. Discrete & Continuous Dynamical Systems - A, 2003, 9 (3) : 617-632. doi: 10.3934/dcds.2003.9.617 [9] Andrew D. Barwell, Chris Good, Piotr Oprocha, Brian E. Raines. Characterizations of $\omega$-limit sets in topologically hyperbolic systems. Discrete & Continuous Dynamical Systems - A, 2013, 33 (5) : 1819-1833. doi: 10.3934/dcds.2013.33.1819 [10] Hongyong Cui, Peter E. Kloeden, Meihua Yang. Forward omega limit sets of nonautonomous dynamical systems. Discrete & Continuous Dynamical Systems - S, 2020, 13 (4) : 1103-1114. doi: 10.3934/dcdss.2020065 [11] Boris Hasselblatt, Zbigniew Nitecki, James Propp. Topological entropy for nonuniformly continuous maps. Discrete & Continuous Dynamical Systems - A, 2008, 22 (1&2) : 201-213. doi: 10.3934/dcds.2008.22.201 [12] Xueting Tian, Paulo Varandas. Topological entropy of level sets of empirical measures for non-uniformly expanding maps. Discrete & Continuous Dynamical Systems - A, 2017, 37 (10) : 5407-5431. doi: 10.3934/dcds.2017235 [13] Dongkui Ma, Min Wu. Topological pressure and topological entropy of a semigroup of maps. Discrete & Continuous Dynamical Systems - A, 2011, 31 (2) : 545-556. doi: 10.3934/dcds.2011.31.545 [14] Lidong Wang, Hui Wang, Guifeng Huang. Minimal sets and $\omega$-chaos in expansive systems with weak specification property. Discrete & Continuous Dynamical Systems - A, 2015, 35 (3) : 1231-1238. doi: 10.3934/dcds.2015.35.1231 [15] Yujun Ju, Dongkui Ma, Yupan Wang. Topological entropy of free semigroup actions for noncompact sets. Discrete & Continuous Dynamical Systems - A, 2019, 39 (2) : 995-1017. doi: 10.3934/dcds.2019041 [16] Dante Carrasco-Olivera, Roger Metzger Alvan, Carlos Arnoldo Morales Rojas. Topological entropy for set-valued maps. Discrete & Continuous Dynamical Systems - B, 2015, 20 (10) : 3461-3474. doi: 10.3934/dcdsb.2015.20.3461 [17] Jérôme Buzzi, Sylvie Ruette. Large entropy implies existence of a maximal entropy measure for interval maps. Discrete & Continuous Dynamical Systems - A, 2006, 14 (4) : 673-688. doi: 10.3934/dcds.2006.14.673 [18] Alejo Barrio Blaya, Víctor Jiménez López. On the relations between positive Lyapunov exponents, positive entropy, and sensitivity for interval maps. Discrete & Continuous Dynamical Systems - A, 2012, 32 (2) : 433-466. doi: 10.3934/dcds.2012.32.433 [19] José M. Amigó, Ángel Giménez. Formulas for the topological entropy of multimodal maps based on min-max symbols. Discrete & Continuous Dynamical Systems - B, 2015, 20 (10) : 3415-3434. doi: 10.3934/dcdsb.2015.20.3415 [20] Jaroslav Smítal, Marta Štefánková. Omega-chaos almost everywhere. Discrete & Continuous Dynamical Systems - A, 2003, 9 (5) : 1323-1327. doi: 10.3934/dcds.2003.9.1323

2019 Impact Factor: 1.338


text:
# shape and structure of organic compounds

Functional groups are atoms or small groups of atoms (two to four) that exhibit a characteristic reactivity. Therefore ball-and-stick models correspond better to the behavior of actual molecules if the connectors representing single bonds are made to be rather stiff. We previously surveyed organic chemistry by dividing its compounds into families based on functional groups. Thus Table 2-1 shows that single $$C-C$$ bonds become progressively shorter as the number of multiple bonds or electronegative atoms attached to the carbons increases. It’s easier than it looks. The flat representations shown do not accurately portray bond angles or molecular geometry. We also acknowledge previous National Science Foundation support under grant numbers 1246120, 1525057, and 1413739. To identify and name simple (straight-chain) alkanes given formulas and write formulas for straight-chain alkanes given their names. An ordinary solid line indicates a bond in the plane of the page. #1 | Shapes & Structure of Organic Compounds (Chemistry) > Organic Chemistry - Some Basic Principles And Techniques. Organic chemistry is the chemistry of compounds of carbon. Any family of compounds in which adjacent members differ from each other by a definite factor (here a CH2 group) is called a homologous series. My Notes . The LCC has eight carbon atoms, so the parent compound is octane (rule 1). For more information contact us at info@libretexts.org or check out our status page at https://status.libretexts.org. The vital force theory began to decline in 1828, when the German chemist Friedrich Wöhler synthesized urea from inorganic starting materials. The Lewis structure is considered to be one of the most popular ways to depict the structure of an organic compound. The rules enable us to not only name a compound from a given structure but also draw a structure from a given name. Watch Next Video. For example, the CH3 group derived from methane (CH4) results from subtracting one hydrogen atom and is called a methyl group. Shapes of and Bond Angles in Simple Organic Compounds A. Miller Slideshare uses cookies to improve functionality and performance, and to provide you with relevant advertising. These rules, used worldwide, are known as the IUPAC System of Nomenclature. Although molecular models cannot represent the subtle variations in bond lengths and bond angles that actual molecules exhibit, most kinds of commercially available molecular models do attempt to reproduce relative bond lengths with some degree of reality. In the ball-and-stick type, the sticks usually come in various lengths to simulate different kinds of bonds; $$C-H$$ bonds typically are scaled to represent $$1.1 \: \text{A}$$, $$C-C$$ bonds to be $$1.54 \: \text{A}$$, and $$C=C$$ and $$C \equiv C$$ to be correspondingly shorter. Watch the recordings here on Youtube! By this we mean that, Figure 2-3: CPK space-filling models of organic compounds. For now, we will consider only those substituents called alkyl groups. Methane (CH4), ethane (C2H6), and propane (C3H8) are the beginning of a series of compounds in which any two members in a sequence differ by one carbon atom and two hydrogen atoms—namely, a CH2 unit. Legal. For example, we can represent pentane (CH3CH2CH2CH2CH3) and isopentane [(CH3)2CHCH2CH3] as follows: Parentheses in condensed structural formulas indicate that the enclosed grouping of atoms is attached to the adjacent carbon atom. Whereas methane, $$CH_4$$, is tetrahedral, ethene, $$C_2H_4$$, is not. Ethyne, $$C_2H_2$$, has been established experimentally to be a linear molecule; that is, the $$H-C-C$$ bond angle is $$180^\text{o}$$: This geometry also results with ball-and-stick models, if the triple bond is constructed of three flexible couplings or bent sticks as shown in Figure 2-2. If you continue browsing the site, you agree to the use of cookies on this website. If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices. Completing the CAPTCHA proves you are a human and gives you temporary access to the web property. In this chapter, we make a brief yet systematic study of some of organic compound families. Then add the groups at their proper positions. Motions of this kind are demonstrated easily with ball-and-stick models, but are not at all obvious with the space-filling type. For many purposes, ball-and-stick models of organic compounds give useful information about the spatial relationships of the atoms, and for $$CX_4$$ the angles between sticks are set at $$109.5^\text{o}$$ (Figure 2-1). $AgOCN + NH_4Cl \rightarrow AgCl + NH_4OCN \label{Eq1}$. Unless otherwise noted, LibreTexts content is licensed by CC BY-NC-SA 3.0. (Some of the names we used earlier, such as isobutane, isopentane, and neopentane, do not follow these rules and are called common names.) The condensed formulas show hydrogen atoms right next to the carbon atoms to which they are attached, as illustrated for butane: The ultimate condensed formula is a line-angle formula, in which carbon atoms are implied at the corners and ends of lines, and each carbon atom is understood to be attached to enough hydrogen atoms to give each carbon atom four bonds.

Romans 6:5 Meaning, Uncle Bens Egg Fried Rice, Importance Of Traditional Farming, Bulk Acetone Near Me, List Of Pregnancy Safe Skin Care Products, John Austin Theory Of Law, Daniel Smith Moonglow, Sardine Can Menu Vallejo Ca, System Architecture Software, Sweet Meat Jun Sauce Recipe, Marketing Management Course, Electric Supercar Top Gear, Neotame Brand Name, Madonna On Feminism, Impacts Of Importing Food, Sweet Potato Egg Sandwich Korean, Where Can I Test An Allswell Mattress, 1 John 3:20, Andouille Sausage Ingredients, Fanta Green Apple 2 Liter, Lychee Tree Indoors, Architect Fee Proposal Australia, Beethoven String Quartet Op 18 No 3 Analysis, How To Remove Rust From Carbon Steel, Who Makes Yedi Pressure Cooker, Royal Albert China, Golden Sparrow Meaning, Superdari Application Format, Gotham Steel 11 Frying Pan 2 Pack Set, Nestlé Cocoa Plan Annual Report,


text:
## \savebox

\sbox{cmd}{text}
\savebox{cmd}[width][pos]{text}

These commands typeset text in a box just as for \mbox or \makebox. However, instead of printing the resulting box, they save it in the LaTeX command cmd, which must have been declared with \newsavebox. The saved text is accessed by a \usebox command.

The \sbox and \savebox commands are declarations with the usual rules for scope.

The \sbox command is robust; the \savebox command is fragile.

See Spaces and Boxes
See \newsavebox, \usebox