text:
Q: rescaled metric quantities on rescaling metrics I have the following basic, surely stupid, questions. Assume we have a Riemannian metric $g$ on a manifold $M$. let $a\in\mathbb{R}$ a constant and consider the metric $g_1=ag$. Which are the transformation rules for the scalar and sectional curvature and for the Ricci tensor? For the sectional I guess are the same $K_g(\pi)=K_{g_1}(\pi)$, but what about sectional and Ricci tensor. Moreover how does change the metric on tensors: is it true that $g_1(v,w)=a^{l-m}g(v,w)$ if $v,w$ are $(l,m)$-tensors? Thank you

A: If you look here: http://en.wikipedia.org/wiki/Levi-Civita_connection#Christoffel_symbols you'll see that the Levi-Civita connection for both metrics are the same.  Therefore the curvature tensor is the same.  Since everything else you mentioned is in terms of the curvature tensor and metric, its easy to see what happens.  For example, $K_{g_1} = \frac{1}{a} K_g$.
You also have to be a little careful since the curvature tensors are the same as $(3,1)$ tensors but if you raise or lower indices you will get different tensors (since you're using different metrics to raise/lower).

A: Warning: If $a \leq 0$, the tensor field $g_1 = a g$ will not be a metric and the notion of 'curvature' is not meaningful for $g_1$. However, for $a > 0$ the question is valid, even if $a$ is a smooth positive function on $M$. This is called a 'conformal change' and you will find many transformation laws under this keyword, for instance http://en.wikipedia.org/wiki/List_of_formulas_in_Riemannian_geometry#Under_a_conformal_change


text:
Q: How to display the source code of a website in a console application? I guess this question is somewhat wide but I'm trying to create a C console application (on windows os) that lets the user input the website address and the app will output the source code on the screen.
The second one was for me to traverse to the site source code to extract some contents.
Given that I know how to code in C (or C++), know how to parse user's input to valid web address and that I know how to traverse to a file,
is there any C library out there that lets me do the part of getting data over a website, like it's source code (HTML)?
Many thanks! :)
Update: C++ libraries also accpeted, but please show example of how to do the part of extracting it's source code or a link perhaps, thank you
 :)

A: cURL. Or, for C++, curlpp.

A: I'm not sure if there is any C standard library to fetch the website content. But I guess you need something like wget. For example, try the following:
wget http://stackoverflow.com/

The website content will get stored in index.html.
OTOH, you can explore libcurl here.

A: You could try something with telnet. If you connect to a server with telnet on port 80, type
GET /<webpage.htm> HTTP/1.1

and press enter twice, you'll get the complete HTTP reply and the html source code of the webpage.
Hope this helps!

A: try maybe:
system("URL2FILE filesource filedestination");
http://www.chami.com/free/url2file_wincon.html

A: This is a small program , i made to extract & save/write Facebook account source code in a text file. You can change it with your need ( you can change "http://www.facebook.com" with "http://www.google.com/").. Also remember to link wininet.a (library) to your project. Hope it will help :)
#include <windows.h>
#include <wininet.h>
#include <iostream>
#include <conio.h>
#include <fstream.h>
fstream fs_obj;
using namespace std;

int main(int argc, char *argv[])
{
  fs_obj.open("temp.txt",ios::out | ios::app);
  HINTERNET hInternet = InternetOpenA("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
  HINTERNET hConnection = InternetConnectA( hInternet, "www.facebook.com", 80, " "," ", INTERNET_SERVICE_HTTP, 0, 0 ); //enter url here
  HINTERNET hData = HttpOpenRequestA( hConnection, "GET", "/", NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0 );

  char buf[ 2048 ] ; string total;
  HttpSendRequestA( hData, NULL, 0, NULL, 0 ) ;
  DWORD bytesRead = 0 ;
  DWORD totalBytesRead = 0 ;

  while( InternetReadFile( hData, buf, 2000, &bytesRead ) && bytesRead != 0 )
  {
    buf[ bytesRead ] = 0 ; // insert the null terminator.
    total=total+buf;
    printf( "%d bytes read\n", bytesRead ) ;

    totalBytesRead += bytesRead ;
  }

  fs_obj<<total<<"\n--------------------end---------------------\n";
  fs_obj.close();
  printf( "\n\n END -- %d bytes read\n", bytesRead ) ;
  printf( "\n\n END -- %d TOTAL bytes read\n", totalBytesRead ) ;
  cout<<total; //it will print source code in console window
  cout<<endl<<total<<endl; //it will save source code to (temp.txt) file
  InternetCloseHandle( hData ) ;
  InternetCloseHandle( hConnection ) ;
  InternetCloseHandle( hInternet ) ;
  system("pause");
}

Rename temp.txt with temp.html , open it with browser you will get that webpage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detect if none of the EditTexts has focus I have a few EditTexts in my activity. The problem is simple: If none of them has focus, I will show a button. If any of them has focus, I will hide the button.
Here's what I did:
    usernameEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            usernameFocus = hasFocus;
            adjustVisibility();
        }
    });

    passwordEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            passwordFocus = hasFocus;
            adjustVisibility();
        }
    });

    private void adjustVisibility() {
        if(usernameFocus || passwordFocus) {
            button.setVisibility(View.GONE);
        } else {
            button.setVisibility(View.VISIBLE);
        }
    }

The problem:
When I change focus from one EditText to the other, the button gets momentarily visible between the focus change. I want to eliminate that. Any suggestions on how to achieve it?
Further elaboration of the problem when a user clicks on the password field after filling up the username field:
BUTTON INVISIBLE

*

*Username Field has focus

*onFocusChange() of Username field gets called

*Username Field loses focus

BUTTON IS VISIBLE

*onFocusChange() of password field gets called

*password field gets focus.

BUTTON INVISIBLE
Clearly, between points 3 and 4, neither username field nor password field has focus. In that small fraction of time, the button becomes visible, which is what I'm trying to get rid of.

A: Put some delay if you don't want to display between switching from one edittext to other
  private void adjustVisibility() {
    if (usernameFocus || passwordFocus) {
        mButtonVisible.setVisibility(View.GONE);
    } else {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 5s = 5000ms
                if (usernameFocus || passwordFocus) {
                    mButtonVisible.setVisibility(View.GONE);
                } else {
                    mButtonVisible.setVisibility(View.VISIBLE);
                }
            }
        }, 5000);
    }
}

A: Try This:
if(parentView.getCurrentFocus() instanceof EditText)
{
   //Hide Buttom
}else{
   // Show Button
}

A: Before calling adjust visibility in focus change listener just check if the other edit text does not have focus like below.
 usernameEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        usernameFocus = hasFocus;
        if(!passwordEditText.hasFocus())
        adjustVisibility();
    }
});

passwordEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        passwordFocus = hasFocus;
        if(!usernameEditText.hasFocus())
        adjustVisibility();
    }
});

See if this solves your problem.


text:
Q: ASP.Net Error in inserting Data To OleDb I keep getting this error. I read that OleDb doesn't support named parameters so I changed them to (?, ?).
But is keep getting the same error

System.Data.OleDb.OleDbException: Syntax error in INSERT INTO
  statement. at
  System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
  hr) at
  System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
  dbParams, Object& executeResult) at
  System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
  executeResult) at
  System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
  behavior, Object& executeResult) at
  System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
  behavior, String method) at
  System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at
  Registration.ImageButton1_Click(Object sender, ImageClickEventArgs e)
  in c:\Users\Nirre\Desktop\Cti Project\Book Club TRY
  2\Registration.aspx.cs:line 51

Here is the code in the .cs class
 protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    if (IsPostBack)
    {
        OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        conn.Open();
        string insCmd = @"INSERT COUNT(*) INTO Registration(UserName, [Password], EmailAddress, FullName, Country, PasswordRecovery)
                     VALUES (?, ?, ?, ?, ?, ?)";
        OleDbCommand insertUser = new OleDbCommand(insCmd, conn);
        insertUser.Parameters.AddWithValue("@UserName", txtUserName.Text);
        insertUser.Parameters.AddWithValue("@Password", txtPassoword.Text);
        insertUser.Parameters.AddWithValue("@EmailAddress", txtEmail.Text);
        insertUser.Parameters.AddWithValue("@FullName", txtFullName);
        insertUser.Parameters.AddWithValue("@Country", DdlCountry.SelectedItem.ToString());
        insertUser.Parameters.AddWithValue("@PasswordRecovery", txtAnswer.Text);

        try
        {
            insertUser.ExecuteNonQuery();
            conn.Close();
            Response.Redirect("Login.aspx");
        }
        catch (Exception er)
        {
            Response.Write(er);
            lblError.Visible = true;
            lblError.Text = "An error has ocured pleas try again...!";
        }
        finally
        {
            // Code
        }
    }
}

A: INSERT COUNT(*) is not a valid SQL statement, simply remove COUNT(*) and the rest of your code seems correct.
See here for refs

A: string insCmd = @"INSERT COUNT(*) INTO Registration(UserName, [Password], EmailAddress, FullName, Country, PasswordRecovery)
                     VALUES (?, ?, ?, ?, ?, ?)";

Should be
string insCmd = @"INSERT INTO Registration(UserName, [Password], EmailAddress, FullName, Country, PasswordRecovery)
                     VALUES (@UserName, @Password, @EmailAddress, @FullName, @Country, @PasswordRecovery)";

I don't understand what did you want to do with COUNT. If you want to then return number of affected rows, just add return parameter and assign @@ROWCOUNT to it
Edit: I've never used question marks as parameter placeholders outside Reporting Services so try replacing them with named parameters as shown above.


text:
Q: How to use Require.js with angularjs for lazy load I am developing the app with angularjs and codeigniter. And I have done with it( DEMO app ), mostly.
What I want to do is: implement lazy loading or don't want to include all these files at start, just include when needed.
Here is my Layout HEAD tag including the required js and css files.
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>UMS : Admin </title>
    <!-- added for Angular JS -->
    <link href="<?php echo base_url(); ?>angular/css/loading-bar.min.css" rel="stylesheet">
    <link href="<?php echo base_url(); ?>angular/css/animation.css" rel="stylesheet">
    <link href="<?php echo base_url(); ?>angular/css/angular-chart.css" rel="stylesheet">
    <!-- added for Angular JS -->

    <!-- Bootstrap Core CSS -->
    <link href="<?php echo base_url(); ?>bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- MetisMenu CSS -->
    <link href="<?php echo base_url(); ?>bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">

    <!-- Timeline CSS -->
    <link href="<?php echo base_url(); ?>dist/css/timeline.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="<?php echo base_url(); ?>dist/css/sb-admin-2.css" rel="stylesheet">

    <!-- Morris Charts CSS -->
    <link href="<?php echo base_url(); ?>bower_components/morrisjs/morris.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="<?php echo base_url(); ?>bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>

<body>
    <!-- jQuery -->
    <script src="<?php echo base_url(); ?>bower_components/jquery/dist/jquery.min.js"></script>
    <!-- jQuery -->
    <!-- Bootstrap Core JavaScript -->
    <script src="<?php echo base_url(); ?>bower_components/bootstrap/dist/js/bootstrap.min.js"></script>

    <!-- Metis Menu Plugin JavaScript -->
    <script src="<?php echo base_url(); ?>bower_components/metisMenu/dist/metisMenu.min.js"></script>

    <!-- DataTables JavaScript REMOVED -->

    <!-- Custom Theme JavaScript -->
    <script src="<?php echo base_url(); ?>dist/js/sb-admin-2.js"></script>

    <!-------------Angular js------------------->
    <script src="<?php echo base_url();?>angular/js/angular.min.js"></script>
    <script src="<?php echo base_url();?>angular/js/angular-route.min.js"></script>
    <!-- flash msg -->
    <script src="<?php echo base_url();?>angular/js/angular-flash.js"></script>
    <!-- flash msg -->
     <!--loading bar-->
   <script src="<?php echo base_url();?>angular/js/loading-bar.min.js"></script>
   <script src="<?php echo base_url();?>angular/js/angular-animate.min.js"></script>
    <!--loading bar-->
    <!-- charts-->
    <script src="<?php echo base_url();?>angular/js/chart.min.js"></script>
    <script src="<?php echo base_url();?>angular/js/angular-chart.min.js"></script>
    <!--[if lt IE 9]><script src="<?php echo base_url();?>angular/js/IE8_9/excanvas.js"></script><![endif]-->
    <!--[if lt IE 9]><script src="<?php echo base_url();?>angular/js/IE8_9/es5-shim.js"></script><![endif]-->
    <!-- charts-->
    <!-- core angular APPLICATION specific -->
    <script src="<?php echo base_url();?>angular/js/admin/demo_angular.js"></script>
    <script src="<?php echo base_url();?>angular/js/admin/app.js"></script>
    <script src="<?php echo base_url();?>angular/js/admin/demo-dropdown-controller.js"></script>
    <!-- core angular APPLICATION specific -->
    <!--Directives developed by VANESH -->
    <script src="<?php echo base_url();?>angular/js/angular-directives.js"></script>
    <!--Directives developed by VANESH -->
    <!-- ui bootstrap pagination -->
    <script src="<?php echo base_url();?>angular/js/ui-bootstrap-tpls-0.12.0.js"></script>
    <!-- ui bootstrap pagination -->

    <!-------------Angular js------------------->

Here is my app. js (just showing the structure or how i am injecting the dependancies)
/* this is the angular js file for our UMS */
var base_url="http://localhost/ums/";
/* angularapp (asssigned to html tag in view) */
/* angularControllers is module created in demo_angular.js */
var angularapp = angular.module('angularapp', ['ngRoute','angularControllers','flash','angular-loading-bar','ngAnimate','ui.bootstrap','input_match','uniqueField','uniqueEdit','chart.js']);
angularapp.config(['$routeProvider', function($routeProvider){

// routing configuration.......
}]);

Here is another js (demo_angular.js) where i have/had bunhch of controllers named as single module.
 var base_url="http://localhost/ums/";
    var angularControllers = angular.module('angularControllers', ['flash']);
    angularControllers.controller('AddUserCtrl', ['$scope','$http', '$timeout','Flash', function($scope,$http, $timeout,Flash)
    {/*...doing stuff...*/}
    //other controllers same like above (edit user, all users, delete user, delete users...)

This app is working fine! Just there is need to implement lazy load(that i don't know).
    Listen about Require.js.
Main Problem: How to use Require.js in this (my app: mentioned above).
Please do suggest some important with example.
IMPORTANT:

*

*Is there anyone who can guide me (above) app specific? Means how my app.js and demo_angular.js will look like? how my main.js and require.js will look like? NOTE: I am injecting dependancies in app and controllers, dependancies in the sense services, directives, which are constructed or third party

A: There is a very good  example which can help you?
Lazy Loading with Require js and Angualar js
Your main.js will look like
'use strict';
var app = angular.module('app', ['ngRoute']);

require js will look like
require.config({
    baseUrl: './scripts/',
    urlArgs: 'v=1.1',
    waitSeconds: 200,
    paths: {

        'jquery': './libs/jquery.min',
        'jquery-migrate.min': './libs/jquery-migrate.min',
        'jquery-ui.min': './libs/jquery-ui.min',
        'jquery.mobile.custom.min': './libs/jquery.mobile.custom.min',
        'jquery.easyui.min': './libs/jquery.easyui.min',
        'angular-resource': './libs/1.3.14/angular-resource.min',
        'angular': './libs/1.3.14/angular.min',
        'angular-route': './libs/1.3.14/angular-route.min',
        'angular-animate': './libs/1.3.14/angular-animate.min',
        'bootstrap': './libs/bootstrap',
        'toastr': './modules/toastr',
        'jsapi': './libs/jsapi',
        'ngPopover': './modules/ngPopover',
        'angular-file-upload': './modules/angular-file-upload',
        'ckeditor': './javascripts/ckeditor4.4.7/ckeditor',
        //'ng-infinite-scroll.min': './modules/ng-infinite-scroll.min',
        'app': 'app',
        'tr': './modules/tr',
        'en': './modules/en',
        'hi': './modules/hi',
        'ru': './modules/ru',
        'fr': './modules/fr',
        'de': './modules/de',
    }
});
require(
    {
        shim: {
            //*************Jquery*****************
            'angular-resource': {
                deps: ['angular']
            },
            'angular-route': {
                deps: ['angular']
            },
            'jquery-migrate.min': {
                deps: ['jquery']
            },
            'jquery-ui.min': {
                deps: ['jquery',
                    'jquery-migrate.min']
            },
            'jquery.easyui.min': {
                deps: ['jquery',
                    'jquery-migrate.min']
            },
            'libs/shoppingCart': {
                deps: ['jquery']
            },

            //Jquery ends

            //************bootstrap**************
            'bootstrap': {
                deps: ['jquery',
                    'jquery-migrate.min',
                    'jquery-ui.min']
            },
            'javascripts/theme': {
                deps: ['jquery', 'jquery-ui.min',
                    'javascripts/plugins/autosize/jquery.autosize-min',
                    'javascripts/plugins/charCount/charCount',
                    'javascripts/plugins/bootstrap_maxlength/bootstrap-maxlength.min',
                    //'javascripts/plugins/bootstrap_datetimepicker/bootstrap-datetimepicker',
                    'javascripts/plugins/bootstrap_daterangepicker/bootstrap-daterangepicker',
                    //'javascripts/plugins/common/bootstrap-wysihtml5',
                    'javascripts/plugins/nestable/jquery.nestable',
                    'javascripts/plugins/tabdrop/bootstrap-tabdrop',
                    //'javascripts/plugins/naked_password/naked_password-0.2.4.min',
                    'javascripts/plugins/datatables/jquery.dataTables.min',
                    'javascripts/plugins/datatables/jquery.dataTables.columnFilter',
                    'javascripts/plugins/bootstrap_colorpicker/bootstrap-colorpicker.min',
                    'javascripts/plugins/modernizr/modernizr.min']
            },
            //bootstrap ends

            //***********plugins*****************
            //'javascripts/plugins/msdropdown/jquery.dd': {
            //    deps: ['libs/jquery']
            //},
            'javascripts/plugins/select2/select2': {
                deps: ['jquery',
                    'bootstrap']
            },
            'javascripts/plugins/timeago/jquery.timeago': {
                deps: ['javascripts/theme']
            },
            'javascripts/plugins/autosize/jquery.autosize-min': {
                deps: ['jquery']
            },
            'javascripts/plugins/charCount/charCount': {
                deps: ['jquery']
            },
            'javascripts/plugins/bootstrap_maxlength/bootstrap-maxlength.min': {
                deps: ['jquery']
            },
            //'javascripts/plugins/common/wysihtml5.min': {
            //    deps: ['jquery']
            //},
            //'javascripts/plugins/common/bootstrap-wysihtml5': {
            //    deps: ['jquery', 'javascripts/plugins/common/wysihtml5.min']
            //},
            'javascripts/plugins/nestable/jquery.nestable': {
                deps: ['jquery']
            },

            'javascripts/plugins/bootstrap_daterangepicker/bootstrap-daterangepicker': {
                deps: ['jquery']
            },

            'javascripts/plugins/tabdrop/bootstrap-tabdrop': {
                deps: ['jquery']
            },
            'javascripts/plugins/naked_password/naked_password-0.2.4.min': {
                deps: ['jquery']
            },
            'javascripts/plugins/datatables/jquery.dataTables.min': {
                deps: ['jquery']
            },
            'javascripts/plugins/datatables/jquery.dataTables.columnFilter': {
                deps: ['jquery']
            },
            'javascripts/plugins/bootstrap_colorpicker/bootstrap-colorpicker.min': {
                deps: ['jquery']
            },
            'javascripts/plugins/modernizr/modernizr.min': {
                deps: ['jquery']
            },
            'javascripts/plugins/bootbox/bootbox.min': {
                deps: ['jquery']
            },
            'javascripts/plugins/validate/jquery.validate.min': {
                deps: ['jquery',
                    'jquery-ui.min',
                    'javascripts/theme']
            },
            'javascripts/plugins/FlowJs/flow': {
                deps: ['jquery']
            },
            'javascripts/plugins/FlowJs/fusty-flow': {
                deps: ['jquery',
                    'javascripts/plugins/FlowJs/flow']
            },
            'javascripts/plugins/FlowJs/fusty-flow-factory': {
                deps: ['jquery']
            },
            'javascripts/plugins/validate/jquery.validate.min': {
                deps: ['bootstrap']
            },
            'javascripts/plugins/validate/additional-methods': {
                deps: ['javascripts/plugins/validate/jquery.validate.min']
            },
            'javascripts/JsCookies': {
                deps: ['jquery']
            },
            'ckeditor' : {
                deps: ['jquery']
            },
            //plugins end

            //***********modules*****************
            'modules/resettableForm': {
                deps: ['angular']
            },
            'toastr': {
                deps: ['jquery-migrate.min']
            },
            'modules/resettableForm': {
                deps: ['angular',
                    'toastr']
            },
            'modules/angular-gettext': {
                deps: ['angular']
            },
            'modules/angular-multi-select': {
                deps: ['app']
            },
            'modules/common': {
                deps: ['angular',
                    'toastr']
            },
            'modules/logger': {
                deps: ['angular',
                    'modules/common']
            },
            'modules/ui-bootstrap-tpls-0.9.0': {
                deps: ['angular',
                    'toastr']
            },
            'modules/bootstrap.dialog': {
                deps: ['angular',
                    'modules/ui-bootstrap-tpls-0.9.0',
                    'modules/common']
            },
            'modules/translations': {
                deps: ['app']
            },
            'modules/loading-bar': {
                deps: ['app']
            },
            'angular-file-upload': {
                deps: ['angular', 'toastr']
            },
            //'ng-infinite-scroll.min': {
            //    deps: ['angular']
            //},
            'ngPopover': {
                deps: ['app']
            },

            //'modules/SharedServices': {
            //    deps: ['app']
            //},
            'modules/ng-flow': {
                deps: ['app',
                    'angular']
            },
            'en': {
                deps: ['app']
            },
            'fr': {
                deps: ['app']
            },
            'de': {
                deps: ['app']
            },
            'hi': {
                deps: ['app']
            },
            //'modules/tr': {
            //    deps: ['app']
            //},
            'ru': {
                deps: ['app']
            },
            'modules/paypalfactory': {
                deps: ['app']
            },
            'angular-animate': {
                deps: ['app']
            },

            //'modules/ngAutocomplete': {
            //    deps: ['app']
            //},
            'modules/bootstrap-select.min': {
                deps: ['app']
            },

            //modules end

            //***********Angular Common*****************
            'app': {
                deps: ['angular',
                    'angular-route',
                    'angular-resource',
                    'libs/Base64',
                    'libs/moment',
                    'modules/common',
                    'angular-file-upload']//,
                //'modules/ngAutocomplete']
            },
            'routes': {
                deps: ['app']
            },
            //Angular Common ends

            //***********Angular Controllers***********
            'controllers/manageEbayScheduledInventoryController': {
                deps: ['app']
            },

            'jsapi': {
                deps: ['app']
            },

            //'controllers/googleChartController': {
            //    deps: ['app', 'libs/jsapi']
            //},

            //Angular Controller ends

            //***********Angular Services*************
            'services/manageEbayScheduledInventoryService': {
                deps: ['app']
            },

            //Angular Utility Services Ends

            //Angular Filters
            'filters/ellipsis': {
                deps: ['app']
            },

            //Angular Filters ends

            //Angular Directives
            'directives/passwordValidate': {
                deps: ['app']
            },

        }
    },
    // Including all of the modules to allow concencation and minification for deployment
    [
         //*************Jquery*****************'
         'jquery', 'libs/moment', 'jquery.easyui.min',
         //Jquery ends

         //************bootstrap**************
          'bootstrap', 'javascripts/theme', 'libs/shoppingCart',
         //bootstrap ends

         //***********plugins*****************
          /*'javascripts/plugins/msdropdown/jquery.dd',*/ 'javascripts/plugins/select2/select2', 'javascripts/JsCookies', 'javascripts/plugins/bootbox/bootbox.min',
          'javascripts/plugins/FlowJs/flow', 'javascripts/plugins/FlowJs/fusty-flow', 'javascripts/plugins/FlowJs/fusty-flow-factory',
          'javascripts/plugins/validate/jquery.validate.min', 'javascripts/plugins/timeago/jquery.timeago','ckeditor',
         //plugins end

         //***********modules*****************
         'toastr', 'modules/resettableForm', 'modules/angular-gettext', 'modules/angular-multi-select', 'modules/common', 'modules/logger',
         'modules/ui-bootstrap-tpls-0.9.0', 'modules/bootstrap.dialog', 'modules/translations', 'ngPopover', //'modules/SharedServices',
         'modules/ng-flow', 'en', 'de', 'fr', 'hi',  'ru', //'modules/tr',
         'modules/paypalfactory', 'modules/loading-bar', 'angular-animate', 'modules/bootstrap-select.min', 'angular-file-upload', //'ng-infinite-scroll.min', //'modules/ngAutocomplete',
         //modules end

         //***********Angular Common*****************
         'app', 'routes', 'jsapi',
         //Angular Common ends

        //***********Angular Controllers***********'controllers/supplierController',
          'controllers/manageEbayScheduledInventoryController',

        //Angular Controller ends

        //***********Angular Services*************'services/supplierService','services/uploadManagerService','services/createPurchaseOrderService',
        'services/manageEbayScheduledInventoryService',
         //Angular Services ends

         //Angular Utility Services Starts
         'services/sortingService',
         //Angular Utility Services Ends

         //Angular filters
        'filters/ellipsis', 'filters/currency',
         //Angular filters ends

         //Angular Directive
         'directives/passwordValidate', 'directives/focus', 'directives/mypopover', 'directives/priceBox', 'directives/onDragStart'
    ],
    function () {
        angular.bootstrap(document, ['app']);
    }
);

In reuire.js you can find how dependecy is working
'javascripts/plugins/timeago/jquery.timeago': {
                    deps: ['javascripts/theme']
                },

Here javascripts/plugins/timeago/jquery.timeago  depends on  'javascripts/theme'
You can refer this link also it is a very good example


text:
Q: Add Additional Objects to JSON Encoded Array I am currently using a JSON encoded array to display the users in my database for an auto-suggest feature.
It looks something like this:
$sth = mysql_query("SELECT id, name FROM users");

$json = array();

    while($row = mysql_fetch_assoc($sth)) {
        $json['name'] = $row['name'];
        $json['id'] = $row['id'];
        $data[] = $json;
    }

print json_encode($data);

This returns:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"}]

My question is somewhat 2-fold:
First, how would I manually add an additional object to this output?  For example, let's say I wanted to add:  {"id":"444","name":"A New Name"}
Thus, it'd look like:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"},{"id":"444","name":"A New Name"}]

Second, let's say I also wanted to add more objects to the array from a separate table as well, such as:
$sth = mysql_query("SELECT id, title FROM another_table");

$json = array();

    while($row = mysql_fetch_assoc($sth)) {
        $json['name'] = $row['title'];
        $json['id'] = $row['id'];
        $data[] = $json;
    }

print json_encode($data);

This way I could have both tables populated in the JSON array, thus, showing up as additional options in my autosuggest.
Hopefully this makes sense, as I've tried hard to articulate what I am trying to accomplish.
Thanks!

A: Try in this way:-
$temp = json_encode($json);  //$json={"var1":"value1","var2":"value2"}
$temp=substr($temp,0,-1);
$temp.=',"variable":"'.$value.'"}';

A: Just keep pushing to the $data array.
$json = array();

    while($row = mysql_fetch_assoc($sth)) {
        $json['name'] = $row['name'];
        $json['id'] = $row['id'];
        $data[] = $json;
    }

$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;

Then at the very end, do your json_encode. Assuming you're not referring to merging it in the JS itself with multiple ajax calls.
And if you have separate scripts, combine them in one php page.

A: You could edit the JSON (text), but it's much easier to modify the array before you encode it.
Or am I missing something?

A: I'm not an expert in any of these fields, but I'll try and see if I can help.  Try one of these:
Option 1 (I don't know how unions work in mysql):
$sth = mysql_query("SELECT id, name FROM users union SELECT id, name FROM (SELECT id, title as name from another_table) as T2");

    $json = array();

        while($row = mysql_fetch_assoc($sth)) {
            $json['name'] = $row['name'];
            $json['id'] = $row['id'];
        }

    $json['name'] = 'A new name';
    $json['id'] = '444';
    $data[] = $json;

    print json_encode($data);

I've never done PHP, so I'm making assumptions.  I've also never used MySql, so there's more assumptions.
Option 2:
$sth = mysql_query("SELECT id, name FROM users");

    $json = array();

        while($row = mysql_fetch_assoc($sth)) {
            $json['name'] = $row['name'];
            $json['id'] = $row['id'];
        }

$sth = mysql_query("SELECT id, title from another_table");

        while($row = mysql_fetch_assoc($sth)) {
            $json['name'] = $row['title'];
            $json['id'] = $row['id'];
        }

    $json['name'] = 'A new name';
    $json['id'] = '444';
    $data[] = $json;

    print json_encode($data);

Hope this helps.


text:
Q: How do I select nth element in a given set How do I select first span, second span or last span for the following html?

    Text

How can I select the nth element in a given set?

A: Use the nth-child selector:
span:nth-child(2) {}

This selects the first span since it's the second child. If you want to select the second span, you can use this instead:
span:nth-of-type(2) {}

You can also use first-child, last-child, nth-child(odd) or nth-child(even), among others.

A: use n-th child if i make that code for example in this way i Specify  background color is blue for  every   tag element that is the second child of it parent is:
p:nth-child(2) {
background: blue;
}

A: The :nth-child selector allows you to select one or more elements based on their source order, according to a formula
The formula is constructed using the syntax an+b, where:
"a" is an integer value
"n" is the literal letter "n"
"+" is an operator and may be either "+" or "-"
"b" is an integer and is required if an operator is included in the formula

Here are some ways you can achieve this as per your requirement:
div span:first-child {

}
div span:nth-child(an+b) {

}
div span:last-child {

}

Here are some other relative properties you can use as well:

*

*nth-last-child

*nth-of-type

*nth-last-of-type

*first-of-type

*last-of-type


text:
Q: Move a file and rename it Figured PHP's rename would be my best bet. I didn't see many examples on how to use relative URLs in it though, so I kind of compromised. Either way, this give me permission denied:
I want to do this:
$file = "../data.csv";
rename("$file", "../history/newname.csv");

Where ../ of course would go back 1 directory from where the script is being ran. I couldn't figure out a way...so I did this instead:
$file = "data.csv";
$path = dirname(realpath("../".$file));
rename("$path/$file", "$path/history/newname.csv");

However I am getting permission denied (yes the history folder is owned by www-data, and yes data.csv is owned by www-data). I thought it was weird so I tried a simple test:
rename( 'tempfile.txt', 'tempfile2.txt' );

and I made sure www-data had full control over tempfile.txt...still got permission denied. Why? does the file your renaming it to have to exist? can you not rename like linux's mv? So I instead just copy() and unlink()?

A: In order to move a file from "../" to "../history/", a process needs write permission to both "../" and "../history/".
In your example, you're obviously lacking write permission to "../". Permissions for the file being moved are not relevant, by the way.

A: Not only ownership plays a role, but also file permissions. Make sure that the permissions are set up correctly on the source file and destination directory (e.g. chmod 644 data.csv).
Is www-data the same user as Apache?
Edit: Take care to provide existing, absolute paths to realpath(). Also beware of the following:
$path = dirname(realpath("../".$file));

This might yield nothing, because the file ../data.csv might not exist. I.e., the result of realpath() on a non-existent file is false.
Here's some code that might work better for you:
$file = "data.csv";
$path1 = realpath($file);
$path2 = realpath(dirname($file).'/..').'/history/newname.csv';
rename($path1, $path2);

You should be extremely careful that $file cannot be edited by the visitor, because he could change a request manipulate which file is renamed to where.


text:
Q: Is there a way to clone elements using JQuery? Is there a way to clone HTML elements using JQuery?
However, I want to be able to assign the cloned elements new attributes "id, name". So if I had a textfield element, I want to clone it without its value and change its id and name attribute to "exmple2" if it was named "example" previously.
I would appreciate any help on this and any other implementation I can use to add more elements to my html form that already exists on the page.
Thanks all

A: Once you have a cloned element you can change it any way you want to
Updated: Didn't notice that you wanted to change both name and id.
$("#example").clone()
             .attr({"id":"example2", "name":"example2"})
             .html("new content")
             .appendTo("#container");

A: documentation
I use jQuery over $ so it works with other libraries. Here is an example on an input text field.
jQuery('#example').clone().val('').attr('id', 'exmple2').attr('name', 'exmple2').insertAfter('#example');

If you want to clone the event handlers as well, you have to use clone(true).

A: Here is sample of creating clone using jquery.
Html code::

<input type="text" name="text" id="text"/>

<input type="button" value="Add New Div" onclick="addNewDiv();" style="background-color: #3E8DE1; color: white;" />

Javascript code::
var count=1;

function addNewDiv(){
    var $clone = $(".cloneTable:first").clone(true);
        $clone.find(':text,:file').each(function() {
            $(this).attr('id',($(this).attr("id")+count));
            $(this).val('');
        });
         $clone.find("a").each(function() {
              $(this).val('').attr('id', function(_, id) {
                return count;
              });
            });
         $clone.find("span").each(function() {
             $(this).attr({
                id: $(this).attr("id") + count
         });
        });

              $clone.attr( 'id', function() {

                  return this.id + count; })

         .appendTo('#addNewDiv');
    count=count+1;
  }

Here is the link of fiddle of same example. Clone Fiddle


text:
Q: MacBook Pro updated to EL Captain 10.11 but QuickTime Player didn't upgrade The ONLY reason I upgraded to EL Captain because the new QuickTime Player allows me to make a video of my app while I play on my device. However, I've upgraded to EL Captain 10.11 but the QuickTime Player is still version 10.4
The El Capitan upgrade went smoothly for my MacBook Pro. Everything works well. How do I update the QuickTime Player? I tried going through App store but in search, I couldn't find it.

A: QuickTime 10.4 is the newest version. It was already possible to record your iOS-device in Yosemite. Source.


text:
Q: Libcurl SSL certificate verification I made a simple program to send/receive XML from a server through HTTPS and libcurl. I just disbaled the certificate & server verification by setting CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST as 0. With this the connection is happening from one machine and able to get XML. But from other machine, I get 77 error from curl always. But when I run curl command with -k option on the error-machine, I get proper XML from server. http://curl.haxx.se/docs/sslcerts.html says the above two options are enough, aren't they enough? How can I make the libcurl library to work the same way as curl command in this case?
liburl version, On success machine: curl-7.15.5-9.el5, curl-devel-7.15.5-9.el5.
liburl version, On error-machine :curl-7.19.7-26.el6_1.2.x86_64, curl-7.19.0-8.el6.x86_64, libcurl-7.19.7-26.el6_1.2.i686, libcurl-7.19.7-26.el6_1.2.x86_64
Platfor: Linux, Language: C.

A: Found :)
the binary was compiled with old lib-curl version 3. but the error-machine has only version 4. Also somebody made a link to version 4 with name of version 3. so after compiling with libcurl4 it worked like charm... :)


text:
Q: $x^2+3$ has two zeros over ${\Bbb F}_p$ provided that $x^2+x+1\in{\Bbb F}_p[x]$ has two? The following is an exercise in abstract algebra:

If $p=1\pmod{3}$, then $x^2+x+1\in\Bbb{F}_p[x]$ has two zeros. Prove in this case that $-3$ is a quadratic residue mod $p$.

Showing that $(x^2+x+1)\mid (x^p-x)$, one can get the first part done. But I don't see how the second part, namely, $x^2+3\in\Bbb{F}_p[x]$ has two zeros, can be deduced from the first one. Could one come up with some hints of how to get the first part? (I was thinking one might relate $x^2+3$ to $x^2+x+1$ to make an argument about the zeros of $x^2+3$. But I don't see how I can go on.)

A: The motivation is that $\sqrt{-3}$ is a root of the first and the second has roots ${-1\pm\sqrt{-3}\over 2}$, where these are understood in the more general sense of finite field elements, since the quadratic formula works for any field of characteristic not $2$.
But then it is clear how to get the roots of the second from the first, we can assume $p>3$ from the condition, so that we have that $2^{-1}$ exists in the field, hence we just note that if $\zeta_1,\zeta_2$ are the roots of $x^2+x+1$ we have that $2\zeta_i+1$ are the two roots to $x^2+3$, in other words they are the two things which square to $-3$, proving it is a quadratic residue. You can check this directly as well, even if you don't believe the intuition from the classical quadratic formula, just letting the $\zeta_i$ to be the roots of $x^2+x+1$ we have

$$(2\zeta_i+1)^2+3=4\zeta_i^2+4\zeta_i+1+3=4(\zeta_i^2+\zeta_i+1)=4\cdot 0=0.$$

A: Complete the square. We have $x^2+x+1\equiv 0\pmod{p}$ iff $4x^2+4x+4\equiv 0\pmod{p}$ iff $(2x+1)^2\equiv -3\pmod{p}$.
Remark: Let $F$ be any field that has characteristic $\ne 2$. Then we can make precisely the same argument: We have $x^2+x+1=0$ if and only if $4x^2+4x+4=0$ if and only if $(2x+1)^2=-3$. So if $x^2+x+1=0$ has a solution, then $w^2=-3$ has a solution. And if $w^2=-3$, then by solving $2x+1=w$ we obtain a solution of $x^2+x+1=0$.

A: The map $f\colon x\mapsto 2x+1$ maps roots of $x^2+x+1$ to roots of $x^2+3$. Indeed, $$f(x)^2+3=(2x+1)^2+3=4(x^2+x+1)=0$$ whenever $x^2+x+1=0$.
On the other hand, if $2$ is invertible, then the map $g\colon x\mapsto \frac12(x-1)$ maps roots of $x^2+3$ to roots of $x^2+x+1$. Indeed, $$g(x)^2+g(x)+1=\frac14(x-1)^2+\frac12(x-1)+1=\frac14(x^2+3)=0$$ whenever $x^2+3=0$.
Since $f$ and $g$ are inverse maps (if $2$ is invertible), they show that the sets of roots of $x^2+3$ and $x^2+x+1$ are in bijection, hence of the same cardinality.
Of course, the claim is trivially true for $\mathbb F_2$ (though it would be wrong for $\mathbb F_4$, which has two roots of $2^2+x+1$ and only one root of $x^2+3$)


text:
Q: $ctrl object not available in transcluded scope? I am unable to access the $ctrl scope binding of a new angular.component() when using ng-transclude.
I want to access $ctrl in place of a .controller() on the page as we're looking to migrate to angular2 down't the track.
There's a plunkr here demonstrating this: https://plnkr.co/edit/M4k7Av8Q2OrMSsvhZjsb?p=preview
Hopefully someone can shed some light! Code below:
// app.js

angular.module('test.app', [])

.component('transcludedComponent', {
  transclude: true,
  template: '

',
  controller: function(){
    this.text = 'hello world'
  }
})

.component('regularComponent', {
  template: '
{{$ctrl.otherText}}
',
  controller: function(){
    this.otherText = 'this binding works';
  }
});

angular.element(document.body).ready(function(){
    angular.bootstrap(document, ['test.app']);
});

<transcluded-component>

transcluded text has no $ctrl: {{ $ctrl.text }}

  <regular-component></regular-component>
</transcluded-component>

A: Anyone who has the same issue, I just ended up using $parent in place of $ctrl to access the correct scope. Hacky as hell, but it works.


text:
Q: Magicsuggest replace letters when user is typing i use the Magicsuggest with JSON Output.
In my database i have some Words with html for example ä = & auml; and so on.
The Magicsuggest-List shows the html tags correctly. But it is not possible to search for it.
For example: When the user types München, the suggest is 0, when the User types München the suggest is 1.
Can i replace the ü to & uuml; in the background?

A: The list of combo options that fills the component is provided by your server call. Transform the data's html entities on the server side before serving them to MagicSuggest.


text:
Q: In Cascading dropdown fails but first works fine using jquery Ajax I have a dropdown that lists the data fetched from database using PHP and jQuery Ajax.

*

*First dropdown List fetches data successfully and populates it in the dropdown.

HTML for first dropdownlist :
$(document).ready(function () {
        $(function() {
            $.ajax({
                type: 'POST',
                url: 'getGroupzBase.php',
                datatype: 'json',
                success: function(data) {
                // Call this function on success
                    console.log(data);
                   var yourArray = JSON.parse(data);
                   console.log(yourArray);
                    $.each(yourArray, function (index, yourArray) {
                        $('#builder_group').append($('<option/>', {
                            value: yourArray.id,
                            text : yourArray.name,
                        }));
});
},
error: function() {
    displayDialogBox('Error', err.toString());
}
});
});

And the dropdown tag -
<select id="builder_group"></select>

*

*For the second dropdown menu does not work with the first dropdown. I have to use jQuery Ajax for the second dropdown as well.
HTML for second dropdownlist :
  <script>
    $("#builder_group").change(function(){
        console.log("Hello 1");
        $('#Ivrmapping_groupZCode').find('option').remove().end(); //clear the city ddl
        var builder = $(this).find("option:selected").text();
        alert(builder);
        //do the ajax call
        $.ajax({
            url:'getGroupzCode.php'
            type:'GET',
            data:{city:builder},
            dataType:'json',
            cache:false,
        success: function(data) {
                    // Call this function on success
                        console.log(data);
                       var yourArray = JSON.parse(data);
                       console.log(yourArray);
                        $.each(yourArray, function (index, yourArray) {
                        );
    });
    },
    error: function() {
        displayDialogBox('Error', err.toString());
    }
    });

        });

    });
</script>

And the dropdown tag -
<select name="Ivrmapping[groupZCode]" id="Ivrmapping_groupZCode">..
</select>

Why is the second dropdownlist not working with first.
Can we have more than one jQuery Ajax calls in one page.

A: I think there is problem of brackets:: Try this:
$("#builder_group").change(function(){
        console.log("Hello 1");
        $('#Ivrmapping_groupZCode').find('option').remove().end(); //clear the city ddl
        var builder = $(this).find("option:selected").text();
        alert(builder);
        //do the ajax call
        $.ajax({
            url:'getGroupzCode.php'
            type:'GET',
            data:{city:builder},
            dataType:'json',
            cache:false,
        success: function(data) {
                    // Call this function on success
                        console.log(data);
                       var yourArray = JSON.parse(data);
                       console.log(yourArray);
                        $.each(yourArray, function (index, yourArray) {/* your plan*/});
    },
    error: function() {
        displayDialogBox('Error', err.toString());
    }
    });
    });

And you should use firebug, or chrome, these errors are clearly shown on the console. Try it out.


text:
Q: Parallel Curves to a Parabola I have been modelling parallel curves to a parabola and realise if the parallel curve to a parabola is offset enough then the curve will overlap.
I came across this research paper to explain why a parallel curve to a parabola is not a parabola: http://apollonius.math.nthu.edu.tw/d1/disk5/js/geometry/osc/0.pdf
However it does not give a mathematical explanation as to why the parabola invokes or evokes (in laymans terms overlaps itself)
Does it have anything to go with the focal length. ie If the focal length is less than the curve offset then it will invoke/evoke
Any I using the terms evoke and invoke correctly to state that a parallel curve overlaps itself.

A: We can parametrize the parabola by $c(t)=(t,\frac{t^2}{4r sin(\theta)})$. In finding the parallel curves, we take the normal vector at t, $n(t)=R^{90}[c'(t)]$ where $R^{90}$ is rotation by $90^{\circ}$, and compute $l_s(t)=c(t)+s\space n(t)$ for each s. Now, fix $t=t_0$. I claim there exist $s$ such that  $c(t_0)+s\space n(t_0)=c(t_1)+s\space n(t_1)$. This is a sufficient condition of a parallel curve intersecting itself. To simply calculations, I will just compute for $c(t)=(t,t^2)$, but you can see that this is true for any parabola. $c'(t)=(1,2t)$ so that $n(t)=(-2t,1).$ So we want $(t_0,t_0^2)+s (-2t_0,1)=(t_1,t_1^2)+s (-2t_1,1)$, that is, $(t_0-2t_0\space s,t_0^2+s)=(t_1-2t_1\space s,t_1^2+s)$. By inspection, we see this could be true only if $t_0=-t_1$ so that $t_0-2t_0\space s=2t_0\space s-t_0$ which implies $s=1/2$ provided that $t_0,t_1\neq0$. Hence, we have a self-intersection point $(t_0-\frac{1}{2}2t_0,t_0^2+\frac{1}{2})=(0,t_0^2+\frac{1}{2})$.


text:
Q: How to prevent InvalidOperationException with XmlDataSource in medium trust for the same domain I'm using an XmlDataSource to fetch an RSS feed on the same domain. Ever since my ISP moved to medium trust, that code is failing with a System.InvalidOperationException.
Is there a way to fix this?

A: After reading a forum post on my ISP's forums, it seems I have to ask them for my data source URL to get whitelisted. That's exactly what I did.


text:
Q: Input of length greater than 255 in postgresql rails I have a field with datatype string in the rails Postgresql table. What happens when I enter value more than 255. Does the Postgresql cut the string to 255 characters or does it prohibits from entering?

A: Postgres will throw an error if you try to write a value longer than the field's limit: https://www.postgresql.org/docs/9.1/datatype-character.html
Here's something you can do (with a migration) if you need bigger limits and want to control it instead of using text type:
change_column :table, :column, :string, limit: 510

A: As per http://www.sqlines.com/postgresql/datatypes/text

...for example, VARCHAR(255) does not allow inserting a string more than 255 characters long.

It won't truncate the string for you, and it will fail if you try to insert one.


text:
Q: Lost connection to MySQL server during query - codeigniter I just made a script in codeigniter which fetches emails and displays them with php imap.
It fetches 500 mails at once no problem.
If i try to fetch about 2000 mails at once, it throws an error.

A Database Error Occurred
  Error Number: 2013
Lost connection to MySQL server during query
SELECT GET_LOCK('77dfd862ae2b7bedaec521bc4c3651952b56e6c9', 300) AS
  ci_session_lock
Filename: libraries/Session/drivers/Session_database_driver.php
Line Number: 358

This project is live on hostgator. I am not sure if it has mysql workbench or not.
I have no idea where it comes from and why.
I have done nothing with mysql in codeigniter before.
I do not know which file to edit and where to start. Please help.


text:
Q: orderBy('id', 'desc') and orderBy('id', 'asc') returning same value
i am trying to get result query in mongodo using the orderBy "asc" and "desc" . but both of them are returning the result in same order..
db.languages.find().sort({a:1})
 db.languages.find().sort({a:-1})

A: Sort in mongoDB
you can sort only by field names in collection. a or id is not field,
You can try with _id or created_by also.
db.languages.find().sort({name :1})
db.languages.find().sort({ name : -1})


text:
Q: Apache and Memory issues I run a little startup on a Cloud server with 512MB and monitor the CPU/memory consumption with htop and phpsysinfo. Once, the server has ran out of RAM and on some instance get as high as consuming close to 90% of RAM. htop shows apache (httpd) as the top process with some (httpd) process consuming up to 7.5% in some instance. Is this amount (7.5%) too much for a single httpd process? What are the recommendations for reducing apache memory consumption?

A: 7.5% for a single child doesn't sound too abnormal, but it all depends on what the child is supposed to do... I run systems with apache and mod_perl and those children get huge.
Watch your apache children memory footprints over time to see if they stabilize.
If not, use MaxRequestsPerChild to control how often they are restarted.
Use MaxClients to limit how many concurrent children you have (to avoid swap or out of virtual memory issues).
In my experience, it's generally a memory bottleneck on the webservers.

A: That sounds pretty normal.  To reduce the memory footprint would be to figure out which modules you need and don't need and compile your own version.  Although with dynamic modules maybe that doesn't help as much.
Here is a nice O'Reilly article about getting your Apache memory requirements down. Although a bit old, not sure if has the enhancements that come with Apache 2.


text:
Q: Java Applet: My program creates more circle and rectangles than I want. Sometimes they are only half drawn Design and implement an applet that draws 3 circles of random radius (a radius between 20 and 100 inclusively) and 3 rectangles of random width and height (a width between 50 and 150 inclusively and a height between 30 and 90 inclusively) in random locations. Draw a string with your name on the bottom right corner of the applet. Use a width of 400 and a height of 300 for your applet.
import javax.swing.JApplet;
import java.awt.*;
import java.util.Random;

public class Applet extends JApplet
{

    public void paint(Graphics circle)
    {
        // Height and width of window
        final int MAX_WIDTH = 400;
        final int MAX_HEIGHT = 300;
        resize(MAX_WIDTH, MAX_HEIGHT);

        // Creates random diameter for each circle
        Random rand = new Random();
        int diameter1 = rand.nextInt(81) + 20;
        int diameter2 = rand.nextInt(81) + 20;
        int diameter3 = rand.nextInt(81) + 20;

        // Draws circles
        circle.drawOval(rand.nextInt(MAX_WIDTH), rand.nextInt(MAX_HEIGHT),
                        diameter1, diameter1);
        circle.drawOval(rand.nextInt(MAX_WIDTH), rand.nextInt(MAX_HEIGHT),
                        diameter2, diameter2);
        circle.drawOval(rand.nextInt(MAX_WIDTH), rand.nextInt(MAX_HEIGHT),
                        diameter3, diameter3);

        // Creates random heights and widths for rectangles
        int randWidth1 = rand.nextInt(101) + 50;
        int randWidth2 = rand.nextInt(101) + 50;
        int randWidth3 = rand.nextInt(101) + 50;

        int randHeight1 = rand.nextInt(61) + 30;
        int randHeight2 = rand.nextInt(61) + 30;
        int randHeight3 = rand.nextInt(61) + 30;

        // Draws rectangles
        circle.drawRect(rand.nextInt(MAX_WIDTH), rand.nextInt(MAX_HEIGHT),
                        randWidth1, randHeight1);
        circle.drawRect(rand.nextInt(MAX_WIDTH), rand.nextInt(MAX_WIDTH),
                        randWidth2, randHeight2);
        circle.drawRect(rand.nextInt(MAX_WIDTH), rand.nextInt(MAX_WIDTH),
                        randWidth3, randHeight3);

     }

}


text:
Q: How to sum datetime in sql server SELECT DISTINCT
        s.LastName + ',' + s.FirstName as formattedName
       ,t.Date
       ,t.In1
       ,RIGHT (t.In1, 7) AS TineIn1
       ,RIGHT (t.Out1, 7) AS TimeOut1
       ,RIGHT (t.In2, 7) AS TimeIn2
       ,RIGHT (t.Out2, 7) AS TimeOut1
       ,RIGHT (t.In3, 7) AS TimeIn3
       ,RIGHT (t.Out3, 7) AS TimeOut3
       ,SUM (
              (t.In1-t.Out1)
             +(t.In2-t.Out2)
             +(t.In3-t.Out3)
             ) As WorkedHours

FROM   employee e

JOIN StudentID_EmpID SID
    ON e.EmpID = SID.EmpID
JOIN Student s
    ON SID.StudentID = s.StudentID
    AND s.StudentID = :parm_lb_StudenEE.studentID
JOIN Time t
    ON s.StudentID = t.StudentID

WorkedHours part does not work while trying to get total hour worked. I got following error message
 "Microsoft OLEDB provider for sQL Server : operand data type datetime is invalid for sum operator"
my date format in database is In1 1/1/1900 8:30:00 AM and Out1 1/1/1900 12:30:00 PM and so on. that's the reason I have to do
 "RIGHT (t.In1, 7) AS TineIn1"
just to get time as date here does not matter for me.
any help will be appreciated.

A: You can use the DATEDIFF function to get the difference between two dates, and add those together:
 (DATEDIFF(second,t.IN1,t.Out1)
 +DATEDIFF(second,t.IN2,t.Out2)
 +DATEDIFF(second,t.IN3,t.Out3))/3600.0 AS WorkedHours

In this case, take the total seconds and divide by 3600.0 to return hours with decimal portion.  Other output options are mentioned in comments.
If any of the fields are NULL the result will be NULL so you can wrap them in ISNULL():
 (ISNULL(DATEDIFF(second,t.IN1,t.Out1),0)
 +ISNULL(DATEDIFF(second,t.IN2,t.Out2),0)
 +ISNULL(DATEDIFF(second,t.IN3,t.Out3),0))/3600.0 AS WorkedHours


text:
Q: How can I generate a set of (short) unique identifiers which are easy to check but hard to spoof? For example, such as the license keys much software uses. I had thought of cryptographically signing a sequence, so I could have maybe 4 bytes for the ID and say 8 bytes for the signature, but I can't find a suitable algorithm.
What I need is something that an attacker can't readily generate, but which is stored in less than approx 20 ASCII bytes. I also need to be confident of uniqueness. This doesn't need to be completely secure, only secure against a casual attack.
Note: I'm doing this in java on appengine.

A: Just generate a GUID for each ID and keep track of the ones you've generated in a database. The universe of GUIDs is so large that each will be unique. It's not cryptographic so there's a possibility that anyone who has a large enough population of your generated ones could produce a match, but I think the odds are still miniscule.
A GUID is 128 bits, which can be encoded in 23 bytes using Base64.

A: Sounds like HMAC. You will probably need to ensure uniqueness manually though.

A: Calculate the values including the id into a string and use the byte based HDMAC with a secret key and max length. Just make sure that you have a unique part in the values to encrypt. This could be server time or some other ID. The length will need to be tested that it remains within your 20 character requirement.

A: Encryption is reversible, so the output is guaranteed unique for unique inputs.  Just encrypt 0, 1, 2, 3, 4, 5 etc. using the same key every time.  For 128 bit output use AES and 128 bit numbers in ECB mode.  Other modes will need identical IV/Nonces as well.  For 64 bit numbers use DES.  For other size numbers either use Hasty Pudding cypher or roll your own simple Feistel cypher for the size you want.
ECB is not the most secure mode, but I do not get the impression that you are looking for very high levels of security here.


text:
Q: Powershell Bulk Rename Files by Date Taken I wrote a quick script (below) to rename files b replacing/removing things (particularly changing innate picture formats to only have the date (and adding things at the end).
Some photo formats don't have the date taken in the file name. Is there a way to alter what I have below to add date/time taken? I have looked around and have not come across anything helpful - or concise/simple. I feel like this shouldn't require 10 lines. Thanks.
get-childitem *.jpg | foreach { rename-item $_ $_.Name.Replace("IMG_", "") }

A: This would put the creationtime in the filename.  Although you can easily do things like ls | where creationtime -gt 9/13.
ls *.jpg | rename-item -NewName {
  $base, $time = $_.basename, $_.creationtime.tostring('yyyyMMdd')
  $_.name -replace $_.basename, "$base-$time" } -whatif

Output:
What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/file1.jpg Destination: /Users/js/foo/file1-20190914.jpg".
What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/file2.jpg Destination: /Users/js/foo/file2-20190914.jpg".
What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/file3.jpg Destination: /Users/js/foo/file3-20190914.jpg".


text:
Q: Custom useForm typescript not working properly Below is my useForm hook:
const useForm = () => {
  const [state, setState] = useState({});

  const inputHandler: (e: React.ChangeEvent<HTMLInputElement>) => void = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    e.persist();
    setState((preState) => ({
      ...preState,
      [e.target.name]: e.target.value,
    }));
  };

  return [state, inputHandler];
};
export default useForm;

Then in tsx file I have code:
const [state, inputHandler] = useForm();
...
    <input
          name="title"
          type="text"
          value={"title" in state ? state.title : ""}
          onChange={inputHandler} // error!!!
          placeholder="Title"
          className="mb-2 focus:ring-red-500 focus:border-red-500 block w-full pr-12 sm:text-sm border-red-300 rounded-md"
        />

but the onChange always complain Type {} is not assignable to type ChangeEventHandler<HTMLInputElement>. I've change the {} to Any but it seems the inputHandler always return init state not event handler function I defined in the custom hook.

A: After a couple of hours investigation, I found the error is caused by the return []. I replace it with return {...}. The hook works like a charm


text:
Q: Tetrahedron edge test When testing where a point is respective to a tetrahedron there are 4 cases. It's inside the tetrahedron, it is closest to a vertex, closest to a edge, or closest to a face. Here's a diagram of it in 2D, http://i.imgur.com/AmYNO.png . For example a point P is closest to a vertex A when the dot product of P - A and B - A, C - A and D - A are all negative. If u were to stretch a triangular face in the direction of the normal to create a prisim, the point would be closest to that face if it is contained within that space. It would be closest to an edge if it were in neither of those cases.
I want to be able to exclusively test whether or not it is closest to an edge without relying on the results of a vertex or face test. Is there a relatively efficient way to do this? The tetrahedron is not regular.

A: Do you mean, closest to a particular edge, or closest to an edge in general (as opposed to a vertex or plane)?
If the former, then a point is closest to (a particular) edge if it lies in the intersection of four half-spaces defined by two planes perpendicular to the adjoining faces and passing through the edge, and two planes perpendicular to the edge and passing through the adjoining vertices. So test your point against all four planes and if it lies in the appropriate half-space for all of them, it's closest to that edge.
In detail, suppose we want to test whether the point P is closest to the edge AB, which lies between the faces ABC and BAD (vertices given clockwise). Then the four tests are:

*

*(P − A) · (A − B) < 0

*(P − B) · (B − A) < 0

*(P − A) · ((B − C) × (A − C) × (A − B)) < 0

*(P − B) · ((A − D) × (B − D) × (B − A)) < 0

(I wonder if there's a cheaper way to do the third and fourth tests? If you know of one, let me know!)


text:
Q: Why can't I delete original user in multisite? Options for manual removal So, I've been trying to delete the original user for a multisite installation. After removing the super-admin privileges and setting another user to the network admin, I noticed that hitting the delete button from the network user admin would just refresh the page.
I then proceeded to remove this user as the admin user in the General settings of each individual site. Still just a refresh when I try to remove.
This led me to dig into the Wordpress code to see why this was happening, and I see that WP is behaving exactly as intended, and that I am programatically prevented from removing the user with ID = 1.
Line 30 of users.php has the following conditional:
if ( $id != '0' && $id != '1' ) {

The delete code simply won't execute on this user. I can find a way around this, but seeing this baked into the code has me thinking twice about it.
So my question is twofold:

*

*Why is this restriction hard coded? If I've got other users with sufficient permissions to do everything, what unforeseen consequences will there be if this user dissappears?

*What's my best strategy for circumventing this? My first thought is just to delete that user's lines from the user and usermeta table. But it occurs to me I could also change the users ID to make sure the normal WP user removal processes complete. Or is there possibly another option?

A: Don't delete the user, just change the email, username(optionally) and password in the users table.  you can insert a MD5 string in the password field of the users table and WordPress will salt and hash it to a more secure format the first time you log in.


text:
Q: angularjs - don`t access to my $scope value I want to use angular-ui to create a dynamic menu
in my LoginCtrl. I call a service to get menu from server to show in dashboard.
here is my code:
in LoginCtrl controller:
    UserService.getMenu().then(
    function (result) {
        $scope.menu = result;
        $location.path('/dashboard');

    }, function (status) {
        $scope.msg = "error " + status + " has been occur,please report to admin ";
    }
);

in dashboard.html
<div ng-controller="LoginCtrl">
  <label class="checkbox">
    <input type="checkbox" ng-model="oneAtATime">Open only one at a time
  </label>

  <accordion close-others="oneAtATime">
    <!--nashta-->
    <accordion-group heading="{{project.name}}" ng-repeat="project in menu.projectName">

      <accordion close-others="oneAtATime">
        <!--bank-->
        <accordion-group heading="{{bank.name}}" ng-repeat="bank in menu.bankingList">

          <accordion close-others="oneAtATime">
            <!--working pack-->
            <accordion-group heading="{{wp.name}}" ng-repeat="wp in menu.workingPackList">

              <accordion close-others="oneAtATime">
                <!--product pack-->
                <accordion-group heading="{{pr.name}}" ng-repeat="pr in menu.productList">
                </accordion-group>
              </accordion>

            </accordion-group>
          </accordion>

        </accordion-group>
      </accordion>

    </accordion-group>
  </accordion>
</div>

but I don`t no why it does not work.my menu load from server successfully but in dashboard.html I can not access to $scope.menu.
I was wandering whay it work in another html file
for example if I copy the above code in login.html, I can access to $scope.menu

but It does not work in dashboard!!!
my login controller:
'use strict';

angular.module('mabnaaApp')
    .controller('LoginCtrl', function ($scope, $location, UserService) {
    $scope.oneAtATime = true;

    $scope.user = {
        username: '',
        password: ''
    };

    $scope.submit = function (user) {
        if ($scope.loginForm.$valid) {

            UserService.login(user).then(
                function (result) {

                    UserService.getMenu().then(
                        function (result) {
                            $scope.menu = result;
                            $location.path('/dashboard');

                        }, function (status) {
                            $scope.msg = "error " + status + " has been occur,please report to admin ";
                        });

                }, function (reason) {
                    $scope.msg = "username or password is not correct";
                });
            $scope.reset();
        }
    };

    $scope.reset = function () {
        $scope.user = {
            username: '',
            password: ''
        };
    };

    var existy = function (x) {
        return x != '';
    };

    $scope.userExists = function () {
        return  existy($scope.user.username);
    };

    $scope.isLogin = !existy($scope.user.username);
});


text:
Q: How create an alert in the delete function without confirm of the JavaScript, only AngularJS? I have a small project to create the TODO List in CRUD. But have a specification that I can't finish the function. It's an alert in the delete function but can't have a alert in JavaScript must be a AngularJS function.
 $scope.delete = function() {
      $scope.index = this.$index;
       $scope.showConfirm = true;
    }

    $scope.yes = function(){
      $scope.tasks.splice($scope.index, 1);
        $scope.showConfirm = false;
    }

    $scope.no = function(){
       $scope.showConfirm = false;
    }

Link: https://plnkr.co/edit/zReV2knGp6dxZcfPoqld?p=preview

A: In a pure angularJS app I would use the sweetalert plugin:
swal({
   title: "Are you sure?",
   text: "You will not be able to recover this task!",
   type: "warning",
   showCancelButton: true,
   confirmButtonColor: "#DD6B55",
   confirmButtonText: "Yes, delete it!",
   closeOnConfirm: false
}, function(){
   swal("Deleted!", "Your taske has been deleted.", "success");
});

--OLD ANSWER
Only angularJS allowed?
You can use plain javascript:
  if(confirm("Delete task?"))
    $scope.tasks.splice(this.$index, 1);

A: I dont now why you dont want the confirm function but if you still need it, here's a simple trick designed for you code that will help you, without using any 3rd party library.
DEMO
You can just adjust the style for the confirmation box.


text:
Q: Do apps using multiple processes share a Dalvik instance? I'm studying Android process management and I'm wondering whether apps using multiple processes (not threads) share a Dalvik instance or there exists a Dalvik instance per process, even for the same app.
Could you point me to some official source (doc, talk, paper etc.)?
Thanks

A: No.  Dalvik doesn't span processes.
However, the Binder IPC mechanism can do a very convincing job of making objects appear to migrate to a different process and its Dalvik instance.  Also, the memory management is very good about sharing read-only pages across all processes that need them.  The Dalvik process hosting a typical app is forked off of zygote with all the common android libraries already mapped, so new unique copies don't have to be opened.


text:
Q: Finding the expected value of the cdf? I have this question on a homework assignment, and I'm not sure how to solve it.
Assume $X \sim \exp(\lambda=2)$, define $Y=F(x)$, where F(x) is the cdf function of $X$. Calculate the expected value of $Y$, i.e., $E(Y)$.
I thought maybe you could use the Law of the Unconscious Statistician and have the integral of $F(x) * f(x)$? Any help would be appreciated.

A: Yes, you can definitely use LOTUS. Alternatively, you can use the Probability Integral Transform which says that the CDF of a continuous random variable follows the uniform distribution. You might want to see if you can arrive at the same result using both methods.


text:
Q: Remove Hashbang on VueJs with Laravel I have already tried the suggestions stated regarding the hashbang (/#/) with Vue and Laravel, and it seems it still doesn't work for me.
routes.js
let routes = [
    {
        path: '/',
        component: Home,
        children: [
            {
                path: '/blog',
                component: PageBlogLists,
            },
            {
                path: '/post/:page_id',
                component: PageBlog
            }
        ]
    },
];

export default new VueRouter({
    // This does not work
    mode: 'history',
    routes
});

app.js
// Vue Router
import VueRouter from 'vue-router';
import router from './router/routes';

require('./bootstrap');
window.Vue = require('vue');
Vue.use(VueRouter);

const app = new Vue({
    el: '#app',
    router
});

Has anyone successfully tried removing it?


text:
Q: How do I make a Global Menu in Android TV? I'm building an Android TV app with a side menu that lists the different parts of the application such as "Home, My Videos, Search, Settings" etc.  However, it's not clear how to do this.
The example Google provides shows the list items corresponding with the title of each row that is currently being displayed.
https://developer.android.com/training/tv/playback/browse.html
The only way I have been able to add items to the list is by calling:
 mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());

 HeaderItem header = new HeaderItem(i, "Category " + i);

 mRowsAdapter.add(new ListRow(header, listRowAdapter));

where listRowAdapter is one of the rows being displayed.  For example, I want to be able to add a Settings item and then load a Settings fragment or Activity when the user selects it. I'm guessing the ListRowPresenter is not the way to go.
Most, if not all, TV apps do this, so I must be missing something.  Any help would be appreciated.  Thanks!


text: Q: Google Tag Manager Tracking for sorting I want to add some tracking parameter in google tag manager for sorting function based on price. I wanted to know what could potentially be event action, category and label?


text:
Q: Why does Relay need a mutation id to reconcile GraphQL mutations? I've tried to figure out why, but always end up concluding that the "tracking" could be easily done within the closure of the request that was sent. I'm clearly missing something here.
Why does Relay need a mutation ID to track the request/response?

A:
"tracking" could be easily done within the closure of the request that was sent

You're thinking in terms of implementation. Relay is a JavaScript framework that implements the Relay specification. Under the specification, it is not a good idea to rely on something (closure) that a language may or may not support. Therefore, Relay Input Object Mutations Specification specifies clientMutationId to track the mutation.


text:
Q: FreeBSD jails - Nginx, PHP-FPM, Wordpress - Share folder between jails (read-only) Question
I want to separate PHP (PHP-FPM) and Nginx into different jails. One jail with Nginx, and one with PHP-FPM / PHP / Wordpress.
Nginx is good at serving static assets, so I would like to serve those directly with Nginx. How can I mount a folder from one jail into another jail (read-only)?
I also have a Nodejs app in another jail, so I would also like to serve the static assets of it directly with Nginx.
Side question: When you host multiple PHP sites on the same server. Do you have to install PHP / PHP-FPM in each jail if you want each web-app in each own jail?
Info

*

*Version: FreeBSD 10.2

*Filesystem: root on ZFS

Sources

*

*keramida.wordpress.com - freebsd-nullfs

*cyberciti.biz - freebsd-mount_nullf-usrports-inside-jail
I have found this blog on using mount_nullfs for it. But can you use it between jails instead of between the host and a jail?

A: nullfs can be used to give a jail read-only access to parts of the host's file system. All the jails live within the host's file system, so the idea of jail-to-jail access is moot.
On my system (and I do jails the hard way) I have the following directive in /etc/jails.conf:
mount.fstab = "/etc/fstab.${name}";

which means I have separate fstabs for each jail, which then contains something like:
/jail/base /jail/somejail/base nullfs ro 0 0

There is obviously a whole range of arguments regarding the partitioning of jails, processes and applications. Personally, I like to keep an application self contained within a single jail, then use (yet another) nginx jail to reverse-proxy to all of the application jails. Using ZFS and one application per jail makes it very easy to manage different versions of the stack simultaneously, test new versions, and roll-back where necessary. In summary, I advocate running nginx and php-fpm in each application jail (that contain both static and dynamic content).


text:
Q: at sign @ with Imperavi Redactor wysiwyg editor i try to add an @ sign in a text using Redactor JS but it seems to be a shortcut key so it dont work for me, nothing appears.
I can type it in the "code mode" but not in the "editor mode"
Do you have an idea for overriding this bug ?
I'm french so i use ALT Gr + 0 , which is also the key for the à and @
Thank you

A: Problem fixed :
this problem is from shortcuts key ALT Gr + 0
I find the line 1766 in the redactor.js and i bypass the condition by adding RETURN to avoid the e.preventDefault() which is blocking my @.
replace :
if (key === 48) this.shortcutsLoadFormat(e, 'p'); // ctrl + alt + 0
by :
if (key === 48) return;


text:
Q: CSS Grid 2 cols and half height Im trying to get my CSS grid into 2 columns with the same parent height but each smaller box half the height of the main box. See attached image. However I can't quite get the right layout and need some help. Please see my code so far.

.item1 { grid-area: header; }
.item2 { grid-area: menu; height:200px;}
.item3 { grid-area: main; height:100px;}
.item4 { grid-area: right; height:100px;}
.item5 { grid-area: footer; height:200px;}

.grid-container {
  display: grid;
  grid-template-areas:
    'header header'
    'menu right'
    'main footer';
  gap: 10px;
  background-color: #2196F3;
  padding: 10px;
}

.grid-container > div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
<!DOCTYPE html>

Grid Layout

Header

Menu

Main

Right

Footer

A: There is a missing row in the grid template areas definition.

.item1 {
  grid-area: header;
}

.item2 {
  grid-area: menu;
  height: 200px;
}

.item3 {
  grid-area: main;
  height: 100px;
}

.item4 {
  grid-area: right;
  height: 100px;
}

.item5 {
  grid-area: footer;
  height: 200px;
}

.grid-container {
  display: grid;
  grid-template-areas: 'header header' 'menu right' 'menu footer' 'main footer';
  gap: 10px;
  background-color: #2196F3;
  padding: 10px;
}

.grid-container>div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
<!DOCTYPE html>

Grid Layout

Header

Menu

Main

Right

Footer


text:
Q: How to take an action when message bubble tapped I've been trying to figure out how to insert a handler to take action when a user taps on the message bubble. I've found the section in the readme about "customize your cells" and have tried a couple of different approaches, but so far no luck. Here's what I've tried:
Implemented:
- (void)collectionView:(JSQMessagesCollectionView *)collectionView didTapMessageBubbleAtIndexPath:(NSIndexPath *)indexPath

in my viewController as:
override func collectionView(collectionView: JSQMessagesCollectionView, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
    super.collectionView(collectionView, didTapMessageBubbleAtIndexPath: indexPath)
    println("They tapped!")
}

However, this doesn't seem to get called at all for some reason.
The other thing I've tried is implementing:
- (UICollectionViewCell *)collectionView:(JSQMessagesCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

In my view controller as:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell

    let myDelegate = MyJSQMessagesCollectionViewCellDelegate(origDelegate: cell.delegate!)
    cell.delegate = myDelegate

    return cell;
}

This gets called, but the methods in my delegate don't get invoked.
So, any suggestions on how I can properly get my JSQMessagesCollectionViewCellDelegate put in place so that it gets invoked? Or is my initial attempt to just override the didTapMessageBubbleAtIndexPath method the proper way to go?
Any suggestions are appreciated.

A: OK, I got it figured out. My attempt to insert my own delegate was actually breaking things (in addition to not accomplishing what I tried to do). Once I removed my "cellForItemAtIndexPath" method my "didTapMessageBubbleAtIndexPath" started firing.


text:
Q: Is there a better way to set TabbedPage bottom tab bar height than in ViewModel? I want to change the height of the bottom TabBar in my Xamarin app. Now I am doing this via ViewModel properties:
public partial class MainPage : TabbedPage
{
    public int TabBarHeight
    {
        get { return _tabBarHeight; }
        set { _tabBarHeight = value; OnPropertyChanged(); }
    }
    int _tabBarHeight = 200;

And a custom renderer for iOS:
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using System.Diagnostics;
using Ja.Enums;
using System.ComponentModel;
using CoreGraphics;

[assembly: ExportRenderer(typeof(TabbedPage), typeof(Ja.iOS.TabbedPageRenderer))]
namespace Ja.iOS
{
    public class TabbedPageRenderer : TabbedRenderer
    {
        private MainPage _page;

        public TabbedPageRenderer()
        {
            this.ViewControllerSelected += OnTabbarControllerItemSelected;
        }

        public override void ViewWillLayoutSubviews()
        {
            base.ViewWillLayoutSubviews();
            TabBar.Frame = new CGRect(TabBar.Frame.X, TabBar.Frame.Y + (TabBar.Frame.Height - _page.TabBarHeight), TabBar.Frame.Width, _page.TabBarHeight);
        }

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                e.OldElement.PropertyChanged -= Current_PropertyChanged;
                return;
            }

            if (e.NewElement != null)
            {
                _page = (MainPage)e.NewElement;
                e.NewElement.PropertyChanged += Current_PropertyChanged;
            }
        }

        void Current_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FrameHeight")
                ViewWillLayoutSubviews();
        }

    }
}

Is this an optimal way to be doing this?  I seem to remember having a shared class. That class would contain the code that's in the first few lines of my main as bound elements.
Could anyone comment on this and perhaps suggest a better way of doing this.

A: Looks like something I would use a Custom Control for (which is what I think you mean with 'shared class').
First you create the class below in your PCL. A CustomTabbedPage, which inherits from TabbedPage but has one extra property: 'TabBarHeight'
public class CustomTabbedPage : TabbedPage {

    public static readonly BindableProperty TabBarHeightProperty = BindableProperty.Create("TabBarHeight", typeof(int), typeof(TabbedPage), 0);

    public int TabBarHeight {
        get { return (int)GetValue(TabBarHeightProperty); }
        set { SetValue(TabBarHeightProperty, value); }
    }
}

Now edit your renderer to a renderer of the CustomTabbedPage. Then you can easily access the TabBarHeight property by using this.Element.TabBarHeight.
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using System.Diagnostics;
using Ja.Enums;
using System.ComponentModel;
using CoreGraphics;

[assembly: ExportRenderer(typeof(CustomTabbedPage), typeof(Ja.iOS.CustomTabbedPageRenderer))]
namespace Ja.iOS
{
    public class CustomTabbedPageRenderer : TabbedRenderer
    {
        public TabbedPageRenderer()
        {
            this.ViewControllerSelected += OnTabbarControllerItemSelected;
        }

        public override void ViewWillLayoutSubviews()
        {
            base.ViewWillLayoutSubviews();

            TabBar.Frame = new CGRect(TabBar.Frame.X, TabBar.Frame.Y + (TabBar.Frame.Height - this.Element.TabBarHeight), TabBar.Frame.Width, this.Element.TabBarHeight);
        }

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null) {
                e.OldElement.PropertyChanged -= Element_PropertyChanged;
            }

            if (e.NewElement != null) {
                e.NewElement.PropertyChanged += Element_PropertyChanged;
            }
        }

        void Current_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FrameHeight")
                ViewWillLayoutSubviews();
        }

    }
}

There might be some syntax errors in there but you get the point.
Shoot if you have any questions.


text:
Q: How to grow a single tree model with continuous and categorical predictors? I'm trying to implement the recursive binary splitting algorithm to grow a simple tree model. My aim is that it serves both for regression and classification trees.
My problem is choosing which variable to split when I have both continuous and categorical predictor variables.
$$f: X \rightarrow Y$$
$$ X : \{X_1 = Discrete, X_2 = Continuous\}$$
I understand that for continuous variables we use the residual sum of the squares (RSS) of the two regions (given an optimal split point) to determine which minimizes this metric. On the other hand, for categorical variables we use the information gain criterium to determine which variable maximizes this metric.
But I don't understand how to relate categorical and continuous variables criterium in order to choose the following predictor to split and also how to compute the respective metrics when I have the following scenarios:

*

*RSS when I have continuous predictors vs categorical response

*Information gain criterium when I have categorical predictors vs continuous response


text:
Q: Object not being added to ArrayList inside a Thread of Application class I'm working with Kotlin in Android app development.
This is the code I'm trying to run when the Application is instantiated
class SpeechApp: Application() {
    var isDictionaryRead = false
    lateinit var wordslist : ArrayList<String>

    override fun onCreate() {
        super.onCreate()
        wordslist = ArrayList()

        Thread {
            Runnable {
                execute()
            }
        }.start()
    }

    fun execute() {
        val inputStream = assets.open("words.txt")
        val reader = BufferedReader(InputStreamReader(inputStream))

        var line = reader.readLine()
        while (line != null) {
            Log.i("Read" , line)
            wordslist.add(line)
            line = reader.readLine()
        }
        isDictionaryRead = true
    }
}

I'm expecting this code to work, but in my logs I cannot see any line being added that has the tag Read. But if I call the execute() outside the Thread like:
class SpeechApp: Application() {
    var isDictionaryRead = false
    lateinit var wordslist : ArrayList<String>

    override fun onCreate() {
        super.onCreate()
        wordslist = ArrayList()

        execute()
    }

    fun execute() {
        val inputStream = assets.open("words.txt")
        val reader = BufferedReader(InputStreamReader(inputStream))

        var line = reader.readLine()
        while (line != null) {
            Log.i("Read" , line)
            wordslist.add(line)
            line = reader.readLine()
        }
        isDictionaryRead = true
    }
}

I can see a lot of lines in my logcat with the "Read" tag. I do not want it to work this way, as there is a visible lag of ~5s before I see my MainActivity, as the system is busy processing the 479k words inside words.txt.
How can I make execute() work inside the thread?

A: The Runnable is actually never run. Instead run it manually or use the proper constructors:
Thread { execute() }.start()

Thread(::execute).start()

Thread(Runnable {
    execute()
}).start()

Thread {
    Runnable {
        execute()
    }.run()
}.start()

The reason for your issue is more visible when not using SAM conversion for the constructor:
Thread(object : Runnable {
    override fun run() {
        Runnable {
            execute()
        }
    }
}).start()


text:
Q: Is the smallest ball enclosing a compact a Lipschitz function of the compact? Let $\mathbf R^n$ be endowed with the standard Euclidean structure and let $\mathcal X$ be the collection of (nonempty) compact subspaces of $\mathbf R^n$. Let $\mathcal B\subset \mathcal X$ be the sub-collection of all closed ball in $\mathbf R^n$. Then we can endow $\mathcal X$ (and hence $\mathcal B$) with the Hausdorff metric defined by
$$d_H(C,D)=\max\left\{\max_{x\in C}d(x,D),\max_{x\in D}d(x,C)\right\}.$$
Given a compact subspace $K\subset \mathbf R^n$, there is a unique closed ball $B_K$ of least radius containing $K$. This yields a map
$$F:\mathcal X\longrightarrow\mathcal B.$$
I would like to understand the regularity of $F$. More precisely :

Is $F$ Lipschitz or locally Lipschitz ?

I was able to show that $F$ is continuous. The key thing to note is that the center $x_K$ of $B_K$ is characterized by the fact that it minimizes the distance to $K$ :
$$d_H(\{x_K\},K)< d_H(\{x\},K) ~~\forall x\in\mathbf{R}^n,~x\neq x_K.$$
A compactness argument shows that $K\mapsto x_K$ is continuous.
Also if $r_K$ denotes the radius of $B_K$, then for $K,L\in\mathcal X$ we have $$K\subset L +d_H(K,L)\subset \bar{B}(x_L,r_L)+d_H(K,L)=\bar{B}(x_L,r_L+d_H(K,L)),$$ so $r_K\leq r_L+d_H(K,L)$ and therefore $K\mapsto r_K$ is 1-Lipschitz.
Finally if we endow $\mathbf{R}^n\times\mathbf{R}_+$ with the product distance, then the natural map $(x,r)\mapsto \bar{B}(x,r)$ is an isometry of $\mathbf{R}^n\times\mathbf{R}_+$ onto $\mathcal B$, so $F$ is continuous by composition. In fact we just have to show that $K\mapsto x_K$ is Lipschitz in order to prove that $F$ is.
I tried proving that $K\mapsto x_K$ is locally Lipschitz by geometric arguments without success.  Any help will be greatly appreciated.
Proof that $K\mapsto x_K$ is continuous :
Let $(K_n)_n$ be a sequence of compact subspaces converging to $K$. Write $x_n = x_{K_n}$. We want to show that $(x_n)_n$ converges to $x_K$. For $n\geq 0$ we have
$$d_H(\{x_n\},K)\leq d_H(\{x_n\},K_n)+d_H(K_n,K)\leq \underbrace{d_H(\{0\},K_n)+d_H(K_n,K)}_{\text{bounded since }(K_n)_n\text{ converges}},$$
so the sequence $(x_n)_n$ lives in a compact set. Hence we just need to show that $x_K$ is the only possible limit for a sub-sequence of $(x_n)_n$. Assume that
$$x_{\varphi(n)}\underset{n\to +\infty}{\longrightarrow} y$$
for some $y\in \mathbf R^n$. For every $x\in \mathbf R^n$ and every $n\geq 0$ we have $$d_H(\{x_{\varphi(n)}\},K_{\varphi(n)})\leq d_H(\{x\},K_{\varphi(n)}).$$
By passing to the limit we get $$d_H(\{y\},K)\leq d_H(\{x\},K)$$ which is true for any $x$, so $y=x_K$.

A: I think I found a counterexample for local Lipschitz-continuity of $F$
and $K\mapsto x_K$, where $n=2$.
In this example, we still get Hölder estimates with exponent $1/2$,
and I would conjecture that $F$ is Hölder continuous with exponent $1/2$.
construction of counterexample:
Let $n=2$.
We define
$$
K= B_1((0,0))\cap \{(x,y) : x\geq 0\},
K_\varepsilon := B_1((2\varepsilon,0)) \cap K,
$$
where $\varepsilon>0$ is a small number.
Then one can calculate that
$$
x_K=(0,0)
\qquad
x_{K_\varepsilon}=(\varepsilon,0)
$$
and
$$
d_H(K,K_\varepsilon) = \sqrt{1+4\varepsilon^2}-1 = O(\varepsilon^2)
$$
Also, one can calculate that $r_K=1$ and
$r_\varepsilon := r_{K_\varepsilon}=\sqrt{1-\varepsilon^2}$ holds.
However, $F$ cannot be Lipschitz continuous, because of
$$
d_H(F(K),F(K_{\varepsilon}))
= d_H(B_1((0,0)),B_{r_\varepsilon}((\varepsilon,0)))
= \varepsilon + (1- \sqrt{1-\varepsilon^2}) \geq \varepsilon.
$$
(sorry that I did not include detailed calculations for all the Hausdorff metrics.
One can draw the sets on a piece of paper and estimate
that the calculations are approximately right.)


text:
Q: What are the major advantages of const versus #define for global constants? In embedded programming, for example, #define GLOBAL_CONSTANT 42 is preferred to const int GLOBAL_CONSTANT = 42; for the following reasons:

*

*it does not need place in RAM (which is usually very limited in microcontrollers, and µC applications usually need a large number of global constants)

*const needs not only a storage place in the flash, but the compiler generates extra code at the start of the program to copy it.

Against all these advantages of using #define, what are the major advantages of using const?
In a non-µC environment memory is usually not such a big issue, and const is useful because it can be used locally, but what about global constants? Or is the answer just "we should never ever ever use global constants"?
Edit:
The examples might have caused some misunderstanding, so I have to state that they are in C. If the C compiler generated the exact same code for the two, I think that would be an error, not an optimization.
I just extended the question to C++ without thinking much about it, in the hopes of getting new insights, but it was clear to me, that in an object-oriented environment there is very little space for global constants, regardless whether they are macros or consts.

A: Are you sure your compiler is too dumb to optimize your constant by inserting its value where it is needed instead of putting it into memory? Compilers usually are good in optimizations.
And the main advantage of constants versus macros is that constants have scope. Macros are substituted everywhere with no respect for scope or context. And it leads to really hard to understand compiler error messages.
Also debuggers are not aware of macros.
More can be found here

A: Another reason that hasn't been mentioned yet is that const variables allow the compiler to perform explicit type-checking, but macros do not.  Using const can help prevent subtle data-dependent errors that are often difficult to debug.

A: The answer to your question varies for C and C++.
In C, const int GLOBAL_CONSTANT is not a constant in C, So the primary way to define a true constant in C is by using #define.
In C++, One of the major advantage of using const over #define is that #defines don't respect scopes so there is no way to create a class scoped namespace. While const variables can be scoped in classes.
Apart from that there are other subtle advantages like:
Avoiding Weird magical numbers during compilation errors:
If you are using #define those are replaced by the pre-processor at time of precompilation So if you receive an error during compilation, it will be confusing because the error message wont refer the macro name but the value and it will appear a sudden value, and one would waste lot of time tracking it down in code.
Ease of Debugging:
Also for same reasons mentioned in #2, while debugging #define would provide no help really.

A: I think the main advantage is that you can change the constant without having to recompile everything that uses it.
Since a macro change will effectively modify the contents of the file that use the macro, recompilation is necessary.

A: In C the const qualifier does not define a constant but instead a read-only object:
#define A  42       // A is a constant
const int a = 42;  // a is not constant

A const object cannot be used where a real constant is required, for example:
static int bla1 = A;  // OK, A is a constant
static int bla2 = a;  // compile error, a is not a constant

Note that this is different in C++ where the const really qualifies an object as a constant.

A: The only problems you list with const sum up as "I've got the most incompetent compiler I can possibly imagine". The problems with #define, however, are universal- for example, no scoping.

A: There's no reason to use #define instead of a const int in C++.  Any decent C++ compiler will substitute the constant value from a const int in the same way it does for a #define where it is possible to do so.  Both take approximately the same amount of flash when used the same way.
Using a const does allow you to take the address of the value (where a macro does not).  At that point, the behavior obviously diverges from the behavior of a Macro.  The const now needs a space in the program in both flash and in RAM to live so that it can have an address.  But this is really what you want.
The overhead here is typically going to be an extra 8 bytes, which is tiny compared to the size of most programs.   Before you get to this level of optimization, make sure you have exhausted all other options like compiler flags.  Using the compiler to carefully optimize for size and not using things like templates in C++ will save you a lot more than 8 bytes.