text:
Q: Custom variable in email I need to send order email in this  shipping_arrival_time how to send this
observer.php
class Bc_Deliverydate_Model_Observer
    {

        public function checkout_controller_onepage_save_shipping_method($observer)
        {
            if (Mage::getStoreConfig('deliverydate/deliverydate_general/on_which_page')==1){
                $request = $observer->getEvent()->getRequest();
     //           $quote =  $observer->getEvent()->getQuote();

        $quotes = Mage::getModel('sales/quote')->getCollection();

                $desiredArrivalDate = Mage::helper('deliverydate')->getFormatedDeliveryDateToSave($request->getPost('shipping_arrival_date', ''));
                if (isset($desiredArrivalDate) && !empty($desiredArrivalDate)){
                    $quotes->setShippingArrivalDate($desiredArrivalDate);
                    $quotes->setShippingArrivalComments($request->getPost('shipping_arrival_comments'));
                    $quotes->setShippingArrivalTime($request->getPost('shipping_arrival_time'));
                    $quotes->save();
                }
            }

            return $this;
        }

}

A: For adding variable follow below step:
copy app/code/local/Mage/Sales/Model/Order.php or or rewrite core files.
better is to rewrite:
in queueNewOrderEmail() function you need set you variable in template params like other parameters you will find below snippet around at line no 1341:
$mailer->setTemplateParams(array(
  'order'        =>  $this,
  'billing'      =>  $this->getBillingAddress(),
  'payment_html' => $paymentBlockHtml,
  'ShippingArrivalTime'  => "YOUR_VALUE FROM QUOTE"
));

After that edit transaction email on below path in admin:
System > Transnational Emails > New Order Email
and in template access variable like below
{{ var ShippingArrivalTime}}

I hope it will help you.
For saving it after selecting shipping method it should be like this.
And field name should be shipping_arrival_time in sales_flat_quote table.
class Bc_Deliverydate_Model_Observer
{

    public function checkout_controller_onepage_save_shipping_method($observer)
    {
        if (Mage::getStoreConfig('deliverydate/deliverydate_general/on_which_page')==1){
            $request = $observer->getEvent()->getRequest();
            $quote =  $observer->getEvent()->getQuote();
            $quote->setShippingArrivalTime($request->getPost('shipping_arrival_time'));
            $quote->save();
        }

        return $this;
    }
}

A: copy app/code/local/Mage/Sales/Model/Order.php or or rewrite core files. better is to rewrite:
<?php
class Mage_Sales_Model_Order extends Mage_Sales_Model_Abstract
{
  public function queueNewOrderEmail($forceMode = false)
  {
    $storeId = $this->getStore()->getId();

    if (!Mage::helper('sales')->canSendNewOrderEmail($storeId)) {
        return $this;
    }

    // Get the destination email addresses to send copies to
    $copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO);
    $copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $storeId);

    // Start store emulation process
    /** @var $appEmulation Mage_Core_Model_App_Emulation */
    $appEmulation = Mage::getSingleton('core/app_emulation');
    $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);

    try {
        // Retrieve specified view block from appropriate design package (depends on emulated store)
        $paymentBlock = Mage::helper('payment')->getInfoBlock($this->getPayment())
            ->setIsSecureMode(true);
        $paymentBlock->getMethod()->setStore($storeId);
        $paymentBlockHtml = $paymentBlock->toHtml();
    } catch (Exception $exception) {
        // Stop store emulation process
        $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
        throw $exception;
    }

    // Stop store emulation process
    $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);

    // Retrieve corresponding email template id and customer name
    if ($this->getCustomerIsGuest()) {
        $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId);
        $customerName = $this->getBillingAddress()->getName();
    } else {
        $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId);
        $customerName = $this->getCustomerName();
    }

    /** @var $mailer Mage_Core_Model_Email_Template_Mailer */
    $mailer = Mage::getModel('core/email_template_mailer');
    /** @var $emailInfo Mage_Core_Model_Email_Info */
    $emailInfo = Mage::getModel('core/email_info');
    $emailInfo->addTo($this->getCustomerEmail(), $customerName);
    if ($copyTo && $copyMethod == 'bcc') {
        // Add bcc to customer email
        foreach ($copyTo as $email) {
            $emailInfo->addBcc($email);
        }
    }
    $mailer->addEmailInfo($emailInfo);

    // Email copies are sent as separated emails if their copy method is 'copy'
    if ($copyTo && $copyMethod == 'copy') {
        foreach ($copyTo as $email) {
            $emailInfo = Mage::getModel('core/email_info');
            $emailInfo->addTo($email);
            $mailer->addEmailInfo($emailInfo);
        }
    }

    // Set all required params and send emails
    $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId));
    $mailer->setStoreId($storeId);
    $mailer->setTemplateId($templateId);
    $mailer->setTemplateParams(array(
        'order'        => $this,
        'billing'      => $this->getBillingAddress(),
        'payment_html' => $paymentBlockHtml,
        'shippingarrivaltime' => $this->getShippingArrivalTime()
    ));

    /** @var $emailQueue Mage_Core_Model_Email_Queue */
    $emailQueue = Mage::getModel('core/email_queue');
    $emailQueue->setEntityId($this->getId())
        ->setEntityType(self::ENTITY)
        ->setEventType(self::EMAIL_EVENT_NAME_NEW_ORDER)
        ->setIsForceCheck(!$forceMode);

    $mailer->setQueue($emailQueue)->send();

    $this->setEmailSent(true);
    $this->_getResource()->saveAttribute($this, 'email_sent');

    return $this;
}
}

After that edit transaction email on below path in admin: System > Transnational Emails > New Order Email
and in template access variable like below
{{ var shippingarrivaltime}}


text:
Q: Oracle Linux: How to set the metric of a NIC? How can I set the metric of a network interface (DHCP) permanently in Oracle Linux (think it is managed my NetworkManager)?

A: The network is managed by NetworkManager, you can use nmcli to set the metric:
to show connection use nmcli c (nmcli connection) , then use :
nmcli c edit CONNECTION_NAME

from the interactive mode to get the current metric use  print:
nmcli> print

to set a metric:
nmcli> set ipv4.route-metric <value>
nmcli> set ipv6.route-metric <value>
nmcli> save
nmcli> quit

Or you can use the following command without running the interactive mode:
nmcli connection modify uuid UUID_CONNECTION ipv4.route-metric <value>
nmcli connection modify uuid UUID_CONNECTION ipv6.route-metric <value>

Then restart NetworkManager
sudo systemctl restart NetworkManager

to check it:
route -n

or
nmcli connection show uuid UUID_CONNECTION |grep route-metric

redpajama_set_name: RedPajamaStackExchange


text:
Q: google Data Studio - send data back to google spread sheet or another location We are working on marketing dashboards and reports and would like to add the ability for a user of the report to take action based on report data.
For example, if an item in a report needs to be re-ordered, or an ad needs to be paused; the user would click a link or a check box. That would ideally insert info into a google spread sheet, or cal a url that would log the data.
i know these are reports, and the purpose of reports is to view and analyze data. What i would like is to give the users the ability to act on the data in the report.

A: The only way I can think of is when using tables (pivot or normal) you can hold down ctrl and select specific rows of your table. If you have other tables on that page, they will filter those rows you've selected in the other table, it works like a filter. You can then manually export those filtered table views to spreadsheet, saving the filtered data.
Or you could use filters in general, maybe with calculated fields (not sure if that works tbh) and if statements, so that you can filter your tables accordingly and then export them manually to spreadsheets using the three dots top right of each visualisation in datastudio.
Maybe you can find a workaround with this information to come closer to your desired situation.
Seeing as datastudio is just a reporting tool, I don't think there is another way to do this.


text:
Q: Is Modernizr covering the prefix for css? Sorry for the silly question, but I am really beginner and I need your help.
I added modernizr-2.8.3.min.js in my website.
I visited the modernizr home page, but I don't understand how to download it.
Then, I found this modernizr file in the html5 boilerplate.
When I add this in my ,  is this helping me not to add vendor prefix?
Or, if I do not do anything with modernizr, should I use some kind of 'prefix free' file?
Thanks.

A: Modernizr is a javascript library that detects the browser features. You can use it two ways.

*

*Just include this in your file.
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js">

*Go to https://modernizr.com/download?setclasses and select the features you want modernizer to detect. I can see how this can be confusing if you are a beginner so I suggest that you use the first option.
Once you include this in your html change your html tag to this <html class="no-js"> and when you see your page in the browser you will see something like this.
<html class=" js no-flexbox no-canvas no-canvastext no-webgl no-touch no-geolocation no-borderimage no-borderradius no-boxshadow no-textshadow no-opacity no-cssanimations no-csscolumns no-cssgradients ... etc">
Now you can write your css for regular browsers and the one that doesn't support your feature.
So if you want to add gradients to <div class="gradient"> for regular browsers you do something like this.
div.gradient{
  background: linear-gradient(red, yellow);
}

but for browsers that doesn't support border-radius modernizr adds no-borderradius to your html tag, see above. So for these browsers you can write your css like this to ensure a consistent view.
.no-cssgradients div.gradient{
  background: url("glossybackground.png");
}


text:
Q: Maximization using Lagrange multiplier when one constraint is homogenous Suppose I have $a,b,c\ge-1$. If I wish to maximize the function $f(a,b,c)=a+b+c$ subject to the constraint $g(a,b,c)=a^5+b^5+c^5=0$, how do I proceed?
The usual way of partially differentiating $f(a,b,c)+\lambda g(a,b,c)$ and equating to zero gives me no critical points. What should do to find the critical points? How is the condition $a,b,c\ge-1$ to be used here? Any hints? Thanks beforehand.


text:
Q: Problems with quoting while using YQ in PowerShell I'm trying to run this yq command in PowerShell:
yq eval '.. | select(has(""CK_RUN_CASE""))' problemset.yml

but I get this error message:
Error: open .. | select(has("CK_RUN_CASE)) problemset.yml: The filename, directory name, or volume label syntax is incorrect.

I was trying to follow this hint, but no success:
https://mikefarah.gitbook.io/yq/usage/tips-and-tricks#quotes-in-windows-powershell
It works on my Ubuntu machine with quotes like this:
yq eval '.. | select(has("CK_RUN_CASE"))' problemset.yml

but I really need it to work on my Windows machine for some reasons. Any suggestions?

A: Using this test file:
# problemset.yml
CK_RUN_CASE: foo
array:
  - CK_RUN_CASE: bar

Triple quoting the key name in powershell seems to work :
$ yq eval '.. | select(has("""CK_RUN_CASE"""))' problemset.yml
CK_RUN_CASE: foo
array:
  - CK_RUN_CASE: bar
CK_RUN_CASE: bar

Same for escaping the double quotes :
$ yq eval '.. | select(has(\"CK_RUN_CASE\"))' problemset.yml
CK_RUN_CASE: foo
array:
  - CK_RUN_CASE: bar
CK_RUN_CASE: bar

However, I can't find a syntax that works on both powershell and WSL/linux...


text:
Q: angularjs nvd3 Line chart not updating the data I'm using angular-nvd3-directives to create line chart.
This is the HTML file
<div class="line-chart" ng-controller="LineChartController as viewAll">

    <nvd3-line-chart
    data="viewAll.linechart"
    id="exampleId"
    width="800"
    height="400"
    showXAxis="true"
    showYAxis="true"
    tooltips="true"
    interactive="true"
    xAxisTickValues="[1378387500, 1378388100, 1378388700, 1378389900]"
    xAxisTickFormat="xAxisTickFormatFunction()"
    margin="{left:50,top:50,bottom:50,right:50}">

        <svg></svg>

    </nvd3-line-chart>

</div>

This is the JS file
    (function() {
        var app = angular.module('linechart-directives', ['nvd3ChartDirectives', 'LocalStorageModule']);

        app.controller('LineChartController', function($scope, $http, localStorageService, $interval) {
                $scope.viewAll = this;
                $scope.viewAll.linechart = [];

                $scope.pollActiveCon = function() {
                        if (localStorageService.get("getAll") == 0 || localStorageService.get("getAll") == undefined) {
                                $http.get('/statistics/getAllData').success(function(data) {
                                        $scope.viewAll.linechart = data;
                                        localStorageService.set("getAllData",1);
                                });
                        }else{
                                $http.get('/statistics/getLastData').success(function(data) {
                                        if ($scope.viewAll.linechart[0]==null) {
                                                $scope.viewAll.linechart = data;
                                        }else{
                                                console.log($scope.viewAll.linechart);
                                                $scope.viewAll.linechart[0]['values'].push(data[0]['values'][0]);
                                        }
                                });
                        }
                };

                $scope.pollActiveCon();

                $interval( function(){
                        $scope.pollActiveCon();
                }, 120000);

                $scope.xFunction =function(){
                        return function(d){
                                return d[0];
                        }
                }

                $scope.yFunction = function(){
                        return function(d){
                                return d[1];
                        }
                }
                $scope.xAxisTicksFunction = function() {
                        console.log('xAxisTicksFunction');
                        console.log(d3.svg.axis().ticks(d3.time.minutes, 5));
                        return function(d) {
                                return d3.svg.axis().ticks(d3.time.minutes, 5);
    };
                };
                $scope.xAxisTickFormatFunction = function() {
                        return function(d) {
                                return d3.time.format('%H:%M')(moment.unix(d).toDate());
                        };
                };

        });
})();

The problem is the data is not updating in the chart, but when I checked the $scope.viewAll.linechart variable, the last data was added successfully to it. What am I missing?

A: Adding this to the html objectEquality="true" solves the problem.

A: My data updating problem is solved using objectEquality="true"


text:
Q: Obtain compiler flags in skylark I'd like to convert a CMake-based C++ library to bazel.
As part of the current CMake project, I'm using a libclang-based code generator that parses C++ headers and generates C++ code from the parsed AST. In order to do that, I need the actual compiler flags used to build the cc_library the header is part of. The flags are passed to the code generation tool so it can use clang's preprocessor.
Is there any way I could access the compiler flags used to build a dependency from a skylark- or gen_rule rule? I'm particularly interested in the include paths and defines.

A: We're working on it. Well, not right now, but will soon. You might want to subscribe to the corresponding issue, and maybe describe your requirements there so we take them into account when designing the API.


text:
Q: Print/Save complete Laravel Artisan Command output(large array from debug line) to file I am working in Laravel 6.x project, where I have added debug line inside an Artisan command to get the large array generated from that line into text file as output.
It looks almost like following code in the handle method of said command:
....
if(!$dataArray->isEmpty())
{
    foreach ($dataArr as $dataEle)
    {
        $dataArrToPrnt[] = $dataEle->toArray();
        ....
    }
}
die(var_dump($dataArrToPrnt));
....

But the problem is the dataArray is huge, so after few entries, the command output skips the rest of the data and prints (...more elements) instead.
And I am running the command like below for printing to file(Windows 10 x64 with GitBash, so I have use php.exe instead of php):
php.exe artisan command-namespace:command >> result.out

How can I override/avoid that from happening and print the complete dataArray to file regardless of it's size ?

A: Try using the global Log. Add a logging channel to your config/logging.php file like so:
'dataLogger' => [
    'driver' => 'daily',
    'path' => storage_path('logs/data.log'),
    'level' => 'info',
],

And use in your code like:
use Log;
foreach ($dataArr as $dataEle){
    Log::channel('dataLogger')->info($dataEle);
}

(Or however you'd like to format your data.)


text:
Q: dustjs, duplication check while looping While templating, what is the way to check if an array has same value?
I would like to skip if the array has duplicate value.
[
  {name: 1},
  {name: 3},
  {name: 3},
  {name: 4}
]

Sould out 1,3,4 on loop basically. Thanks

A: In general, Dust follows a philosophy that you should keep logic about your data out of the template. If you need to adjust your data before rendering it, you can write a helper function to pass the data through. Here's an example that uses Lodash's uniqBy to do this.
Context
{
  yourArray: [{name: 1}, {name: 3}, {name: 3}, {name: 4}],
  unique: function(chunk, context, bodies, {values, by}) {
    const uniqueValues = _.uniqBy(values, by);
    return chunk.section(uniqueValues, context, bodies);
  }
}

Template
{#unique values=yourArray by="name"}
  {name}{~n}
{/unique}

In this example, I've defined a context helper unique that accepts two parameters, an array to filter and a key to filter by.
I call _.uniqBy to filter the array, and then use chunk.section to render my block once for each value in uniqueValues.
Then, in the template, I call my context helper {#unique} and pass it the parameters.


text:
Q: How to group by with max date in cosmos db I have the following cards container in my cosmos DB:
Card: {
    createdAt:"2022-10-17T11:36:53"
    modifiedAt:"2022-10-17T11:36:53"
    id:"49a9f63c-cca6-4424-8eb1-3f742f4c7fef"
    userId:"b66b6801-de31-4ea1-bba7-d77effc2aaaa"
    number : "1234567"
}

Each user might have one or more cards. I need a query to select the latest issued card with all details grouped by userId. Is it something possible to achieve with cosmos DB?
Inner queries and self-joins are not supported by Cosmos DB
I tried below SQL query:
SELECT e.userId, max(e.modifiedAt) as modifiedAt
from Card AS e
WHERE ARRAY_CONTAINS([""], e.userId)
group by e.userId

but this gives me only userIds with the latest modified card.


text:
Q: AsyncContext Servlet 3.0 client disconnect I'm trying to implement Server-Sent Events using Servlet 3.0 AsyncContext.
But when the client is disconnected the exception is not called.
PrintWriter writer = ctx.getResponse().getWriter();
writer.println(json);                               ctx.getResponse().flushBuffer();
This post is same as the problem here: AsyncContext and I/O error handling (when peer disconnects)


text:
Q: Can I change object without using object reference as well as in non-static context? In code,What is the difference of calling in main?

*

*input.reverseArray(input);

*reverseArray(input);

*input = reverseArray(input);

*input =input.reverseArray(input);
Finally, Would these be applicable if reverseArray was not static?

public class reverse
{

    public static void main(String args[])
    {
        int [] input = new int[]{4, 5, 8, 9, 10};
    }
    public static void reverseArray(int inputArray[])
        {

            int temp;

            for (int i = 0; i < inputArray.length/2; i++)
            {
                temp = inputArray[i];

                inputArray[i] = inputArray[inputArray.length-1-i];

                inputArray[inputArray.length-1-i] = temp;
            }

        }
}

A: *

*input.reverseArray(input); doesn't compile because reverseArray is not a method defined by the type of input, namely int[].

*reverseArray(input); compiles and works correctly.

*input = reverseArray(input); doesn't compile because reverseArray returns void, so it can't be assigned to input.

*input =input.reverseArray(input); doesn't compile for both of the above reasons.

If reverseArray were not static, then none of the above would compile. In particular, reverseArray(input) is called from a static context (i.e., from a static method) in a static way (without using an object as in foo.reverseArray(input)), but reverseArray is not static. The way to call reverseArray is to use an object of type reverse, since the reverse class defines the method reverseArray:
reverse myReverse = new reverse();
myReverse.reverseArray(input);

Also note that by Java convention, classes should be named in CamelCase, so you should change reverse to Reverse.


text:
Q: Python CSV Import as Complex Nested List, Sort, and Output as Text or Back to CSV I have a data structure, we'll call it an inventory, in CSV that looks similar to:
ResID,Building,Floor,Room,Resource
1.1.1.1,Central Park,Ground,Admin Office,Router
1.1.2.1,Central Park,Ground,Machine Closet,Router
1.3.1.1,Central Park,Mezzanine,Dungeon,Whip
2.1.3.1,Chicago,Roof,Pidgeon Nest,Weathervane
1.13.4.1,Central Park,Secret/Hidden Floor,c:\room,Site-to-site VPN for 1.1.1.1
1.2.1.1,Central Park,Balcony,Restroom,TP

And I am trying to get it to output in a sorted CSV, and in the format of a text file following the format:
1 Central Park
1.1 Ground
1.1.1 Admin Office
1.1.1.1 Router
1.1.2 Machine Closet
1.1.2.1 Router
1.2 Balcony
1.2.1 Restroom
1.2.1.1 TP
1.3 Mezzanine
1.3.1 Dungeon
1.3.1.1 Whip
1.13 Secret/Hidden Floor
1.13.4 c:\room
1.13.4.1 Site-to-site VPN for 1.1.1.1
2 Chicago
2.1 Roof
2.1.3 Pidgeon Nest
2.1.3.1 Weathervane

I envision a data structure similar to:
Building = {
    1 : 'Central Park',
    2 : 'Chicago'
}
Floor = {
    1 : {
        1 : 'Ground',
        2 : 'Balcony',
        3 : 'Mezzanine',
        13: 'Secret/Hidden Floor'
    },
    2  : {
        1 : 'Roof'
    }
}

Room = {
    1 : {
        1 : {
            1 : 'Admin Office',
            2 : 'Machine Closet'
        }
        2 : {
            1 : 'Restroom'
        }
        3 : {
            1 : 'Dungeon'
        }
... Hopefully by now you get the idea.

My complication is that I do not know if this is the best way to represent the data and then iterate over it as:
for buildingID in buildings:
    for floorID in floors[buildingID]:
        for roomID in rooms[buildingID][floorID]:
            for resource in resources[buildingID][floorID][roomID]:
                do stuff...

Or if there is a MUCH more sane way to represent the data in script, but I need the full document heading numbers AND names intact, and this is the only way I could visualize to do it at my skill level.
I am also at a loss for an effective way to generate this information and build it into the data structure from a CSV in this format.
This may seem trivial to some, but I am not a programmer by trade, and really only dabble on a infrequent basis.
My ultimate goal is to be able to ingest the CSV into a sane data structure, sort it appropriately in ascending numerical order, generate line entries in the text structure shown above that lists each building, floor, room, and resource only once and listed in context with each other, and then ostensibly it would be trivially for me to handle the output to text or back to sorted CSV.
Any recommendations would be GREATLY appreciated.
EDIT: SOLUTION
Leveraging my accepted answer below I was able to generate the following code. Thank you to the guy that deleted his answer and comments that simplified my sorting process too!
import csv

def getPaddedKey(line):
    keyparts = line[0].split(".")
    keyparts = map(lambda x: x.rjust(5, '0'), keyparts)
    return '.'.join(keyparts)

def outSortedCSV(reader):
    with open(fOutName, 'w') as fOut:
        writer = csv.writer(fOut, delimiter=',')
        head = next(reader)
        writer.writerow(head)
        writer.writerows(sorted(reader, key=getPaddedKey))

s = set()
fInName = 'fIn.csv'
fOutName = 'fOut.csv'

with open(fInName, 'r') as fIn:
    reader = csv.reader(fIn, delimiter=',')
    outSortedCSV(reader)
    fIn.seek(0)
    next(fIn)
    for row in reader:
        ids = row[0].split('.')      # split the id
        for i in range(1, 5):
            s.add(('.'.join(ids[:i]), row[i])) # add a tuple with initial part of id and name

for e in sorted(list(s), key=getPaddedKey):
    print e[0] + '  ' + e[1]

A: extract the id's
ids = ['Building_id', 'Floor_id', 'Room_id', 'Resource_id']
labels = ['ResID', 'Building', 'Floor', 'Room', 'Resource']

df2 = df.join(pd.DataFrame(list(df['ResID'].str.split('.')), columns=ids))

 df2

    ResID   Building    Floor   Room    Resource    Building_id     Floor_id    Room_id     Resource_id
0   1.1.1.1     Central Park    Ground  Admin Office    Router  1   1   1   1
1   1.1.2.1     Central Park    Ground  Machine Closet  Router  1   1   2   1
2   1.3.1.1     Central Park    Mezzanine   Dungeon     Whip    1   3   1   1
3   2.1.3.1     Chicago     Roof    Pidgeon Nest    Weathervane     2   1   3   1
4   1.13.4.1    Central Park    Secret/Hidden Floor     c:\room     Site-to-site VPN for 1.1.1.1    1   13  4   1
5   1.2.1.1     Central Park    Balcony     Restroom    TP  1   2   1   1

iterate over this
little helper method
def pop_list(list_):
    while list_:
        yield list_[-1], list_.copy()
        list_.pop()

for (id_, remaining_ids), (label, remaining_labels) in zip(pop_list(ids), pop_list(labels)):

    print(label, ': ', df2.groupby(remaining_ids)[label].first())

returns
Resource :  Building_id  Floor_id  Room_id  Resource_id
1            1         1        1                                    Router
                       2        1                                    Router
             13        4        1              Site-to-site VPN for 1.1.1.1
             2         1        1                                     TP
             3         1        1                                      Whip
2            1         3        1                               Weathervane
Name: Resource, dtype: object

Room :  Building_id  Floor_id  Room_id
1            1         1            Admin Office
                       2          Machine Closet
             13        4                 c:\room
             2         1                Restroom
             3         1                 Dungeon
2            1         3            Pidgeon Nest
Name: Room, dtype: object

Floor :  Building_id  Floor_id
1            1                        Ground
             13          Secret/Hidden Floor
             2                       Balcony
             3                     Mezzanine
2            1                          Roof
Name: Floor, dtype: object

Building :  Building_id
1    Central Park
2         Chicago
Name: Building, dtype: object

Explanation
for (id_, remaining_ids), (label, remaining_labels) in zip(pop_list(ids), pop_list(labels)):
    print((id_, remaining_ids), (label, remaining_labels))

returns
('Resource_id', ['Building_id', 'Floor_id', 'Room_id', 'Resource_id']) ('Resource', ['ResID', 'Building', 'Floor', 'Room', 'Resource'])
('Room_id', ['Building_id', 'Floor_id', 'Room_id']) ('Room', ['ResID', 'Building', 'Floor', 'Room'])
('Floor_id', ['Building_id', 'Floor_id']) ('Floor', ['ResID', 'Building', 'Floor'])
('Building_id', ['Building_id']) ('Building', ['ResID', 'Building'])

So this just iterates over the different levels in your building structure
res = df2.groupby(remaining_ids)[label].first()

builds per level in your structure a DataFrame representing the items at this level with as (Multi)index the nested ID's to this level. This is the info you want  for your eventual datatructure, it just needs to be transformed to a nested dict
Building_id  Floor_id
1            1                        Ground
             13          Secret/Hidden Floor
             2                       Balcony
             3                     Mezzanine
2            1                          Roof

to text (no nesting)
res.index = res.index.to_series().apply('.'.join)
print(res)

1.1                  Ground
1.13    Secret/Hidden Floor
1.2                 Balcony
1.3               Mezzanine
2.1                    Roof
Name: Floor, dtype: object

A: If you have no reason to build your proposed structure, you could simply add for each line the building, floor, room and resource along with its id to a set (to automatically eliminate duplicates). Then you convert the set to a list, sort it and you are done.
Possible Python code, assuming rd is a csv.reader on the inventory (*):
next(rd)                         # skip the headers line
s = set()
for row in rd:
    ids = row[0].split('.')      # split the id
    for i in range(1, 5):
        s.add(('.'.join(ids[:i]), row[i])) # add a tuple with initial part of id and name
l = list(s)                      # convert to a list
l.sort()                         # sort it

You have now a list of 2-tuples [('1', 'Central Park'), ('1.1', 'Ground'), ('1.1.1', 'Admin Office'), ...], you can use it to build a new csv or just print it as text:
for i in l:
    print(" ".join(i))

(*) In Python 3, you would use:
with open(inventory_path, newline = '') as fd:
    rd = csv.reader(fd)
    ...

while in Python 2, it would be:
with open(inventory_path, "rb") as fd:
    rd = csv.reader(fd)
    ...


text:
Q: Git says nothing to commit after running ng build --prod I saved the changes to my files in the VSCode terminal. Ran the following commands:
git status(This showed the changes.)
git add .
git status (This showed the files added)
git commit -m "My commit message."
git push (This showed the files were pushed up to git).

Then I run the ng build --prod. The build runs without a problem. I run git status and I get the following:
$git status
On branch qa
Your branch is up to date with 'origin/qa'.
nothing to commit, working tree clean
I'm on the correct branch. I've rebuilt this a number of times without a problem. Anyone have any idea how to fix it.

A: Angular builds are usually saved in dist folder which is in root path.
In .gitignore file, paths are declared which omits in source control. dist folder is one among them. That is the reason you are unable to see the files during git status.
Here is the sample of .gitignore file contents.
# See http://help.github.com/ignore-files/ for more about ignoring files.

# compiled output
/dist -----> /dist is mentioned in this file
/tmp
/out-tsc

# dependencies
/node_modules

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

A: your / dist directory is in the .gitignore file at the root of the project, if you need to upload the compiled version to git (it can be done, but it is not a good practice), you should remove this directory from the .gitignore file, and run git status again to check


text:
Q: PHP MYSQL : now I am fed-up with the same warning I tried every thing in below code but I am not at all able to arrange resulted table in ascending order.
This time I am getting the table but not in arranged order and also two warnings.
My code is as follows:
     <?PHP

         require_once("lib/connection.php");
         $array = array();
         $result = mysql_query("SHOW TABLES FROM st_db_1");
         while($row = mysql_fetch_row($result) ){
         $result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
         $row_tb=mysql_fetch_array($result_tb);
         $array = $row[0];

        echo "{$row[0]}<br/>" ;
         }
    sort($array);
    foreach ($array as $item) {
        echo $item;
    }
   ?>

And the output I am getting is below :
 class_1
 class_10
 class_11
 class_12
 class_2
 class_3
 class_4
 class_5
 class_6
 class_7
 class_8
 class_9

  ( ! ) Warning: sort() expects parameter 1 to be array, string given in C:\wamp\www\Copy (4) of st_db_1\test_2.php on line 15

Call Stack
  ( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\Copy (4) of      st_db_1\test_2.php on line 1 call Stack

But I want output in the below mentioned order:
 class_1
 class_2
 class_3
 class_4
 class_5
 class_6
 class_7
 class_8
 class_9
 class_10
 class_11
 class_12

Please help.

A: use $array[] = $row[0]; instead of using $array = $row[0];
$row[0] is a string, and yo are over-writing $array with the string. Thats why $array is a string not array.


text:
Q: Non-Capture Cucumber Expression Transitioning off of Regex and to cucumber expressions.  Had a question about how to do non-capturing groups?
"I see the unread badge display {string} unread message(s) for the chat with the {string} user/personal-group/official-group"

Previously it was:
"^I see the unread badge display REGEX unread message(?: |s) for the chat with the REGEX (?:user/personal group/official group)$"

I was told the - will link characters but it is not reading that in my feature files.  What's the best way to handle non-capturing words?


text:
Q: At what speed does the magnetic field move from pole to pole? the magnetic field moves in a loop right? How long does it take to go from one pole to another?

A:
the magnetic field moves in a loop right?

Consider the static magnetic field due to a bar magnet. Is the magnetic field moving?
Sure, the diagrams that you see suggest that there is movement because there's an arrow on the field lines, right?

Image credit
But the arrows aren't an indication of movement, they're more of an indication of the direction of the magnetic field vectors that are tangent to the field line.
A magnetic field can, however, 'move' in the sense that it changes with time. For example, the magnetic field due to a current loop where the current is changing with time.

A: The arrows on the field lines just show the direction of the field. A magnetostatic field like this just sits there, with a certain magnitude and a certain direction at each point. It's not changing and not "moving". It's not like flowing water.
For example, the looping magnetic field of a point dipole $\vec m$ is
$$\vec B=\frac{\mu_0}{4\pi}\frac{3\hat{r}(\vec{m}\cdot\hat{r})-\vec{m}}{r^3}.$$
This expression is a particular vector at each point, and doesn't represent a changing field.

A: Magnetic and electric Fields carry the information of presence of a charge and are limited by the speed limit of the universe.
They travel at the speed of light This is still only experimentally verified. and theory on why speed is $c$ is not yet ready. There are developments going on - Quantum Electro Dynamics explains this by saying that two electrons exchange a virtual photon to feel the repulsion. And since magnetic fields arise is due to moving charges, $\vec B$ also travels at the speed of light.


text:
Q: finding weird examples of continuous functions (or, maybe, they're tricks?) I need to find examples of the following, but I feel like they're trick questions.

*

*A unbounded function on a bounded closed interval (the function must be defined at every point in the interval)

I was thinking something like 1/x, but it's not defined at 0 (it'd need to be (0,1] ), so I don't see how I can provide something that is defined at the boundary points and unbounded on the interval. I would think I'd need something that blows up, but then it won't be defined at every point in the interval

*f : [0, 1] → [0, 1], having the intermediate-value property but continuous at only one point

For a function to experience the intermediate-value property, doesn't it need to be continuous on its domain (the whole closed interval)? How can I provide an example when it's only continuous at one point?

A: f(x) = 0 if x = 0.  f(x) = 1/x if x $ne$ 1.
Unbounded, defined everywhere, but not continuous.

A: The second example:

*

*Take the Conway base 13 function $F(x)$, which is known to take on every real value on each interval (and is, therefore, nowhere continuous), and the interval $(0,1)$.

*Consider $g(t)=\frac12+\frac{1}{\pi}\arctan t$. The function $g\circ F$ takes on every value in $(0,1)$ on each real interval in $(0,1)$.

*Define
$$
f(x)=\left\{
\begin{array}{ll}
0, &\text{ if } x=0,\\
1, &\text{ if } x=1,\\
x\cdot (g\circ F)(x)&\text{ if } x\in(0,1).
\end{array}
\right.
$$
The function $f\colon[0,1]\to[0,1]$ takes on every real value in $(0,b)$ on each interval $(a,b)\subset[0,1]$ and, thus, satisfies IVP on $[0,1]$ and continuous only at $x=0$.

A: I will attempt the second part. To do this I will assume the result that the Cantor set can be mapped surjectively onto $[0,1]$ (which can be done, for example, by sending ternary expansions with 0's and 2's into binary expansions with the corresponding 0's and 1's).
We will construct a set $S \subset [0,1]$ which can be written as the union of countably many disjoint Cantor sets $C_{n,k}$, where each $C_{n,k}$ is contained in the dyadic interval $[k2^{-n}, (k+1)2^{-n}]$. The term "Cantor set" refers to a translate and dilate of the usual $1/3$-Cantor set in $[0,1]$.
If we can construct this set $S$ then we would be done. Indeed, for each $n,k$ there exists a surjection $\phi_{n,k}:C_{n,k} \to [0,1]$. Then we can define a map $\phi: [0,1] \to [0,1]$ as $$\phi(x)=\begin{cases} 0, \;\;\;\;\;\;\;\;\text{ if } x \notin S \\ \phi_{n,k}(x), \;\text{ if } x \in C_{n,k} \text{ for some } n,k \end{cases}$$
This function is discontinuous at every point and has IVT, since any subinterval of $[0,1]$ must contain one of the $C_{n,k}$, which is mapped onto $[0,1]$ by $\phi$. If you want continuity at exactly $1$ point, then just consider $x\phi(x)$.
To finish, we will now construct the sets $C_{n,k}$, for $n \geq 0$ and $k\in \{0,...,2^n-1\}$. We apply induction on $n$ for this construction. First, let $C_{0,0}$ be the usual Cantor set in $[0,1]$. For the inductive step of the construction, suppose that $N \geq 1$ and that we have constructed disjoint Cantor sets $C_{n,k} \subset [k2^{-n},(k+1)2^{-n}]$ for all $k \in \{0,...,2^n-1\}$ with $n<N$. Since each of the sets $C_{n,k}$ is closed and nowhere dense, it follows that the union of these $C_{n,k}$ (for $n<N$ and $0\leq k \leq 2^n-1$) is also closed and nowhere dense. Hence each dyadic interval $[k2^{-N},(k+1)2^{-N}]$ contains an open interval $J_{N,k}$ not intersecting any of these $C_{n,k}$. Now for each $0 \leq k \leq 2^N-1$, just define $C_{N,k}$ to be any Cantor set contained in $J_{N,k}$. Clearly these $C_{N,k}$ are disjoint from the previously constructed $C_{n,k}$. Thus we have defined disjoint Cantor sets $C_{n,k}\subset [k2^{-n},(k+1)2^{-n}]$ for all $0 \leq k \leq 2^n-1$ with $n< N+1$. So continue inductively...


text:
Q: How to calculate $\langle x^{(i)},x\rangle$? I am coding simplified version of Platt's SMO and it defines a function like this:
$$
\newcommand{\<}{\langle}
\newcommand{\>}{\rangle}
f(x) = \sum_{i=1}^{m} \alpha_iy^{(i)} \<x^{(i)},x\> + \hspace{0.20cm} b
$$
where $x$ is a matrix of dimension $m \times n$
$\alpha$ and $y$ are column vectors of size $m$
I am trying to understand how to calculate $\<x^{(i)},x\>$ since it's apparent that the result of $f(x)$ has to be a scalar.

A: All the paper says about $\<A,B\>$ is that it's an "inner product".  There are many choices of inner products over matrices (with a corresponding choice of kernel), but the most commonly used inner product in this context is the Hilbert-Schmidt inner product, given by
$$
\<A,B\> = \operatorname{trace}(A^TB) = \sum_{i = 1}^m\sum_{j=1}^n A_{ij}B_{ij}
$$
That is to say, we can simply take the "dot product" of matrices, as one would with vectors.


text:
Q: Django - fetching data from the different table to be shown in admin, getting the error 'NoneType' object has no attribute 'user' I am beginner for the Django.
I am trying to make the admin page in which I want to show the columns(user) from the table(BillingProfile) which is the foreign key to the Order Table.
I have created the order model as shown below.
Order Model
class Order(models.Model):
    billing_profile     = models.ForeignKey(BillingProfile, null=True, blank=True)
    order_id            = models.CharField(max_length=120, blank=True) # AB31DE3
    shipping_address    = models.ForeignKey(Address, related_name="shipping_address",null=True, blank=True)
    billing_address     = models.ForeignKey(Address, related_name="billing_address", null=True, blank=True)
    cart                = models.ForeignKey(Cart)

    def __str__(self):
        return self.order_id

The BillingProfile model is as shown below.
BillingProfile Model
class BillingProfile(models.Model):
    user        = models.OneToOneField(User, null=True, blank=True)
    email       = models.EmailField()
    active      = models.BooleanField(default=True)

    def __str__(self):
        return self.email

And the Code for the Admin Page is as below.
admin.py
class OrderAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'billing_profile','get_user']
    class Meta:
        model = Order
    def get_user(self, obj):
        return obj.billing_profile.user

admin.site.register(Order,OrderAdmin)

When I am trying to get the user of a specific Billing profile then I am getting the error of 'NoneType' object has no attribute user. this might be due to the fact that few rows of Order table is empty. Can't I show the users of the remaining Rows?

A: Indeed it is because the profile of the order is none/null, and the admin will show this error. Try:
class OrderAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'billing_profile','get_user']
    class Meta:
        model = Order
    def get_user(self, obj):
        return obj.billing_profile.user if obj.billing_profile else None

admin.site.register(Order,OrderAdmin)

Adding: obj.billing_profile.user if obj.billing_profile else None, that will only return the user if the obj (order) has a profile.

A: A simple way is to modify your get_user method:
class OrderAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'billing_profile','get_user']
    class Meta:
        model = Order
    def get_user(self, obj):
        try:
            return obj.billing_profile.user
        except AttributeError:
            return None


text:
Q: get the variable name passed to a function in C I am writing a demo program to print address of the variable. To make the code look cleaner I have created a header file in which the function is declared(ex.pointer.h) and a C file for calling that function(ex. main.c). I want to print the address of the variable with the variable name called in main.c
main.c:
#include "pointer.h"

int main(int argc, char *argv[]){
    int var=40;
    printAddress(var);
}

pointer.h
#include<stdio.h>
int *p;
#define getName(var) #var

void printAddress(int a){
    p=&a;
    printf("Address of variable %s is %p\n",getName(a),p);
}

I tried using macros but it printsAddress of variable a is 0x7fff2424407c which is not the expected outputAddress of variable var is 0x7fff2424407c. Can anyone please tell me what changes I should make and please explain.

A: You can't print the address of a variable using function like you've shown. The reason is that a is local variable, which has a different identity than the variable whose value you passed to printAddress.
You also can't get the name, because the name doesn't exist in that context.
However, you could use a macro:
#define printAddress(x)    printf("Address of variable %s is %p\n", #x, &x)

Note that # here is the stringification operator of the preprocessor; it turns a token into a C string literal (effectively just adding quotes around the token).
Full example:
#include <stdio.h>

#define printAddress(x)    printf("Address of variable %s is %p\n", #x, &x)

int main(void)
{
    int foo;
    printAddress(foo);
    return 0;
}

A: A macro can prepare the name and address of a variable before passing it to the actual function. Do not do this in production code:
#include <stdio.h>

void printAddress(char *name, void *address)
{
    printf("The address of %s is %p.\n", name, address);
}

#define printAddress(x) printAddress(#x, &(x))

int main(void)
{
    int var = 40;
    printAddress(var);
}

A:
I tried using macros but it printsAddress of variable a is 0x7fff2424407c which is not the expected outputAddress of variable var is 0x7fff2424407c.

At the place where you call the getName the variable name is a. There is no way to track back that you have passed a value that has been referenced by variable var before. This is because, as far as the compiler is concerned, you do not pass a "name" of a variable but it value - in this case an integer - which for the purpose of havg the code human readable is names a in the printAddress function body.
Now, the only way to achieve what you want is to get rid of the function and implement the whole thing as a macro.
Alternatively, you could create a template class that would keep the value and a name of the variable as a member variables but that would be an overkill. If you need this for debugging purposes then please consider using debugger such as gdb (or better cgdb) - it would be a much better choice.


text:
Q: Fatal error: ini_set(): To prevent data corruption, you are not allowed to turn on the mongo.native_long setting on 32-bit platforms in Unknown Fatal error: ini_set(): To prevent data corruption, you are not allowed to turn on the mongo.native_long setting on 32-bit platforms in Unknown on line 0
http://localhost/rockmongo/web/rockmongo/index.php
I have installed 32 bit php_mongo.dll and open extension in php.ini and set the environment variables for php.exe and placed the libsasl.dll in system32 folder.
I am currently using window 7 and appear this error.Can somebody pls solve the problem.Thanks!

A: I turned off the ini_set("mongo.native_long",1); as it said not working on 32 bit. and run perfectly instead of preg_replace(): is deprecated and need a little configuration ! :)


text:
Q: How I can return IntArray with reduce or fold? I have the following data for my task:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

As u see, I need to return IntArray, the first thing I used was runningReduce() , but this function is used in the version of Kotlin 1.4.30.
fun runningSum(nums: IntArray): IntArray {
    return nums.runningReduce { sum, element -> sum + element }.toIntArray()
}

Yes, this solution works, but how can I solve the same problem using reduce() or fold()?

A: Try the following:
nums.fold(listOf(0)) { acc, i -> acc + (acc.last() + i) }.drop(1).toIntArray()

The solution is sub-optimal though: it copies the list in each iteration. But looks fancy.
To avoid copying, you could write it as follows:
nums.fold(mutableListOf(0)) { acc, i -> acc += (acc.last() + i); acc }.drop(1).toIntArray()

I think I prefer the first version, the second one is not pure from functional perspective.

A: Mafor is right, fold() is not a good choice when producing a collection because it copies the collection every time so you need to workaround with mutable collections, which defeats the point of the functional style.
If you really want to work with arrays, which are mutable, doing it the old fashioned procedural way may be best:
val array = intArrayOf(1, 2, 3, 4)
for (i in array.indices.drop(1)) {
    array[i] += array[i - 1]
}
println(array.joinToString(", "))

Here's a slightly modified version of Mafor's answer that gives you an IntArray and avoids the use of multiple statements - it still uses the mutable list though:
val input = intArrayOf(1, 2, 3, 4)
val output = input.fold(mutableListOf(0)) { acc, cur ->
    acc.apply { add(last() + cur) }
}.drop(1).toIntArray()

println(output.joinToString(", "))

Both of these print 1, 3, 6, 10.


text:
Q: Use of unresolved identifier 'SWTableViewCel' I'm having a very strange problem here to do with SWTableViewCell.
I know I've implemented it right as I can subclass my prototype cell in the IB.
I get an unresolved identifier error when trying to create a SWTableViewCell programatically or subclass it to use as a custom cell.
Does anyone know why I would be able to subclass it in the IB but not reference it programatically without getting an unresolved identifier error?


text:
Q: No html element when reading html string in XDocument I'm reading HTML with the purpose of extracting only the contents of  from it.
The following markup is generated by a DevExpress RichEditControl
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>
        </title>

Content goes here

Following the example from this answer on how to read the document, I wrote the following function:
private string ParseHtml(string html)
{
    XDocument doc = XDocument.Parse(html);
    return doc.Elements("html").Single().Element("body").Value;
}

Seems like it should work in theory but in practice, the LINQ query returns no results for .Elements("html")
Am I way off the mark here? How can I read the html document and extract what I need?

A: Probably is because you need to add the namespace:
 private string ParseHtml(string html)
 {
    XNamespace xmlns= "http://www.w3.org/1999/xhtml";

    XDocument doc = XDocument.Parse(html);
    return doc.Element(xmlns+"html").Element(xmlns+"body").Value;
 }

Or:
return doc.Descendants(xmlns+"body").Single().Value;

Also a good way to parse an html is using HTML Agility Pack


text:
Q: Want exact_extractr to use categories within raster file to extract, not polygon file I have a raster file containing land types categorised 1-7 and a vector of 2727 polygons where seagrass is present (both are global and same projection). I want to find out how much each of the 7 land types are present within the seagrass polygon/s
(eg how much is urban/grassland/cropland etc)
but i can only get it to run if i put a category from the seagrass polygons and not the raster.
I have tried giving levels to the raster and labelling them but it then gives me Error in [.data.frame(x, i, j, drop = drop) :
undefined columns selected.
This is what I want and the output from running the exact_extractr code on the seagrass column (in polygon data) which i ran just to see what would happen, but I don't want seagrass, i want to extract the landtypes within the raster file
Code is:
r<-rast("7landtypes/SSP1_RCP19/global_SSP1_RCP19_2050.tif")
plot(r)

###aggregate so file is smaller###
r = aggregate(r, fact  = 10)

###READ IN POLYGON DATA AND TRANSFORM TO SAME CRS AS RASTER(CEA) BY TYPING >CMU AND COPY PASTING CRS DETAILS IN OUTPUT####
cmu<- st_read("units-attributes-wgs84L2.gpkg") %>%
  st_transform("+proj=cea +lat_ts=30 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")

###FILTER TO JUST SEAGRASS POLYGONS###
sg<-cmu[, names(cmu)%in% c ("seagrass", "unit_ID")] %>% filter(seagrass==1)
plot(sg)

####RUN EXACT EXTRACT#####
dat<-exact_extract(r, # land raster
                   sg,  #seagrass polygons
                   include_cols="seagrass", force_df=T )   # name of the category````

I know you must put the raster first in extractr function but then how can I get the values within that raster (and not the polygon/seagrass data?
view(r) showing properties within spatraster, values 1-7 each represent a categorical land cover type


text:
Q: IFS in .ksh acting strangly Can someone please explain why my IFS statement is replacing my characters in my output file? What do I need to change in order to solve it? I want to read an input file line by line (record by record) and the IFS to be ignored completely, but I am not sure what to put so that I get out what i put in.
#!/bin/bash
SAVEIFS=$IFS
IFS='\n'
record="The rain in Spain"
record2="c:\user\user\document.txt"
echo $record
echo $record

My output is replacing all my lower case 'n' characters with a space and my '\' characters are being deleted, instead of (what i thought would happen) separating by a new line:
The rai  i  Spai
c: user user docume t.txt

Thanks in advance

A: That's not a literal newline - your field separators are literally the characters \ (backslash) and n. You can use this:
IFS='
'

or this:
IFS=$'\n'


text:
Q: Sharing public folder between Ubuntu machines, via "Personal File Sharing" Launching Personal File Sharing from dash, the application opens with the message: "this feature cannot be enabled because the required packages are not installed on your system". I tried sudo apt-get install gnome-user-share apache2.2-bin libapache2-mod-dnssd as per this article, but that doesn't work (the error for that is: "apache2.2-bin : Breaks: gnome-user-share (< 3.8.0-2~) but 3.0.4-0ubuntu1 is to be installed
"). Is it possible to get this working on 14.04?

A: As far as my own experience tells me, you just have to:
sudo apt-get install apache2.2-bin libapache2-mod-dnssd


text:
Q: Uso de expresión Lambda en C# Teniendo las siguientes entidades
Entidad Carrera:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
namespace WebApiCarreras.Models
{
    public class Carrera
    {

        public Carrera()
        {
            Semestres = new List<Semestre>();
        }

        public int Id { get; set; }
        [StringLength(30)]
        public string Nombre { get; set; }
        public List<Semestre> Semestres { get; set; }
    }
}

Entidad Semestre:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiCarreras.Models
{
    public class Semestre
    {
        public Semestre()
        {
            Cursos = new List<Curso>();
        }
        public int Id { get; set; }
        public string Nombre { get; set; }
        [ForeignKey("Carrera")]
        public int CarreraId { get; set; }
        public Carrera Carrera { get; set; }
        public List<Curso> Cursos { get; set; }
    }
}

Entidad Cursos:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiCarreras.Models
{
    public class Curso
    {
        public int Id { get; set; }
        public string Nombre { get; set; }
        [ForeignKey("Semestre")]
        public int SemestreId { get; set; }
        public Semestre Semestre { get; set; }
    }
}

Atraves del controlador estoy intentando realizar a traves de expresion lambda obtener por ID La carrera, muestro un codigo de ejemplo a traves del controlador.
Controller:
//Para ver un pais por su ID
        [HttpGet("{id}", Name = "carreraCreado")]
        public IActionResult GetById(int id)
        {
            var carreras = _context.carreras.Include(x => x.Semestres).FirstOrDefault(x => x.Id == id);

            if (carreras == null)
            {
                return NotFound();
            }
            return Ok(carreras);
        }

Esto me muestra atraves en el Body:
{
    "id": 1,
    "nombre": "Desarrollo de Software",
    "semestres": [
        {
            "id": 1,
            "nombre": "I",
            "carreraId": 1,
            "cursos": []
        },
        {
            "id": 2,
            "nombre": "II",
            "carreraId": 1,
            "cursos": []
        },
        {
            "id": 3,
            "nombre": "III",
            "carreraId": 1,
            "cursos": []
        },
        {
            "id": 4,
            "nombre": "IV",
            "carreraId": 1,
            "cursos": []
        },
        {
            "id": 5,
            "nombre": "V",
            "carreraId": 1,
            "cursos": []
        },
        {
            "id": 6,
            "nombre": "VI",
            "carreraId": 1,
            "cursos": []
        }
    ]
}

El error que en lambda no se aun como hacer que tambien me muestre la lista de cursos.
Muchas gracias de antemano.

A: Si analizamos la documetacion
Loading Related Entities
veras en el titulo Eagerly loading multiple levels que se puede utilizar
var carreras = _context.carreras
                       .Include(x => x.Semestres.Select(p => p.Cursos))
                       .FirstOrDefault(x => x.Id == id);

en el Include defines el select a los cursos


text:
Q: Debugger ignores errors in dynamically loaded DLLs I have a very strange problem related to debugging of self-coded DLLs. I have an MFC-driven dialog-based application, several projects linked statically and several DLL-projects which are loaded at runtime.
I build solution in debug, run the application and I can easily debug those DLL-projects. Now the problem. If there is some obvious runtime error in DLL like following
int* i = 0;
*i = 4;

debugger asserts no error, throws no exception and silently returns to idle state with even no (visible) stack returns. It looks like when I'm hitting F10 on the statement *i = 4;, the control returns to main application window and program execution continues as nothing happened! And if there are no errors in the code, it executes fine. But I expect errors to be asserted in this case! And they are - in the main application's code.
I use LoadLibrary() function to load my DLL into application. DLL itself has MFC statically linked, same as every other project in solution has.
Any ideas? Don't even know what question to google...

A: Most likely you are loading the DLL with LoadLibrary() from an incorrect location and the lack of PDBs prevent the debugger from setting break point. You  may also load the retail DLLs with Asserts disabled (if by 'errors to be asserted' you mean you have ASSERT in code). If the error is a page fault (as the AV you show in your example) and your debugger doesn't break, it means that the exception is handled. You can always turn on the break on first chance, eg. sxe av. Not sure how you do that from the code editing tool, but you can always use a real debugger.

A: There's an exception handler somewhere in your code base that is swallowing exceptions.  Look for SetUnhandledExceptionFilter first.  Also: Debug + Exceptions, Win32 Exceptions, tick the Thrown checkbox.

A: Oh, it seems like the bug is not related to DLL at all. Debugger behaves the same way in the main application module too. I've inserted this code-snippet into OnInitDialog() function and into button-click OnBnClickedButton1() handler function.
In the first case (when inside OnInitDialog()), exception is thrown as usual and the program could not recover from this error. The following messages are traced in output window:

First-chance exception at 0x00a3a83e
  in dmc.exe: 0xC0000005: Access
  violation writing location 0x00000000.
First-chance exception at 0x00a3a83e
  in dmc.exe: 0xC0000005: Access
  violation writing location 0x00000000.
Unhandled exception at 0x00a3a83e in
  dmc.exe: 0xC0000005: Access violation
  writing location 0x00000000.

But in second case (when inside OnBnClickedButton1()) no exception is thrown, execution of OnBnClickedButton1() is aborted and the program continues to run normally. The following messages are traced in output window:

First-chance exception at 0x00a3c23f
  in dmc.exe: 0xC0000005: Access
  violation writing location 0x00000000.

So it seems like some top-level exception handler appears after the application is initialized. I've created new test application and tried the same thing with it - exceptions are thrown in both cases. I've compared their project-settings (diff on .vcproj files) and found no differences related to this issue.
Maybe this behavior is controlled by some weird MFC macro-defines? Or have I unintentionally affected it by some other settings?
Sorry for mistakes in the first version of problem.

A: Oh, it turned out that problem is caused by OpenGL wglMakeCurrent() call and is experienced only under Windows 7 64-bit with NVIDIA GeForce 8800 graphic card, meanwhile all works fine under Windows Vista 32-bit.
I asked new question here. Thanks for your feedback.


text:
Q: Python + PostgreSQL : [Id] + row IndexError: list index out of range I'm new with working in Python 3.7 (anaconda) + PostgreSQL. The task is to put data into the PostgreSQL database, but I'm keep receiving this thing:
Traceback (most recent call last):
  File "/Users/gshn/PycharmProjects/StatsWithPandasRSQL/Pandas/load_data_to_postgres.py", line 37, in <module>
    [Id] + row
IndexError: list index out of range

How can I fix it?
The code itself:
import psycopg2
import csv

conn = psycopg2.connect("host=localhost port=5433 dbname=gshn     user=postgres password=secret")
cursor = conn.cursor()

query = """
CREATE TABLE IF NOT EXISTS adult_data (
    id SERIAL PRIMARY KEY,
    age INTEGER,
    workclass VARCHAR,
    fnlwgt INTEGER,
    education VARCHAR,
    education_num INTEGER,
    marital_status VARCHAR,
    occupation VARCHAR,
    relationship VARCHAR,
    race VARCHAR,
    sex VARCHAR,
    capital_gain INTEGER,
    capital_loss INTEGER,
    hours_per_week INTEGER,
    native_country VARCHAR,
    salary VARCHAR
    )
"""
cursor.execute(query)
conn.commit()

with open('/Users/gshn/PycharmProjects/StatsWithPandasRSQL/Pandas/adult_data.csv', 'r') as f:
    reader = csv.reader(f)
    # Skip the header row
    next(reader)
    for Id, row in enumerate(reader):
        cursor.execute(
            "INSERT INTO adult_data VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
            [Id] + row
        )
conn.commit()


text:
Q: mysql table creation Error Code: 1005 in this specific case I have tried everything in solving this issue and yes I know that this type of question is already asked here but I could not solve my issue
It is mysql database
 Error Code: 1005

Can't create table '.\project\comments.frm' (errno: 150)

the foreign keys are matching in structure (i.e length and type) then what can be the possible problem in the table creation
Table which is giving error is comments:
 CREATE TABLE `comments`(
   `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
   `description` VARCHAR(100) NOT NULL,
   `user_id` INT(10) UNSIGNED NOT NULL,
   `post_id` INT(10) UNSIGNED NOT NULL,
   FOREIGN KEY (`post_id`) REFERENCES `posts`.`id`,
   FOREIGN KEY (`user_id`) REFERENCES `users`.`id`,
   PRIMARY KEY  (`id`)
 ) ENGINE=INNODB DEFAULT CHARSET=latin1;`

Here is posts table which is already created in the databas
 CREATE TABLE `posts` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `title` varchar(30) default NULL,
   `description` longtext,
   `image` varchar(50) default NULL,
   PRIMARY KEY  (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Here is the users table which is also already created in the database
 CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `user_name` varchar(33) default NULL,
    `email` varchar(255) NOT NULL,
    `password` varchar(255) default NULL,
    `type` varchar(255) NOT NULL,
    `registrationDate` date NOT NULL,
    PRIMARY KEY  (`id`,`email`,`type`)
)

A: Your syntax is incorrect.  The REFERENCES keyword should be followed by table (columns):
CREATE TABLE `comments`(
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `description` VARCHAR(100) NOT NULL,
    `user_id` INT(10) UNSIGNED NOT NULL,
    `post_id` INT(10) UNSIGNED NOT NULL,
    FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`),
    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
    PRIMARY KEY  (`id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1;


text:
Q: synonym for "tutor" -- American English I need to translate "tutor" to a language where the same spelling is a false cognate.  It would help me be creative to look at a few synonyms.  But all I've come up with is "private teacher" which brings more problems, because "private" is hard to express in the target language (Latin American Spanish, if you're curious).

A: You could use either mentor, trainer, or educator. But if you want to translate the word don't got too far, tutor in spanish means tutor (same word, almost same pronunciation). I hope it helps you!
And by the way tutor in spanish isn't a false cognate, i speak spanish and i know the meaning of the word. Tutor in spanish means: a person who tutors you and teaches you after school and can  also supervise you.


text:
Q: Moving average by multiple group I have a following DF (demo). I would like to find the previous 3 month moving average of Amount column per ID, Year and Month.
       ID        YEAR       MONTH   AMOUNT
1      ABC       2020        09      100
2      ABC       2020        11      200
3      ABC       2020        12      300
4      ABC       2021        01      400
5      ABC       2021        04      500
6      PQR       2020        10      100
7      PQR       2020        11      200
8      PQR       2020        12      300
9      PQR       2021        01      400
10     PQR       2021        03      500

Following is an attempt.
library(TTR)
library(dplyr)
DF %>% group_by(ID, YEAR, MONTH) %>% mutate(3MA = runMean(AMOUNT, 3))

resulting in error with n=3 is outside valid range.
Desired Output:
       ID        YEAR       MONTH   AMOUNT    3MA
1      ABC       2020        09      100       NA
2      ABC       2020        11      200       NA
3      ABC       2020        12      300       NA
4      ABC       2021        01      400      200 (100+200+300)/3
5      ABC       2021        04      500      300 (400+300+200)/3
6      PQR       2020        10      100       NA
7      PQR       2020        11      200       NA
8      PQR       2020        12      300       NA
9      PQR       2021        01      400      200 (100+200+300)/3
10     PQR       2021        03      500      300 (400+300+200)/3

A: You can use the following code:
library(dplyr)
arrange(DF,ID,YEAR) %>%
  group_by(ID) %>%
  mutate(lag1=lag(AMOUNT),
         lag2=lag(AMOUNT,2),
         lag3=lag(AMOUNT,3),
         movave=(lag1+lag2+lag3)/3)
#> # A tibble: 10 × 8
#> # Groups:   ID [2]
#>    ID     YEAR MONTH AMOUNT  lag1  lag2  lag3 movave
#>    <chr> <int> <int>  <int> <int> <int> <int>  <dbl>
#>  1 ABC    2020     9    100    NA    NA    NA     NA
#>  2 ABC    2020    11    200   100    NA    NA     NA
#>  3 ABC    2020    12    300   200   100    NA     NA
#>  4 ABC    2021     1    400   300   200   100    200
#>  5 ABC    2021     4    500   400   300   200    300
#>  6 PQR    2020    10    100    NA    NA    NA     NA
#>  7 PQR    2020    11    200   100    NA    NA     NA
#>  8 PQR    2020    12    300   200   100    NA     NA
#>  9 PQR    2021     1    400   300   200   100    200
#> 10 PQR    2021     3    500   400   300   200    300

Created on 2022-07-02 by the reprex package (v2.0.1)

A: An option using a sliding window:
library(tidyverse)
library(slider)

df <- tribble(
  ~id, ~year, ~month, ~amount,
  "ABC", 2020, 09, 100,
  "ABC", 2020, 11, 200,
  "ABC", 2020, 12, 300,
  "ABC", 2021, 01, 400,
  "ABC", 2021, 04, 500,
  "PQR", 2020, 10, 100,
  "PQR", 2020, 11, 200,
  "PQR", 2020, 12, 300,
  "PQR", 2021, 01, 400,
  "PQR", 2021, 03, 500
)

df |>
  arrange(id, year, month) |>
  group_by(id) |>
  mutate(ma3 = slide_dbl(lag(amount), mean, .before = 2, complete = TRUE)) |>
  ungroup() # if needed

#> # A tibble: 10 × 5
#>    id     year month amount   ma3
#>    <chr> <dbl> <dbl>  <dbl> <dbl>
#>  1 ABC    2020     9    100    NA
#>  2 ABC    2020    11    200    NA
#>  3 ABC    2020    12    300    NA
#>  4 ABC    2021     1    400   200
#>  5 ABC    2021     4    500   300
#>  6 PQR    2020    10    100    NA
#>  7 PQR    2020    11    200    NA
#>  8 PQR    2020    12    300    NA
#>  9 PQR    2021     1    400   200
#> 10 PQR    2021     3    500   300

Created on 2022-07-02 by the reprex package (v2.0.1)

A: Here is a way.
suppressPackageStartupMessages({
  library(dplyr)
  library(TTR)
})

x <- '       ID        YEAR       MONTH   AMOUNT
1      ABC       2020        09      100
2      ABC       2020        11      200
3      ABC       2020        12      300
4      ABC       2021        01      400
5      ABC       2021        04      500
6      PQR       2020        10      100
7      PQR       2020        11      200
8      PQR       2020        12      300
9      PQR       2021        01      400
10     PQR       2021        03      500  '
DF <- read.table(textConnection(x), header = TRUE)

DF %>%
  arrange(ID, YEAR, MONTH) %>%
  group_by(ID) %>%
  mutate(`3MA` = lag(runMean(AMOUNT, 3)))
#> # A tibble: 10 × 5
#> # Groups:   ID [2]
#>    ID     YEAR MONTH AMOUNT `3MA`
#>    <chr> <int> <int>  <int> <dbl>
#>  1 ABC    2020     9    100    NA
#>  2 ABC    2020    11    200    NA
#>  3 ABC    2020    12    300    NA
#>  4 ABC    2021     1    400   200
#>  5 ABC    2021     4    500   300
#>  6 PQR    2020    10    100    NA
#>  7 PQR    2020    11    200    NA
#>  8 PQR    2020    12    300    NA
#>  9 PQR    2021     1    400   200
#> 10 PQR    2021     3    500   300

Created on 2022-07-02 by the reprex package (v2.0.1)

A: Try this
DF |> arrange(ID , YEAR , MONTH) |> group_by(ID) |>
 mutate(`3M` = (lag(AMOUNT) + lag(AMOUNT ,2) + lag(AMOUNT , 3)) / 3)

*

*output

# A tibble: 10 × 5
# Groups:   ID [2]
   ID     YEAR MONTH AMOUNT  `3M`
   <chr> <int> <int>  <int> <dbl>
 1 ABC    2020     9    100    NA
 2 ABC    2020    11    200    NA
 3 ABC    2020    12    300    NA
 4 ABC    2021     1    400   200
 5 ABC    2021     4    500   300
 6 PQR    2020    10    100    NA
 7 PQR    2020    11    200    NA
 8 PQR    2020    12    300    NA
 9 PQR    2021     1    400   200
10 PQR    2021     3    500   300


text:
Q: Expected value of latent utility in logistic regression I'm looking for an analytical expression for the expected value of the latent utility in a logistic regression.
Setup:
There are two choices indexed by $i \in \{0, 1\}$ with associated utilities $u_i = w_i + \epsilon_i$, with the $\epsilon_i$ i.i.d. Gumbel(0, 1), aka Type I Extreme Value with location 0 and scale 1. The $w_i$ are constants.
(Same setup as http://en.wikipedia.org/wiki/Logistic_regression#As_a_two-way_latent-variable_model)
Let $Z \equiv \max\{u_0, u_1\}$, i.e. $Z$ is the utility you get when choosing the preferred alternative.
Question:
Is there a closed-form expression for the expected value of $Z$? If so, what is it, and how is it derived?
Additional Info:
If you know the answer, skip this section :-)
The $\epsilon_i$ have CDF $F(x) = e^{-e^{-x}}$ and expected value $\gamma \approx 0.5772$, the Euler–Mascheroni constant -- here I'm copying from http://en.wikipedia.org/wiki/Gumbel_distribution, in case this is helpful to anyone reading this question.
I did some googling, and I found something saying $\mathbb{E}[Z] = \ln(\Sigma_i(e^{w_i})) +$ constant. Is this correct?
I wrote some R code to investigate, and it seems like $\mathbb{E}[Z] = \ln(\Sigma_i(e^{w_i})) + \gamma \approx \ln(\Sigma_i(e^{w_i})) + 0.5772$. Is this correct?
Here's the code:
# Binary choice
# w_i + \epsilon_i with \epsilon_i ~ Gumbel
# Is Emax{w_i + \epsilon_i} = log(sum(exp(w_i))) + \gamma?

rgumbel <- function(n) {
  # Slower than Runuran, but avoids installing a new package
  u <- runif(n)
  return(-log(-log(u)))
}
library(Runuran)  # Gumbel
rgumbel <- function(n) {
  distribution <- udgumbel()
  generator <- pinvd.new(distribution)
  return(ur(generator, n))
}

gamma <- 0.57722 # Euler–Mascheroni constant
GetError <- function(w=c(5, 10), n=100000) {
  epsilon <- matrix(nrow=n, ncol=2, data=rgumbel(2*n))
  utility <- pmax(epsilon[, 1] + w[1],
                  epsilon[, 2] + w[2])
  emax <- mean(utility)
  emax.analytical <- log(sum(exp(w))) + gamma  # Correct?
  return(emax - emax.analytical)
}

The GetError function returns the difference between a sample mean and my candidate analytical expression. I played around and tended to see values very close to zero.
Here's my very feeble attempt at getting an analytical expression for $\mathbb{E}[Z]$:
$G(z) \equiv Pr[Z \leq z] = Pr[w_0 + \epsilon_0 \leq z] Pr[w_1 + \epsilon_1 \leq z | w_0 + \epsilon_0 \leq z]$
$G(z) = F(z - w_0) F(z - w_1) = e ^ {-e^{-z + w_0} -e^{-z + w_1}}$
$g(z) \equiv G^\prime(z) = e ^ {-e^{-z + w_0} -e^{-z + w_1}} (e^{-z + w_0} + e^{-z + w_1})$
$\mathbb{E}[Z] = \int z g(z) dz$
So, assuming there are no mistakes up to here, I need to calculate:
$\int z e ^ {-e^{-z + w_0} -e^{-z + w_1}} e^{-z + w_0} dz$ plus a similar second term, but I'm not sure how to deal with this integral.
Many thanks for any help,
Adrian

A: It's been a while, but since I've run into this recently, I'll post my answer.  Letting $i = 1,...,N$, and assuming $\epsilon_i \sim \text{Gumbel}(\mu, 1), \forall i$, the closed form solution for $E[Z]$ is
$$E[Z] = E[\max_i(w_i + \epsilon_i)] = \mu + \gamma + \ln\left(\sum_i^N \exp\left\{w_i \right\} \right),  $$
where $\gamma \approx 0.52277$ is the Euler-Mascheroni constant, and $\mu$ is the location parameter of the Gumbel distribution for each $\epsilon_i$. You can find one proof of this here, along with more details.

A: A partial answer. First,
$$
  F_{U_i}(u_i) = P(U_i\leq u_i) = P(U_i-w_i\leq u_i-w_i) = P(\epsilon_i\leq u_i-w_i) = e^{-e^{-(u_i - w_i)}} \, .
$$
Also,
$$
  F_Z(z) = P(Z\leq z) = P(\max \{U_0,U_1\} \leq z) = P(U_0\leq z, U_1\leq z)
$$
$$
  = P(U_0\leq z)P(U_1\leq z) = F_{U_0}(z)F_{U_1}(z) = e^{-\left(e^{-(z - w_0)}+e^{-(z - w_1)}\right)} \, .
$$
Therefore,
$$
\mathrm{E}[Z] = \int_0^\infty (1 - F_Z(z))dz  - \int_{-\infty}^0 F_Z(z)\,dz
$$
$$
= \int_0^\infty \left( 1 - e^{-\left(e^{-(z - w_0)}+e^{-(z - w_1)}\right)} \right) dz  - \int_{-\infty}^0 e^{-\left(e^{-(z - w_0)}+e^{-(z - w_1)}\right)} dz \, .
$$
These integrals can probably be expressed in terms of the Exponential Integral.


text:
Q: Android ViewPager displays white screen I'm trying to create VeiwPager inside a Fragment using FragmentStatePagerAdapter.
it displays the first fragment but after scrolling to the second fragment there is just white fragment (even on scrolling back to the first fragment)
I've tried to use PagerAdapter and set pictures without fragment but the result is same.
is there RAM problem ? what can I do to solve it?
Home fragment(contains ViewPager) :
private void initSlideShow(View view){
    VPImageSlider = (ViewPager16by9) view.findViewById(R.id.VPImageSlider);
    sliderDotsPanel = (LinearLayout) view.findViewById(R.id.SliderDots);
    VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());

    vpImageSliderAdapter.addSlide(R.drawable.dc_slide_1);
    vpImageSliderAdapter.addSlide(R.drawable.dc_slide_2);
    vpImageSliderAdapter.addSlide(R.drawable.dc_slide_3);
    vpImageSliderAdapter.addSlide(R.drawable.dc_slide_4);
    vpImageSliderAdapter.addSlide(R.drawable.dc_slide_5);

    VPImageSlider.setAdapter(vpImageSliderAdapter);
}

ViewPager Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import iranelab.samsoft.net.iranelab.Classes.ImageView16by9;
import iranelab.samsoft.net.iranelab.R;

public class ViewPagerFragment extends Fragment {

private static final String ARG_PARAM4 = "imageTest";

private int imageTest;

public ViewPagerFragment() {}

public static ViewPagerFragment newInstance(String imageId, String type, String text,int imageTest) {
    ViewPagerFragment fragment = new ViewPagerFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_PARAM4, imageTest);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        imageTest = getArguments().getInt(ARG_PARAM4);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
    ImageView16by9 image = (ImageView16by9) view.findViewById(R.id.IVSlide);
    image.setImageResource(imageTest);
    return view;
}

}

ViewPager Adapter :
public class VPImageSliderAdapter extends FragmentStatePagerAdapter {

private int[] slides = {};

public VPImageSliderAdapter(FragmentManager fm){
    super(fm);
}

public void addSlide(int drawable){
    slides = Arrays.copyOf(slides,slides.length+1);
    slides[slides.length-1]=drawable;
}

@Override
public int getCount() {
    return slides.length;
}

@Override
public Fragment getItem(int position) {
    return ViewPagerFragment.newInstance(slides[position]);
}

}

A: Change
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());

to
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getChildFragmentManager());

it will work

A: Just needed to add :
ViewPager.setOffscreenPageLimit(5);


text:
Q: Import Boto3 causing error when running through py2app I'm building a standalone tool that leverages the AWS API, the main script errors out on the 'import boto3' line. When I run the script via the CLI it operates fine. When I try and run it through a py2app application it throws the following error:
Traceback (most recent call last):
  File "scripts/application.py", line 18, in <module>
    import boto3
  File "<frozen zipimport>", line 259, in load_module
  File "boto3/__init__.pyc", line 16, in <module>
  File "<frozen zipimport>", line 259, in load_module
  File "boto3/session.pyc", line 17, in <module>
  File "/path/application.app/Contents/Resources/lib/python3.8/botocore/session.py", line 29, in <module>
    import botocore.credentials
  File "/path/application.app/Contents/Resources/lib/python3.8/botocore/credentials.py", line 34, in <module>
    from botocore.config import Config
  File "/path/application.app/Contents/Resources/lib/python3.8/botocore/config.py", line 16, in <module>
    from botocore.endpoint import DEFAULT_TIMEOUT, MAX_POOL_CONNECTIONS
  File "/path/application.app/Contents/Resources/lib/python3.8/botocore/endpoint.py", line 22, in <module>
    from botocore.awsrequest import create_request_object
  File "/path/application.app/Contents/Resources/lib/python3.8/botocore/awsrequest.py", line 25, in <module>
    import botocore.utils
  File "/path/application.app/Contents/Resources/lib/python3.8/botocore/utils.py", line 31, in <module>
    import botocore.httpsession
  File "/path/application.app/Contents/Resources/lib/python3.8/botocore/httpsession.py", line 8, in <module>
    from urllib3.util.ssl_ import (
ImportError: cannot import name 'ssl' from 'urllib3.util.ssl_' (/path/application.app/Contents/Resources/lib/python38.zip/urllib3/util/ssl_.pyc)

My current setup.py file is as follows:
import py2app
from setuptools import setup

APP_NAME = "Application"
APP = ['testkinter.py']
DATA_FILES = [('scripts', ['application.py']),
              ('images', ['Application.gif'])]

OPTIONS = { 'argv_emulation': False,
            'iconfile':'Actions.icns',
            'includes':['py2app', 'time', 'json', 'datetime','csv', 'boto3',
                        'tkinter','uuid', 'subprocess', 'pyOpenSSL', 'urllib3']}

setup(
    name = APP_NAME,
    app = APP,
    data_files = DATA_FILES,
    options = {'py2app': OPTIONS},
    setup_requires = ['py2app']
)

pip3 Freeze output:
altgraph==0.17
boto3==1.12.18
botocore==1.15.18
certifi==2019.11.28
cffi==1.14.0
chardet==3.0.4
cryptography==2.8
docutils==0.15.2
idna==2.9
jmespath==0.9.5
macholib==1.14
modulegraph==0.18
py2app==0.21
pycparser==2.20
pyOpenSSL==19.1.0
python-dateutil==2.8.1
requests==2.23.0
s3transfer==0.3.3
six==1.14.0
urllib3==1.25.8

I have tried to uninstall and reinstall boto3, urllib3, and py2app so I know it's not an easy fix like that. I've also tried including / excluding libraries I've placed in the seteup.py file as well.
Thank you.


text:
Q: statistics sample mean and population mean I have this assignment which requires having a sample of 20 houses in my area and comparing their prices to a study that was made, and then making null and alternate hypothesis.
One of the questions is asking to describe mathematically the sample mean compared to the population mean. what do they mean by that as I only know that the sample mean is usually included in the population mean? and how to describe it mathematically?
 thanks in advance :)

A: I am having trouble making this Comment print clearly in a 'comment box', so I'm trying it as an Answer.
I suppose you are expected to view the 'study' as authoritative and use its mean as 'population' mean $\mu$. The mean from your small sample of 20 would be the sample mean $\bar X.$
If there is also a 'population' variance $\sigma$ in the study, then maybe you are expected to start with $Z = \frac{\bar X - \mu}{\sigma/\sqrt{20}},$ assuming it is approximately standard normal. In that case you might be able to test the null hypothesis that your sample
is taken properly from the houses in the study, rejecting at the 5% level if $|Z| > 1.96.$
If there is no SD given in the paper, then
maybe you are expected to use $T = \frac{\bar X - \mu}{S/\sqrt{20}},$ where
$S$ is the sample SD of your sample of 20. Then you would assume that $T$ has Student's t distribution with 19 degrees of freedom, get the critical value 2.093 from a printed table, and reject the null hypothesis if $|T| > 2.093.$
Your description of your assignment is a bit vague, so all of this can only be regarded as guesses.


text:
Q: How to differentiate this equation involving an integral expression? I want to differentiate the Volterra integral equation $\phi(t) + \int_0^t (t - \xi) \, \phi(\xi) \, \mathrm{d}{\xi} = \sin{2t}$.
Am I right in thinking that the integral can just be removed like so?
$\frac{\mathrm{d}}{\mathrm{d}t} \left( \phi(t) + \int_0^t (t - \xi) \, \phi(\xi) \, \mathrm{d}{\xi} = \sin{2t} \right)\\ = \phi'(t) + (t - \xi) \, \phi(\xi) = 2\cos{2t}$
And in general, how do you differentiate equations involving integral expressions? I haven't encountered equations of this nature before.

A: I think you confused the limit of integration and its variable.
If we define $F:\mathbb{R}\rightarrow\mathbb{R}$ by
$$F(t)=\int_0^t(t-\xi)\phi(\xi)d\xi=t\int_0^t\phi(\xi)d\xi-\int_0^t\xi\phi(\xi)d\xi$$
Then deriving both sides using linearity, the product rule and the fundamental theorem of calculus we get
$$F'(t)=\frac{d}{dt}\left(t\int_0^t\phi(\xi)d\xi\right)-\frac{d}{dt}\left(\int_0^t\xi\phi(\xi)d\xi\right)$$
$$F'(t)=1\int_0^t\phi(\xi)d\xi+t\phi(t)-t\phi(t)=\int_0^t\phi(\xi)d\xi$$
In general you should separate the "$t$"s and "$\xi$"s before differentiating


text:
Q: Powershell not handling arguments in function properly Any idea why my script is acting funny?
I am passing it some arguments, but it doesn't seem to be assigning them to the correct variables. E.g.
function test($a, $b, $c){

    write-host "A: " $a
    write-host "B: " $b
    write-host "C: " $c

    $sum = $a + $b + $c

    write-host "The sum is: " $sum
}

test(1,2,3)

Is giving the following output:
A:  1 2 3
B:
C:
The sum is:  1 2 3

What gives?
Ben

A: Dammit.
Should have been using
test 1 2 3

to invoke the function.
Thanks anyway!
Ben


text:
Q: Remove Documents and Pictures Is there a way to remove the 'documents' and 'pictures' options from my personal folders. I have a work machine that I need to upload some files from but don't want to give that machine the option to access my personal documents and pictures.

A: You could try Directory Encryption with encfs.
Encfs is an application that allows you to create encrypted directories, any file that is placed in such a directory will be encrypted. To open an encrypted directory you need a correct password.
Please refer to FolderEncryption for more details.

A: Of course you already need to have access to that machine to even be able to get files.
There are several methods in doing this...

*

*If both have USB use a stick.

*Get the files with scp from that machine to your machine or from your machine to that machine (scp {user}@{server-ip}:/{dir}/{dir}/{files}* .). We use this alot to update our software on a server.

Neither will allow anyone to see your system or your documents/picture folders.


text:
Q: Updating multiple mysqli rows to true or false with a simple form, php and a while loop I have set up a form, created from a while loop of around 20 entries with each mysqli entry it echos back to include a switch.  I'm trying to get the table to recognize if the switch is on or not, if it is set to on input true into the table row and if the switch is not set input false into the table row, updating all rows with one query and php execution file.
The code below consists of first the PHP AND HTML FORM code to create all the entries with a switch wrapped in a form.  The second two examples of code are the php execution attempts.
PHP AND HTML FORM CODE STARTS
<form enctype="multipart/form-data" id="form1" name="form1" method="post" action="add_newsletter.php">

<?php

// get the info from the db
$query = 'SELECT * FROM news_content ORDER BY article_id DESC';

$results = mysqli_query($dbc, $query)or die('Error querying database');

while ($row = mysqli_fetch_array($results)){

// tileAdminBar START
echo '
';

echo '
';
echo '
<input type="checkbox" name="newsletterToggle" id="newsletterToggle" value="true" >

';
echo '
';

echo '
';
// tileAdminBar END

echo '
';
echo '<input type="hidden" value="' . $_GET['article_id'] . '"name="article_id"/> ';
echo '
';

} // end while

?>

<input class="form" type="submit" name="Submit" id="Submit" value="Create newsletter"/>

</form>

PHP EXECUTION EXAMPLE ONE START
<?php

$article_id = $_POST['article_id'];
$newsletterToggle = $_POST['newsletterToggle'];
$newsletterToggle = mysqli_real_escape_string($dbc, $newsletterToggle);

$query = 'SELECT * FROM ontent ORDER BY article_id DESC';

$results = mysqli_query($dbc, $query)or die('Error querying database');

while ($row = mysqli_fetch_array($results)){

if($newsletterToggle == "true"){
//post variables to slt_database and insert into content table
$secondQuery = "UPDATE news_content SET newsletter = 'true' WHERE '$row' = '$article_id'";

$results2 = mysqli_query($dbc, $secondQuery)or die('Error querying database');
}else{

//post variables to slt_database and insert into content table
$secondQuery = "UPDATE news_content SET newsletter = 'false' WHERE '$row' = '$article_id'";

$results2 = mysqli_query($dbc, $secondQuery)or die('Error querying database');

}

}
//End of while

//close slt_database conection
mysqli_close($dbc);
?>

PHP EXECUTION EXAMPLE TWO
<?php

$newsletterToggle = $_POST['newsletterToggle'];
$newsletterToggle = mysqli_real_escape_string($dbc, $newsletterToggle);

$query = 'SELECT * FROM content ORDER BY article_id DESC';

$results = mysqli_query($dbc, $query)or die('Error querying database');

while ($row = mysqli_fetch_array($results)){

if($newsletterToggle == "true"){
//post variables to slt_database and insert into news_content table
$secondQuery = "UPDATE news_content SET newsletter = 'true'";

$results2 = mysqli_query($dbc, $secondQuery)or die('Error querying database');
}else{

//post variables to slt_database and insert into content table
$secondQuery = "UPDATE content SET newsletter = 'false'";

$results2 = mysqli_query($dbc, $secondQuery)or die('Error querying database');

}

}
//End of while

//close slt_database conection
mysqli_close($dbc);
?>
/* PHP EXECUTION EXAMPLE TWO END*/

Using PHP EXECUTION EXAMPLE ONE I try grabbing the article_id to help updating, but when executed I don't get any mysqli or php errors, it just doesn't effect any of the rows for the table column.
Using PHP EXECUTION EXAMPLE TWO without the article_id i can switch 1,2,3 on etc out of the 20 rows and it just updates all the table rows to true.  If I don't switch any of the switches on all the table rows update to false.  My problem is it is not recognizing the switches that have been switch on or off and updating them accordingly

A: You can use jquery and ajax for that .i.e :
Problem  1(PHP EXECUTION EXAMPLE ONE) :
As there are around 20 entries , if you will click on submit button you will never get which row the user have clicked . So, to solve this you can do like below :
Your Php file :
while ($row = mysqli_fetch_array($results)){

// tileAdminBar START
echo '
';

echo '
';
echo '
 //attaching id with article id , i.e : newsletterToggle1,newsletterToggle2 etc
<input type="checkbox" name="newsletterToggle[]" id="newsletterToggle' . $_GET['article_id'] . '" value="'.$_GET['article_id'].'" >

';
echo '
';

echo '
';
// tileAdminBar END

echo '
';
echo '<input type="hidden" value="' . $_GET['article_id'] . '"name="article_id"/> ';
echo '
';
//added button
echo '<button name="submit" data-value="' . $_GET['article_id'] . '" >Submit </button>
}

Now your ajax call will be like below :
$(document).ready(function() {
  $('button').on("click",function() {
  //getting id which is present in button
   var article_id=$(this).attr("data-value");
   //to get checkbox value
var newsletterToggle=false;
if ($('#newsletterToggle'+article_id).is(":checked"))
{
  // it is checked
 newsletterToggle=true;
}else{
//not check
newsletterToggle= false;
}
 //calling ajax
    $.ajax({
      type: "POST",
      url: "yourphppage",
      data: {
        'newsletterToggle': newsletterToggle,//<-passing value to php
        'article_id':article_id
     },
      success: function(response) {
        //display something
        alert(response);
      },
      error: function(jqXHR) {

        alert("There was a problem");
      }
    });

   });
});

Your php page:
if($newsletterToggle == "true"){
//post variables to slt_database and insert into content table
$secondQuery = "UPDATE news_content SET newsletter = 'true' WHERE yourcolumnidname = '$article_id'";

$results2 = mysqli_query($dbc, $secondQuery)or die('Error querying database');
}else{

//post variables to slt_database and insert into content table
$secondQuery = "UPDATE news_content SET newsletter = 'false' WHERE yourcolumnidname  = '$article_id'";

$results2 = mysqli_query($dbc, $secondQuery)or die('Error querying database');

}

Problem 2(PHP EXECUTION EXAMPLE TWO) :
You need something to recognize which checkbox is been switched You don't need to use ajax here .Do like below :
echo '
     //attaching id with article id , i.e : newsletterToggle1,newsletterToggle2 etc
    <input type="checkbox" name="newsletterToggle[]" id="newsletterToggle' . $_GET['article_id'] . '" value="'.$_GET['article_id'].'" >
                            //^value of id

    ';

In above code value="'.$_GET['article_id'].'" <- this will be used to recognize  which rows switch has been change ,so we will update that row only in php file . In you php file PHP EXECUTION EXAMPLE TWO do below changes :
//getting value of checkboxes
$newsletterToggle = $_POST['newsletterToggle'];
if (isset($_POST['newsletterToggle'])) {

    foreach ($newsletterToggle as $values){
    //this will update only those rows where checkbox is selected
    $secondQuery = "UPDATE news_content SET newsletter = 'true' where  youridcolumnname = '$values' ";
    $results2 = mysqli_query($dbc, $secondQuery)or die('Error querying database');
    }
}

Note : You must use prepared statement it is safe an secure.


text:
Q: Why apply() converts date objects to numeric objects? Why apply() converts my date objects to numeric before calling the user function?
apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"), 1)), 1, function(x) { return(class(x)) })
[1] "numeric" "numeric" "numeric" "numeric" "numeric"

And why as.Date() doesn't have the origin parameter set to "1970-01-01" by default?
> as.Date(apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"), 1)), 1, function(x) { return(x) }))
Error in as.Date.numeric(apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"),  :
  'origin' must be supplied
> as.Date(apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"), 1)), 1, function(x) { return(x) }), origin="1970-01-01")
[1] "2010-01-01" "2010-01-02" "2010-01-03" "2010-01-04" "2010-01-05"

A: There is a function seq.Date in the base package that will allow you to make a sequence for a Date object. But a matrix will still only take atomic vectors, so you will either just have to call as.Date() again whenever you need to use the Date, or just store it in a dataframe because that can hold "Date" class values.
As far as the default parameter for as.Date, I don't think it makes sense to have 1970 set as the default. What if people are analyzing data from before that date for whatever possible reason?


text:
Q: Darken screen when modal pops up I'm trying to darken the rest of my screen when my modal pops up. I got the code from here: https://jasonwatmore.com/post/2018/05/25/angular-6-custom-modal-window-dialog-box
What ends up happening is my entire screen goes dark and opaque even before I open the module.
I'm not sure if there is something I'm doing wrong in the CSS or if there is a mistake in the HTML
Here is my code:
....

/* MODAL STYLES
-------------------------------*/
.closed{
  display:none;
}
  .modal {
      /* modal container fixed across whole screen */
      background: #fff;
      text-align: center;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      // top: 0;
      // right: 0;
      // bottom: 0;
      // left: 0;

      /* z-index must be higher than .modal-background */
      z-index: 1000;

      /* enables scrolling for tall modals */
      overflow: auto;

      .modal-body {
          padding: 20px;
          background: #fff;

          /* margin exposes part of the modal background */
          margin: 40px;
      }
      .modal-header{
        padding: 20px;
        background: #fff;

        /* margin exposes part of the modal background */
        margin: 40px;
      }

  }

  .modal-background {
      /* modal background fixed across whole screen */
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;

      /* semi-transparent black  */
      background-color: #000;
      opacity: 0.75;

      /* z-index must be below .modal and above everything else  */
      z-index: 1;
  }

body.modal-open {
  /* body overflow is hidden to hide main scrollbar when modal window is open */
  overflow: hidden;
}

....

HTML:

<modal id="custom-modal-2" >

A Custom Modal!

                Home page text: <input type="text" [(ngModel)]="bodyText" />

            <button (click)="closeModal('custom-modal-2');">Close</button>

</modal>

A: So your modal is set to be displayed automatically and so you are displaying the whole thing once it is added to your page. You can add the "closed" class to your modal as a default, then have the open and close button change that value.
One thing you may want to consider, if you aren't already doing it, is having the modal with a state of isOpen, and then have that be the trigger for whether or not it is displaying the modal. The reason I would suggest this is because that way the logic is based on something you can see in the Javascript itself and control that with {{isOpen}} rather than adding and removing a class.


text:
Q: Rosenlicht Chapter 1 Problem 11 Unbounded Set I've been working on this problem for over an hour. It is from Maxwell Rosenlicht's text book "Introduction to Analysis" in the first chapter before limits are discussed. I will state the claim, show what I worked to so far, and explain where I am stuck.
Problem: Prove that if $a\in \mathbb R, a>1$, then the set $\{a,a^2,a^3,...\}$ is not bounded from above. (Hint: First find a positive integer n such that $a>1+\frac1n$ and prove that $a^n>(1+\frac1n)^n\ge2$).
For the sake of following the hint he gave me I attempted to prove that claim. Which I will now demonstrate. However, I feel that it may possibly be incorrect. Nevertheless, should my proof of the hint be correct I still do not understand how it is supposed to help me prove the original claim about the set given not being bounded from above.
Lemma 1: If $a>1$ and $n$ is a positive integer, then $a^n>(1+\frac1n)^n\ge2$.
Proof: Following with a proof by induction we prove our base case.
Base Case: Because $a-1>0$ we can say that there exists an integer $n_0$ such that $a-1>\frac{1}{n_0}$ or after adding one to both sides $a>\frac{1}{n_0} +1$ Now, if we let $n_0=n=1$, then we have $2<a$.
Inductive Step: First note that $(1+\frac{1}{n+1})^n<(1+\frac{1}{n})^n$ because, $n<n+1 \Rightarrow \frac{1}{n+1} < \frac{1}{n} \Rightarrow \frac{1}{n+1}+1 < \frac{1}{n} +1 \Rightarrow (\frac{1}{n+1}+1)^n < (\frac{1}{n} +1)^n$.
Now, we assume that $(\frac{1}{k} +1)^k < a^k$ for all positive integers $k$. But, $(\frac{1}{k+1}+1)^k < (\frac{1}{k} +1)^k$ so $(\frac{1}{k+1}+1)^k<a^k$ or simply $(\frac{1}{k+1}+1)<a$. However, if $(\frac{1}{k+1}+1)^k<a^k$ and $(\frac{1}{k+1}+1)<a$, then $(\frac{1}{k+1}+1)^k(\frac{1}{k+1}+1)<aa^k$ or $(\frac{1}{k+1}+1)^{k+1}<a^{k+1}$.
I spent a lot of time trying to figure this proof out, and then again typing it on here so I hope it is correct, but I feel somewhat nervous about it.Any feedback on my proof would be grateful. Also, any advice on where I should go to prove the original statement about the unbounded set after finishing this lemma would be greatly appreciated. Thank you.

A: I love this book and remember doing this problem.
Use the binomial theorem. For $n \in \mathbb{N}$:
$\left( 1 +  \frac{1}{n} \right)^n = 1 + \binom{n}{1} \left(\frac{1}{n} \right)^1+\binom{n}{2} \left( \frac{1}{n} \right)^2 + ... > 1 + \binom{n}{1}\left(\frac{1}{n} \right) = 1 + 1 = 2$
As for the second part, you assume it is bounded so that there is a $B$ such that $a^k \leq B \: \forall k \in \mathbb{N}$.
How can you pick a natural number $k$ so that it works?
We can find a $n$ such that $ a^n > 2$.
Well, how can you pick $k$ so that $2^k > B$?
Now, given that $a^n > 2$, what happens if you raise $a^n$ to this $k$?