Archive for category Code samples

Count number of occurrences of distinct values using LINQ

C# code snippet below finds distinct (case-insensitive) strings in a collection and counts number of occurrences of each unique (case-insensitive again) one.

static void Main(string[] args)
        {

            string[] sa = { "ala", "ma", "ala", "ma", "ma", "abc" };

            var res = from uniqueString
                in sa.Distinct(StringComparer.CurrentCultureIgnoreCase).ToList()
                      select new { str = uniqueString, occur = sa.Count(s => s.ToLower().Equals(uniqueString.ToLower())) };


            foreach(var el in res){
                Console.Write(el.GetType().GetProperty("str").GetValue(el, null) +  "\t");
                Console.WriteLine(el.GetType().GetProperty("occur").GetValue(el, null));
            }

            Console.ReadLine();
        }
Advertisements

,

1 Comment

Blender: Script for exporting models to xml

Python script shown below exports models from Blender 2.44 (but it should work with other versions too) to XML file. the structure of output XML file is something like this:

<objects>
	<object name="Cube">
		<vertices count="18">
			<v>
				<c>
					<x>-0.164879</x><y>0.242091</y><z>-5.895331</z>
				</c>
				<n>
					<x>0.577349</x><y>0.577349</y><z>-0.577349</z>
				</n>
			</v>
			<v>
				<c>
					<x>-0.164879</x><y>-0.524807</y><z>-5.895331</z>
				</c>
				<n>
					<x>0.577349</x><y>-0.577349</y><z>-0.577349</z>
				</n>
			</v>

The script itself is shown below. It can be easily modified in order to produce files of some other structure.

#!BPY

"""
Name: 'To-XML model exporter'
Blender: 244
Group: 'Export'
Tooltip: 'My to-XML model exporter'
"""
import Blender
from Blender import Window
import bpy


print "\n ======== To-XML model exporter ======== "

# just in case - leave edit mode
if Window.EditMode(): 
	print "Forcing to leave edit mode"
	Window.EditMode(0)

# create XML structure
xmlString = "<objects>"

# for each object in the scene
for ob in bpy.data.scenes.active.objects:

	# if this is a mesh
	if ob.type == "Mesh":
		xmlString += "\n\t<object name=\"" + ob.name + "\">"
		
		mesh = ob.getData(mesh=1)
		xmlString += "\n\t\t<vertices count=\"" + ("%d" % (len(mesh.faces) * 3)) + "\">"
		
		allFacesWithNoUV = True
		allFacesWithUV = True
		
		# write down vericles in order how they should be rendered by opengl
		# i.e. if a particualr vertex appears in multiple faces, the vertes is written down multiple times
		for face in mesh.faces:  
			for i in range(0, len(face.v)):
				vertInFace = face.v[i]
				xmlString += "\n\t\t\t<v>"
				
				# write vertilce coords
				xmlString += "\n\t\t\t\t<c>"
				xmlString += "\n\t\t\t\t\t<x>" + ("%f" % mesh.verts[vertInFace.index].co.x) + "</x><y>" + ("%f" % mesh.verts[vertInFace.index].co.y) +"</y><z>" + ("%f" % mesh.verts[vertInFace.index].co.z) + "</z>"
				xmlString += "\n\t\t\t\t</c>"
				
				# write normals
				xmlString += "\n\t\t\t\t<n>"
				xmlString += "\n\t\t\t\t\t<x>" + ("%f" % mesh.verts[vertInFace.index].no.x) + "</x><y>" + ("%f" % mesh.verts[vertInFace.index].no.y) +"</y><z>" + ("%f" % mesh.verts[vertInFace.index].no.z) + "</z>"
				xmlString += "\n\t\t\t\t</n>"
				
				# write texture coords if any
				if hasattr(face, "uv"):
					allFacesWithNoUV &= False # there is a face with uv
					xmlString += "\n\t\t\t\t<uv>"
					xmlString += "\n\t\t\t\t\t<x>" + ("%f" % face.uv[i].x) + "</x><y>" + ("%f" % ( 1.0 - face.uv[i].y)) +"</y>"
					xmlString += "\n\t\t\t\t</uv>"
				else:
					allFacesWithUV &= False # there is a face with no uv
				
				xmlString += "\n\t\t\t</v>"
				
		if not allFacesWithUV and not allFacesWithNoUV:
			print "some faces in object " + ob.name + " are missing uv"
		if not allFacesWithUV:
			print "all faces in object " + ob.name + " are missing uv"
			
		xmlString += "\n\t\t</vertices>"
		xmlString += "\n\t</object>"

xmlString += "\n</objects>"
		
def write(filename):
	outputFile = open(filename, "w")
	outputFile.write(xmlString);
	outputFile.close()
	
Blender.Window.FileSelector(write, "Export")

print "\n ========      end of work      ======== "

, , ,

Leave a comment

Android: draw a number of bitmaps or drawables into a single drawable

In some cases, you might need to render a numer of bitmaps or drawables into a single drawable. For instance, swapping LayerDrawables of different sizes displayed on top of MapView, might render not as it is supposed to. Code snippet below shows how to render LayerDrawable into a single BitmapDrawable. It is a simplified piece of code and contains “magic numbers”, but anyway, this should show the idea:


public Drawable getPersonMapItemDrawable(Drawable drawable1, Drawable drawable2){

  Drawable[] layers = new Drawable[2];
  layers[0] = drawable1;
  layers[1] = drawable2;

  int resourceBitmapHeight = 136, resourceBitmapWidth = 153;

  float widthInInches = 0.9f;

  int widthInPixels = (int)(widthInInches * context.getResources().getDisplayMetrics().densityDpi);
  int heightInPixels = (int)(widthInPixels * resourceBitmapHeight / resourceBitmapWidth);

  int insetLeft = 10, insetTop = 10, insetRight = 10, insetBottom = 10;

  LayerDrawable layerDrawable = new LayerDrawable(layers);
  layerDrawable.setLayerInset(1, insetLeft, insetTop, insetRight, insetBottom);		
  
  Bitmap bitmap = Bitmap.createBitmap(widthInPixels, heightInPixels, Bitmap.Config.ARGB_8888);

  Canvas canvas = new Canvas(bitmap);
  layerDrawable.setBounds(0, 0, widthInPixels, heightInPixels);
  layerDrawable.draw(canvas);
		
  BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), bitmap);
  bitmapDrawable.setBounds(0, 0, widthInPixels, heightInPixels);
		
  return bitmapDrawable;
}

,

3 Comments