Fix problems with concave shapes in the TileSet editor

--- editor/plugins/tile_set_editor_plugin.cpp
+++ editor/plugins/tile_set_editor_plugin.cpp
@@ -1794,13 +1794,13 @@
 			Array sd = tileset->call("tile_get_shapes", get_current_tile());

 			if (convex.is_valid()) {
-				// Make concave
+				// Make concave.
 				undo_redo->create_action(TTR("Make Polygon Concave"));
 				Ref<ConcavePolygonShape2D> _concave = memnew(ConcavePolygonShape2D);
 				edited_collision_shape = _concave;
 				_set_edited_shape_points(_get_collision_shape_points(convex));
 			} else if (concave.is_valid()) {
-				// Make convex
+				// Make convex.
 				undo_redo->create_action(TTR("Make Polygon Convex"));
 				Ref<ConvexPolygonShape2D> _convex = memnew(ConvexPolygonShape2D);
 				edited_collision_shape = _convex;
@@ -1810,14 +1810,20 @@
 				if (sd[i].get("shape") == previous_shape) {
 					undo_redo->add_undo_method(tileset.ptr(), "tile_set_shapes", get_current_tile(), sd.duplicate());
 					sd.remove(i);
-					sd.insert(i, edited_collision_shape);
-					undo_redo->add_do_method(tileset.ptr(), "tile_set_shapes", get_current_tile(), sd);
-					undo_redo->add_do_method(this, "_select_edited_shape_coord");
-					undo_redo->add_undo_method(this, "_select_edited_shape_coord");
-					undo_redo->commit_action();
 					break;
 				}
 			}
+
+			undo_redo->add_do_method(tileset.ptr(), "tile_set_shapes", get_current_tile(), sd);
+			if (tileset->tile_get_tile_mode(get_current_tile()) == TileSet::AUTO_TILE || tileset->tile_get_tile_mode(get_current_tile()) == TileSet::ATLAS_TILE) {
+				undo_redo->add_do_method(tileset.ptr(), "tile_add_shape", get_current_tile(), edited_collision_shape, Transform2D(), false, edited_shape_coord);
+			} else {
+				undo_redo->add_do_method(tileset.ptr(), "tile_add_shape", get_current_tile(), edited_collision_shape, Transform2D());
+			}
+			undo_redo->add_do_method(this, "_select_edited_shape_coord");
+			undo_redo->add_undo_method(this, "_select_edited_shape_coord");
+			undo_redo->commit_action();
+
 			_update_toggle_shape_button();
 			workspace->update();
 			workspace_container->update();
@@ -1984,11 +1990,8 @@
 		}
 		segments.push_back(points[points.size() - 1]);
 		segments.push_back(points[0]);
-		concave->set_segments(segments);
 		undo_redo->add_do_method(concave.ptr(), "set_segments", segments);
 		undo_redo->add_undo_method(concave.ptr(), "set_segments", concave->get_segments());
-	} else {
-		// Invalid shape
 	}
 }


Remove the unneeded namespaces

Remove the unneeded namespaces

--- engine/platform/corevideo/DisplayLink.hpp
+++ engine/platform/corevideo/DisplayLink.hpp
@@ -15,7 +15,7 @@
         explicit DisplayLink(CGDirectDisplayID displayId)
         {
             if (const auto result = CVDisplayLinkCreateWithCGDisplay(displayId, &displayLink); result != kCVReturnSuccess)
-                throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to create display link");
+                throw std::system_error(result, getErrorCategory(), "Failed to create display link");
         }

         ~DisplayLink()
@@ -56,21 +56,21 @@
         void setCallback(CVDisplayLinkOutputCallback callback, void* userInfo)
         {
             if (const auto result = CVDisplayLinkSetOutputCallback(displayLink, callback, userInfo); result != kCVReturnSuccess)
-                throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to set output callback for the display link");
+                throw std::system_error(result, getErrorCategory(), "Failed to set output callback for the display link");
         }

         void start()
         {
             if (displayLink)
                 if (const auto result = CVDisplayLinkStart(displayLink); result != kCVReturnSuccess)
-                    throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to start display link");
+                    throw std::system_error(result, getErrorCategory(), "Failed to start display link");
         }

         void stop()
         {
             if (displayLink)
                 if (const auto result = CVDisplayLinkStop(displayLink); result != kCVReturnSuccess)
-                    throw std::system_error(result, platform::corevideo::getErrorCategory(), "Failed to stop display link");
+                    throw std::system_error(result, getErrorCategory(), "Failed to stop display link");
         }

     private:


better detection of printable strings

better detection of printable strings

--- Console.cpp
+++ Console.cpp
@@ -269,9 +269,15 @@
 			return;
 		case llvm::Type::PointerTyID: {
 			void *p = GVTOP(GV);
-			if (p && QT->isPointerType() &&
-			    QT->getAsPointerType()->getPointeeType()->isCharType() &&
-			    shouldPrintCString((const char *) p)) {
+			bool couldBeString = false;
+			if (const clang::PointerType *PT = QT->getAsPointerType()) {
+				couldBeString = PT->getPointeeType()->isCharType();
+			} else if (QT->isArrayType()) {
+				if (const clang::ArrayType *AT = dyn_cast<clang::ArrayType>(QT)) {
+					couldBeString = AT->getElementType()->isCharType();
+				}
+			}
+			if (p && couldBeString && shouldPrintCString((const char *) p)) {
 				oprintf(_out, "=> (%s) \"%s\"\n", type, p);
 			} else if (QT->isFunctionType()) {
 				string str = "*";


Cache dlsym() lookups for bridged Functor objects.

--- Execute.cpp
+++ Execute.cpp
@@ -257,6 +257,10 @@
     return JSObjectMake(context, Struct_, internal);
 }

+static void *CYCastSymbol(const char *name) {
+    return dlsym(RTLD_DEFAULT, name);
+}
+
 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
     return JSValueMakeBoolean(context, value);
 }
@@ -493,21 +497,24 @@
     return JSObjectMake(context, Pointer_, internal);
 }

-static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type, void **cache = NULL) {
+static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
+    return JSObjectMake(context, Functor_, new cy::Functor(type, function));
+}
+
+static JSObjectRef CYMakeFunctor(JSContextRef context, const char *symbol, const char *type, void **cache) {
     cy::Functor *internal;
-
-    if (cache != NULL && *cache != NULL) {
+    if (*cache != NULL)
         internal = reinterpret_cast<cy::Functor *>(*cache);
-        ++internal->count_;
-    } else {
+    else {
+        void (*function)()(reinterpret_cast<void (*)()>(CYCastSymbol(symbol)));
+        if (function == NULL)
+            return NULL;
+
         internal = new cy::Functor(type, function);
-
-        if (cache != NULL) {
-            *cache = internal;
-            ++internal->count_;
-        }
-    }
-
+        *cache = internal;
+    }
+
+    ++internal->count_;
     return JSObjectMake(context, Functor_, internal);
 }

@@ -965,10 +972,6 @@
     return JSObjectMake(context, Type_privateData::Class_, internal);
 }

-static void *CYCastSymbol(const char *name) {
-    return dlsym(RTLD_DEFAULT, name);
-}
-
 static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
     JSObjectRef global(CYGetGlobalObject(context));
     JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
@@ -998,9 +1001,7 @@
                     return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);

                 case '1':
-                    if (void (*symbol)() = reinterpret_cast<void (*)()>(CYCastSymbol(name.data)))
-                        return CYMakeFunctor(context, symbol, entry->value_, &entry->cache_);
-                    else return NULL;
+                    return CYMakeFunctor(context, name.data, entry->value_, &entry->cache_);

                 case '2':
                     if (void *symbol = CYCastSymbol(name.data)) {


BESDebug modifications, passing context to BESDEBUG and registering debug context in Module classes.

M    FFModule.cc

--- FFModule.cc
+++ FFModule.cc
@@ -47,38 +47,41 @@
 void
 FFModule::initialize( const string &modname )
 {
-    BESDEBUG( "Initializing FF module " << modname << endl )
+    BESDEBUG( "ff", "Initializing FF module " << modname << endl )

-    BESDEBUG( "    adding " << modname << " request handler" << endl )
+    BESDEBUG( "ff", "    adding " << modname << " request handler" << endl )
     BESRequestHandler *handler = new FFRequestHandler( modname ) ;
     BESRequestHandlerList::TheList()->add_handler( modname, handler ) ;

-    BESDEBUG( "    adding " << FF_CATALOG << " catalog" << endl )
+    BESDEBUG( "ff", "    adding " << FF_CATALOG << " catalog" << endl )
     BESCatalogList::TheCatalogList()->add_catalog( new BESCatalogDirectory( FF_CATALOG ) ) ;

-    BESDEBUG( "    adding catalog container storage" << FF_CATALOG << endl )
+    BESDEBUG( "ff", "    adding catalog container storage" << FF_CATALOG << endl )
     BESContainerStorageCatalog *csc = new BESContainerStorageCatalog( FF_CATALOG ) ;
     BESContainerStorageList::TheList()->add_persistence( csc ) ;

-    BESDEBUG( "Done Initializing FF module " << modname << endl )
+    BESDEBUG( "ff", "    adding ff debug context" << endl )
+    BESDebug::Register( "ff" ) ;
+
+    BESDEBUG( "ff", "Done Initializing FF module " << modname << endl )
 }

 void
 FFModule::terminate( const string &modname )
 {
-    BESDEBUG( "Cleaning FF module " << modname << endl )
+    BESDEBUG( "ff", "Cleaning FF module " << modname << endl )

-    BESDEBUG( "    removing FF Handler" << modname << endl )
+    BESDEBUG( "ff", "    removing FF Handler" << modname << endl )
     BESRequestHandler *rh = BESRequestHandlerList::TheList()->remove_handler( modname ) ;
     if( rh ) delete rh ;

-    BESDEBUG( "    removing catalog container storage" << FF_CATALOG << endl )
+    BESDEBUG( "ff", "    removing catalog container storage" << FF_CATALOG << endl )
     BESContainerStorageList::TheList()->del_persistence( FF_CATALOG ) ;

-    BESDEBUG( "    removing " << FF_CATALOG << " catalog" << endl )
+    BESDEBUG( "ff", "    removing " << FF_CATALOG << " catalog" << endl )
     BESCatalogList::TheCatalogList()->del_catalog( FF_CATALOG ) ;

-    BESDEBUG( "Done Cleaning FF module " << modname << endl )
+    BESDEBUG( "ff", "Done Cleaning FF module " << modname << endl )
 }

 /** @brief dumps information about this object


Adding a flag to remove the wierd AR sort order inversion

--- GeneNet.cpp
+++ GeneNet.cpp
@@ -28,6 +28,7 @@

 bool HAS_TO_HAVE_MAJORITY = false;
 bool CPP_USE_HARSHER_BOUNDS = false;
+bool KEEP_SORT_ORDER_INVERTED = true;

 extern bool InvertSortOrder;

@@ -64,12 +65,13 @@
         _T("-id [num] --influenceLevelDelta [num]	Sets how close CMP parents must be in score to be considered for combination.  Default 0.01\n")
         _T("-rd [num] --relaxIPDelta [num]		Sets how fast the bound is relaxed for a and r if no parents are found in InitialParents, Default 0.025\n")
 		_T("--sip_letNThrough [num]			Sets minimum number of parents to allow through in SelectInitialParents. Default 1\n")
-
 		_T("--cpp_harshenBoundsOnTie		Determins if harsher bounds are used when parents tie in CPP.\n")
+
+		_T("--cpp_cmp_output_donotInvertSortOrder	Sets the inverted sort order in the 3 places back to normal")
+		_T("--cpp_seedParents				Determins if parents should be ranked by score, not tsd order in CPP.\n")
+		_T("--cpp_score_mustNotWinMajority	Determins if score should be used when following conditions are not met a > r+n || r > a + n\n")
+		_T("--score_donotTossSingleRatioParents		Determins if single ratio parents should be kept\n")
 		_T("--output_donotRescoreARParents	Determins if AR parents should not be rescored.\n")
-		_T("--cpp_seedParents				Determins if parents should be ranked by score, not tsd order in CPP.\n")
-		_T("--score_donotTossSingleRatioParents		Determins if single ratio parents should be kept\n")
-		_T("--cpp_score_mustNotWinMajority	Determins if score should be used when following conditions are not met a > r+n || r > a + n\n")
 		_T("--output_donotTossChangedInfluenceSingleParents	Determins if parents that change influence should not be tossed\n")
         );
 }
@@ -105,13 +107,14 @@
     { 14,        _T("-rd"),						SO_REQ_SEP },
     { 15,        _T("--relaxIPDelta"),			SO_REQ_SEP },
     { 16,        _T("--sip_letNThrough"),		SO_REQ_SEP },
-
     { 17,        _T("--cpp_harshenBoundsOnTie"),	SO_NONE },
-    { 18,        _T("--output_donotRescoreARParents"),	SO_NONE },
+
+    { 18,        _T("--cpp_cmp_output_donotInvertSortOrder"),		SO_NONE },
     { 19,        _T("--cpp_seedParents"),		SO_NONE },
-    { 20,        _T("--score_donotTossSingleRatioParents"),	SO_NONE },
-    { 21,        _T("--cpp_score_mustNotWinMajority"),	SO_NONE },
-    { 22,        _T("--output_donotTossChangedInfluenceSingleParents"),	SO_NONE },
+    { 20,        _T("--cpp_score_mustNotWinMajority"),	SO_NONE },
+    { 21,        _T("--score_donotTossSingleRatioParents"),	SO_NONE },
+    { 22,        _T("--output_donotRescoreARParents"),	SO_NONE },
+    { 23,        _T("--output_donotTossChangedInfluenceSingleParents"),	SO_NONE },
     SO_END_OF_OPTIONS
 };

@@ -283,6 +286,10 @@
             case 17:
             	CPP_USE_HARSHER_BOUNDS = true;
             	cout << "\tSetting CPP to use harsher bounds\n";
+            	break;
+            case 18:
+            	KEEP_SORT_ORDER_INVERTED = false;
+            	cout << "\tSetting sort order to not be inverted for AR\n";
             	break;
             default:
             	cout << "ERROR: unhandled argument\n";
@@ -823,7 +830,7 @@
 				cout << "Checking if set " << currentWorking << " is better than the subsets\n";
 			}
 			//Bug introduction to match perls
-			if(currentWorking.size()>1){
+			if(currentWorking.size() == 2 && KEEP_SORT_ORDER_INVERTED){
 			  	if(currentWorking.getIndividualScore(currentWorking.get(0)->getGeneUID()) > 0 && currentWorking.getIndividualScore(currentWorking.get(1)->getGeneUID()) < 0){
 				  InvertSortOrder = true;
 			  	}
@@ -941,7 +948,7 @@
 			if(q->size()>1){
 				float a = q->getIndividualScore(q->get(0)->getGeneUID());
 				float b = q->getIndividualScore(q->get(1)->getGeneUID());
-			  	if( (a > 0 && b < 0) || (a < 0 && b > 0)){
+			  	if( (a > 0 && b < 0) || (a < 0 && b > 0) && KEEP_SORT_ORDER_INVERTED){
 				  InvertSortOrder = true;
 			  	}
 			}
@@ -1055,7 +1062,7 @@
 			if (p->size() > 1){
 				mpa = p->getIndividualScore(p->get(0)->getGeneUID());
 				mpb = p->getIndividualScore(p->get(1)->getGeneUID());
-				if((mpa > 0 && mpb < 0) || (mpa < 0 && mpb > 0) ){
+				if((mpa > 0 && mpb < 0) || (mpa < 0 && mpb > 0) && KEEP_SORT_ORDER_INVERTED){
 					InvertSortOrder = true;
 					cout << "Tring to get a different score than " << pScore << " with " << *s << " " << *p << "\n";
 	  				pScore = ScoreBetter(*s,*p,*s->toSet(),E,T,L);


Updated and cleaned up

Updated and cleaned up

--- m4mudex.cc
+++ m4mudex.cc
@@ -5,9 +5,11 @@
  * This sample program only works for media files that stay within 32-bit box/file sizes.
  * If the file is larger than the 32-bit maximum, the following additions could be made:
  *
- * 1. Check for 64-bit boxes size encoding (atom size=1) and adjust according.
+ * TODO
+ * 1. Check for 64-bit boxes size encoding (atom size=1) and adjust accordingly.
  * 2. Find the co64 table instead of stco table, and modify those table entries.
  */
+
 #include "stdio.h"
 #include "stdint.h"
 #include "stdlib.h"
@@ -34,34 +36,30 @@
 const char *const containers_of_interest = "moov|udta|trak|mdia|minf|stbl";
 typedef struct atom_t {
     atom_t* parent;
-    union byte_addressable {
-        uint64_t word;
-        uint8_t bytes[8];
-    } len;
+    uint32_t len;
     char name[5];
-    uint64_t data_size;
-    int64_t data_remaining;
+    uint32_t data_size;
+    int32_t data_remaining;
     unsigned char* data;
-    bool container;
     std::vector<atom_t*> children;
+    bool active;
 } atom_t;

+
 /***
- * Find the next box (atom) in the provided m4a file
+ * Find the next box (atom) starting from the current
+ * position of the provided m4a file.
  *
  * Allocates memory for the atom if necessary, and returns
  * a new atom_t with information about the new atom.
  */
 atom_t* get_next_box(FILE* m4a_file) {
     atom_t *atom = (atom_t*)malloc(sizeof(atom_t));
-    int i;

-    /* Read in big-endian order */
-
-    //atom->len.word = 0;
-    //for(i = 3; i >= 0; i--) {
-    //    fread(&(atom->len.bytes[i]), 1, 1, m4a_file);
-    //}
+    /* Read size in big-endian order */
+    fread(&atom->len, 4, 1, m4a_file);
+    atom->active = true;
+    atom->len = htonl(atom->len);

     fread(atom->name, 1, 4, m4a_file);

@@ -70,15 +68,15 @@
      * the name.
      *
      * Also the header is effectively 16 bytes now. */
-    if(atom->len.word == 1) {
+    //if(atom->len == 1) {
         /* Read in big-endian order */
-        for(i = 7; i >= 0; i--) {
-            fread(&(atom->len.bytes[i]), 1, 1, m4a_file);
-        }
-        atom->data_size = atom->len.word - 16;
-    } else {
-        atom->data_size = atom->len.word - 8;
-    }
+    //    for(i = 7; i >= 0; i--) {
+    //        fread(&(atom->len.bytes[i]), 1, 1, m4a_file);
+    //    }
+    //    atom->data_size = atom->len.word - 16;
+    //} else {
+        atom->data_size = atom->len - 8;
+    //}

     /* Initialize the struct depending on whether
      * it's a container of interest or just a
@@ -106,66 +104,60 @@
 int find_meta(FILE *m4a_file) {
     const char* target = "meta";
     unsigned int tmp;
-    int i;
+    uint32_t i;
     for(i = 0; i < strlen(target); i++) {
         tmp <<= 8;
         tmp |= (unsigned char)target[i];
     }
     const unsigned int target_checksum = tmp; //Sum of characters in "meta"
-    int checksum = 0;
+    uint32_t checksum = 0;
     unsigned char c = 0;
     unsigned char buffer[8] = {0,0,0,0,0,0,0,0};
     int index = 0;
-    bool found = false;
     while(fread(&c, 1, 1, m4a_file) > 0) {
         index++;
         buffer[index & 7] = c;
         checksum <<= 8;
         checksum |= c;
         if(checksum == target_checksum) {
-            found = true;
-            for(i = strlen(target)-1; i >=0; i--) {
-                if(target[i] != buffer[(index+5+i) & 7]) {
-                    found = false;
-                    break;
-                }
-            }
-            if(found == true) {
-                printf("Found 'meta' at position %lu\n", index - strlen(target));
-                return index;
-            }
+            printf("Found 'meta' at position %lu\n", index - strlen(target));
+            return index;
         }
     }
     printf("found no meta box in all %d positions\n",index);
     return -1;
 }

-void print_tree_rec(atom_t* node, int level) {
-    int i;
+/* Print out the atom tree representation
+ * on stdout
+ */
+void print_tree_rec(atom_t* node, uint8_t level) {
+    uint8_t i;
     for(i=0; i<level; i++) {
         printf(".");
     }
-
     //skip root content, it's not *really* an atom
     if(node->parent != NULL) {
-        printf("%llu %s\n", node->len.word, node->name);
+        printf("%u %s\n", node->len, node->name);
     }
     for(i=0; i<node->children.size(); i++) {
-        print_tree_rec(node->children[i], level+1);
+        if(node->children[i]->active == true) {
+            print_tree_rec(node->children[i], level+1);
+        }
     }
 }
 void print_tree(atom_t* node) {
     print_tree_rec(node, 0);
 }

+//Write the atoms back out to file.
 void output_tree(atom_t* node, FILE *out_file) {
-    int i;
+    uint32_t i;

     //skip root content, it's not *really* an atom
     if(node->parent != NULL) {
-        for(i = 3; i >= 0; i--) {
-            fwrite(&node->len.bytes[i], 1, 1, out_file);
-        }
+        uint32_t out_len = htonl(node->len);
+        fwrite(&out_len, 4, 1, out_file);
         fwrite(node->name, 4, 1, out_file);
         if(node->data_size > 0 && node->data != NULL) {
             fwrite(node->data, node->data_size, 1, out_file);
@@ -173,12 +165,18 @@
     }

     for(i=0; i < node->children.size(); i++) {
-        output_tree(node->children[i], out_file);
-    }
-}
-
+        if(node->children[i]->active == true) {
+            output_tree(node->children[i], out_file);
+        }
+    }
+}
+
+//Given an atom that we expect to be a stco block,
+//and an offset_adjustment, fix the data portion of the
+//atom so that the offsets are reduced by the adjustment
+//amount
 void adjust_stco_offset(atom_t *stco, int offset_adjust) {
-    int i,j;
+    int i;
     //Offset past the version byte
     unsigned char* stco_data_ptr = (stco->data + 4);
     int stco_entries = htonl(*((uint32_t*)(stco_data_ptr)));
@@ -197,91 +195,74 @@
     }
 }

+//Strip meta boxes, returning the size of
+//meta tags before mdat boxes for later
+//adjustment.
+void strip_meta_box_rec(atom_t *node, bool do_accumulate, uint32_t &accumulator, atom_t **stco) {
+    uint32_t i;
+    if(strncmp(node->name, "mdat", 4) == 0) {
+        do_accumulate = false;
+    } else if(strncmp(node->name, "stco", 4) == 0) {
+        *stco = node;
+    } else if(do_accumulate && strncmp(node->name, "meta", 4) == 0) {
+        accumulator += node->len;
+        node->active = false;
+    }
+
+    for(i = 0; i < node->children.size(); i++) {
+        strip_meta_box_rec(node->children[i], do_accumulate, accumulator, stco);
+    }
+}
+void strip_meta_box(atom_t *node) {
+    uint32_t offset_adjust = 0;
+    atom_t* stco;
+    strip_meta_box_rec(node, true, offset_adjust, &stco);
+    adjust_stco_offset(stco, offset_adjust);
+}
+
+
+//Create a representation of the tree structure of the atoms
+//This function is called recursively. If an atom is marked as a
+//container, move through the data section of the atom sub-atom
+//at a time, otherwise just dump the whole data thing into a blob.
 atom_t* build_tree(FILE* m4a_file) {
-
-    bool visited_mdat = false;

     //Place to hold the current working atom.
     atom_t *atom;

     //Create an abstract root node to hold the top-level
     //atom list.
-    atom_t *root = (atom_t*)malloc(sizeof(atom_t));
-    root->parent == NULL;
-    root->data_remaining = -1;
+    atom_t *root = (atom_t*)calloc(sizeof(atom_t), 1);

     atom_t *current_parent = root;

-    atom_t *stco = NULL;
-
-    uint64_t chunk_offset_adjust = 0;
-
-    int level = 0;
-
     /* Loop through the rest of the atoms */
-    while((atom = get_next_box(m4a_file))->len.word > 0) {
-        int i;
+    while((atom = get_next_box(m4a_file))->len > 0) {
         //Set the parent of the newly created atom
         atom->parent = current_parent;

-        //Note whether or not we've visited the mdat box
-        //So that we know if stco offsets must be
-        //adjusted later.
-        if(strncmp(atom->name, "mdat", 4) == 0) {
-            visited_mdat = true;
-        }
-
-        //If it's a meta box, don't add it to the
-        //current atom list, so it's removed from
-        //the internal tree structure. Also, iterate
-        //back up through the parent pointers adjusting
-        //box sizes to account for its removal.
-        if(strncmp(atom->name, "meta", 4) == 0) {
-            //reset the parent values
-            atom_t *cur = atom->parent;
-            while(cur != NULL) {
-                cur->len.word -= atom->len.word;
-                cur = cur->parent;
-            }
-            //update the chunk offset adjustment
-            //but only if this meta chunk is before
-            //the mdat box. If it's after,
-            //it won't change stco offsets relative
-            //to the file start.
-            if(visited_mdat == false) {
-                chunk_offset_adjust += atom->len.word;
-            }
-        } else {
-            current_parent->children.push_back(atom);
-        }
-
-        //If we have a chunk_offset_adjust and
-        //the current atom is stco,
-        //save it so we can adjust it at the end if necessary.
-        if(strncmp(atom->name, "stco", 4) == 0) {
-            stco = atom;
-        }
+        //Add new atom to the current parent list.
+        current_parent->children.push_back(atom);

         //Subtract size of current atom from
         //the data_remaining of the parent
-        //before the next step, which might reset the
-        //parent pointer to a new level.
+        //Note: this must occur before the next step
+        //which might change the level. Don't try to
+        //include it in the following step.
         if(current_parent != root) {
-            current_parent->data_remaining -= atom->len.word;
+            current_parent->data_remaining -= atom->len;
         }

         //If the atom has data_remaining set, then must have some children
         if(atom->data_remaining > 0) {
             current_parent = atom;
-            level++;
         }

         //Check if we have data remaining in the parent.
         //If not, if atom was the last one in the parent.
         //So, move back up one level
-        //Make sure we haven't overrun any expected sizes in
-        //parents further up
         if(current_parent != root) {
+            //Make sure we haven't overrun any expected sizes in the parent
             if(current_parent->data_remaining < 0) {
                 printf("Something wrong: child atom overruns the parent size.");
                 printf("Parent name is: %s\n",current_parent->name);
@@ -291,55 +272,55 @@
             //We're done getting the children of this parent, move back up.
             while (current_parent && current_parent->parent && current_parent->data_remaining == 0) {
                 current_parent = current_parent->parent;
-                level--;
             }
         }
     }

-    if(stco != NULL) {
-        adjust_stco_offset(stco, chunk_offset_adjust);
-    }
-
     return root;
 }

-
-
-
 int main(int argc, char** argv) {
-
     FILE *m4a_file;
-    char test[5] = "ftyp";
-    uint32_t *test_convert = (uint32_t*)test;
+    FILE *out_file;

+    //Check inputs, open file, check for success
     if(argc < 3) {
         printf("Usage: m4mudex <infilename> <outfilename>");
         exit(1);
     }
-
     m4a_file = fopen(argv[1], "rb");
-    printf("\nChecking to see if source file has a meta box: \n");
-    find_meta(m4a_file);
-    rewind(m4a_file);
-
-    printf("\n");
-
     if (m4a_file == NULL) {
         printf("Provide the name of an existing m4a file to parse\n");
         exit(1);
     }

+    //Quick sanity check on input file
+    printf("\nChecking to see if source file has a meta box: \n");
+    find_meta(m4a_file);
+    rewind(m4a_file);
+
+    //Build the tree
     atom_t* m4a_tree = build_tree(m4a_file);

-    printf("printing modified tree:\n");
+    //Show the tree
+    printf("printing original tree:\n");
     print_tree(m4a_tree);
     printf("\n");

-    FILE *out_file;
+    //Get rid of metas and adjust offsets
+    strip_meta_box(m4a_tree);
+
+    //Show the modified tree
+    printf("printing modifiedtree:\n");
+    print_tree(m4a_tree);
+    printf("\n");
+
+    //Write out the modified tree.
     out_file = fopen(argv[2], "wb");
     output_tree(m4a_tree, out_file);
     fclose(out_file);

+    //Verify the output file
     printf("\nVerifying that output file has no meta box: \n");
     out_file = fopen(argv[2], "rb");
     find_meta(out_file);


vim-mode: fix cursor position after changing from Insert to Normal mode

--- src/utils/vvim.cpp
+++ src/utils/vvim.cpp
@@ -2241,11 +2241,18 @@
     if (m_mode != p_mode) {
         QTextCursor cursor = m_editor->textCursorW();
         int position = p_position;
-        if (position == -1
-            && m_mode == VimMode::Visual
-            && p_mode == VimMode::Normal
-            && cursor.position() > cursor.anchor()) {
-            position = cursor.position() - 1;
+        if (position == -1) {
+            if (m_mode == VimMode::Visual
+                && p_mode == VimMode::Normal
+                && cursor.position() > cursor.anchor()) {
+                position = cursor.position() - 1;
+            } else if (m_mode == VimMode::Insert
+                       && p_mode == VimMode::Normal) {
+                position = cursor.position() - 1;
+                if (position < 0) {
+                    position = 0;
+                }
+            }
         }

         if (p_clearSelection) {


Fix uninitialized local variable.

Fix uninitialized local variable.

--- src/forces/center_force.cpp
+++ src/forces/center_force.cpp
@@ -10,7 +10,7 @@

 void CenterForce::beforeAll(std::vector<LabelState> &labels)
 {
-  Eigen::Vector2f anchorPositionSum;
+  Eigen::Vector2f anchorPositionSum(0, 0);
   for (auto &labelState : labels)
     anchorPositionSum += labelState.anchorPosition2D;


Header size in packet should be uint16_t so that it doesn't overflow.

git-svn-id: c3635bff6e270807241d5934e964f2d007b3d5d6@4513 a83610d8-ad2a-0410-a6ab-fc0612d85776

--- src/utp_stream.cpp
+++ src/utp_stream.cpp
@@ -121,7 +121,7 @@
 	ptime send_time; // the last time this packet was sent
 	boost::uint16_t size;
 	boost::uint8_t num_transmissions;
-	boost::uint8_t header_size;
+	boost::uint16_t header_size;

 	char buf[];
 };


logging granularity fixes

logging granularity fixes

git-svn-id: 4b20f32ac28c752316e0f948a8a743f4a1700c23@4635 a83610d8-ad2a-0410-a6ab-fc0612d85776

--- src/utp_stream.cpp
+++ src/utp_stream.cpp
@@ -2179,13 +2179,13 @@

 				UTP_LOG("[%08u] %8p: "
 					"actual_delay:%u "
-					"our_delay:%u "
-					"their_delay:%u "
-					"off_target:%d "
+					"our_delay:%f "
+					"their_delay:%f "
+					"off_target:%f "
 					"max_window:%d "
 					"upload_rate:%d "
 					"delay_base:%s "
-					"delay_sum:%d "
+					"delay_sum:%f "
 					"target_delay:%d "
 					"acked_bytes:%d "
 					"cur_window:%d "
@@ -2207,13 +2207,13 @@
 					"\n"
 					, int(total_microseconds(receive_time - min_time())), this
 					, sample
-					, int(delay / 1000)
-					, int(their_delay / 1000)
-					, int(m_sm->target_delay() - delay) / 1000
+					, float(delay / 1000.f)
+					, float(their_delay / 1000.f)
+					, float(m_sm->target_delay() - delay) / 1000.f
 					, int(m_cwnd >> 16)
 					, 0
 					, our_delay_base
-					, (delay + their_delay) / 1000
+					, float(delay + their_delay) / 1000.f
 					, m_sm->target_delay() / 1000
 					, acked_bytes
 					, m_bytes_in_flight


uTP timeout fix

uTP timeout fix

--- src/utp_stream.cpp
+++ src/utp_stream.cpp
@@ -2882,6 +2882,16 @@

 		m_cwnd = boost::int64_t(m_mtu) << 16;
 		if (m_outbuf.size()) ++m_num_timeouts;
+
+		if (m_num_timeouts > m_sm->num_resends())
+		{
+			// the connection is dead
+			m_error = asio::error::timed_out;
+			m_state = UTP_STATE_ERROR_WAIT;
+			test_socket_state();
+			return;
+		}
+
 		m_timeout = now + milliseconds(packet_timeout());

 		UTP_LOGV("%8p: timeout resetting cwnd:%d\n"


Enable pak enforcement at mempool/block level when appropriate

--- src/validation.cpp
+++ src/validation.cpp
@@ -607,6 +607,13 @@
     std::string reason;
     if (fRequireStandard && !IsStandardTx(tx, reason))
         return state.DoS(0, false, REJECT_NONSTANDARD, reason);
+
+    // And now do PAK checks. Filtered by next blocks' enforced list
+    if (chainparams.GetEnforcePak()) {
+        if (!IsPAKValidTx(tx, GetActivePAKList(chainActive.Tip(), chainparams.GetConsensus()))) {
+            return state.DoS(0, false, REJECT_NONSTANDARD, "invalid-pegout-proof");
+        }
+    }

     // Do not work on transactions that are too small.
     // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
@@ -2117,6 +2124,18 @@
     txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated

     // ELEMENTS:
+
+    // Enforce PAK post-dynafed
+    if (chainparams.GetEnforcePak() && !block.m_dyna_params.IsNull()) {
+        // GetActivePAKList computes for the following block, so use previous index
+        CPAKList paklist = GetActivePAKList(pindex->pprev, chainparams.GetConsensus());
+        for (const auto& tx : block.vtx) {
+            if (!IsPAKValidTx(*tx, paklist)) {
+                return state.DoS(100, error("ConnectBlock(): Bad PAK transaction"), REJECT_INVALID, "bad-pak-tx");
+            }
+        }
+    }
+
     // Used when ConnectBlock() results are unneeded for mempool ejection
     std::set<std::pair<uint256, COutPoint>> setPeginsSpentDummy;


Triangle splitter should work

Triangle splitter should work


expected version fix

expected version fix

--- src/validation.cpp
+++ src/validation.cpp
@@ -2228,7 +2228,9 @@
         for (int i = 0; i < 100 && pindex != NULL; i++)
         {
             int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
-            if (pindex->GetBaseVersion() > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
+            /* Myriadcoin: we only use the lowest 8 bits for BIP9, so we mask the chainid and algo (0x00FFFF00)*/
+            //if (pindex->GetBaseVersion() > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
+            if (pindex->GetBaseVersion() > VERSIONBITS_LAST_OLD_BLOCK_VERSION && ((pindex->nVersion & ~nExpectedVersion) & 0xFF0000FF) != 0)
                 ++nUpgraded;
             pindex = pindex->pprev;
         }


Fix 'mempool min fee not met' debug output

Output the value that is tested, rather than the unmodified fee value.

--- src/validation.cpp
+++ src/validation.cpp
@@ -712,7 +712,7 @@

         CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
         if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
-            return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
+            return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nModifiedFees, mempoolRejectFee));
         }

         // No transactions are allowed below minRelayTxFee except from disconnected blocks


compile

compile

Former-commit-id: 5de0f88edcebfd052a9af2cd501a1ec1939f6dc9

--- src/validation.cpp
+++ src/validation.cpp
@@ -4662,7 +4662,7 @@
         // SYSCOIN must flush for now because disconnect may remove asset data and rolling forward expects it to be clean from db
         if(passetdb != nullptr){
             if(!passetdb->Flush(mapAssets) || !pethereumtxmintdb->FlushErase(mapMintKeys) || !pblockindexdb->FlushErase(vecTXIDs)){
-                return error("RollbackBlock(): Error flushing to asset dbs on disconnect %s", pindex->GetBlockHash().ToString());
+                return error("VerifyDB(): Error flushing to asset dbs on disconnect %s", pindex->GetBlockHash().ToString());
             }
         }
         while (pindex != ::ChainActive().Tip()) {
@@ -5713,7 +5713,7 @@
     return WriteBatch(batch);
 }

-bool CBlockIndexDB::PruneIndex()) {
+bool CBlockIndexDB::PruneIndex() {
     AssertLockHeld(cs_main);
     if(MAX_BLOCK_INDEX > ::ChainActive().Height())
         return true;


hurl use addr info cache.

hurl use addr info cache.

--- src/hurl/hurl.cc
+++ src/hurl/hurl.cc
@@ -977,7 +977,7 @@

         // hlx settings
         l_hlx->set_collect_stats(true);
-        l_hlx->set_dns_use_ai_cache(false);
+        l_hlx->set_dns_use_ai_cache(true);
         l_hlx->set_dns_use_sync(true);
         l_hlx->set_num_threads(l_max_threads);
         l_hlx->set_num_parallel(l_start_parallel);


INTEGRATION: CWS sb59 (1.9.488); FILE MERGED 2006/08/03 13:47:04 cl 1.9.488.1: removed compiler warnings

--- svx/inc/imapdlg.hxx
+++ svx/inc/imapdlg.hxx
@@ -4,9 +4,9 @@
  *
  *  $RCSfile: imapdlg.hxx,v $
  *
- *  $Revision: 1.9 $
- *
- *  last change: $Author: rt $ $Date: 2005-09-08 17:56:14 $
+ *  $Revision: 1.10 $
+ *
+ *  last change: $Author: obo $ $Date: 2006-10-12 11:45:06 $
  *
  *  The Contents of this file are made available subject to
  *  the terms of GNU Lesser General Public License Version 2.1.
@@ -146,6 +146,7 @@
 {
     friend class IMapOwnData;
     friend class IMapWindow;
+    using Window::Update;

     ToolBox             aTbxIMapDlg1;
     FixedText           aFtURL;


INTEGRATION: CWS writercorehandoff (1.12.172); FILE MERGED 2005/12/20 15:00:15 tra 1.12.172.4: RESYNC: (1.14-1.15); FILE MERGED 2005/09/13 11:19:33 tra 1.12.172.3: RESYNC: (1.13-1.14); FILE MERGED 2005/07/11 06:08:27 tra 1.12.172.2: RESYNC: (1.12-1.13); FILE MERGED 2005/06/06 07:07:21 tra 1.12.172.1: Unnecessary includes removed #i50348#

--- sw/inc/dbgoutsw.hxx
+++ sw/inc/dbgoutsw.hxx
@@ -4,9 +4,9 @@
  *
  *  $RCSfile: dbgoutsw.hxx,v $
  *
- *  $Revision: 1.15 $
+ *  $Revision: 1.16 $
  *
- *  last change: $Author: rt $ $Date: 2005-11-08 17:11:44 $
+ *  last change: $Author: hr $ $Date: 2006-08-14 15:19:01 $
  *
  *  The Contents of this file are made available subject to
  *  the terms of GNU Lesser General Public License Version 2.1.
@@ -32,7 +32,6 @@
  *    MA  02111-1307  USA
  *
  ************************************************************************/
-
 #ifndef __DBGOUTSW_HXX
 #define __DBGOUTSW_HXX


Fix when editor ui hasn't been updating when resized

--- Source/Atomic/UI/UI.cpp
+++ Source/Atomic/UI/UI.cpp
@@ -194,6 +194,7 @@
     SubscribeToEvent(E_KEYUP, HANDLER(UI, HandleKeyUp));
     SubscribeToEvent(E_TEXTINPUT, HANDLER(UI, HandleTextInput));
     SubscribeToEvent(E_UPDATE, HANDLER(UI, HandleUpdate));
+    SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
     SubscribeToEvent(SystemUI::E_CONSOLECLOSED, HANDLER(UI, HandleConsoleClosed));

     SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));


Modify options of usage function.

Modify options of usage function.

--- src/ias/main.cpp
+++ src/ias/main.cpp
@@ -99,10 +99,11 @@
     std::cout << "Run as server: ias --server --config <path>" << std::endl;
     std::cout << "Run as controller: ias --controller --config <path>" << std::endl;
     std::cout << "Run as client: ias --client [options]" << std::endl;
-    std::cout << "Run as eventstream: ias --eventstream --key <API key>" << std::endl;
+    std::cout << "Run as eventstream: ias --eventstream --key <API key> [options]" << std::endl;
     std::cout << std::endl;
     std::cout << "Options:" << std::endl;
     std::cout << " --address [hostname]" << std::endl;
+    std::cout << " --ssl" << std::endl;
 }

 void initializeSsl( void ) {


more graphic editor stuff

more graphic editor stuff

it may crash, but next commit will fix it, i promise

--- src/ide/main.cpp
+++ src/ide/main.cpp
@@ -57,7 +57,7 @@
   int originX, originY;
   int subgraphics;
   bool background;
-  unsigned char** data;
+  std::vector<unsigned char*> data;
   int colmode;
   unsigned char** colmask;
 };
@@ -190,6 +190,9 @@
     if (mouseX<256 && mouseY>64) {
       cureditid=(mouseY-64)/20;
       curedittype=curview;
+      switch (curview) {
+        case 0: geditor->setdata(graphics[cureditid].data[0], graphics[cureditid].width, graphics[cureditid].height); break;
+      }
     }
   }
 }
@@ -204,6 +207,12 @@
       graphics[formersize].id=formersize;
       graphics[formersize].name="graphic";
       graphics[formersize].name+=std::to_string(formersize);
+      // create pre-defined graphic
+      graphics[formersize].subgraphics=1;
+      graphics[formersize].width=32;
+      graphics[formersize].height=32;
+      graphics[formersize].data.resize(1);
+      graphics[formersize].data[0]=new unsigned char[4096];
       break;
     case 1:
       formersize=sounds.size();


was/Output: call destructor

was/Output: call destructor

--- src/was/Output.cxx
+++ src/was/Output.cxx
@@ -80,19 +80,39 @@
         ScheduleWrite();
     }

+    void Destroy() noexcept {
+        this->~WasOutput();
+    }
+
+    void DestroyEof() noexcept {
+        auto &_handler = handler;
+        Destroy();
+        _handler.WasOutputEof();
+    }
+
+    void DestroyPremature(std::exception_ptr ep) noexcept {
+        const auto _sent = sent;
+        auto &_handler = handler;
+        Destroy();
+        _handler.WasOutputPremature(_sent, ep);
+    }
+
+    void DestroyError(std::exception_ptr ep) noexcept {
+        auto &_handler = handler;
+        Destroy();
+        _handler.WasOutputError(ep);
+    }
+
     void ScheduleWrite() {
         event.ScheduleWrite();
         timeout_event.Schedule(was_output_timeout);
     }

     void AbortError(std::exception_ptr ep) {
-        event.Cancel();
-        timeout_event.Cancel();
-
         if (input.IsDefined())
             input.ClearAndClose();

-        handler.WasOutputError(ep);
+        DestroyError(ep);
     }

     bool CheckLength();
@@ -177,7 +197,7 @@
         if (!known_length && !handler.WasOutputLength(sent))
             return false;

-        handler.WasOutputEof();
+        DestroyEof();
         return false;
     }

@@ -236,7 +256,7 @@
         if (!known_length && !handler.WasOutputLength(sent))
             return false;

-        handler.WasOutputEof();
+        DestroyEof();
         return false;
     }

@@ -302,7 +322,7 @@
     if (!known_length && !handler.WasOutputLength(sent))
         return;

-    handler.WasOutputEof();
+    DestroyEof();
 }

 void
@@ -311,10 +331,8 @@
     assert(input.IsDefined());

     input.Clear();
-    event.Cancel();
-    timeout_event.Cancel();
-
-    handler.WasOutputPremature(sent, ep);
+
+    DestroyPremature(ep);
 }

 /*
@@ -341,10 +359,9 @@
     if (output->input.IsDefined())
         output->input.ClearAndClose();

-    output->event.Cancel();
-    output->timeout_event.Cancel();
-
-    return output->sent;
+    const auto sent = output->sent;
+    output->Destroy();
+    return sent;
 }

 bool


Use vector_as_array() in unix_domain_socket_posix.cc

BUG=65151
TEST=None

Review URL: http://codereview.chromium.org/7216022

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@90049 0039d316-1c4b-4281-b951-d872f2087c98

--- content/common/unix_domain_socket_posix.cc
+++ content/common/unix_domain_socket_posix.cc
@@ -1,4 +1,4 @@
-// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Copyright (c) 2011 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.

@@ -12,6 +12,7 @@
 #include "base/eintr_wrapper.h"
 #include "base/logging.h"
 #include "base/pickle.h"
+#include "base/stl_util-inl.h"

 // static
 bool UnixDomainSocket::SendMsg(int fd,
@@ -94,7 +95,7 @@
   }

   fds->resize(wire_fds_len);
-  memcpy(&(*fds)[0], wire_fds, sizeof(int) * wire_fds_len);
+  memcpy(vector_as_array(fds), wire_fds, sizeof(int) * wire_fds_len);

   return r;
 }
@@ -143,4 +144,3 @@

   return reply_len;
 }
-


Get another instance of a FatalLog without allowing --force

--- shared/sprite.cpp
+++ shared/sprite.cpp
@@ -588,7 +588,9 @@
     }

     if (bigPalette.size() > 256 && !params.force)
-        FatalLog("Image after reducing sprites to 4bpp still contains more than 256 distinct colors. Found %d colors. Please fix.", bigPalette.size());
+        FatalLog("Image after reducing tiles to 4 bpp still contains more than 256 distinct colors. Found %d colors. Please fix. Use --force to override.", bigPalette.size());
+    else if (bigPalette.size() > 256 && params.force)
+        WarnLog("Image after reducing tiles to 4 bpp still contains more than 256 distinct colors. Found %d colors. Potential for image color quality loss.");

     // Greedy approach deal with tiles with largest palettes first.
     std::sort(sprites.begin(), sprites.end(), SpritePaletteSizeComp);


todo.

todo.

--- libdariadb/statistic.cpp
+++ libdariadb/statistic.cpp
@@ -24,6 +24,7 @@
 }

 void BaseMethod::call(const dariadb::Meas&m){
+	//TODO add check to m.Id. id must be one.
     if(_is_first){
         _last=m;
         _is_first=false;


fixed bug in referenceList

fixed bug in referenceList

--- src/ReferenceList.cpp
+++ src/ReferenceList.cpp
@@ -62,7 +62,7 @@
   vector<string> new_ids = {id};

   if (group.hasData(ds_name)) {
-    DataSet ds = group.openData("sources");
+    DataSet ds = group.openData(ds_name);
     PSize old_size = ds.size();
     PSize new_size = old_size + 1;
     ds.extend(new_size);


am 8fe7faed: Merge "Fix initiazation bug in teglSwapBuffersWithDamage.cpp"

* commit '8fe7faed268258f41a2c2e99e7a37329e38cf7b3':
  Fix initiazation bug in teglSwapBuffersWithDamage.cpp

--- modules/egl/teglSwapBuffersWithDamageTests.cpp
+++ modules/egl/teglSwapBuffersWithDamageTests.cpp
@@ -528,6 +528,9 @@

 	for (int iterationNdx = 0; iterationNdx < m_iterationTimes; iterationNdx++)
 	{
+		clearColorScreen(m_gl, clearColor);
+		EGLU_CHECK_CALL(egl, swapBuffersWithDamageKHR(m_eglDisplay, m_eglSurface, DE_NULL, 0));
+
 		for (int frameNdx = 0; frameNdx < numFrames; frameNdx++)
 		{
 			vector<EGLint>	damageRegion;


[GDNative] fixed issue with library unloading order

--- modules/gdnative/nativescript/nativescript.cpp
+++ modules/gdnative/nativescript/nativescript.cpp
@@ -881,6 +881,9 @@
 NativeScriptLanguage *NativeScriptLanguage::singleton;

 void NativeScriptLanguage::_unload_stuff(bool p_reload) {
+
+	Map<String, Ref<GDNative> > erase_and_unload;
+
 	for (Map<String, Map<StringName, NativeScriptDesc> >::Element *L = library_classes.front(); L; L = L->next()) {

 		String lib_path = L->key();
@@ -916,6 +919,40 @@
 			gdn = E->get();
 		}

+		for (Map<StringName, NativeScriptDesc>::Element *C = classes.front(); C; C = C->next()) {
+
+			// free property stuff first
+			for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = C->get().properties.front(); P; P = P.next()) {
+				if (P.get().getter.free_func)
+					P.get().getter.free_func(P.get().getter.method_data);
+
+				if (P.get().setter.free_func)
+					P.get().setter.free_func(P.get().setter.method_data);
+			}
+
+			// free method stuff
+			for (Map<StringName, NativeScriptDesc::Method>::Element *M = C->get().methods.front(); M; M = M->next()) {
+				if (M->get().method.free_func)
+					M->get().method.free_func(M->get().method.method_data);
+			}
+
+			// free constructor/destructor
+			if (C->get().create_func.free_func)
+				C->get().create_func.free_func(C->get().create_func.method_data);
+
+			if (C->get().destroy_func.free_func)
+				C->get().destroy_func.free_func(C->get().destroy_func.method_data);
+		}
+
+		erase_and_unload.insert(lib_path, gdn);
+	}
+
+	for (Map<String, Ref<GDNative> >::Element *E = erase_and_unload.front(); E; E = E->next()) {
+		String lib_path = E->key();
+		Ref<GDNative> gdn = E->get();
+
+		library_classes.erase(lib_path);
+
 		if (gdn.is_valid() && gdn->get_library().is_valid()) {
 			Ref<GDNativeLibrary> lib = gdn->get_library();
 			void *terminate_fn;
@@ -926,31 +963,6 @@

 				terminate((void *)&lib_path);
 			}
-		}
-
-		for (Map<StringName, NativeScriptDesc>::Element *C = classes.front(); C; C = C->next()) {
-
-			// free property stuff first
-			for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = C->get().properties.front(); P; P = P.next()) {
-				if (P.get().getter.free_func)
-					P.get().getter.free_func(P.get().getter.method_data);
-
-				if (P.get().setter.free_func)
-					P.get().setter.free_func(P.get().setter.method_data);
-			}
-
-			// free method stuff
-			for (Map<StringName, NativeScriptDesc::Method>::Element *M = C->get().methods.front(); M; M = M->next()) {
-				if (M->get().method.free_func)
-					M->get().method.free_func(M->get().method.method_data);
-			}
-
-			// free constructor/destructor
-			if (C->get().create_func.free_func)
-				C->get().create_func.free_func(C->get().create_func.method_data);
-
-			if (C->get().destroy_func.free_func)
-				C->get().destroy_func.free_func(C->get().destroy_func.method_data);
 		}
 	}
 }
@@ -1363,6 +1375,7 @@
 			MutexLock lock(NSL->mutex);
 #endif
 			NSL->_unload_stuff(true);
+
 			for (Map<String, Ref<GDNative> >::Element *L = NSL->library_gdnatives.front(); L; L = L->next()) {

 				Ref<GDNative> gdn = L->get();
@@ -1376,7 +1389,6 @@
 				}

 				gdn->terminate();
-				NSL->library_classes.erase(L->key());
 			}

 			unloaded = true;


move the constants to VoltDB scope for memcheck build

--- src/ee/common/Pool.hpp
+++ src/ee/common/Pool.hpp
@@ -27,6 +27,8 @@
 #include "common/FatalException.hpp"

 namespace voltdb {
+static const size_t TEMP_POOL_CHUNK_SIZE = 262144;
+
 #ifndef MEMCHECK
 /**
  * Description of a chunk of memory allocated on the heap
@@ -66,8 +68,6 @@
                 k = k | k >> i;
         return k+1;
 }
-
-static const size_t TEMP_POOL_CHUNK_SIZE = 262144;

 /**
  * A memory pool that provides fast allocation and deallocation. The


argc, argV

argc, argV

--- src/ish.cpp
+++ src/ish.cpp
@@ -1,2 +1,3 @@
-int main() {
+int main(int argc, char **argv) {
+  return 0;
 }


Style

Style

--- src/job.cpp
+++ src/job.cpp
@@ -25,8 +25,7 @@
 	if (index_major == images.size())
 		return {nullptr, nullptr};

-	auto index_minor_old = index_minor;
-	auto index_major_old = index_major;
+	auto result = ImagePair{images[index_minor], images[index_major]};

 	if (index_minor == index_major) {
 		index_major++;
@@ -35,7 +34,7 @@
 		index_minor++;
 	}

-	return {images[index_minor_old], images[index_major_old]};
+	return result;
 }

 float Job::get_progress() const {


Make `change::is_overriding()` `const noexcept`

--- src/join.cc
+++ src/join.cc
@@ -13,7 +13,9 @@
     join_c(const contents& contents)
         : y(contents.y)
         , x(contents.cont[y].size()) {}
-    virtual bool is_overriding() override { return true; }
+    virtual bool is_overriding() const noexcept override {
+        return true;
+    }
     virtual void undo(contents& contents) override {
         contents.cont.insert(contents.cont.begin() + y + 1,
                              contents.cont[y].substr(x));


making find recursive

making find recursive

--- mthread_find/win32find/win32find/win32find.cpp
+++ mthread_find/win32find/win32find/win32find.cpp
@@ -32,28 +32,28 @@

 void _search(wchar_t base_path[], wchar_t filename[])
 {
-	LPWIN32_FIND_DATA hFile = (LPWIN32_FIND_DATA) GlobalAlloc(GMEM_ZEROINIT, sizeof(WIN32_FIND_DATA));
-	HANDLE findResult = NULL;
+	LPWIN32_FIND_DATA hFile = (LPWIN32_FIND_DATA)GlobalAlloc(GMEM_ZEROINIT, sizeof(WIN32_FIND_DATA));
+	LPWIN32_FIND_DATA hDirectory = (LPWIN32_FIND_DATA) GlobalAlloc(GMEM_ZEROINIT, sizeof(WIN32_FIND_DATA));
+
+	HANDLE findFileResult = NULL;
+	HANDLE findDirectoryResult = NULL;

-	wchar_t combined_filename[MAX_PATH] = TEXT("");
+	wchar_t wildcard[MAX_PATH] = L"";

-	StringCchCat(combined_filename, MAX_PATH - FILENAME_MAX - 1, base_path);
-	StringCchCat(combined_filename, 1, TEXT("/"));
-	StringCchCat(combined_filename, FILENAME_MAX, filename);
-
-	findResult = FindFirstFile((LPCWSTR)combined_filename, hFile);
-
-	if (findResult == INVALID_HANDLE_VALUE)
+	size_t bp_sz = wcsnlen_s(base_path, MAX_PATH);
+
+	StringCchCat(wildcard, bp_sz + 1, base_path);
+	StringCchCat(wildcard, bp_sz + 2, L"*");
+
+	findDirectoryResult = FindFirstFile((LPCWSTR)wildcard, hDirectory);
+
+	if (findDirectoryResult == INVALID_HANDLE_VALUE)
 	{
 		DWORD dw_error_code = 0;

 		dw_error_code = GetLastError();

-		if (dw_error_code == ERROR_FILE_NOT_FOUND)
-		{
-			_tprintf(TEXT("No results to display.\n"));
-		}
-		else
+		if (dw_error_code != ERROR_FILE_NOT_FOUND)
 		{
 			_tprintf(TEXT("FindFirstFile failed %d\n"), dw_error_code);
 		}
@@ -61,10 +61,57 @@

 	do
 	{
-		_tprintf(TEXT("%s\n"), hFile->cFileName);
-	} while (FindNextFile(findResult, hFile));
+		if (hDirectory->dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
+			&& wcscmp(hDirectory->cFileName, L".") != 0
+			&& wcscmp(hDirectory->cFileName, L"..") != 0)
+		{
+			wchar_t new_bp[MAX_PATH] = L"";

-	FindClose(findResult);
+			size_t fn_sz = wcsnlen_s(hDirectory->cFileName, FILENAME_MAX);
+
+			StringCchCat(new_bp, bp_sz + 1, base_path);
+			StringCchCat(new_bp, bp_sz + fn_sz + 1, hDirectory->cFileName);
+			StringCchCat(new_bp, bp_sz + fn_sz + 2, L"\\");
+
+			_search(new_bp, filename);
+		}
+
+	} while (FindNextFile(findDirectoryResult, hDirectory));
+
+	wchar_t combined_filename[MAX_PATH] = TEXT("");
+
+	StringCchCat(combined_filename, bp_sz + 1, base_path);
+	StringCchCat(combined_filename, bp_sz + 2, TEXT("\\"));
+	StringCchCat(combined_filename, bp_sz + wcsnlen_s(filename, FILENAME_MAX) + 2, filename);
+
+	findFileResult = FindFirstFile((LPCWSTR)combined_filename, hFile);
+
+	if (findFileResult == INVALID_HANDLE_VALUE)
+	{
+		DWORD dw_error_code = 0;
+
+		dw_error_code = GetLastError();
+
+		if (dw_error_code != ERROR_FILE_NOT_FOUND)
+		{
+			_tprintf(TEXT("FindFirstFile failed %d\n"), dw_error_code);
+			return;
+		}
+
+		return;
+	}
+
+	do
+	{
+		wchar_t fpn[MAX_PATH] = L"";
+		StringCchCat(fpn, bp_sz + 1, base_path);
+		StringCchCat(fpn, bp_sz + 2, L"\\");
+		StringCchCat(fpn, bp_sz + wcsnlen_s(hFile->cFileName, FILENAME_MAX) + 2, hFile->cFileName);
+
+		_tprintf(TEXT("%s\n"), fpn);
+	} while (FindNextFile(findFileResult, hFile));
+
+	FindClose(findFileResult);
 }

 int main(int argc, char *argv[])
@@ -79,7 +126,7 @@
 		wchar_t fn[FILENAME_MAX];
 		mbstowcs_s(NULL, fn, argv[1], FILENAME_MAX);

-		StringCchCat(base_path, 4, L".\\");
+		StringCchCat(base_path, sizeof(wchar_t) * 3, L".\\");
 		StringCchCat(file_name, FILENAME_MAX * sizeof(wchar_t), fn);
 	}
 	else if (argc == 3)


add sink that append to an std::ostream &

--- silicium/sink.hpp
+++ silicium/sink.hpp
@@ -139,6 +139,37 @@
 		return make_iterator_sink<typename Container::value_type>(std::back_inserter(destination));
 	}

+	struct ostream_ref_sink : flushable_sink<char>
+	{
+		explicit ostream_ref_sink(std::ostream &file)
+		   : m_file(file)
+		{
+		}
+
+		virtual boost::iterator_range<char *> make_append_space(std::size_t) SILICIUM_OVERRIDE
+		{
+		   return {};
+		}
+
+		virtual void flush_append_space() SILICIUM_OVERRIDE
+		{
+		}
+
+		virtual void append(boost::iterator_range<char const *> data) SILICIUM_OVERRIDE
+		{
+		   m_file.write(data.begin(), data.size());
+		}
+
+		virtual void flush() SILICIUM_OVERRIDE
+		{
+		   m_file.flush();
+		}
+
+	private:
+
+		std::ostream &m_file;
+	};
+
 	struct ostream_sink : flushable_sink<char>
 	{
 		//unique_ptr to make ostreams movable


Fix a typo

Fix a typo

--- src/ScenesManager.cpp
+++ src/ScenesManager.cpp
@@ -150,13 +150,13 @@

 void ScenesManager::_destroyScene(Scene* pScene)
 {
-	// CScenesManager
+	// Assertions
 	assert(pScene && "Invalid scene");

 	// Declarations
 	tScenesNativeIterator iter, iterEnd;

-	// Search the entity
+	// Search the scene
 	for (iter = m_scenes.begin(), iterEnd = m_scenes.end(); iter != iterEnd; ++iter)
 	{
 		if (*iter == pScene)


Changed the autocompletion listbox member to be a pointer. Added some extra listbox initialisation parameters needed because of pixmaps. Using new CaretFromEdge member of listbox to align with content text. Implemented SCI_CLEARREGISTEREDIMAGES.

--- src/ScintillaBase.cxx
+++ src/ScintillaBase.cxx
@@ -2,7 +2,7 @@
 /** @file ScintillaBase.cxx
  ** An enhanced subclass of Editor with calltips, autocomplete and context menu.
  **/
-// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
+// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
 // The License.txt file describes the conditions under which this software may be distributed.

 #include <stdlib.h>
@@ -26,6 +26,7 @@
 #include "CallTip.h"
 #include "KeyMap.h"
 #include "Indicator.h"
+#include "XPM.h"
 #include "LineMarker.h"
 #include "Style.h"
 #include "ViewStyle.h"
@@ -211,7 +212,7 @@
 			return;
 		}
 	}
-	ac.Start(wMain, idAutoComplete, currentPos, lenEntered);
+	ac.Start(wMain, idAutoComplete, currentPos, lenEntered, vs.lineHeight, IsUnicodeMode());

 	PRectangle rcClient = GetClientRectangle();
 	Point pt = LocationFromPosition(currentPos - lenEntered);
@@ -224,7 +225,7 @@
 		pt = LocationFromPosition(currentPos);
 	}
 	PRectangle rcac;
-	rcac.left = pt.x - 5;
+	rcac.left = pt.x - ac.lb->CaretFromEdge();
 	if (pt.y >= rcClient.bottom - heightLB &&  // Wont fit below.
 	        pt.y >= (rcClient.bottom + rcClient.top) / 2) { // and there is more room above.
 		rcac.top = pt.y - heightLB;
@@ -237,19 +238,19 @@
 	}
 	rcac.right = rcac.left + widthLB;
 	rcac.bottom = Platform::Minimum(rcac.top + heightLB, rcClient.bottom);
-	ac.lb.SetPositionRelative(rcac, wMain);
-	ac.lb.SetFont(vs.styles[STYLE_DEFAULT].font);
-	ac.lb.SetAverageCharWidth(vs.styles[STYLE_DEFAULT].aveCharWidth);
-	ac.lb.SetDoubleClickAction(AutoCompleteDoubleClick, this);
+	ac.lb->SetPositionRelative(rcac, wMain);
+	ac.lb->SetFont(vs.styles[STYLE_DEFAULT].font);
+	ac.lb->SetAverageCharWidth(vs.styles[STYLE_DEFAULT].aveCharWidth);
+	ac.lb->SetDoubleClickAction(AutoCompleteDoubleClick, this);

 	ac.SetList(list);

 	// Fiddle the position of the list so it is right next to the target and wide enough for all its strings
-	PRectangle rcList = ac.lb.GetDesiredRect();
+	PRectangle rcList = ac.lb->GetDesiredRect();
 	int heightAlloced = rcList.bottom - rcList.top;
 	widthLB = Platform::Maximum(widthLB, rcList.right - rcList.left);
 	// Make an allowance for large strings in list
-	rcList.left = pt.x - 5;
+	rcList.left = pt.x - ac.lb->CaretFromEdge();
 	rcList.right = rcList.left + widthLB;
 	if (((pt.y + vs.lineHeight) >= (rcClient.bottom - heightAlloced)) &&  // Wont fit below.
 	        ((pt.y + vs.lineHeight / 2) >= (rcClient.bottom + rcClient.top) / 2)) { // and there is more room above.
@@ -258,7 +259,7 @@
 		rcList.top = pt.y + vs.lineHeight;
 	}
 	rcList.bottom = rcList.top + heightAlloced;
-	ac.lb.SetPositionRelative(rcList, wMain);
+	ac.lb->SetPositionRelative(rcList, wMain);
 	ac.Show();
 	if (lenEntered != 0) {
 		AutoCompleteMoveToCurrentWord();
@@ -304,10 +305,10 @@
 }

 void ScintillaBase::AutoCompleteCompleted() {
-	int item = ac.lb.GetSelection();
+	int item = ac.lb->GetSelection();
 	char selected[1000];
 	if (item != -1) {
-		ac.lb.GetValue(item, selected, sizeof(selected));
+		ac.lb->GetValue(item, selected, sizeof(selected));
 	}
 	ac.Cancel();

@@ -510,7 +511,11 @@
 		return ac.dropRestOfWord;

 	case SCI_REGISTERIMAGE:
-		ac.lb.SetTypeXpm(wParam, reinterpret_cast<const char *>(lParam));
+		ac.lb->RegisterImage(wParam, reinterpret_cast<const char *>(lParam));
+		break;
+
+	case SCI_CLEARREGISTEREDIMAGES:
+		ac.lb->ClearRegisteredImages();
 		break;

 	case SCI_CALLTIPSHOW: {


Fixed bug #1772351 SCI_CALLTIPSETBACK setting foreground rather than background colour.

--- src/ScintillaBase.cxx
+++ src/ScintillaBase.cxx
@@ -643,7 +643,7 @@

 	case SCI_CALLTIPSETBACK:
 		ct.colourBG = ColourDesired(wParam);
-		vs.styles[STYLE_CALLTIP].fore = ct.colourBG;
+		vs.styles[STYLE_CALLTIP].back = ct.colourBG;
 		InvalidateStyleRedraw();
 		break;


vtkAxisActor2D tick distance was wrong in RulerMode

For the axis wLength of 101.0 and a rulerDistance of 50.0, the number of
ticks should be 4: 0, 50, 100 and 101.
When converting to viewport coordinates, if the axis length is 10.1,
the tick distance should then be 5.0.
Note that the number of ticks must contain the start and end ticks, so
they can be skipped in the for loop that adds tick points in the polyline.
If the last tick is confounded with the end tick mark, don't add the end
tick to numTicks.

Change-Id: I6713e7a0d8f90c7887c61fa7a1a64910c0555764

--- Rendering/vtkAxisActor2D.cxx
+++ Rendering/vtkAxisActor2D.cxx
@@ -430,21 +430,34 @@
   p21[2] = p2[2] - p1[2];
   length = vtkMath::Normalize(p21);

+  // Sum of all the ticks: minor and majors. Contains the start and end ticks.
   int numTicks;
+  // Distance between each minor tick.
   double distance;
   if ( this->RulerMode )
     {
-    double wp1[3], wp2[3], wp21[3], wLength, wDistance;
+    double wp1[3], wp2[3], wp21[3];
     this->PositionCoordinate->GetValue(wp1);
     this->Position2Coordinate->GetValue(wp2);
     wp21[0] = wp2[0] - wp1[0];
     wp21[1] = wp2[1] - wp1[1];
     wp21[2] = wp2[2] - wp1[2];
-    wLength = vtkMath::Norm(wp21);
-    wDistance = this->RulerDistance / (this->NumberOfMinorTicks+1);
-    numTicks = (wDistance <= 0.0 ? 0 : static_cast<int>(wLength / wDistance)+1);
-    wDistance *= numTicks;
-    distance = (length / (numTicks-1)) * (wDistance/wLength);
+    const double worldLength = vtkMath::Norm(wp21);
+    const double worldDistance = this->RulerDistance / (this->NumberOfMinorTicks+1);
+    numTicks = static_cast<int>(
+      worldDistance <= 0.0 ? 0. : (worldLength / worldDistance));
+    const double precision = std::numeric_limits<double>::epsilon();
+    const bool hasRemainderInDivision = worldDistance <= 0.0 ? false:
+      std::fmod(worldLength, worldDistance) > precision;
+    // numTicks must contain the start and end ticks
+    // Don't add the end tick if it is already in numTicks:
+    //   when wLength / wDistance is an integer.
+    numTicks += hasRemainderInDivision ? 2 : 1;
+    // Tick distance was computed in world coordinates, convert to viewport
+    // coordinates.
+    const double worldToLocalRatio =
+      (worldLength < 0.0 ? 0. : length / worldLength);
+    distance = worldDistance * worldToLocalRatio;
     }
   else
     {
@@ -453,6 +466,7 @@
     distance = length / (numTicks-1);
     }

+  // Only draw the inner ticks (not the start/end ticks)
   for (i = 1; i < numTicks - 1; i++)
     {
     int tickLength = 0;


World: Tidy up; separate block generation from chunk generation

--- Sub-Terra/src/World.cpp
+++ Sub-Terra/src/World.cpp
@@ -8,16 +8,12 @@
 }

 void World::Update(DeltaTicks &, std::vector<Object *> &) {
-	chunks.With([] (ChunksType &chunks) {
-		//INFO(chunks.size());
-	});
-
 	if(cameraObj == nullptr) { return; }
 	auto camera = cameraObj->Get<PlayerCameraComponent>();
 	if(camera != nullptr) {
 		auto pos = cameraObj->Get<PositionComponent>();
 		if(pos != nullptr) {
-			const unsigned char distance = 6;
+			const unsigned char distance = 5;

 			auto chunkSizeF = glm::fvec3(chunkSize);
 			auto keyBase = glm::ivec3(glm::floor(pos->position.To<glm::fvec3>()) / chunkSizeF);
@@ -108,13 +104,8 @@
 }

 std::vector<bool> World::Generate(const ChunkKeyType &keyTuple) const {
-	/*const float start = -0.5, end = -0;
-	static double factor = 1.0f;
-	factor /= 1.0001f;
-	auto r = factor * (start - end) + end;*/
-
-	const float scale = 0.5f;
-	const float scaleX = scale, scaleY = scale * 2, scaleZ = scale;
+	const float scale = 1.0f;
+	const float scaleX = scale, scaleY = scale, scaleZ = scale;

 	std::vector<bool> blocks;
 	blocks.resize(chunkSize.x * chunkSize.y * chunkSize.z);
@@ -124,14 +115,17 @@
 	for(float z = 0; z < 1; z += zIncr) {
 		for(float x = 0; x < 1; x += xIncr) {
 			for(float y = 0; y < 1; y += yIncr) {
-				double random = noise.eval(
+				blocks.at(i++) = GenerateBlock(
 					( std::get<0>(keyTuple) + x) * scaleX,
 					( std::get<1>(keyTuple) + y) * scaleY,
 					(-std::get<2>(keyTuple) + z) * scaleZ
 				);
-				blocks.at(i++) = random > 0.45f;
 			}
 		}
 	}
 	return blocks;
 }
+
+bool World::GenerateBlock(const float x, const float y, const float z) const {
+	return noise.eval(x, y, z) > 0.45f;
+}


Various World fixes

Various World fixes

Objects must be removed outside of the camera object iterator range loop as doing so may invalidate the range, leading to undefined behaviour.

The camera position is now rounded instead of floored.

Additionally, position components of new chunks are now constructed from the generation thread to further reduce main thread overhead.

--- Sub-Terra/src/World.cpp
+++ Sub-Terra/src/World.cpp
@@ -18,12 +18,12 @@
 		if(pos != nullptr) {
 			const unsigned char distance = 5;

-			auto chunkSizeF = glm::fvec3(chunkSize);
-			auto keyBase = glm::ivec3(glm::floor(pos->position.To<glm::fvec3>()) / chunkSizeF);
+			auto chunkSizeF = Point3(chunkSize);
+			auto keyBase = glm::ivec3(glm::round(pos->position.Get()) / chunkSizeF);
 			auto jobM = engine->systems.Get<JobManager>();

 			/* clean up chunks outside distance */
-			chunks.With([this, distance, &keyBase] (ChunksType &chunks) {
+			chunks.With([this, jobM, distance, &keyBase] (ChunksType &chunks) {
 				for(auto it = chunks.begin(); it != chunks.end();) {
 					auto &keyTuple = it->first;
 					auto obj = std::get<1>(it->second);
@@ -38,7 +38,7 @@
 							break;
 						case ChunkStatus::Alive:
 						case ChunkStatus::Dead:
-							engine->RemoveObject(obj);
+							jobM->Do([this, obj] () { engine->RemoveObject(obj); }, JobPriority::Low, JobThread::Main);
 							chunks.erase(it++);
 							continue;
 						}
@@ -70,14 +70,13 @@
 									});
 									if(dead) { return; }

-									auto chunkPos = glm::fvec3(key) * chunkSizeF;
-									auto pos = Point3(chunkPos.x, chunkPos.y, chunkPos.z);
+									auto pos = new PositionComponent(Point3(key) * chunkSizeF);
 									auto data = GenerateChunk(Point3(std::get<0>(keyTuple), std::get<1>(keyTuple), std::get<2>(keyTuple)));
 									auto chunk = new Chunk(chunkSize.x, chunkSize.y, chunkSize.z, std::move(data));

 									jobM->Do([this, keyTuple, chunk, pos] () {
 										auto id = engine->AddObject();
-										engine->AddComponent<PositionComponent>(id, pos);
+										engine->InsertComponent<PositionComponent>(id, pos);
 										engine->InsertComponent<ModelComponent>(id, chunk);
 										chunks.With([&keyTuple, id] (ChunksType &chunks) {
 											chunks.at(keyTuple) = std::make_tuple(ChunkStatus::Alive, id);


Implemented check for shaders directory

Implemented check for shaders directory

Addresses issue #191

--- TIGLViewer/src/main.cpp
+++ TIGLViewer/src/main.cpp
@@ -57,8 +57,25 @@
 #else
     shaderDir += "/../share/tigl/shaders";
 #endif
-    if (qgetenv("CSF_ShadersDirectory").isNull()) {
+
+    QByteArray envVar = qgetenv("CSF_ShadersDirectory");
+    if (envVar.isNull()) {
         qputenv("CSF_ShadersDirectory", shaderDir.toUtf8());
+    }
+    else {
+        shaderDir = envVar;
+    }
+
+    // check existance of shader dir
+    if (!QFile(shaderDir+"/PhongShading.fs").exists()) {
+        std::stringstream str;
+        str << "Illegal or non existing shader directory "
+            << "
" << shaderDir.toStdString() << "
"
+            << "Set the enviroment variable CSF_ShadersDirectory to provide a path for the OpenCASCADE shaders.";
+        QMessageBox::critical(0, "Startup error...",
+                                  str.str().c_str(),
+                                  QMessageBox::Ok );
+        return 1;
     }

     int retval = parseArguments(app.arguments());


fixed compiler problem

fixed compiler problem

--- TRD/AliTRDRawStream.cxx
+++ TRD/AliTRDRawStream.cxx
@@ -1108,8 +1108,8 @@
 		  , fDataWord, fSM, fLAYER, fSTACK, fSIDE+10
                   , fTracklPadRow, fTracklPadPos, fTracklDefL, fTracklPID));

-  if( (fSTACK == 2) && (fTracklPadRow >= (Int_t)fGeo->RowmaxC0) ||
-      (fSTACK != 2) && (fTracklPadRow >= (Int_t)fGeo->RowmaxC1) ) {
+  if( (fSTACK == 2) && (fTracklPadRow >= (Int_t) fGeo->RowmaxC0()) ||
+      (fSTACK != 2) && (fTracklPadRow >= (Int_t) fGeo->RowmaxC1()) ) {
     AliError(Form("Strange Row read from Tracklet Word: %d", fTracklPadRow));
   }


Added protection against Log(0) in the gas gain calulation

--- TRD/AliTRDdigitizer.cxx
+++ TRD/AliTRDdigitizer.cxx
@@ -15,6 +15,9 @@

 /*
 $Log$
+Revision 1.10  2000/10/05 07:27:53  cblume
+Changes in the header-files by FCA
+
 Revision 1.9  2000/10/02 21:28:19  fca
 Removal of useless dependecies via forward declarations

@@ -551,7 +554,11 @@
               Int_t timeD = timeH - timeE;

               // Apply the gas gain including fluctuations
-              Int_t signal = (Int_t) (-fGasGain * TMath::Log(gRandom->Rndm()));
+              Float_t ggRndm = 0.0;
+              do {
+                ggRndm = gRandom->Rndm();
+	      } while (ggRndm <= 0);
+              Int_t signal = (Int_t) (-fGasGain * TMath::Log(ggRndm));

 	      // The distance of the electron to the center of the pad
 	      // in units of pad width


coverity fix

coverity fix

--- TRD/AliTRDrecoParam.cxx
+++ TRD/AliTRDrecoParam.cxx
@@ -354,8 +354,8 @@
     // y correction due to wrong tail cancellation.
     fYcorrTailCancel[0][0] = par[5];fYcorrTailCancel[0][1] = par[6];fYcorrTailCancel[0][2] = par[7];
     fYcorrTailCancel[1][0] = par[8];fYcorrTailCancel[1][1] = par[9];fYcorrTailCancel[1][2] = par[10];
-    fYcorrTailCancel[2][0] = par[11];fYcorrTailCancel[2][1] = par[12];fYcorrTailCancel[2][3] = par[13];
-    fYcorrTailCancel[3][0] = par[14];fYcorrTailCancel[3][1] = par[15];fYcorrTailCancel[3][3] = par[16];
+    fYcorrTailCancel[2][0] = par[11];fYcorrTailCancel[2][1] = par[12];fYcorrTailCancel[2][2] = par[13];
+    fYcorrTailCancel[3][0] = par[14];fYcorrTailCancel[3][1] = par[15];fYcorrTailCancel[3][2] = par[16];
     // inflation factor of error parameterization in r-phi due to wrong estimation of residuals.
     fS2Ycorr[0] = par[17];
     fS2Ycorr[1] = par[18];


The size of the array is checked in First() (M.Ivanov)

--- TRD/AliTRDtrackHits.cxx
+++ TRD/AliTRDtrackHits.cxx
@@ -45,6 +45,12 @@
   //
   //set Current hit for the first hit
   //
+
+  if (fArray->GetSize()<=0) {
+    fCurrentHit->fStatus = kFALSE;
+    return kFALSE;
+  }
+
   AliTrackHitsParamV2 *param = (AliTrackHitsParamV2 *)fArray->At(0);
   if (!fHit)
     fHit = new AliTRDhit;


fix typo

fix typo

--- TRD/AliTRDtrackerV1.cxx
+++ TRD/AliTRDtrackerV1.cxx
@@ -570,7 +570,7 @@
       }

       // Prolongate to TPC
-      if (PropagateToX(track, xTPC, AliTRDReconstructor::GetMaxStep())) { //  -with update
+      if (PropagateToX(track, xToGo, AliTRDReconstructor::GetMaxStep())) { //  -with update
         seed->UpdateTrackParams(&track, AliESDtrack::kTRDrefit);
         found++;
         kUPDATE = kTRUE;
@@ -580,7 +580,7 @@
     // Prolongate to TPC without update
     if(!kUPDATE) {
       AliTRDtrackV1 tt(*seed);
-      if (PropagateToX(tt, xTPC, AliTRDReconstructor::GetMaxStep())) seed->UpdateTrackParams(&tt, AliESDtrack::kTRDbackup);
+      if (PropagateToX(tt, xToGo, AliTRDReconstructor::GetMaxStep())) seed->UpdateTrackParams(&tt, AliESDtrack::kTRDbackup);
     }
   }
   AliInfo(Form("Number of seeds: TRDout[%d]", nseed));


core: properly initialize request object variables

especially http version major/minors (with 0, currently)

--- src/x0/request.hpp
+++ src/x0/request.hpp
@@ -73,7 +73,20 @@

 // {{{ request impl
 inline request::request(x0::connection& conn) :
-	connection(conn)
+	connection(conn),
+	method(),
+	uri(),
+	path(),
+	fileinfo(),
+	query(),
+	http_version_major(0),
+	http_version_minor(0),
+	headers(),
+	body(),
+	username(),
+	document_root(),
+	custom_data(),
+	hostid_()
 {
 }


meta: compare function shouldn't be static

--- src/entt/meta/meta.hpp
+++ src/entt/meta/meta.hpp
@@ -180,7 +180,7 @@

 template<typename Type>
-static bool compare(const void *lhs, const void *rhs) {
+bool compare(const void *lhs, const void *rhs) {
     if constexpr(!std::is_function_v<Type> && is_equality_comparable_v<Type>) {
         return *static_cast<const Type *>(lhs) == *static_cast<const Type *>(rhs);
     } else {


changed strategy for refit inward. Added also tracks stopped in TRD do the inward propagation only up to radial position 250 cm

--- TRD/AliTRDtrackerV1.cxx
+++ TRD/AliTRDtrackerV1.cxx
@@ -412,7 +412,7 @@
           track.GetStatusTRD(0), track.GetStatusTRD(1), track.GetStatusTRD(2), track.GetStatusTRD(3), track.GetStatusTRD(4), track.GetStatusTRD(5)));
         continue;
       } else {
-        AliDebug(2, Form("Track @ idx[%4d] #cl[%3d]", currentIndexESD, track.GetNumberOfClusters()));
+        AliDebug(2, Form("Track @ idx[%4d] #cl[%3d] expect[%+3d]", currentIndexESD, track.GetNumberOfClusters(), expectedClr));
         nFound[kTPC]++;
         // compute PID
         track.CookPID();
@@ -540,24 +540,25 @@
   for (Int_t itrack = 0; itrack < event->GetNumberOfTracks(); itrack++) {
     AliESDtrack *seed = event->GetTrack(itrack);
     ULong_t status = seed->GetStatus();
-
+    // reject tracks which did not entered TRD from bellow (also produced by the TRD stand alone tracker)
+    if(!(status & AliESDtrack::kTRDin)) continue;
+    // reject TRD tracks with no clusters. This condition is softer than previously used
+    // !(status & AliESDtrack::kTRDout)
+    // since it allows also tracks stopped
+    if(!seed->GetTRDncls()) continue;
+    // check back-up quality
     new(&track) AliTRDtrackV1(*seed);
     if (track.GetX() < 270.0) {
       seed->UpdateTrackParams(&track, AliESDtrack::kTRDbackup);
       continue;
     }
-
-    // reject tracks which failed propagation in the TRD or
-    // are produced by the TRD stand alone tracker
-    if(!(status & AliESDtrack::kTRDout)) continue;
-    if(!(status & AliESDtrack::kTRDin)) continue;
-    nseed++;
+    nseed++;

     track.ResetCovariance(50.0);

     // do the propagation and processing
     Bool_t kUPDATE = kFALSE;
-    Double_t xToGo = (status & AliESDtrack::kTPCout)?250.0:80.0;
+    Double_t xToGo = 250.;//(status & AliESDtrack::kTPCout)?250.0:.1;
     if(FollowProlongation(track)){
       // Update the friend track
       if (fkRecoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 0){


MoarShapes

MoarShapes

--- GalaxyGen/Galaxy.cpp
+++ GalaxyGen/Galaxy.cpp
@@ -168,8 +168,14 @@
 	{
 		for (long x = -length; x < length; ++x)
 		{
-			distance = pow(y,2) + pow(x, 2);
-			if (((distance < interior) && (distance < hyp)) || ((x == 0) && (y == 0)))
+			//Determine radial distance from any corner
+			double corner_dist = pow((length/2) - abs(x),2) + pow((length/2) - abs(y), 2);
+			distance = pow(x, 2) + pow(y, 2);
+
+
+
+
+			if ((distance < interior) || ((x == 0) && (y == 0)))
 			{
 				color = CoreTemperatureToColor(temperature).values.intValue;
 			}


AudioLoader Leak Fix

AudioLoader Leak Fix

--- src/algorithms/io/audioloader.cpp
+++ src/algorithms/io/audioloader.cpp
@@ -19,7 +19,7 @@

 #include "audioloader.h"
 #include "algorithmfactory.h"
-#include <iomanip>  //  setw()
+

 using namespace std;

@@ -30,7 +30,6 @@
 const char* AudioLoader::description = DOC("This algorithm loads the single audio stream contained in the given audio or video file, as well as the samplerate and the number of channels. Supported formats are all those supported by the ffmpeg library, which is, virtually everything.\n"
 "\n"
 "This algorithm will throw an exception if it hasn't been properly configured which is normally due to not specifying a valid filename.\n"
-"If using this algorithm on Windows, you must ensure that the filename is encoded as UTF-8.\n"
 "Note: ogg files are decoded in reverse phase, due to a (possible) bug in the ffmpeg library.\n"
 "\n"
 "References:\n"
@@ -50,8 +49,10 @@
     closeAudioFile();

     av_freep(&_buffer);
-    av_freep(&_md5Encoded);
+
+#if LIBAVCODEC_VERSION_INT >= AVCODEC_AUDIO_DECODE4
     av_freep(&_decodedFrame);
+#endif

 #if !HAVE_SWRESAMPLE
     av_freep(&_buff1);
@@ -67,24 +68,21 @@
     // set ffmpeg to be silent by default, so we don't have these annoying
     // "invalid new backstep" messages anymore, when everything is actually fine
     av_log_set_level(AV_LOG_QUIET);
-    _computeMD5 = parameter("computeMD5").toBool();
     reset();
 }

+
 void AudioLoader::openAudioFile(const string& filename) {
-    E_DEBUG(EAlgorithm, "AudioLoader: opening file: " << filename);
+    E_DEBUG(EAlgorithm, "AudioLoader: opening file: " << parameter("filename").toString());

     // Open file
+    if (avformat_open_input(&_demuxCtx, filename.c_str(), NULL, NULL) != 0) {
+        throw EssentiaException("AudioLoader: Could not open file \"", filename, "\"");
+    }
+
+    // Retrieve stream information
     int errnum;
-    if ((errnum = avformat_open_input(&_demuxCtx, filename.c_str(), NULL, NULL)) != 0) {
-        char errorstr[128];
-        string error = "Unknown error";
-        if (av_strerror(errnum, errorstr, 128) == 0) error = errorstr;
-        throw EssentiaException("AudioLoader: Could not open file \"", filename, "\", error = ", error);
-    }
-
-    // Retrieve stream information
     if ((errnum = avformat_find_stream_info(_demuxCtx, NULL)) < 0) {
         char errorstr[128];
         string error = "Unknown error";
@@ -111,6 +109,7 @@

     // Load corresponding audio codec
     _audioCtx = _demuxCtx->streams[_streamIdx]->codec;
+
     _audioCodec = avcodec_find_decoder(_audioCtx->codec_id);

     if (!_audioCodec) {
@@ -150,35 +149,7 @@
         E_DEBUG(EAlgorithm, "AudioLoader: using sample format conversion from "
                             "deprecated audioconvert");

-        if (av_sample_fmt_is_planar(_audioCtx->sample_fmt)) {
-          // Ugly hack to treat planar audio format as interleaved
-          E_WARNING("AudioLoader: using depricated audioconvert and manually converting planar format to interleaved");
-          switch (_audioCtx->sample_fmt) {
-            case AV_SAMPLE_FMT_S16P:
-              _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, AV_SAMPLE_FMT_S16, 1, NULL, 0);
-              break;
-            case AV_SAMPLE_FMT_S32P:
-              _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, AV_SAMPLE_FMT_S32, 1, NULL, 0);
-              break;
-            case AV_SAMPLE_FMT_FLTP:
-              _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, AV_SAMPLE_FMT_FLT, 1, NULL, 0);
-              break;
-            case AV_SAMPLE_FMT_DBLP:
-              _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, AV_SAMPLE_FMT_DBL, 1, NULL, 0);
-              break;
-            default:
-              ostringstream msg;
-              msg << "AudioLoader: Error converting"
-                  << " from " << av_get_sample_fmt_name(_audioCtx->sample_fmt)
-                  << " to "   << av_get_sample_fmt_name(AV_SAMPLE_FMT_S16)
-                  << "using deprecated av_audio_convert. Format unsupported.";
-              throw EssentiaException(msg);
-              break;
-          }
-        }
-        else {
-          _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, _audioCtx->sample_fmt, 1, NULL, 0);
-        }
+        _audioConvert = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1, _audioCtx->sample_fmt, 1, NULL, 0);

         // reserve some more space
         _buff1 = (int16_t*)av_malloc(MAX_AUDIO_FRAME_SIZE * 3);
@@ -193,12 +164,24 @@

     av_init_packet(&_packet);

+#if LIBAVCODEC_VERSION_INT >= AVCODEC_AUDIO_DECODE4
     _decodedFrame = avcodec_alloc_frame();
     if (!_decodedFrame) {
         throw EssentiaException("Could not allocate audio frame");
     }
-
-    av_md5_init(_md5Encoded);
+#endif
+
+
+#if LIBAVCODEC_VERSION_INT < AVCODEC_51_28_0
+    E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio() function");
+#elif LIBAVCODEC_VERSION_INT < AVCODEC_52_47_0
+    E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio2() function");
+#elif LIBAVCODEC_VERSION_INT < AVCODEC_AUDIO_DECODE4
+    E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio3() function");
+#else
+    E_DEBUG(EAlgorithm, "AudioLoader: using ffmpeg avcodec_decode_audio4() function");
+#endif
+
 }

@@ -214,11 +197,11 @@
     // Close the codec
     avcodec_close(_audioCtx);

+    // free AVPacket
+    av_free_packet(&_packet);
+
     // Close the audio file
     avformat_close_input(&_demuxCtx);
-
-    // free AVPacket
-    av_free_packet(&_packet);

     _demuxCtx = 0;
     _audioCtx = 0;
@@ -239,20 +222,6 @@
     _sampleRate.push(sampleRate);
 }

-
-void AudioLoader::pushCodecInfo(std::string codec, int bit_rate) {
-    _codec.push(codec);
-    _bit_rate.push(bit_rate);
-}
-
-
-string uint8_t_to_hex(uint8_t* input, int size) {
-    ostringstream result;
-    for(int i=0; i<size; ++i) {
-        result << setw(2) << setfill('0') << hex << (int) input[i];
-    }
-    return result.str();
-}

 AlgorithmStatus AudioLoader::process() {
@@ -264,43 +233,18 @@
     do {
         int result = av_read_frame(_demuxCtx, &_packet);
         //E_DEBUG(EAlgorithm, "AudioLoader: called av_read_frame(), got result = " << result);
+
         if (result != 0) {
-            // 0 = OK, < 0 = error or EOF
-            if (result != AVERROR_EOF) {
-                char errstring[1204];
-                av_strerror(result, errstring, sizeof(errstring));
-                ostringstream msg;
-                msg << "AudioLoader: Error reading frame: " << errstring;
-                E_WARNING(msg.str());
-            }
-            // TODO: should try reading again on EAGAIN error?
-            //       https://github.com/FFmpeg/FFmpeg/blob/master/ffmpeg.c
             shouldStop(true);
             flushPacket();
             closeAudioFile();
-            if (_computeMD5) {
-                av_md5_final(_md5Encoded, _checksum);
-                _md5.push(uint8_t_to_hex(_checksum, 16));
-            }
-            else {
-                string md5 = "";
-                _md5.push(md5);
-            }
             return FINISHED;
         }
     } while (_packet.stream_index != _streamIdx);

-    // compute md5 first
-    if (_computeMD5) {
-        av_md5_update(_md5Encoded, _packet.data, _packet.size);
-    }
-
-    // decode frames in packet
-    while(_packet.size > 0) {
-        if (!decodePacket()) break;
-        copyFFmpegOutput();
-    }
-
+    decodePacket();
+    copyFFmpegOutput();
+    av_free_packet(&_packet);
     return OK;
 }

@@ -309,6 +253,24 @@
                                     int16_t* output,
                                     int* outputSize,
                                     AVPacket* packet) {
+
+
+#if LIBAVCODEC_VERSION_INT < AVCODEC_51_28_0
+
+    int len = avcodec_decode_audio(audioCtx, output, outputSize,
+                                 packet->data, packet->size);
+
+#elif LIBAVCODEC_VERSION_INT < AVCODEC_52_47_0
+
+    int len = avcodec_decode_audio2(audioCtx, output, outputSize,
+                                    packet->data, packet->size);
+
+#elif LIBAVCODEC_VERSION_INT < AVCODEC_AUDIO_DECODE4
+
+    int len = avcodec_decode_audio3(audioCtx, output, outputSize,
+                                    packet);
+
+#else

     int gotFrame = 0;
     avcodec_get_frame_defaults(_decodedFrame);
@@ -347,19 +309,6 @@
         }
 #  else
         // direct copy, we do the sample format conversion later if needed
-
-        // TODO: Libav 9 introduced planar sample formats and converted audio
-        // codecs to use these instead of interleaving the samples in the
-        // codec after decoding. Unfortunately av_audio_convert doesn't deal
-        // with planar formats, so libavresample should be used.
-
-        // NOTE: Meanwhile, as we ship outdated av_audio_convert ourselves,
-        // we need to check if the format is planar or interleaved to convert
-        // decoded frame data correctly. We will treat planar data as if it was
-        // interleaved for convertion, which is safe as long as no sample rate
-        // conversion is done. Afterwards, we will copy the results to audio
-        // output accordingly to it being planar or interleaved.
-
         memcpy(output, _decodedFrame->data[0], inputDataSize);
         *outputSize = inputDataSize;
 #  endif
@@ -369,6 +318,8 @@
         E_DEBUG(EAlgorithm, "AudioLoader: tried to decode packet but didn't get any frame...");
         *outputSize = 0;
     }
+
+#endif

     return len;
 }
@@ -381,14 +332,7 @@
         empty.data = 0;
         empty.size = 0;

-        int len = decode_audio_frame(_audioCtx, _buffer, &_dataSize, &empty);
-        if (len < 0) {
-            char errstring[1204];
-            av_strerror(len, errstring, sizeof(errstring));
-            ostringstream msg;
-            msg << "AudioLoader: decoding error while flushing a packet:" << errstring;
-            E_WARNING(msg.str());
-        }
+        decode_audio_frame(_audioCtx, _buffer, &_dataSize, &empty);
         copyFFmpegOutput();

     } while (_dataSize > 0);
@@ -407,6 +351,7 @@
     E_DEBUG(EAlgorithm, "flags: " << _packet.flags);
     E_DEBUG(EAlgorithm, "duration: " << _packet.duration);
     */
+
     int len = 0;

     // buff is an offset in our output buffer, it points to where we should start
@@ -423,65 +368,26 @@
     // _dataSize  input = number of bytes available for write in buff
     //           output = number of bytes actually written (actual: S16 data)
     //E_DEBUG(EAlgorithm, "decode_audio_frame, available bytes in buffer = " << _dataSize);
-
-    // Note: md5 should be computed before decoding frame, as the decoding may
-    // change the content of a packet. Still, not sure if it is correct to
-    // compute md5 over packet which contains incorrect frames, potentially
-    // belonging to id3 metadata (TODO: or is it just a missing header issue?),
-    // but computing md5 hash using ffmpeg will also treat it as audio:
-    //      ffmpeg -i file.mp3 -acodec copy -f md5 -
-
     len = decode_audio_frame(_audioCtx, buff, &_dataSize, &_packet);

     if (len < 0) {
-        char errstring[1204];
-        av_strerror(len, errstring, sizeof(errstring));
-        ostringstream msg;
-
+        // only print error msg when file is not an mp3, because mp3 streams can have tag
+        // frames (id3v2?) which libavcodec tries to read as audio anyway, and we don't want
+        // to print an error message for that...
         if (_audioCtx->codec_id == CODEC_ID_MP3) {
-            msg << "AudioLoader: invalid frame, skipping it: " << errstring;
-            // mp3 streams can have tag frames (id3v2?) which libavcodec tries to
-            // read as audio anyway, and we probably don't want print an error
-            // message for that...
-            // TODO: Are these frames really id3 tags?
-
-            //E_DEBUG(EAlgorithm, msg);
-            E_WARNING(msg.str());
+            E_DEBUG(EAlgorithm, "AudioLoader: invalid frame, probably an mp3 tag frame, skipping it");
         }
         else {
-            msg << "AudioLoader: error while decoding, skipping frame: " << errstring;
-            E_WARNING(msg.str());
+            E_WARNING("AudioLoader: error while decoding, skipping frame");
         }
         return 0;
     }
-
-    if (len != _packet.size) {
-        // https://www.ffmpeg.org/doxygen/trunk/group__lavc__decoding.html#ga834bb1b062fbcc2de4cf7fb93f154a3e
-
-        // Some decoders may support multiple frames in a single AVPacket. Such
-        // decoders would then just decode the first frame and the return value
-        // would be less than the packet size. In this case, avcodec_decode_audio4
-        // has to be called again with an AVPacket containing the remaining data
-        // in order to decode the second frame, etc... Even if no frames are
-        // returned, the packet needs to be fed to the decoder with remaining
-        // data until it is completely consumed or an error occurs.
-
-        E_WARNING("AudioLoader: more than 1 frame in packet, decoding remaining bytes...");
-        E_WARNING("at sample index: " << output("audio").totalProduced());
-        E_WARNING("decoded samples: " << len);
-        E_WARNING("packet size: " << _packet.size);
-    }
-
-    // update packet data pointer to data left undecoded (if any)
-    _packet.size -= len;
-    _packet.data += len;
-

     if (_dataSize <= 0) {
         // No data yet, get more frames
-        // cout << "no data yet, get more frames" << endl;
+        //cout << "no data yet, get more frames" << endl;
         _dataSize = 0;
-        return len;
+        return 0;
     }

 #if !HAVE_SWRESAMPLE
@@ -495,14 +401,11 @@
         int ostride[6]      = { av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)     };
         int totalsamples    = _dataSize / istride[0]; // == num_samp_per_channel * num_channels

-        if (int result = av_audio_convert(_audioConvert, obuf, ostride, ibuf, istride, totalsamples) < 0) {
-            char errstring[1204];
-            av_strerror(result, errstring, sizeof(errstring));
+        if (av_audio_convert(_audioConvert, obuf, ostride, ibuf, istride, totalsamples) < 0) {
             ostringstream msg;
             msg << "AudioLoader: Error converting "
-                << " from " << av_get_sample_fmt_name(_audioCtx->sample_fmt)
-                << " to "   << av_get_sample_fmt_name(AV_SAMPLE_FMT_S16)
-                << ". " << errstring;
+                << " from " << avcodec_get_sample_fmt_name(_audioCtx->sample_fmt)
+                << " to "   << avcodec_get_sample_fmt_name(SAMPLE_FMT_S16);
             throw EssentiaException(msg);
         }

@@ -514,6 +417,17 @@
     }
 #endif

+    if (len != _packet.size) {
+        // FIXME: investigate why this happens and whether it is a big issue
+        //        (looks like it only loses silent samples at the end of files)
+
+        // more than 1 frame in a packet, happens a lot with flac for instance...
+        E_WARNING("AudioLoader: more than 1 frame in packet, dropping remaining bytes...");
+        E_WARNING("at sample index: " << output("audio").totalProduced());
+        E_WARNING("decoded samples: " << len);
+        E_WARNING("packet size: " << _packet.size);
+    }
+
     return len;
 }

@@ -535,27 +449,16 @@
     vector<StereoSample>& audio = *((vector<StereoSample>*)_audio.getTokens());

     // FIXME: use libswresample
-
     if (_nChannels == 1) {
         for (int i=0; i<nsamples; i++) {
           audio[i].left() = scale(_buffer[i]);
         }
     }
     else { // _nChannels == 2
-      if (av_sample_fmt_is_planar(_audioCtx->sample_fmt)) {
-        // planar
-        for (int i=0; i<nsamples; i++) {
-            audio[i].left() = scale(_buffer[i]);
-            audio[i].right() = scale(_buffer[nsamples+i]);
-        }
-      }
-      else {
-        // interleaved
         for (int i=0; i<nsamples; i++) {
             audio[i].left() = scale(_buffer[2*i]);
             audio[i].right() = scale(_buffer[2*i+1]);
         }
-      }
     }

     // release data
@@ -573,7 +476,6 @@
     openAudioFile(filename);

     pushChannelsSampleRateInfo(_audioCtx->channels, _audioCtx->sample_rate);
-    pushCodecInfo(_audioCodec->name, _audioCtx->bit_rate);
 }

 } // namespace streaming
@@ -605,19 +507,18 @@
 void AudioLoader::createInnerNetwork() {
     _loader = streaming::AlgorithmFactory::create("AudioLoader");
     _audioStorage = new streaming::VectorOutput<StereoSample>();
+    _srStorage = new streaming::VectorOutput<Real>(&_sampleRateStorage);
+    _cStorage = new streaming::VectorOutput<int>(&_channelsStorage);

     _loader->output("audio")           >>  _audioStorage->input("data");
-    _loader->output("sampleRate")      >>  PC(_pool, "internal.sampleRate");
-    _loader->output("numberChannels")  >>  PC(_pool, "internal.numberChannels");
-    _loader->output("md5")             >>  PC(_pool, "internal.md5");
-    _loader->output("codec")           >>  PC(_pool, "internal.codec");
-    _loader->output("bit_rate")        >>  PC(_pool, "internal.bit_rate");
+    _loader->output("sampleRate")      >>  _srStorage->input("data");
+    _loader->output("numberChannels")  >>  _cStorage->input("data");
+
     _network = new scheduler::Network(_loader);
 }

 void AudioLoader::configure() {
-    _loader->configure(INHERIT("filename"),
-                       INHERIT("computeMD5"));
+    _loader->configure(INHERIT("filename"));
 }

 void AudioLoader::compute() {
@@ -627,37 +528,24 @@
     }

     Real& sampleRate = _sampleRate.get();
-    int& numberChannels = _channels.get();
-    string& md5 = _md5.get();
-    int& bit_rate = _bit_rate.get();
-    string& codec = _codec.get();
+    int& nChannels = _channels.get();
     vector<StereoSample>& audio = _audio.get();

     _audioStorage->setVector(&audio);
-    // TODO: is using VectorInput indeed faster than using Pool?

     // FIXME:
     // _audio.reserve(sth_meaningful);

     _network->run();

-    sampleRate = _pool.value<Real>("internal.sampleRate");
-    numberChannels = (int) _pool.value<Real>("internal.numberChannels");
-    md5 = _pool.value<std::string>("internal.md5");
-    bit_rate = (int) _pool.value<Real>("internal.bit_rate");
-    codec = _pool.value<std::string>("internal.codec");
-
+    sampleRate = _sampleRateStorage[0];
+    nChannels = _channelsStorage[0];
     // reset, so it is ready to load audio again
     reset();
 }

 void AudioLoader::reset() {
     _network->reset();
-    _pool.remove("internal.md5");
-    _pool.remove("internal.sampleRate");
-    _pool.remove("internal.numberChannels");
-    _pool.remove("internal.codec");
-    _pool.remove("internal.bit_rate");
 }

 } // namespace standard


Remove test for Greek upper/lowercase

Remove test for Greek upper/lowercase

Doesn’t seem to be portable.

--- src/all/sfz/string-utils.test.cpp
+++ src/all/sfz/string-utils.test.cpp
@@ -40,8 +40,8 @@

 TEST_F(StringUtilitiesTest, Upper) {
     std::pair<pn::string_view, pn::string_view> inputs[] = {
-            {"", ""},         {"a", "A"},         {"Na", "NA"},         {"WTF", "WTF"},
-            {"w00t", "W00T"}, {"Ελένη", "Ελένη"}, {"林さん", "林さん"},
+            {"", ""},       {"a", "A"},       {"Na", "NA"},
+            {"WTF", "WTF"}, {"w00t", "W00T"}, {"林さん", "林さん"},
     };
     for (const auto& input : inputs) {
         pn::string      actual   = upper(input.first);
@@ -53,8 +53,8 @@

 TEST_F(StringUtilitiesTest, Lower) {
     std::pair<pn::string_view, pn::string_view> inputs[] = {
-            {"", ""},         {"A", "a"},         {"Na", "na"},         {"ill", "ill"},
-            {"HNO2", "hno2"}, {"Ελένη", "Ελένη"}, {"林さん", "林さん"},
+            {"", ""},       {"A", "a"},       {"Na", "na"},
+            {"ill", "ill"}, {"HNO2", "hno2"}, {"林さん", "林さん"},
     };
     for (const auto& input : inputs) {
         pn::string      actual   = lower(input.first);


Change how alloc_mmap's TemporaryFile class works. Don't expose
the name at all; instead unlink it at the end of the constructor,
so by the time it is fully constructed it is purely an anonymous
file descriptor.

mkstemp has a weird interface and returns the final name of the
file in its template argument. This prevented us from using a
std::string, since c_str's return is const (and we can't use
&string[0], because that might not be NULL-terminated). This
previously required doing nasty things like explicit new/delete
and using strcpy (the strcpy was what got me started on looking
at this; OpenBSD complains about it, so I was trying to figure
out a good way to remove it).

Instead, use the idea from http://www.gotw.ca/gotw/042.htm, and
use a std::vector to hold the mkstemp argument/result. That works
consistently everywhere, and we don't need to rely on strcpy, and
don't have to worry about memory leaks either. Only minor nit is
having to add an explicit NULL terminator as the std::string
doesn't contain it.

--- src/alloc/alloc_mmap/mmap_mem.cpp
+++ src/alloc/alloc_mmap/mmap_mem.cpp
@@ -6,6 +6,7 @@
 */

 #include <botan/internal/mmap_mem.h>
+#include <vector>
 #include <cstring>

 #include <sys/types.h>
@@ -44,38 +45,44 @@
       {
       public:
          int get_fd() const { return fd; }
-         const std::string path() const { return filepath; }

          TemporaryFile(const std::string& base)
             {
-            const std::string path = base + "XXXXXX";
+            const std::string mkstemp_template = base + "XXXXXX";

-            filepath = new char[path.length() + 1];
-            std::strcpy(filepath, path.c_str());
+            std::vector<char> filepath(mkstemp_template.begin(),
+                                       mkstemp_template.end());
+            filepath.push_back(0); // add terminating NULL

             mode_t old_umask = ::umask(077);
-            fd = ::mkstemp(filepath);
+            fd = ::mkstemp(&filepath[0]);
             ::umask(old_umask);
+
+            if(fd == -1)
+               throw MemoryMapping_Failed("Temporary file allocation failed");
+
+            if(::unlink(&filepath[0]) != 0)
+               throw MemoryMapping_Failed("Could not unlink temporary file");
             }

          ~TemporaryFile()
             {
-            delete[] filepath;
+            /*
+            * We can safely close here, because post-mmap the file
+            * will continue to exist until the mmap is unmapped from
+            * our address space upon deallocation.
+            */
             if(fd != -1 && ::close(fd) == -1)
                throw MemoryMapping_Failed("Could not close file");
             }
       private:
          int fd;
-         char* filepath;
       };

    TemporaryFile file("/tmp/botan_");

    if(file.get_fd() == -1)
       throw MemoryMapping_Failed("Could not create file");
-
-   if(::unlink(file.path().c_str()))
-      throw MemoryMapping_Failed("Could not unlink file '" + file.path() + "'");

    if(::lseek(file.get_fd(), n-1, SEEK_SET) < 0)
       throw MemoryMapping_Failed("Could not seek file");


(#6216)  Update the default AMI.

(#6216)  Update the default AMI.

--- src/annexd/GenerateConfigFile.cpp
+++ src/annexd/GenerateConfigFile.cpp
@@ -24,10 +24,9 @@
 	mapping[ "SecretKeyFile" ] = "ANNEX_DEFAULT_SECRET_KEY_FILE";

 	// FIXME: Do something clever for versioning.
-	// (Should these be in the param table?)
 	scratchpad->Assign( "odiDefaultInstanceType", "m4.large" );
 	mapping[ "odiDefaultInstanceType" ] = "ANNEX_DEFAULT_ODI_INSTANCE_TYPE";
-	scratchpad->Assign( "odiDefaultImageID", "ami-83269195" );
+	scratchpad->Assign( "odiDefaultImageID", "ami-35b13223" );
 	mapping[ "odiDefaultImageID" ] = "ANNEX_DEFAULT_ODI_IMAGE_ID";

 	// Append the annex configuration to the user config file.