text:
Q: Referencia a objeto no establecida como instancia de un objeto ASP.NET Amigos soy nuevo en .NET y empecé a trabajar con ASP.NET en Visual Studio 2017 y he tenido un problemita al ejecutar el siguiente javascript para los usuarios que tengan rol
<script type='text/javascript'>

        var role = @HttpContext.Current.Session["typeUser"].ToString();

   switch (role){
    case "usuario" :
           document.getElementByName("Matricula").disabled = true;
           document.getElementByName("Nombre").disabled = true;
   break;
}

    </script>

El error esta ocurriendo en la linea 19
var role = '@HttpContext.Current.Session["typeUser"].ToString()';

Descripción: Excepción no controlada al ejecutar la solicitud Web actual. Revise el seguimiento de la pila para obtener más información acerca del error y dónde se originó en el código.
El error es el siguiente al ejecutar la aplicación

Información de versión:
Versión de Microsoft .NET Framework:4.0.30319;
Versión ASP.NET:4.7.3429.0
Stacktrace
[NullReferenceException: Referencia a objeto no establecida como instancia de un objeto.]
   ASP._Page_Views_RegistroTicket_FormTicket_cshtml.<Execute>b__3_0() in C:\Users\User\Desktop\Views\RegistroTicket\FormTicket.cshtml:20
   System.Web.WebPages.<>c__DisplayClass42_0.<RenderSection>b__0(TextWriter tw) +316
   System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +10
   System.Web.WebPages.WebPageBase.Write(HelperResult result) +80
   ASP._Page_Views_Shared__Layout_cshtml.Execute() in C:\Users\User\Desktop\Views\Shared\_Layout.cshtml:39
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +90
   System.Web.WebPages.<>c__DisplayClass40_0.<RenderPageCore>b__0(TextWriter writer) +232
   System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +10
   System.Web.WebPages.WebPageBase.Write(HelperResult result) +80
   System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +63
   System.Web.WebPages.WebPageBase.PopContext() +237
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +98
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +198
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
   System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9873649
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

A: coloca el stacktrace para saber quien dispara el null.
Los mas probables es que no esté seteado el valor de sesión "typeUser" y cuando hace el ".ToString()" explota.
Otro error que vas a tener es en javascript, debés colocar así:
var role = '@HttpContext.Current.Session["typeUser"].ToString()';


text:
Q: How to introduce a while loop in order to calculate monthly interest rate? I have a question where im asked to calculate interest rate of an account after asking user for:
P   is  the present value   of  the account.
i   is  the monthly interest    rate.
t   is  the number  of  months.

The current code I have is this:
def get_value(p, i , t):
    return p * (1 + i) ** t

def main():
    p = float(input("Please enter the current amount of money in your account: "))
    i = float(input("Please enter the monthly interest rate: "))
    t = float(input("Please enter the number of months: "))
    #the while loop would probably go here, but I just dont know how to do it#

    future_total = get_value(p, i, t)
    print ("\nAfter", t, "months, you will have $", format(future_total, ".2f"), "in your account.")

main()

But the output is only giving me the final amount after 10 months, how do I implement a loop in order to see how much money would be in the account since month 1?

A: I would first make a variable called month and set it equal to 1. Then I would use the while loop so that when the month is less than the inputted month, the present value will be updated based on the inputted information. This will print out the money in the account for each month and not just the final value.
def get_value(p, i , t):
    month = 1

    while month <= t:
        p = p * (1 + i)
        print(month, p)
        month += 1

def main():
    p = float(input("Please enter the current amount of money in your account: "))
    i = float(input("Please enter the monthly interest rate: "))
    t = float(input("Please enter the number of months: "))

    print(get_value(p,i,t))
    # future_total = get_value(p, i, t)
    # print ("\nAfter", t, "months, you will have $", format(future_total, ".2f"), "in your account.")
    # print(f'After {t} months, you will have ${future_total} in your account.')

main()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Advanced Collaboration with Google Maps Is there a way for me to create a custom Google Map for my website which the public may add markers to but may not remove markers that other people have already placed.
So are there any permissions I can edit to allow people to add but not remove markers?

A: You can use google map as a basemap and create your own layer in order manage it from your own server using eg mapserver and/or geospatial database such as PostGIS and openlayers on the front end. This way you will have a full control over who can add what and you can do it outside of googlemaps API sandbox


text:
Q: Dynamic Custom Options; data in orders with out normal custom options feilds The need is that I have a guest count on a product (product A) that changes the qty of the ordered amount.  What I have done is set up a bunch of custom options for the questions based on the guest for that particular product programmatically when the product  (product A) is added to the cart.
Currently it is saving the options to the product (product A) and this is working, but there has to be a better way. Here is what I want to do better on.  As you add a guest there are a set of questions for that guest of the product.  So as I add an order, this product (product A) get a custom option guest_1_menu=>'some text' is saved to the product (product A)  and you can see this new option on the back when editing the product (product A) .  Now when I make another order the product  (product A) this time was added to the cart with 2 guests which have there options, so guest_1_menu=>'some text new value' and guest_2_menu=>'some text'.  Now when you go to look at the product in the back end you have 2 custom options.
This all works like I said, but lets say over many order someone get to 10 guests when they check out, that product (product A) would have 10 custom options.  Here is a more visual representation of what I'm doing now
Order #0001
***(product A)***
    \___ guest 1
            \___ menu
             \___ gift

The product on the back now has 2 custom options,
- guest_1_menu
- guest_1_gift

Now we take a second order
Order #0002
***(product A)***
    \___ guest 1
            \___ menu
             \___ gift
    \___ guest 2
            \___ menu
             \___ gift

The product on the back now has 4 custom options,
- guest_1_menu
- guest_1_gift
- guest_2_menu
- guest_2_gift

Now we take a third order
Order #0003
***(product A)***
    \___ guest 1
            \___ menu
             \___ gift
    \___ guest 2
            \___ menu
             \___ gift
    \___ guest 3
            \___ menu
             \___ gift

The product on the back now has 6 custom options,
- guest_1_menu
- guest_1_gift
- guest_2_menu
- guest_2_gift
- guest_3_menu
- guest_3_gift

So just to be clear, if the number of custom options are a high water mark basically. (one last order example)
Order #0004
***(product A)***
    \___ guest 1
            \___ menu
             \___ gift

The product on the back still has 6 custom options as order 3 pushed it up there,
- guest_1_menu
- guest_1_gift
- guest_2_menu
- guest_2_gift
- guest_3_menu
- guest_3_gift

SO again this works, but you can see how messy this gets, so is there a better way to attach data to an order that will show from cart to invoice?  Happy to add classes or blocks that will help, but I really don't want to have it something that can get edited from the product in the admin.  I hope this was clear.

A: I think you need to set the custom options to the Quote Item and not to the product.
Check this method:
\Mage_Sales_Model_Quote_Item::addOption

It will be shown on the cart if you add it with the array code: additional_options
But you need to make sure that you are not overwriting the options that are already there.
Check this answer from Vinai on how to add options to the quote item and persist them: https://stackoverflow.com/a/9496266


text:
Q: Find/Replace characters next to numbers without replacing the actual number I try to express myself as good as I can.
I am trying to find all "A" in a text with a "B" but only the ones that contain a number after it.
With the extended search I tried the following:
A[^A-Za-z]

This works, but this selects the number as well I do not want to replace the number. I only want to replace the character "A" to "B", while leaving the numbers as they are.
Is this somehow possible in Notepad++?
I greatly appreciate any suggestion.

A: *

*Find what: A(?=\d)

*Replace with: B

*

*Replace all


text:
Q: Query to filter multiple elements from the array in results I do have this one working if I want to query attributes of employee by specifying a single email ID.
db.employee.find({},{
                _id: 0,
                employee: {
                    $elemMatch: {
                        email: "john@companyx.com"
                    }
                }})

Lets say if I want to query by specifying more than one email ID to get attributes of multiple employee.
I read through, it has something to do with $or operator, but I am not sure how to lay that one out..
My mongoDB data as per below example:
{
 "_id" : ObjectId("53dbb05fa976627439d43884"),
 "employee" : [
  {
    "email" : "john@companyx.com",
    "deptName" : "x",

},
{
    "email" : "keen@companyx.com",
    "deptName" : "y",

},
{
    "email" : "hung@companyx.com",
    "deptName" : "y",

}
 ]
 }

A: Array filtering can only be done by the aggregation framework. It allows more manipulation of the document than is available by basic projection.
Just like any query though, you should always use a $match pipeline first in order to make use of in index where possible. regardless of what other operations are being performed afterwards:
db.employee.aggregate([

    //  Always match first to reduce results
    { "$match": {
         "employee.email": { "$in": ["john@companyx.com", "keen@companyx.com"] }
    }},

    // Unwind to de-normalize the array elements as documents
    { "$unwind": "$employee" },

    // Match to "filter" the array content
    { "$match": {
         "employee.email": { "$in": ["john@companyx.com", "keen@companyx.com"] }
    }},

    // Group back to a document with the array
    { "$group": {
        "_id": "$_id",
        "employee": { "$push": "$employee" }
    }},

    // Optionally project to remove the "_id" field from results
    { "$project": {
        "_id": 0,
        "employee": 1
    }}
])

So that explains the basic process. After finding the "documents" that match your conditions, you use $unwind to effectively make each element of the array an document on it's own, sharing any parent fields. The additional $match is there to "filter" those elements in the results. When the $group is done, then only the matched elements are put back into the array.
With MongoDB 2.6 you can do this in a different way that should work better with larger arrays. There are new operators such as $map for processing an array "in-line" without using $unwind. There is also other "set" filtering options as $setDifference. So you can do this where your documents always contain unique "email" values in their own array:
db.employee.aggregate([

    //  Always match first to reduce results
    { "$match": {
         "employee.email": { "$in": ["john@companyx.com", "keen@companyx.com"] }
    }},

    // Project filtered array content "in-line"
    { "$project": {
        "_id": 0,
        "employee": {
            "$setDifference": [
                { "$map": {
                    "input": "$employee",
                    "as": "el",
                    "in": {
                        "$cond": [
                            { "$or": [
                                { "$eq": [ "$$el.email", "john@companyx.com" ] },
                                { "$eq": [ "$$el.email", "keen@companyx.com" ] }
                            ]},
                            "$$el",
                            false
                        ]
                    }
                }},
                [false]
            ]
        }
    }}
])

Aside from the new operators mentioned earlier, the $cond operator is used here to evaluate each element of the array that is passed through $map to see if it meets the conditions. If so the element is is returned in the resulting array, otherwise the element is false.
The $setDifference operator then "filters" any false values from the "set" returned, as would be any duplicates so the array elements would need to be unique in each document as mentioned.
For "non-unique" elements, there is always this alternate to the first method in modern versions as well:
db.employee.aggregate([

    //  Always match first to reduce results
    { "$match": {
         "employee.email": { "$in": ["john@companyx.com", "keen@companyx.com"] }
    }},

    // Redact removes document levels that do not match the condition
    { "$redact": {
        "$cond": [
            { "$or": [
                { "$eq": [
                    { "$ifNull": [ "$email", "john@companyx.com" ] },
                    "john@companyx.com"
                ]},
                { "$eq": [
                    { "$ifNull": [ "$email", "keen@companyx.com" ] },
                    "keen@companyx.com"
                ]}
            ]},
            "$$DESCEND",
            "$$PRUNE"
        ]
    }}
])

This uses $redact in a slightly contrived way to remove the array elements from the documents that do not match the condition. The catch here is that $redact is recursive, so that is why we test for the presence of the tested field and where it does not exist just return a value to match. Really only needs one $ifNull statement in there actually.
Essentially, whatever approach you choose, it is the aggregation framework that has the "souped up" manipulation of documents that does more than basic projection can.

A: If I have understood what you meant, I think that the solution for you is the $in operator, and I think that you should put your condition in the selector parameter, not in the projection one, if I have understood your needs. So your query would be something like:
db.employee.find({email:{$in:["email1@foo.bar", "email2@bar.foo"]}},{_id:0})

A: Projection operator $elemMatch only returns one element from the array, so I think you may consider aggregate, like
var emails = [ "john@companyx.com", "hung@companyx.com" ];
var match = {
    $match : {
        "employee.email" : {
            $in : emails
        }
    }
};

db.employee.aggregate([ match, {
    $unwind : "$employee"
}, match, {
    $group : {
        _id : "$_id",
        employee : {
            $push : "$employee"
        }
    }
}, {
    $project : {
        _id : 0,
        employee : 1
    }
} ]);


text:
Q: Docker exec fails, permission denied: unknown I'm new to docker and I'm just trying to create a simple Symfony API. I ran docker-compose up -d which created these containers:
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                                         NAMES
071de3320346        willdurand/elk      "/usr/bin/supervisor…"   About a minute ago   Up About a minute   0.0.0.0:81->80/tcp                            simple-api_elk_1
c24132f645be        simple-api_nginx    "nginx"                  About a minute ago   Up About a minute   0.0.0.0:80->80/tcp, 443/tcp                   simple-api_nginx_1
37128a03b667        simple-api_php      "php-fpm7 -F"            About a minute ago   Up About a minute   0.0.0.0:9000->9000/tcp                        simple-api_php_1
aa7738c59891        mysql               "docker-entrypoint.s…"   About a minute ago   Up About a minute   3306/tcp, 33060/tcp, 0.0.0.0:3307->3307/tcp   simple-api_db_1

I then took the id from the simple-api_php and ran
docker exec 37128a03b667 composer create-project symfony/website-skeleton symfony-api
It returns:
OCI runtime exec failed: open /tmp/runc-process126262263: permission denied: unknown

here is my docker-compose.travis.yml:
version: '2'
services:
    db:
    image: mysql
    environment:
        MYSQL_ROOT_PASSWORD: root
        MYSQL_DATABASE: symfony
        MYSQL_USER: symfony
        MYSQL_PASSWORD: symfony
    php:
        build: ./php-fpm
        expose:
            - "9000"
        volumes:
            - ./symfony:/var/www/symfony
            - ./logs/symfony:/var/www/symfony/var/logs
        links:
            - db
    nginx:
        build: ./nginx
        ports:
            - "80:80"
        links:
            - php
        volumes_from:
            - php
        volumes:
            - ./logs/nginx/:/var/log/nginx
    elk:
        image: willdurand/elk
        ports:
            - "81:80"
        volumes:
            - ./elk/logstash:/etc/logstash
            - ./elk/logstash/patterns:/opt/logstash/patterns
        volumes_from:
            - php
            - nginx

Just don't have enough knowledge to troubleshoot this.
Thanks!!

A: *

*You should edit your elk service.
elk:
  image: willdurand/elk
  ports:
    - "81:80"
  volumes:
    - ./elk/logstash:/etc/logstash
    - ./elk/logstash/patterns:/opt/logstash/patterns <-------- remove this line
  volumes_from:
    - php
    - nginx <-------- remove this line

Note: comments are marked with arrow <------

*Also, if you still have the same issue - try to remove images and containers and then rebuild them.
// This command will remove all containers and images in your docker-compose.travis.yml file
$: docker-compose down

// Or you can remove container and images manually
$: docker rm container_name
$: docker rmi image_name


text:
Q: Binding doesn't work on DependencyObject created in XAML I'm trying to pass multiple CommandParameters in XAML with the use of a custom class.
I have created a class called ValueCommandArgs that inherits from DependencyObject and has two DepencyProperties (lets call them Value1 and Value2 for this example).
The button which is supposed to call a command and pass this object looks like this:
<Button Command="{Binding ChangeValueCommand}" Content="Execute Command">
    <Button.CommandParameter>
        <args:ValueCommandArgs Value1="{Binding TestValue1}" Value2="{Binding TestValue2}" />
    </Button.CommandParameter>
</Button>

I do get an ValueCommandArgs-Object in my command as paramter, however the properties Value1 and Value2 are always null/empty.
I know this can be solved with a MultiBinding and Converter, but I think the way I'm trying it would be a cleaner approach.
Why doesn't this work?

A: A Binding needs a source object to be able to provide a value. When the Binding source is not specified (with Source or ElementName etc.) eg: Value1="{Binding TestValue1}" the DataContext of the element is used.
The args:ValueCommandArgs object does not inherit the DataContext from the Button element because property value inheritance is particularly about how property values can inherit from one element to another on the basis of the parent-child relationships within a tree of elements.
The button object does not include the value of the CommandParameter property in its logical nor the visual tree.
In many cases the need for such a CommandParameter with multiple bound values can be avoided by binding the values directly to the ViewModel.
When it can't be avoided you can use a different type of binding markup extension like: https://github.com/JohanLarsson/Gu.Reactive#ninjabinding that will use the root FrameworkElement as the source of the binding.
Another approach would be a binding proxy technique shown in this blog post: How to bind to data when the DataContext is not inherited


text:
Q: Filling HashMaps > i've a problem by filling the Hashmap<Object, Collection<Object>>.
every time i want to fill the value part of the HashMap(in this case the Collection) my object, which needs to be added to the Collection, only takes the last received value of the object.
for example my code is like this(Using LastFM API):
Map<Object, Collection<Tag>> tracksTags = new HashMap<Track, Collection<Tag>>();
Collection<Track> trackSet = tracks.getPageResults();
Collection<Tag> tags  = new HashSet<Tag>();

String artist = "";
String trackTitle = "";

int counter = 0;

for (Track track : trackSet) {
    tags.clear();

    artist = track.getArtist();
    trackTitle = track.getName();

    Collection<Tag> tagList = Track.getTopTags(artist, trackTitle,
                apiKey);

    for (Tag tag : tagList) {
            if (counter <= 9) {

                counter++;

                System.out.println(trackTitle + " " + tag.getName() + " "
                        + tag.getCount());
                tags.add(tag);

            } else
                break;
    }
    counter = 0;

    tracksTags.put(track, tags);

}

My problem is that tags only takes the value of the last retrieval... still have no idea why. Even i dont know if it is a Hashmap-Filling problem.
Would appreciate any help.

A: All of your tracks share the same inner HashSet instance.
Therefore, tags.clear() at the top of the loop, and the inner loop to populate the set, affect all of the tracks.
You need to create a new HashSet<>() for each track inside the loop.


text:
Q: Getting an attribute price to format to 2 decimal places I have the following code in my list.phtml file, this pulls in the price of the product and then multiplies it by 1.20 (this works great but it displays 3 or 4 numbers after the decimal point
 <?php if($_product->getData('deals_bus_price')) : ?>
    <?php  $attribute = $_product->getResource()->getAttribute('deals_bus_price');
if ($attribute) { echo "£", $attribute_value = $attribute ->getFrontend()->getValue($_product)*1.20 ; } ?>

<?php endif; ?>

Is there any way that I can add something which forces it to display only 2 decimals after the point..
I have tried getValue($_product)*1.20, 2;  etc but that doesn't work, all it displays is £288.492

A: Try this core helper function :
// This will show a price with Currency symbol
Mage::helper('core')->currency(PRICE_HERE, true, false);

Otherwise use number_format :
number_format(PRICE_HERE, 2, '.', '');
number_format($products->getPrice(), 2, '.', '') ;

The complete code:
<?php if($_product->getData('deals_bus_price')) : ?>
<?php
    $attribute = $_product->getResource()->getAttribute('deals_bus_price');
    if ($attribute) {
        $attribute_value = $attribute->getFrontend()->getValue($_product)*1.20 ;
        echo Mage::helper('core')->currency($attribute_value, true, false);
    }
?>
<?php endif; ?>

A: You can use php's number_format() function.
This function returns a string.

A: Try this
<?php if($_product->getDealsBusPrice()) : ?>
<?php  $attributeValue = $_product->getAttributeText('deals_bus_price');?>
<?php $attributeValue = ($attributeValue * 1.20)?>
<?php $attributeValue =  round($attributeValue, 2); ?>
<?php echo "£".$attributeValue; ?>
<?php endif; ?>

OR
<?php if($_product->getDealsBusPrice()) : ?>
<?php  $attributeValue = $_product->getAttributeText('deals_bus_price');?>
<?php $attributeValue = ($attributeValue * 1.20)?>
<?php echo Mage::helper('checkout')->formatPrice($attributeValue);?>
<?php endif; ?>

A: Use this code for 2 decimal places :
<?php if($_product->getData('deals_bus_price')) : ?>
    <?php  $attribute = $_product->getResource()->getAttribute('deals_bus_price');
if ($attribute) { echo "£", $attribute_value = number_format($attribute ->getFrontend()->getValue($_product)*1.20,2) ; } ?>

<?php endif; ?>


text:
Q: Query to count data where meet specific condition I have a problem to count c1 where they have a1 and a2 and count a1 and a2 alone.
C1 | C2
_______
a  | a1
a  | a2
b  | a1
b  | a2
c  | a1
d  | a2

Result.
a1 | a1 & a2 | a2       ---> from C2
________________
1 |     2     | 1         ---> from C1

I want to count where value from c1 have 2 value from c2.

A: Please try the following query.
   select [a1], [a1&a2],[a2]
from
(
  SELECT DISTINCT t2.c2 AS C2,COUNT(*) as col FROM Table1 t1
inner join Table1 t2 ON  t1.c1=t2.c1 GROUP BY t2.c2,t2.c1 HAVING COUNT(*)<2
UNION ALL
select distinct
   LTRIM(REPLACE(REPLACE(stuff((SELECT distinct '& ' + cast(c2 as varchar(10))
           FROM Table1 t2
           where t2.c1 = t1.c1
           FOR XML PATH('')),1,1,''),'& ','&'),'amp;','')) AS C2,Count(*) as col
from Table1 t1 group by c1 HAVING COUNT(*)>1
) d
pivot
(
  max(col)
  for c2 in ([a1],[a1&a2] ,[a2])
) piv;


text:
Q: How to run svcutil.exe from behind authenticating proxy I want to run the svcutil.exe tool to access a web service on the internet. Unfortunately, whenever I try, I get a bunch of errors that include the following message:

The request failed with HTTP status 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy filter is denied.

As I have learned from this related post (with more details here), the problem is that I am sitting behind an authenticating proxy. That post explains that I need to edit the app.config file, but I can't figure out how to do that. I think I will use the  /svcutilConfig:alternate_app.config switch, but I don't know how to construct a valid .config file to pass to that switch. What is the default app.config file that svcutil.exe uses?

A: Well, I think I have figured out the answer to my question:
It turns out that the default .config file used by svcutil.exe is called svcutil.exe.config, and (at least for me) it lives in this folder:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

I decided to just edit that file directly (rather than fumble around with the /svcutilConfig switch). I needed Admin privileges to do so.
The final contents of that file looked like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <generatePublisherEvidence enabled="false" />
  </runtime>
  <system.net>
    <defaultProxy useDefaultCredentials="true" />
  </system.net>
</configuration>

(with the secret sauce buried in the <system.net> element.)
In order for this all to work, I had to start the Command Prompt as Administrator, navigate to the folder listed above, and run the svcutil.exe command from there.
Hope this helps some other poor soul who gets stuck in this mess! Thanks to @AndrewWebb for the clues that got me going!


text:
Q: Fastest way to get the min index of 1D array value in another 1D bin array I want to get the index of one 1D array called value in another 1D array called bin and calculate the minimum index in each bin.
Here's the whole step:

Here's my current method:
import numpy as np

bin = np.array([1, 2, 3, 4])
value = np.array([1.2, 1.3, 2.1, 3.1])
extend_bin = np.append(bin[1:], np.iinfo('int').max)
mask = (bin[:, None] <= value[None, :]) & (value[None, :] < extend_bin[:, None])
res = np.argmax(mask, axis=-1)[:-1]

However, when the two 1D arrays are longer, I could get the memory error because of the large 2D mask array:
import random
import numpy as np

length = int(4e6)

a = np.random.rand(length)
order = np.argsort(a)
bin = a[order]
value = np.random.rand(length)
random.shuffle(value)
extend_bin = np.append(bin[1:], np.iinfo('int').max)
mask = (a[:, None] <= value[None, :]) & (value[None, :] < extend_bin[:, None])
res = np.argmax(mask, axis=-1)[:-1]

Memory error:
    mask = (a[:, None] <= value[None, :]) & (value[None, :] < extend_bin[:, None])
numpy.core._exceptions.MemoryError: Unable to allocate 14.6 TiB for an array with shape (4000000, 4000000) and data type bool

Is there any simpler and valid method to deal with problem?

A: Similar to the pd.cut proposed in the comments, one could use numpy.digitize:
import numpy as np
bin = np.array([1, 2, 3, 4])
value = np.array([1.2, 1.3, 2.1, 3.1])
extend_bin = np.append(bin[1:], np.iinfo('int').max)
binned_values = np.digitize(value, extend_bin)
# The above returns [0, 0, 1, 2]
_, res = np.unique(binned_values, return_index=True)
# res equals [0, 2, 3], i.e. the first index where each value happens

This also works in the extended case:
from time import time
length = int(4e6)
a = np.random.rand(length)
bin = np.concatenate([[0], np.sort(a), [1]])
value = np.random.rand(length)
tstart = time()
binned_values = np.digitize(value, bin)
print(time() - tstart)
# On my machine, the above takes about 4 seconds
tstart = time()
_, res = np.unique(binned_values, return_index=True)
print(time() - tstart)
# And this takes less than one second


text:
Q: Is there a linear transformation $T:\mathbb R^3\to \mathbb R^2$ such that $T(1,0,2) = (1,1)$ and $T(1,-1,4)=(2,2)$? Just as title says, I have no idea how to solve this one...
I checked the similar question at the site but the other one has the resulting vectors linearly independent, while in this example I got $(1,1)$ and $(2,2)$.
Please give a detailed explanation as I am a bit slow :C

A: Let $$\pmatrix{a & b & c \\ d & e & f}$$ be such a transformation. Then we need
\begin{align*}
a+2c &= 1\\
d+ 2f &= 1\\
a-b+4c &= 2\\
d-e+4f &= 2
\end{align*}
Hence we have
$2c = 1+b$ and consequently, $a+b = 0$. Similarly, $d+e = 0$. Thus we can take $a = 1, b = -1, c = 0$, and $d = 1, e = -1, f = 0$. Thus the required transformation is
$$T = \pmatrix{1 & -1 & 0 \\ 1 & -1 & 0}$$


text:
Q: Conda env Spyder Python interpreter ipython kernel crash I have a python 2.7 environment set up in Conda, and when launching Spyder it uses the system default python interpreter: Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, Dec 20 2016, 23:09:15)
After telling it to use the python interpreter that the environment is using: Python 2.7.14 |Anaconda, Inc.| (default, Dec  4 2017, 23:37:59)
[GCC 7.2.0] on linux2
The ipythonkernel crashes repeatedly. Maybe the reason is because it's launching spyder3 and not spyder2?
Any suggestions?
Edit* Crash code added:

File "/home/fosa/anaconda2/lib/python2.7/site‑packages/spyder/utils/ipython/start_kernel.py", line 212, in main
  from utils.ipython.spyder_kernel import SpyderKernel
  ImportError: No module named ipython.spyder_kernel
  Traceback (most recent call last):

Edit 2* Here is the path of the python interpreter causing the issue

/home/fosa/anaconda2/envs/tensorflow2/bin/python


text:
Q: How to project a function over a 3D plane When I looked up the method to express two variable functions as a sequence of intersecting horizontal planes, I thought to use PGFplots to construct a simple set of "slices" of a generic function (represented as a blue line).
Here is my MWE as the first plot (the first slice) is complied without errors:
\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
%
\begin{document}
%
Initial \TeX{}t
\begin{figure}[h]
\begin{centering}
\begin{tikzpicture}
\tikzset{%
 small dot/.style={fill=cyan,circle,scale=0.25}%
}
\begin{axis}[%
 grid=major,
 colormap/cool,
 zlabel=$z$,
 zmin=-5,
 ztick={-5,-2.5,0,2.5,5},
 ytick={-5,-2.5,0,2.5,5},
 zmax=5,
 xmin=-5,
 xmax=5,
 xlabel=$x$,
 ylabel=$y$%
]
\addplot3 [surf] {0};
\addplot3 [color=blue] coordinates {(0,-5,0) (0,5,0)};
\addplot3 [color=blue] coordinates {(-5,0,0) (5,0,0)};
\node[small dot,pin=-60:{$z_1$}] at (axis cs:2.5,-5,0) {};
%
\end{axis}
\end{tikzpicture}
\par
\end{centering}
\caption{Funzione definita $f_{1}(x,y)$ o $z_{1}$}
\end{figure}
\par
Ending \TeX{}t
%
\end{document}

And the output is evidently correct:

Now comes the major problem: I'd like to put ad additional layer with the specific function projected onto the new plane, but I have no idea on how to do this properly; as it can be seen the function on the MWE isn't really a function but some sort of "cheat".
The problem will be solved if a macro will be able to plot some function (i.e. sin(x)) onto a plane into the third dimension.
As I can see, this question is very similar to Tim N's Question (for comparison).
If the adding of a new layer will be too tricky, I'll accept the answer regarding the projection because it's the most important one, as the adding of more layers is easily solvable by re-correcting the position of the plots in my document.

A: So, your input is a 2d function f(x,y) and its surface, and you want to see its trace through z=0. This can be accomplished by means of a contour plot with level 0.
Here is a solution:

\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
%
\begin{document}
\thispagestyle{empty}
%
Initial \TeX{}t
\begin{figure}[h]
\begin{centering}
\begin{tikzpicture}
\tikzset{%
 small dot/.style={fill=cyan,circle,scale=0.25}%
}
\begin{axis}[%
 grid=major,
 colormap/cool,
 zlabel=$z$,
 zmin=-5,
 ztick={-5,-2.5,0,2.5,5},
 ytick={-5,-2.5,0,2.5,5},
 zmax=5,
 xmin=-5,
 xmax=5,
 xlabel=$x$,
 ylabel=$y$%
]

\addplot3 [surf] {0};

\addplot3[contour gnuplot={labels=false,levels={0},draw color=blue},domain=-4:4]
    {exp(-x^2 -0.3*y^2 -0.2*x*y)*5- 0.1};

%
\end{axis}
\end{tikzpicture}
\par
\end{centering}
\caption{Funzione definita $f_{1}(x,y)$ o $z_{1}$}
\end{figure}
\par
Ending \TeX{}t
%
\end{document}

I took the freedom to discard the blue cross to show only the contour plot fragment. Note that I used some random surface which came to my mind, but any expression or table data is suitable here.
This example requires gnuplot as pgfplots is unable to compute the contour levels on its own. Consequently, you need to run it with -shell-escape (like pdflatex -shell-escape <file.tex>).
The argument labels=false deactivates contour text labels, the levels key chooses the requested contour levels (accepts a list), and draw color is necessary because otherwise, the current colormap would be used which is inadequate in this context.

EDIT the following is OPTIONAL.
For the records, here is my earlier (mis)understanding of the request. It addresses a slighty different use-case, namely one in which the 1d contour is given and the question is how to position it correctly.
From what I understand, you are given some 1d function f(x) which is given either as math expression (your example with sin(x)) or perhaps as data table, right? And you want that to be plotted into a 3D plane which happens to be orthogonal to one of the cube faces?
In this case, you can use either a parametric plot (if the function is to be sampled) or reorder the columns if the plot function is given as data table.
Here is your example with modifications:

\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
%
\begin{document}
\thispagestyle{empty}
%
Initial \TeX{}t
\begin{figure}[h]
\begin{centering}
\begin{tikzpicture}
\tikzset{%
 small dot/.style={fill=cyan,circle,scale=0.25}%
}
\begin{axis}[%
 grid=major,
 colormap/cool,
 zlabel=$z$,
 zmin=-5,
 ztick={-5,-2.5,0,2.5,5},
 ytick={-5,-2.5,0,2.5,5},
 zmax=5,
 xmin=-5,
 xmax=5,
 xlabel=$x$,
 ylabel=$y$%
]
\addplot3[green] table[x=X,y expr=5,z=Y]
{
X Y
-5 5
-4 -1
-3 0
-2 1
-1 1.2
0 1
1 2
2 3
4 1
5 0
};

\addplot3 [surf] {0};
\addplot3 [color=blue] coordinates {(0,-5,0) (0,5,0)};
\addplot3 [color=blue] coordinates {(-5,0,0) (5,0,0)};
\node[small dot,pin=-60:{$z_1$}] at (axis cs:2.5,-5,0) {};

\addplot3[red,samples y=1]
    (x,{4*sin(deg(x))},0);

%
\end{axis}
\end{tikzpicture}
\par
\end{centering}
\caption{Funzione definita $f_{1}(x,y)$ o $z_{1}$}
\end{figure}
\par
Ending \TeX{}t
%
\end{document}

The red plot is a parametric plot; you see that I provided x,y,and z coordinate values explicitly, z being zero here due to the z=0 plane. Note that samples y=1 is required because \addplot3 {<expression>} always samples a 2d function f(x,y). If we say samples y=1, we tell pgfplots that it actually has just one coordinate, i.e. that it should sample a line although it is a 3d plot.
The green plot is a table plot in which I mapped the table's two columns X and Y to the plane y=5 . Note that the ordering of plots is important.
Is this what you had in mind?


text:
Q: What does the f do in plt.ylabel(f'g(x)')? Firstly,
import matplotlib.pyplot as plt
import matplotlib

In an elementary example on how to plot with matplotlib in our lecture I encountered the following line
plt.ylabel(f'g(x)')

What I have tried
In the documentation there's no mention of an additional parameter to be inserted before the actual label text. I further checked out examples where plt.ylabel was used and discovered here that also r seems to be a valid option.
Also, I discovered in this example that the "parameter" r can also be used in plt.title, but also in the corresponding documentation I didn't find anything.
Entire Code
plt.figure(figsize=(6,4))
X = np.arange(0,2*np.pi,0.2)
plt.plot(X,np.sin(X),'o-',label='$\sin(x)$')
plt.plot(X,np.cos(X),'*-',c='g', label='$\cos(x)$')
plt.ylabel(f'f(x)' rotation=0)
plt.grid() # adds grid
_=plt.legend(loc=3)

A: f stands for format string
u can use it everywhere it is not
matplotlib specific
example:
x = 12
print(f'Hello {x}') # That will print 'Hello 12'

Also:
print(f'Hello') # Also Works Just fine That will print 'Hello'

check if it is a left over f

A: As others have mentioned, the f in your code is probably a leftover from an f-string. You can read more on f-strings here.
As you mentioned, you can also find an r (or R) before a string. This defines a raw string. Raw strings are raw string literals that treat backslash (\) as a literal and not as an escape character.
Example:
dummy_str = "This is a \n normal string"
print(dummy_str)

raw_dummy_str = r"This is a \n raw string"
print(raw_dummy_str)

The above code will print out:
This is a
 normal string
This is a \n raw string

You can read more about raw string here.


text:
Q: How can we mock session values (request.getSession() ) in JUnit? private BankApp processSelection(HttpServletRequest request,
        String[] facets, String selectedText) {
    DebugUtility.debug(LOG, "Enter into JiraController :: processDashBoardPortFolioSelection()");
    BankApp project = new BankApp();
    List<BankApp> dataAgg = (List<BankApp>) request.getSession()
            .getAttribute(PROJECT_WISE_SESSION);
    if (CollectionUtils.isNotEmpty(dataAgg)) {
        List<BankApp> projects = new ArrayList<>();
        for (String currentProjectId : facets) {
            Project currProject = vendorUtils.getProjectDetails(currentProjectId);
            List<SourceProjectAssocation> sourceSystem = currProject.getSourceSytems("JIRA");
            List<String> jiraProjects = new ArrayList<>();
            sourceSystem.stream().forEach(s -> jiraProjects.add(s.getAssociatedJiraProject()));
            for (BankApp projectData : dataAgg) {
                if (jiraProjects.contains(projectData.getProjectKey())) {
                    projects.add(projectData);
                }
            }
        }
        project = processAllProjectsData(projects);
        project.setProjectKey(selectedText);
        project.setProjectsCount(projects.size());
    }
    DebugUtility.debug(LOG, "project in processDashBoardPortFolioSelection :: " + project);
    DebugUtility.debug(LOG, "Exit from JiraController :: processDashBoardPortFolioSelection()");
    return project;
}

How can we write junit test case for this method? The challenge I'm facing here is we need to mock request.getSession().getAttribute(PROJECT_WISE_SESSION). So I tried when(request.getSession()).thenReturn(session); but with request.getSession() I'm getting null.

A: try something like that
@Test
public void test() {
    HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
    HttpSession sessionMock = Mockito.mock(HttpServletRequest.class);
    Mockito.when(requestMock.getSession()).thenReturn(sessionMock);

    processSelection(requestMock, <and your facets and selectedText here>)

    //do some asserts/verifies here
}


text:
Q: Can you use "MaxErrorIncreases" when numerically integrating over a region? How do you pass the option "MaxErrorIncreases" to NIntegrate[] when integrating over a region?
Taking a simple ;) example from
Problems with NIntegrate, errors NIntegrate::slwcon and NIntegrate::inumri:
Ω = ImplicitRegion[
   0 <= x <= 34 && -18 <= y <= 0 && ! ((12 < x < 15 && -12 < y) ||
    (15 < x < 20 && -3 < y) || (20 < x < 23 && -7 < y) ||
    (23 < x <= 34 && -3 < y)), {x, y}];
fi = NDSolve[{
   Derivative[0, 2][φ][x, y] + Derivative[2, 0][φ][x, y] == NeumannValue[0,
     x == 0 && -18 < y < 0 || 0 < x < 34 && y == -18 ||
      x == 34 && -18 < y < -3 || x == 23 && -7 < y < -3 ||
      20 < x < 23 && y == -7 || x == 20 && -7 < y < -3 ||
      15 < x < 20 && y == -3 || x == 15 && -12 < y < -3 ||
      12 < x < 15 && y == -12 || x == 12 && -12 < y < 0],
   DirichletCondition[φ[x, y] == 1.5, 0 <= x <= 12 && y == 0],
   DirichletCondition[φ[x, y] == 0.4, 23 <= x <= 34 && y == -3]},
   φ, {x, y} ∈ Ω,
  "ExtrapolationHandler" -> {0 &, "WarningMessage" -> False}];

Then on this integral we get a warning that suggests raising "MaxErrorIncreases":
ClearAll[ff];
dxφ = Derivative[1, 0][φ] /. First[fi];
ff[x_?NumericQ, y_?NumericQ] := Quiet@Check[dxφ[x, y], 0.];
NIntegrate[ff[x, y], {x, y} ∈ Ω]

NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more than 2000 times....Increasing the value of the GlobalAdaptive option MaxErrorIncreases might lead to a convergent numerical integration....

However, using the usual Method setting results in an error:
NIntegrate[ff[x, y], {x, y} ∈ Ω, Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 5000}]

NIntegrate::regm: Method GlobalAdaptive is not applicable for a region domain. Continuing with method Automatic.

Is it possible to use "MaxErrorIncreases" with NIntegrate[] over a region?

A: I found the strategy, "SymbolicDomainDecomposition":
NIntegrate[ff[x, y], {x, y} ∈ Ω,
 Method -> {"SymbolicDomainDecomposition",
   Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 5000}}]

NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more than 5000 times....

(*  -6.0019  *)

It turns out not to be good way to integrate this function. Even with a setting of "MaxErrorIncreases" -> 100000, the result still has a large error.
There are better methods for the example integral in the OP, which may be found in the linked question.


text:
Q: Stylelint not warning about !important I have a project that make use of styled-components and I just have installed Stylelint following the official guide[1].
My .stylelintrc.json already have declaration-no-important set to true but seems have no effect, because I have one component that make use of !important (see bellow)
{
  "processors": ["stylelint-processor-styled-components"],
  "extends": ["stylelint-config-recommended", "stylelint-config-styled-components"],
  "rules": {
      "declaration-no-important": true
  }
}

$ ag important
lib/components/molecules/Checkbox/Checkbox.styles.ts
24:      border-color: #7e77a1 !important;

What I need to do to Stylelint warn me about the use of !important?
1 - https://styled-components.com/docs/tooling#stylelint

A: Could you try this instead?
'declaration-no-important': [true, { 'severity': 'warning' }]


text:
Q: Rotating UIPanGestureRecognizer? Have an app here where I have a UIScrollView being displayed on the TV using AirPlay, and I'm taking its UIPanGestureRecognizer (scroll gesture) and adding it to my own custom view on the iPad. Works wonderfully, and I can scroll the UIScrollView on the TV by touching my local view.
However, I have problems once I rotate the iPad. Since the view on the TV isn't rotating, the gesture doesn't rotate either. Meaning that panning up on my local view now becomes left (or right) on the UIScrollView on the TV.
So far I've tried removing the gesture before the rotation, and then adding it back in afterwards to see if that would help, but it's still stuck on being sideways when in landscape mode. I also don't want to create my own pan gesture as it wouldn't be as smooth as the one built into the scrollview.
Anybody here have any suggestions as to how to make this work?


text:
Q: Button adds input to form, but only first one. Not on multiple forms/divs I'm stuck here.
I have a 'working' function below (for each PHP array row, I"m creating a div with a form. The form has an empty input, a '+' button, and a submit button).
Using the first form/div, if I click the '+' button it adds an input field every time up to 10, which is exactly what I want.
However, when I do this on the 2nd, 3rd, or 4th form it adds inputs, but all of them to the first form. So if I click the '+' button on form 2, it adds an input to form 1. I know this has to do with having a non-unique button id and carrying that through my form inputs but I'm totally stuck on what to do here.
I need each form/div to have it's own independent fields, '+' button and submit button. Reason being, I'm going to add an AJAX call to the submit button that will submit any added input values for that given form (using the ticker ID given here `
`<?php echo $ticker['ticker'] ?>``) .

How can I fix this functionality to work for as many divs/forms as I have at any given time?

    <?php foreach($tickerDisplays as $key => $ticker):?>
        <form id="Items" method="post">

                            Item 1:
                            <input type="text" name="Items[]">

                            <button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>

                            <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
                            <input type="submit" name="saveTickerItems" value="Save Ticker Items">
                    </form>
    <?php endforeach;?>

A: Tom, the id attribute for an HTML element needs to be unique, always make sure to use unique id's, if you want to do something for elements that are similar in most ways, use class, on a side note to solve your problem:
Also change your Html to this (pass the button into the function)
Also I changed your id to a class as moreItems_add and removed the id entirely:
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>

//Accepts the button object
function moreItems(button) {
   //Instead of using a global iterator, grab the number of siblings of input type text
  const currentInputs = $(button).siblings('input:text').length;
  //Now use this variable to check if we hit the max of ten
  if(currentInputs < 10){}

replace these lines:
    $('
').insertBefore("#moreItems_add");
    $(label).insertBefore("#moreItems_add");
    $(input).insertBefore("#moreItems_add");

with these lines:
    //$(button) refers to the button which was clicked
    //.siblings() will check the node structure for element(s) with the given selector on the same level as the button
    //pass the jquery object of the button which was clicked into insertBefore()
    //Pass the newly created object into the line of code before calling .siblings
     //These 2 are inserting the new label and input
     $($(label)).insertBefore($(button));
     $($(input)).insertBefore($(button));
     //Insert a line break so that the next label and input are on new line
     $('
').insertBefore($(button));

A: You can't use the same ID to reference different DOM elements, use classes or an ID with a postfix.

A: If you are calling the JavaScript function to apply to a specific form you should instead call a function with a class name that applies to all of your forms. Instead of using an ID use a class

A: The  ids have to be unique. How about if you "build them" by appending ticket number?.
Something like
id="<? php echo ("Items".$ticket) ?>". Then you can get the element's id in the js, and insertBefore as appropriate.
For the button, it would be something like this:
<button type="button" id="<?php echo "moreItems_add".$ticker ?>" onclick="moreItems(this);">+</button>
Similarly for the form element:
<form id="<?php echo "Items".$ticker ?>" method="post">
This will give each form element and each button element a unique id. --edit->- The idea being you could use that id in the js instead of #moreItems_add here'
').insertBefore("#moreItems_add"); (from the original iteration of the post). That said, I hadn't groked that no object was being sent to the function (ie this here  moreItems(this); and button here function moreItems(button). (And on top of all that, jquery is, ahem, not my best thing). The bottom line is: if you need an unique id for the button in the javascript, you will find it now at button.id.


text:
Q: Find the resource pages of evaluations on human learning rate against deep learning Maybe one year ago I read a paper about the comparison between humans and machines' learning rate. It says the human can learn fast in the beginning then get slower later, machines oppositely. I lost my search history and googled a lot but fail to find it. Hope someone can help me find the source page or give me a simple explanation about it. I remember there are some mathematical proofs behind it.
Hope I made this question clear. Thanks!


text:
Q: How to retrieve Location Objects from a database? I want to store Location objects into my database, and then be able to load them. How can I build a Location object from its attributes?

*

*Should I create a blank Location and then set the attributes? (If yes, how?)

*Should I use my database as a LocationProvider? (If yes, how?)

Thanks!
EDIT: The only working solution I found so far is to retrieve the current Location, and override all the attributes... There has to be a better way!
my code:
public Location selectLocationById(int id){
    String query = "SELECT * FROM " + LOCATIONS_TABLE + " WHERE id = " + id + ";";
    Cursor c = db.rawQuery(query, null);
    Location l = null;
    if(c.getCount() == 1) {
        c.moveToFirst();
        if(c.getColumnCount() == 8){
            l = new Location(MyProject.getCurrentLoc());
            l.setAccuracy(c.getFloat(1));
            l.setAltitude(c.getDouble(2));
            l.setBearing(c.getFloat(3));
            l.setLatitude(c.getDouble(4));
            l.setLongitude(c.getDouble(5));
            l.setSpeed(c.getFloat(6));
            l.setTime(c.getLong(7));
        }
    }

    if(c != null && !c.isClosed()) {
        c.close();
    }

    return l;
}

A: This makes sense. I believe you could use
l = new Location(null);

So that you don't have to get your current location. This should still create a new Location, but with a provider string of null, using the other Location constructor:
Location(String provider)

See http://developer.android.com/reference/android/location/Location.html


text:
Q: What are typescript `--lib` library files? There is a similar question.  That covers what typescript does with the option.  The below question and answer covers where the lib files come from at runtime.
When I looked up the description for the --lib compiler option it says:

List of library files to be included in the compilation.

What are these library files and how are they included?  The repository I'm studying has the following settings?
"compilerOptions": {
  "target": "es5",
  "module": "es2015",
  "lib": ["es2015", "dom"]
},

How would the output be different if --lib were not set to ["es2015", "dom"]?

A: They tell the typescript compiler that those type libraries are available during the run-time and it won't complain that your target es version is missing features.
Your config is targeting es5, but you're telling typescript that "es2015" features will be available - so for example Promise and Map. Similarly you have "dom", so typescript knows that you have window and browser-dom features.
As far as I'm aware, it won't alter the output... typescript will simply error when you try to use features that are not present in your target es version.
You'd do this when you want to target old browsers, but also want to use, for example, Promises. So we tell the compiler its available with lib:["es2015.promise"] then you run something like core-js or bluebird at execution-time to polyfill the Promise  functionality.


text:
Q: Making UITableView scroll to right location when using custom keyboard I have a UITableView and I need to use a custom keyboard with it and, for a few reasons, I can't use it as an inputView.  So I am having a my keyboard view appear as a subview.  Its height is 260.  I want the table view to scroll so that the selected cell always has a y-position between 0 and 260.  Is this possible?  Here is what I am currently trying... (this is in the keyboard class)
-(void)showForCellAtIndexPath:(NSIndexPath*)indexPath{
[UIView beginAnimations:nil context:NULL];
self.view.frame = CGRectMake(0.0,220.0,320.0,260.0);
delegate.tableView.contentInset = UIEdgeInsetsMake(0.0,0.0,260.0,0.0);
delegate.tableView.scrollIndicatorInsets = delegate.tableView.contentInset;
delegate.view.frame = CGRectMake(0.0,-210.0, delegate.view.frame.size.width,delegate.view.frame.size.height);
[UIView commitAnimations];
[delegate.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}
I would love your help.  Thanks!

A: Alright...this solution is kind of a hack, but if someone searches and finds this, I don't want them to go thru the hell I did to figure it out.
What I did was modify the header height of the first section of the grouped table view to be large (300px was big enough for me).  Then I changed the y-inset (in my case to -255), so that everything looked normal.  When the user selects a section, I immediately  eliminate the inset and do a scroll to bottom... Then, when the user hits done, I re-add the inset, so that the user doesn't have to go through extra scrolling.
I hope this helps anyone who has this same issue!


text:
Q: How can I rename an XML node using PowerShell? I'm trying to rename an XML node using PowerShell. For example:
<configuration>
<desktops>
   <name>PC001</name>
   <domain>CORP</domain>
</desktops>
<laptops>
   <name>PC002</name>
   <domain>CORP</domain>
</laptops>
</configuration>

I want to rename the first <name> tags to <PC1name> (and </PC1name> respectively). Here's what I have, so far:
$InputFile = "NetworkConfigs.xml"
$xml = [xml](get-content $InputFile)
$root = $xml.get_DocumentElement();
#replace the node
$root.desktops.name.?

$xml.Save($InputFile)

I don't know how to replace the <name> tag with something else. Tips?

A: Bottom line, an XML node's name is immutable. Reference msdn.
Here's a quick example of creating a new node with the required data. Hope it helps.
$InputText = @"
<configuration>
<desktops>
<name>PC001</name>
<domain>CORP</domain>
</desktops>
<laptops>
<name>PC002</name>
<domain>CORP</domain>
</laptops>
</configuration>
"@

$xml = [xml]($inputText)
$desktopsNode = [System.Xml.XmlElement]$xml.configuration.desktops
$nameNode = $desktopsNode.SelectSingleNode('name')
$pcNameNode = $xml.CreateElement('PC1Name')
$pcNameNode.InnerText = $nameNode.InnerText
[void]$desktopsNode.AppendChild($pcNameNode)
[void]$desktopsNode.RemoveChild($nameNode)
$xml.OuterXML

Output:
<configuration><desktops><domain>CORP</domain><PC1Name>PC001</PC1Name></desktops><laptops><name>PC002</n
ame><domain>CORP</domain></laptops></configuration>

A: Renaming nodes in XML is more complicated than you might expect. It's especially bad if the node is a root node, or parent with a complex hierarchy of child nodes. Most "rename" methods I've seen will clone the children and append them to the new node. This process is made a little easier if your API also includes a ReplaceChild method. (I can provide details if you need them.)
An alternative method that I have used (especially if the XML can be represented as a string) is to replace the text in the XML before converting it to XmlDocument.
$InputText = @"
<configuration>
<desktops>
<name>PC001</name>
<domain>CORP</domain>
</desktops>
<laptops>
<name>PC002</name>
<domain>CORP</domain>
</laptops>
</configuration>
"@

$regex = [regex]'(</?)name>'
$ModifiedText = $regex.Replace($InputText,"`$1PC1Name>",2)
$xml = [xml]$ModifiedText

Note that the replace statement finds and fixes the first 2 occurrences of the match--the opening and closing tag of the first element only. Remove the number to find and replace all occurrences in the string. Note also that the regular expression captures the opening tag characters, so that they can be inserted into the string match as $1.

A: $oldtag = "name"
$newtag = "PC1name"
$xml = Get-Content D:\oldfile.xml
$new = $xml -replace $oldtag, $newtag
Set-content -path D:\newfile.xml -value $new

My way is I convert the XML to a string, then replace the node (which in this case is just normal string).
It works for me.

A: Inspired by a simple C# solution I ended up with this function (which also takes care of attributes):
Function RenameXmlNode ($oldNode, $newName) {
    $newNode = $oldNode.OwnerDocument.CreateElement($newName)

    foreach ($childNode in $oldNode.ChildNodes) {
        $newNode.AppendChild($childNode.CloneNode($true))
    }

    foreach ($attribute in $oldNode.Attributes) {
        $newNode.Attributes.Append($attribute)
    }

    $parent = $oldNode.ParentNode
    $parent.ReplaceChild($newNode, $oldNode)
    return $newNode
}

If the result is not needed, it can be ignored - the renamed node is already part of the document, the $oldNode belonged to.
Example:
$InputFile = "NetworkConfigs.xml"
[xml] $doc = Get-Content $InputFile
$nameNode = $doc.SelectSingleNode('/configuration/desktops/name')

RenameXmlNode $nameNode $nameNode.InnerText

$xml.Save($InputFile)


text:
Q: jQuery AJAX POST to ASMX web service results in "Cannot convert object of type System.String to System.Collections.Generic.IDictionary" I have an ASMX web service set up as follows as a test:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool Test (string id)
{
    if (id != null)
    {
        return true;
    }
    else
        return false;
}

From jQuery I then wasn't to call that web method and pass in a parameter "id". So I use:
$.ajax({
    var data = JSON.stringify("id: 123");
    data: data,
    dataType: "json",
    url: url
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function (result) {},
    error: function (xmlHttpRequest, textStatus, errorThrown) {
          console.log(xmlHttpRequest.responseText);
          console.log(textStatus);
          console.log(errorThrown);
    }
});

I have used JSON.stringify to make sure the JSON is correct. However when I run the above I get the following 500 Internal Server error back:

{"Message":"Cannot convert object of type \u0027System.String\u0027 to
  type
  \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":"
  at
  System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object
  o, Type type, JavaScriptSerializer serializer, Boolean throwOnError,
  Object\u0026 convertedObject)\r\n   at
  System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object
  o, Type type, JavaScriptSerializer serializer, Boolean throwOnError,
  Object\u0026 convertedObject)\r\n   at
  System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String
  input)\r\n   at
  System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
  context, WebServiceMethodData
  methodData)","ExceptionType":"System.InvalidOperationException"}
  VM12798:89 error

It looks to me like this error is occurring once the request as been received via the server. I'm not sure however, why its trying to turn the string into an IDictonary?
The above code seems simplistic. Am I setting up the JSON wrong? If I console.log data it returns:
"id: 123"

Is ASMX expecting something different?

A: You are declaring var data inside a JSON object.  Just set the data property directly.
Also, you are using JSON.stringify incorrectly.  It should be used to convert a JavaScript object into a JSON string.
See updated code below:
$.ajax({
        data: JSON.stringify({id: "123"}),
        dataType: "json",
        url: url
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (result) {},
        error: function (xmlHttpRequest, textStatus, errorThrown) {
              console.log(xmlHttpRequest.responseText);
              console.log(textStatus);
              console.log(errorThrown);
        }
});


text:
Q: OS X ejabberd configure error: SQLite3 library >= 3.6.19 was not found I tried to install ejabberd in my local Mac OS X machine, but while configuring sqlite using following command as mentioned in steps. I'm stuck at the following issue.
./configure --prefix=$HOME/my-ejabberd --enable-sqlite

Error received
checking for SQLite3 library >= 3.6.19... yes
cat: /include/sqlite3.h: No such file or directory
./configure: line 4172: test: !=: unary operator expected
configure: WARNING: Cannot find SQLITE_VERSION macro in sqlite3.h header to retrieve SQLite version!
configure: error: SQLite3 library >= 3.6.19 was not found

Steps I followed from - https://docs.ejabberd.im/developer/install-osx/

A: If you just want to install vanilla Ejabberd then you can simply do brew install ejabberd.
According to the issue, you can also try:
./configure --prefix=$HOME/my-ejabberd --enable-sqlite --with-sqlite3=/usr/local/opt/sqlite
P.S. I have filed the issue on Github Ejabberd.


text:
Q: Prove that norm of Yosida approximations blows up I need an help with the following exercise about Yosida approximations. Let's fix the notation: let $A$ be an unbounded linear operator define on a  dense domain $D(A)\subset X$ of a Banach space $X$.
Define the resolvents $J_n:=(I-\frac{1}{n}A)^{-1}$ and the Yosida approximations $A_n:=n(J_n-I)$.
We have already proved that, if $x\in D(A)$, $||A_n x||\to ||A x||$ as $n\to \infty.$ Our aim is to prove that, if $x\notin D(A)$ then the sequence $\{||A_nx||\}$ is increasing and unbounded, i.e. $||A_nx||\to \infty$.
How can we prove it? We have tried to prove it directly by definition of $A_n$, but we got stuck. Any help is really appreciated.


text:
Q: Ask user to activate Mobile Network/3G via a dialog type alert in Android I am developing an Android Application and I need to make sure that the user is connected to the internet somehow. I can already check for WiFi, however, not everyone will be near a WiFi zone all the time, so I am thinking that Mobile Data is a valid alternative (of course assuming that the device is capable of having a SIM and all). So far, I can check if the user has enabled his or her mobile data as follows:
if(checkForMobileNetworkActive()){
    //with mobile active
}
else{ // mobile not active
}

What I want to do is this: If the mobile network is NOT active, I will ask the user to turn it on. Very similar to what I have done in the past where I prompt the user to turn on their Bluetooth or the Location services. However, upon searching online, most answers pointed me to opening the WiFi settings via intent as such:
Intent i = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(i);

I have 2 issues with this solution:

*

*This opens a new activity and not an alert dialog-style prompt to turn the WiFi on.

*This turns on the WiFi and not the Mobile Data.

Has anyone tried to prompt the user to turn on their Mobile Data? As much as possible, I want it to look like the dialog box prompt and not an entire new activity (which is bad user experience in my opinion). I've looked on how to do it programmatically, however, what I stumbled upon no longer works for non-rooted device on Android Lollipop+ and I don't want to run the risk of the app no longer running when users upgrade the OS of their Android Devices.
Edit
I saw the link posted in the comment below, and I've tried this:
if(checkForMobileNetworkActive()){
}
else{
    Intent i = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
    startActivity(i);
}

But it opens the Mobile Data/Data Roaming Settings as a new activity. While it works, it enables the user to check the checkbox for Mobile Data and pressing the back button goes back to my app, it is not a very smooth user experience.

A: First of all, you have to use this permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

After that, with this code, you can know whether it connected to internet by mobile data or not:
public static boolean isConnectedMobile(Context context){
    NetworkInfo info = Connectivity.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}

UPDATE 1:
If you want to enable/disable the mobile network in your app, you can use this solution:
private void enableMobileData(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    final ConnectivityManager cm = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(cm.getClass().getName());
    final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
    connectivityManagerField.setAccessible(true);
    final Object connectivityManager = connectivityManagerField.get(cm);
    final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}

And don't forget to use this permission:
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>


text:
Q: group a set of records by date in teradata Currently I have data in a table as shown below:
date        id   value
1-Jan-13    1    100
2-Jan-13    1    100
3-Jan-13    1    100
4-Jan-13    1    200
5-Jan-13    1    200
6-Jan-13    1    100
7-Jan-13    1    100

I am trying to group the records based on the id and val and version records with startdate and end date .
Desired output:
start date  end date    id   value
1-Jan-13    3-Jan-13    1    100
4-Jan-13    5-Jan-13    1    200
6-Jan-13    7-Jan-13    1    100

A: I'm not an expert in Teradata but you most likely, since windowing functions are supported (specifically ROW_NUMBER),  be able to do something like this
SELECT MIN(date) start_date, MAX(date) end_date, id, value
  FROM
(
  SELECT date, id, value,
         ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) -
         ROW_NUMBER() OVER (PARTITION BY id, value ORDER BY date) island
    FROM table1
) q
 GROUP BY id, value, island
 ORDER BY start_date, end_date

Sample output:

| START_DATE |   END_DATE | ID | VALUE |
|------------|------------|----|-------|
| 2013-01-01 | 2013-01-03 |  1 |   100 |
| 2013-01-04 | 2013-01-05 |  1 |   200 |
| 2013-01-06 | 2013-01-07 |  1 |   100 |

Here is SQLFiddle demo (It's a SQL Server demo, but should work as expected in Teradata)

A: The ROW_NUMBER version can be further simplified: modified SQL Fiddle
For Teradata:
SELECT
   id,val,MIN(dt),MAX(dt)
FROM
 (
   SELECT
      id,val,dt,
      dt - ROW_NUMBER() OVER (PARTITION BY id ORDER BY val, dt) AS dummy
   FROM table1
 ) AS dt
GROUP BY 1,2,dummy

And there are some hardly known functions in TD13.10 for processing time series data:
WITH cte(id,val,pd) AS
 (
   SELECT id, val, PERIOD(dt, dt+1) AS pd
   FROM table1
 )
SELECT
   id, val,
   BEGIN(pd) AS start_dt,
   LAST(pd) AS end_dt
FROM
   TABLE (TD_NORMALIZE_MEET
           (NEW VARIANT_TYPE(cte.id,cte.val)
           ,cte.pd)
   RETURNS (id INTEGER
           ,val INTEGER
           ,pd PERIOD(DATE)
           ,Nrm_Count INTEGER)
   HASH BY id
   LOCAL ORDER BY id, val, pd
   ) A
ORDER BY start_dt, end_dt


text:
Q: Need a interface for a sql database as a form on django website I have a django website on which i need to embed a form which is nothing but just a table interface on an SQL database. I would like to perform dynamic changes i.e. add, delete, modify etc. operations . I am not sure how I could achieve this?
I have looked on few things such as backbone js and ember and some other.
Could someone advise me which one I can use and if there any resources or examples I can look at?

A: Since you have tagged this with Javascript and Jquery, I'm assuming you are referring to doing changes asynchronously via ajax in the client. Otherwise the standard way to do this in Django is to use the ModelForm
For async CRUD operations (Create, Read, Update, Delete) I do the following:
1) Use Django Tastypie to create a RESTful HTTP interface to your models. This will ensure that you will get a POST, GET, PATCH/PUT, DELETE http urls for each operation.
2) Use jquery $.ajax to bind your form fields to these operations
$.ajax({
  url: 'http://localhost:8000/api/v1/yourmodel/1/',
  type: 'GET',
  accepts: 'application/json',
  dataType: 'json'
})

Use a tool like Postman in your browser to test your API or alternatively you can use curl


text:
Q: How to implement surface calculation of a elliptical cone and elliptical paraboloid (in R)? How can I calculate the surface of an elliptical paraboloid in R, having only the two major axes a and b, and the height h?
Background: got a population of things which which resemble elliptical paraboloids. (Think of hummocks, e.g.). What I'm statistically interested in is: how large is the mean and SD error I introduce when I approximate the surfaces of the population as rectangular (a * b) instead of properly modelling their surface? I could just go for a cone, but I've got some really long ellipses in that population of data. This made me look for how to calculate an elliptical paraboloid, and and elliptic cone. Which did not help me answering my question so far.
I can't translate the neither Wolfram nor Wikipedia properly, just started for the cone with
paraboloid.surf <- function(a,b,h){2*a*sqrt(b^2+h^2)* E * sqrt((1-b^2/a^2)/(1+b^2/a^2))}

without knowing how to calculate E, or even understanding if this is E multiplied by the term, or a function E(k) of k = the term.
Can somebody help me out and provide some code? I would be interested in both the conical as the parabolical solution, but any is better than none. I hope this is really non-trivial, and I'm not totally stupid. =)

A: So I assume you want the surface area of an elliptic paraboloid. The basic framework is given here, from which the following image is taken.

So the question is how to compute this in R? The hardest part is the double integral, which can be evaluated using the adaptIntegrate(...) function in the cubature package.
A <- function(a,b,h) {
  require(cubature)
  integrand <- function(x,a,b){
    u <- x[1]
    v <- x[2]
    E <- 1+((a*cos(v))^2 + (b*sin(v))^2)/(4*u)
    F <- (b^2 - a^2)*sin(2*v)/4
    G <- u*((a*sin(v))^2+(b*cos(v))^2)
    return(sqrt(E*G-F^2))
  }
  adaptIntegrate(integrand,
                 lowerLimit=c(0,0), upperLimit=c(h,2*pi), a=a,b=b)$integral
}

We can confirm this by noting that when

a = b = h = 1
E = 1 + 1/4u
F = 0
G = u
A = 2π ∫du sqrt(u+1/4)

Which can be evaluated in closed form as:

A = 4π/3 [ (5/4)3/2 - (1/4)3/2 ] = 5.330414

A(1,1,1)
# [1] 5.330413
(4*pi/3)*((5/4)^(3/2) - (1/4)^(3/2))
# [1] 5.330414

A: From https://en.wikipedia.org/wiki/Elliptic_paraboloid the defining equation for an elliptic parabola is z/c = x^2/a^2 + y^2/b^2. We can transform this to make a hill with height 'h' and base at z=0 being an ellipse.
For a elliptic parabola
   z = h*(1 - ((x/a)^2+(y/b)^2)).

Where a and b are the semi-major and semi-minor axis of the ellipse generated by cutting the cone by z=0 and h is the height of the point above (0,0).
For a elliptical cone
   z = h*(1 - sqrt((x/a)^2+(y/b)^2))`.

Where a and b are the semi-major and semi-minor axis of the ellipse generated by cutting the cone by z=0.
To plot both you need to clip by the plane z=0 use max(0,h*(1 - ((x/a)^2+(y/b)^2)).
Volumes
The area of an ellipse is pi a b, the volume of a cone is 1/3 basearea * h so volume of the cone is
    1/3 pi a b h.

As mentioned elsewhere the volume of the elliptic paraboloid is a bit tricky.
We can try doing it by slicing in the z-direction.
    int_{z=0}^{h} area of ellipse at height z dz.

If the ellipse at height z has semis a(z) and b(z) then the area is
    A(z) = pi a(z) b(z).

To find the a(z) and b(z) slice the paraboloid by the planes y=0, x=0, these give two parabolas z = h *(1 - (x/a)^2), z = h *(1 - (y/b)^2). Rearrange z/h = 1 - (x/a)^2, (x/a)^2 = 1 - z/h x/a = sqrt(1-z/h) x=a*sqrt(1-z/h) this is our a(z). Similary b(z)=b*sqrt(1-z/h). The area of the ellipse at height z is
 A(z) = pi a(z) b(z)
      = pi a sqrt(1-z/h) b sqrt(1-z/h)
      = pi a b (1-z/h)

Integrate
 int_{z=0}^h pi a b (1-z/h)
    = pi a b [z - z^2/(2 h)]_0^h
    = pi a b (h - h^2/(2 h))
    = 1/2 pi a b h

remarkably simple.
For comparison the volume of the cuboid with height h and lengths 2a and 2b would be
    4 a b h.

Surface areas
From https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_second_kind the circumference of a ellipse with semi-major axis a and eccentricity e is
    4 a E(e)

where E(e) is a complete Elliptical integral of the second kind. The eccentricity e is
    e = sqrt( 1 - b^2/a^2 ).

In both the cone and elliptic paraboloid cases the eccentricity is constant for all horizontal slices. The integrals for surface areas then simplify nicely. For the cone
a(z) = a * ( h - z). So
    int_z 4 a(z) E(e) dz
       = 4 E(e) int_z a(z) dz
       = 4 E(e) int_{z=0}^h a * (h -z ) dz
       = 4 a E(e) int_{z=0}^h h - z dz
       = 4 a E(e) [h z - z^2/2]_{z=0}^h
       = 4 a E(e) h^2/2
       = 2 a E(e) h^2

For the elliptic paraboloid a(z)=a*sqrt(1-z/h) and the integral is
    int_z 4 a(z) E(e) dz
       = 4 E(e) int_z a(z) dz
       = 4 E(e) int_{z=0}^h a * sqrt(1-z/h) dz

change variables with w=1-z/h limits are 1 and 0 dz/dw = -h so
       = 4 E(e) int_{w=1}^0 a * sqrt(w) * -h dw
       = 4 a E(e) h int_{w=0}^1 sqrt(w) dw      // switching limits round
       = 4 a E(e) h [ 2 w^(3/2) /3]_{w=0}^1
       = 8/3 a E(e) h.

Multivariate normal distribution
An alternative and more standard model is as a 2D gaussian https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function
    z = 1/(2 pi a b) exp( -( (x/a)^2 + (y/b)^2 )/2).

This will look pretty close to the paraboloid apart from at the base.


text:
Q: Xcode 10.1: Profile is not an "iOS In House" profile I am attempting to distribute via the Enteprise method on my Xcode 10.1 so I can get the .ipa to the organization.
For App Thinning I selected All compatible device variants and selected Rebuild from Bitcode.
On the PROD.app select, I select the PROD mobile provisioning profile the organization provided to me, but I get the following error below:

What does this mean and how do I resolve it?

A: When you create your provisioning profile and certificate in "Certificates, Identifiers & Profiles" on Apple's Developer web site - you have chosen the wrong type of provisioning profile. You'll need to choose "In House" from under the "Distribution" headline in order to get the right kind of profile.


text:
Q: Taking a bug report from Galaxy S3 One of my users has Samsung Galaxy S3 with JellyBean.
I tried to instruct him on sending me a bug report, but apparently, the option doesn't exist on his device.
The normal power + volume up + volume down doesn't work.
There is no option for that in "Developer Options".
The device runs JB, so 3rd party logcat apps don't work.
I prefer not to code or use a bug report library in my app just so Galaxy S3 can send a bug report...
Anything I missed?
Any 3rd party app that invokes the "send bug report" feature?


text:
Q: Autorelease iPhone Coming up towards the end of developing an iPhone application and I'm wondering just how bad is it to use autorelease when developing for the iphone. I'm faced with some fairly random crashes and, so far, I can't pinpoint it to anything other than sloppy memory usage.
As a Cocoa newbie I remember initially reading a guideline document that strongly suggested avoiding autorelease in favor of manual retain/release for iPhone. However, a more 'senior' Cocoa developer came on board early on (who ironically has been let go since), who used autorelease all over the place. Admittedly, I was went into "monkey see monkey do" mode, and it appears to be coming back to haunt me (I'm now the only developer on the project).
So what to do next? It seems to me that I have to branch the code and try to go through and replace, where possible, autorelease code keeping my fingers crossed that I don't inadvertently break the app. It seems a lot of library calls result in autoreleased objects like stringWithFormat and pretty much anything where I'm not using alloc myself. Any other gotchyas and/or suggestions I should be looking out for? Thanks Cocoa gurus.

A: More important than the autorelease or manual-release choice is how often you alloc and dealloc your NSAutoreleasePools.  Since most of the Cocoa frameworks use autorelease liberally, you need to have a proper pool draining strategy.  Once that is in place, the choice of whether to release or autorelease becomes much less an issue.
That being said, the only areas you should worry about are tight loops--allocate and release an NSAutoreleasePool every few iterations for best results; and when you have spawned another NSThread that doesn't have a Runloop--create a pool and drain it every so often becomes idle.  Since most applications only allocate a small amount of data per event, UIKit's strategy of allocating the pool before the event is dispatched and releasing it after the dispatch returns works very well.

A: If you think you dunno how to use autorelease, check out CS193p FALL 2010 on iTunes U -> Lecture number 4.
It teaches you all about memory management and stuff (if you skip the first 10 minutes or so)

A: Using release instead of autorelease can improve memory usage in tight spots (which is good on the iPhone), but it's not going to help at all with crashing if you're not following the retain / release rules. I would read a few tutorials on memory management in Obj-C if you're still a little hazy on what you should be doing, and then go after those crashes using the debugger and crash reports to find out where you're over releasing objects. This and this are two good places to start.

A: For iPhone performance reasons, Apple suggest that, whenever possible, you shouldn't use autoreleased objects. Instead, explicitly release your objects when you are done with them.

A: Using autorelease pools means that you might be leaving some unused memory lying around.  Since the iPhone has less memory to go around, you might improve performance if you free up unneeded memory as soon as possible, rather than letting it sit around taking up resources while it waits for an autorelease.

A: When you autorelease, you're basically saying: "I don't need this any longer, but anyone else is free to pick it up (before the auto release pool is drained)". When you explicitly relase an object you're saying: "I don't need this any longer and unless anyone else has already said otherwise (acquired), it should be deallocated immediately."
Consequently, autorelease is not normally the wrong thing to. It is required when you want to pass objects back to the sender of a message without requiring the sender to take care of releasing the object.


text:
Q: Understanding Connectors ActiveMQ Artemis I am new in ActiveMQ Artemis
I have read doc and found connectors    are used    by  a   client  to  define how  it  connects    to  a   server.
I have a broker.xml file which have following peace of code
     <connectors>
             <connector name="netty-connector">tcp://0.0.0.0:61616</connector>
             <!-- connector to the server1 -->
             <connector name="server1-connector">tcp://0.0.0.0:9616</connector>
          </connectors>
   <!-- Acceptors -->
      <acceptors>
         <acceptor name="netty-acceptor">tcp://0.0.0.0:61616</acceptor>
      </acceptors>

so here acceptor is saying,Hey you can connect with  me on port 61617, I am listening on it(which is making sense for me)
but what about role of connector in this broker.xml.
Connector is targeting same port(tcp://0.0.0.0:61616) as in acceptor,
 I want to understand it what is it port means which is mentioned in Connector, can some please explain it.

A: Did you happen to read the documentation on this subject?  There is a section titled "Understanding Connectors" which should answer most, if not all, of your questions.  I'll quote the most salient parts:

Whereas acceptors are used on the server to define how we accept connections, connectors are used to define how to connect to a server.
A connector is used when the server acts as a client itself, e.g.:

*

*When one server is bridged to another

*When a server takes part in a cluster

In these cases the server needs to know how to connect to other servers. That's defined by connectors.


text:
Q: How to tint sub-menu icon with a color selector? I'm building an android app with several menu on actionbar. And here is the menu.xml.
<menu>
 <item
        android:id="@+id/menu_comment"
        android:icon="@drawable/gsm_comment_selector"
        android:title="@string/COACH_COMMENT"
        app:showAsAction="always"/>

    <item
        android:id="@+id/menu_more"
        android:icon="@drawable/menu_more_selector"
        android:title="@string/MORE"
        app:showAsAction="always">
        <menu>
            <item
                android:id="@+id/menu_share"
                android:icon="@drawable/menu_share_selector"
                android:title="@string/SHARE"/>
            <item
                android:id="@+id/menu_help"
                android:icon="@drawable/menu_help_selector"
                android:title="@string/HELP"/>
        </menu>
    </item>
</menu>

And this is what a XXX_selector looks like. It contains a drawable and a template_selector(a color state list) so I can change the icon color when I click it.
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/ic_more_vert_white_24dp"
        android:tint="@color/template_selector"/>

The result is that when pressing menu_comment and menu_more, its icon color are changed. But menu_share and menu_help are not.
So what should I do to fix it?
Thanks

A: You should be able to do something like following (called from onCreateOptionsMenu)
    Drawable drawable = DrawableCompat.wrap(menuItem.getIcon());
    DrawableCompat.setTint(drawable.mutate(), context.getResources().getColor(tint));
    view.setIcon(drawable);


text:
Q: time.Since() with months and years I am trying to convert a timestamp like this:
2015-06-27T09:34:22+00:00

to a time since format so it would say like 9 months ago 1 day 2 hours 30 minutes 2 seconds.
something like that.
I used time.Parse and time.Since to get to this:
6915h7m47.6901559s

But how do I convert from there on? Something like this is what I thought:
for hours > 24 {
        days++
        hours -= 24
}

But the issue with this is that this won't be accurate for months because months can have 28, 30 and 31 days.
Is there a better way of achieving what I want?

A: Foreword: I released this utility in github.com/icza/gox, see timex.Diff().

The days in a month depends on the date, just like the days in a year (leap years).
If you use time.Since() to get the elapsed time since a time.Time value, or when you calculate the difference between 2 time.Time values using the Time.Sub() method, the result is a time.Duration which loses the time context (as Duration is just the time difference in nanoseconds). This means you cannot accurately and  unambiguously calculate the difference in years, months, etc. from a Duration value.
The right solution must calculate the difference in the context of the time. You may calculate the difference for each field (year, month, day, hour, minute, second), and then normalize the result to not have any negative values. It is also recommended to swap the Time values if the relation between them is not the expected.
Normalization means if a value is negative, add the maximum value of that field and decrement the next field by 1. For example if seconds is negative, add 60 to it and decrement minutes by 1. One thing to look out for is when normalizing the difference of days (days in month), the number of days in the proper month has to be applied. This can easily be calculated with this little trick:
// Max days in year y1, month M1
t := time.Date(y1, M1, 32, 0, 0, 0, 0, time.UTC)
daysInMonth := 32 - t.Day()

The logic behind this is that the day 32 is bigger than the max day in any month. It will get automatically normalized (extra days rolled to the next month and day decremented properly). And when we subtract day we have after normalization from 32, we get exactly what the last day was in the month.
Time zone handling:
The difference calculation will only give correct result if both of the time values we pass in are in the same time zone (time.Location). We incorporate a check into our function: if this is not the case, we "convert" one of the time value to be in the same location as the other using the Time.In() method:
if a.Location() != b.Location() {
    b = b.In(a.Location())
}

Here's a solution which calculates difference in year, month, day, hour, min, sec:
func diff(a, b time.Time) (year, month, day, hour, min, sec int) {
    if a.Location() != b.Location() {
        b = b.In(a.Location())
    }
    if a.After(b) {
        a, b = b, a
    }
    y1, M1, d1 := a.Date()
    y2, M2, d2 := b.Date()

    h1, m1, s1 := a.Clock()
    h2, m2, s2 := b.Clock()

    year = int(y2 - y1)
    month = int(M2 - M1)
    day = int(d2 - d1)
    hour = int(h2 - h1)
    min = int(m2 - m1)
    sec = int(s2 - s1)

    // Normalize negative values
    if sec < 0 {
        sec += 60
        min--
    }
    if min < 0 {
        min += 60
        hour--
    }
    if hour < 0 {
        hour += 24
        day--
    }
    if day < 0 {
        // days in month:
        t := time.Date(y1, M1, 32, 0, 0, 0, 0, time.UTC)
        day += 32 - t.Day()
        month--
    }
    if month < 0 {
        month += 12
        year--
    }

    return
}

Some tests:
var a, b time.Time
a = time.Date(2015, 5, 1, 0, 0, 0, 0, time.UTC)
b = time.Date(2016, 6, 2, 1, 1, 1, 1, time.UTC)
fmt.Println(diff(a, b)) // Expected: 1 1 1 1 1 1

a = time.Date(2016, 1, 2, 0, 0, 0, 0, time.UTC)
b = time.Date(2016, 2, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(diff(a, b)) // Expected: 0 0 30 0 0 0

a = time.Date(2016, 2, 2, 0, 0, 0, 0, time.UTC)
b = time.Date(2016, 3, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(diff(a, b)) // Expected: 0 0 28 0 0 0

a = time.Date(2015, 2, 11, 0, 0, 0, 0, time.UTC)
b = time.Date(2016, 1, 12, 0, 0, 0, 0, time.UTC)
fmt.Println(diff(a, b)) // Expected: 0 11 1 0 0 0

Output is as expected:
1 1 1 1 1 1
0 0 30 0 0 0
0 0 28 0 0 0
0 11 1 0 0 0

Try it on the Go Playground.
To calculate how old you are:
// Your birthday: let's say it's January 2nd, 1980, 3:30 AM
birthday := time.Date(1980, 1, 2, 3, 30, 0, 0, time.UTC)
year, month, day, hour, min, sec := diff(birthday, time.Now())

fmt.Printf("You are %d years, %d months, %d days, %d hours, %d mins and %d seconds old.",
    year, month, day, hour, min, sec)

Example output:
You are 36 years, 3 months, 8 days, 11 hours, 57 mins and 41 seconds old.

The magic date/time at which the Go playground time starts is: 2009-11-10 23:00:00 UTC
This is the time when Go was first announced. Let's calculate how old Go is:
goAnnounced := time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC)
year, month, day, hour, min, sec := diff(goAnnounced, time.Now())
fmt.Printf("Go was announced "+
    "%d years, %d months, %d days, %d hours, %d mins and %d seconds ago.",
    year, month, day, hour, min, sec)

Output:
Go was announced 6 years, 4 months, 29 days, 16 hours, 53 mins and 31 seconds ago.

A: The solution proposed by izca is great, but it misses one thing. If you add the following example, you can see the effect:
a = time.Date(2015, 1, 11, 0, 0, 0, 0, time.UTC)
b = time.Date(2015, 3, 10, 0, 0, 0, 0, time.UTC)
fmt.Println(diff(a, b))
// Expected: 0 1 27 0 0 0
// Actual output: 0 1 30 0 0 0

playground
The code is calculating the remaining days of the next incomplete month based on the total days of the first month (y1,M1), but it needs to be computed from the previous month of the later date month (y2,M2-1).
The final code is as follows:
package main

import (
    "fmt"
    "time"
)

func DaysIn(year int, month time.Month) int {
    return time.Date(year, month, 0, 0, 0, 0, 0, time.UTC).Day()
}

func Elapsed(from, to time.Time) (inverted bool, years, months, days, hours, minutes, seconds, nanoseconds int) {
    if from.Location() != to.Location() {
        to = to.In(to.Location())
    }

    inverted = false
    if from.After(to) {
        inverted = true
        from, to = to, from
    }

    y1, M1, d1 := from.Date()
    y2, M2, d2 := to.Date()

    h1, m1, s1 := from.Clock()
    h2, m2, s2 := to.Clock()

    ns1, ns2 := from.Nanosecond(), to.Nanosecond()

    years = y2 - y1
    months = int(M2 - M1)
    days = d2 - d1

    hours = h2 - h1
    minutes = m2 - m1
    seconds = s2 - s1
    nanoseconds = ns2 - ns1

    if nanoseconds < 0 {
        nanoseconds += 1e9
        seconds--
    }
    if seconds < 0 {
        seconds += 60
        minutes--
    }
    if minutes < 0 {
        minutes += 60
        hours--
    }
    if hours < 0 {
        hours += 24
        days--
    }
    if days < 0 {
        days += DaysIn(y2, M2-1)
        months--
    }
    if days < 0 {
        days += DaysIn(y2, M2)
        months--
    }
    if months < 0 {
        months += 12
        years--
    }
    return
}

func main() {
    var a, b time.Time
    a = time.Date(2015, 5, 1, 0, 0, 0, 0, time.UTC)
    b = time.Date(2016, 6, 2, 1, 1, 1, 1, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 1 1 1 1 1 1

    a = time.Date(2016, 1, 2, 0, 0, 0, 0, time.UTC)
    b = time.Date(2016, 2, 1, 0, 0, 0, 0, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 0 0 30 0 0 0

    a = time.Date(2016, 2, 2, 0, 0, 0, 0, time.UTC)
    b = time.Date(2016, 3, 1, 0, 0, 0, 0, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 0 0 28 0 0 0

    a = time.Date(2015, 2, 11, 0, 0, 0, 0, time.UTC)
    b = time.Date(2016, 1, 12, 0, 0, 0, 0, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 0 11 1 0 0 0

    a = time.Date(2015, 1, 11, 0, 0, 0, 0, time.UTC)
    b = time.Date(2015, 3, 10, 0, 0, 0, 0, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 0 1 27 0 0 0

    a = time.Date(2015, 12, 31, 0, 0, 0, 0, time.UTC)
    b = time.Date(2015, 3, 1, 0, 0, 0, 0, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 0 9 30 0 0 0

    a = time.Date(2015, 12, 31, 0, 0, 0, 0, time.UTC)
    b = time.Date(2016, 3, 1, 0, 0, 0, 0, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 0 2 1 0 0 0

    a = time.Date(2015, 12, 31, 0, 0, 0, 0, time.UTC)
    b = time.Date(2016, 2, 28, 0, 0, 0, 0, time.UTC)
    fmt.Println(Elapsed(a, b)) // Expected: 0 2 1 0 0 0
}

playground

A: If you use PostgreSQL, you can easily get the result with age function.
Suppose you have two dates a and b.
Like icza said, be careful, a and b must be in the same time zone.
First, you can invoke age with two parameters, in your case date a and date b. This function return a interval type that contains years, months, weeks, days, hours, minutes, seconds, and milliseconds.
SELECT age('2016-03-31', '2016-06-30'); -- result is: -2 mons -30 days

The second possibilty is to use age function with one parameter. The result is a interval too but in this case, age subtract from current_date (at midnight). Suppose today is 2016/06/16:
SELECT age(timestamp '2016-06-30'); -- result is: -14 days

Note, timestamp keyword is needed to cast the date '2016-06-30'.
For more details, you can use date_part or directly extract function that return one specific field (years, months, days...).
SELECT date_part('month', age('2016-03-31', '2016-06-30')); --result is: -2
SELECT date_part('day',   age('2016-03-31', '2016-06-30')); --result is: -30

Full request:
SELECT
    date_part('year', diff) as year
  , date_part('month', diff) as month
  , date_part('day', diff) as day
FROM (
  SELECT age(timestamp '2016-06-30') AS diff
) as qdiff;

-- result is:
-- year month day
-- 0    0     -14

(with CTE - Common Table Expression):
WITH qdiff AS (
  SELECT age(timestamp '2016-06-30') AS diff
)
SELECT
    date_part('year', diff) as year
  , date_part('month', diff) as month
  , date_part('day', diff) as day
FROM qdiff

-- result is:
-- year month day
-- 0    0     -14

PostgreSQL documentation (current version): https://www.postgresql.org/docs/current/static/functions-datetime.html

A: Something like this would work, probably not the most efficient but it is as accurate as you gonna get:
func main() {
    a := time.Date(2015, 10, 15, 0, 0, 0, 0, time.UTC)
    b := time.Date(2016, 11, 15, 0, 0, 0, 0, time.UTC)
    fmt.Println(monthYearDiff(a, b))
}

func monthYearDiff(a, b time.Time) (years, months int) {
    m := a.Month()
    for a.Before(b) {
        a = a.Add(time.Hour * 24)
        m2 := a.Month()
        if m2 != m {
            months++
        }
        m = m2
    }
    years = months / 12
    months = months % 12
    return
}

playground

A: You could try working with my date package, which includes the period package for working with ISO-style periods of time (Wikipedia).
The Period type comes with a formatter that understands plurals, printing readable strings such as "9 years, 2 months" and "3 hours, 4 minutes, 1 second", along with the ISO equivalents ("P9Y2M" and "PT3H4M1S").
Periods are, of course, tricky due to the variable lengths of days (due to DST) and months (due to the Gregorian calendar). The period package tries to help you by providing an API that allows both precise and imprecise calculations. For short periods (up to ±3276 hours) it is able to convert a Duration precisely.
duration := time.Since(...)
p, _ := period.NewOf(duration)
str := p.String()

If you need precise durations over longer spans, you need to use the Between function (which embody icza's excellent answer).
p := period.Between(t1, t2)
str := p.String()


text:
Q: Fluent Nhibernate Decimal Primary key with Auto Increment Is it Possible to created Decimal as a Primery key with Auto Incremented from FNH Mapping??

A: I ran across the same thing. It appears that fluent-nhibernate is enforcing this constraint.
If you know that the database will allow this (in this case, it should be fine) you can just bypass the constraint like so:
Id(x => x.MyDecimalId).GeneratedBy.Custom<IdentityGenerator>();

This will use the same strategy as Identity() would have, but not raise an exception. In my case, I've added an extension method on IdentityGenerationStrategyBuilder<IdentityPart> as such:
public static class IdentityPartExtensions
{
    public static void NumericIdentity(this IdentityGenerationStrategyBuilder<IdentityPart> identityBuilder)
    {
        identityBuilder.Custom<IdentityGenerator>();
    }
}

So then you can just do:
Id(x => x.MyDecimalId).GeneratedBy.NumericIdentity();

A: To achieve auto increment Identity type must be integral int, long, uint, ulong.
ex :
public class User
{
     public virtual int Id { get; set; }
     public virtual IList Names { get; set; }
}
Id(x => x.ID).Column("ID").GeneratedBy.Increment();
for decimal properties :
Id(x => x.ID).Column("ID").GeneratedBy.Assigned();
Assign the value while creating a new object. Value should be increment of last generated key in your database.
OR you can just implement a Custom ID Generator for NHibernate.
http://lucisferre.net/2009/07/14/implementing-a-custom-id-generator-for-nhibernate/