text:
Q: XSLT: Is it possible to use resulting tag value for calculation of next tag? Given we have some XSLT transformation which transforms XML A into XML B.
During this process some field B.a is populated basing on some rules by our transformation.
After this we want to populate B.b. But the rules of that field population are based on B.a value! So we need to do this is a consequtive manner and use B.a value in next calculations.
Is it possible in XSLT?

A: Essentially, it comes down to following this pattern:
<xsl:template match="/">
   <!-- get the result -->
   <xsl:copy-of select="$b.b" />
</xsl:template>

<xsl:variable name="$b.a">
    <xsl:apply-templates select="doc('a.xml')" mode="a" />
</xsl:variable>

<xsl:variable name="$b.b">
    <xsl:apply-templates select="doc('b.xml')" mode="b" />
</xsl:variable>

<xsl:template match="some/node/in/a" mode="a">
   <!-- do your thing here -->
</xsl:template>

<xsl:template match="some/node/in/b[$b.a/based/on/a[@x]]" mode="b">
   <!-- do your thing here -->
</xsl:template>

If you are unfortunate and stuck with XSLT 1.0 for some reason, use exslt:node-set() on the variables when re-applying nodes to them. Also, you will have to make the difference in that case in the selections, instead of in the (preferred) matching templates pattern expressions, because patterns in XSLT 1.0 cannot use variable references.


text:
Q: Avalonia: DataGrid in TabControl Content Template I want to make automatic creation of tabs with datagrid inside - Amount of Tabs and it's content depends on data files. The tab control has the path TabItem, and the DataGrid sees the path MainWindowViewModel
<TabControl Name="TC_TEST" Items="{Binding TtabItem}">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Header}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <DataGrid AutoGenerateColumns="True" CanUserSortColumns="False" CanUserResizeColumns="True" Items="{Binding Content}"/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

How to generate DataGrid in tabs?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Complete account deletion on Github- commits made my same ssh key ported into new account
I deleted my old github account earlier this year, so that my old content is labeled as 'Ghost'.  However, when i used my old ssh-keys to push into my new github account, Github went back in time and linked my new account to all my old commits using that key.  Is there a way to get github to deflag these commits and label them too as Ghost?
not sure where else to ask

A: The commit-user association is set after the account email.
If your new account uses the same email as the old deleted one, chances are GitHub would show those commits with your current account avatar.
Using the old ssh key should not work to push, unless you set your old public SSH key in your new GitHub account profile.
Or if you are actually using an HTTPS URL, in which case no SSH key (old or new) would be used anyway.
To "deflag these commits and label them too as Ghost", you would need to amend those commits, changing their author email.
Or you need to make sure your new account is not using your old commit author email.


text:
Q: Why django-viewflow internal table 'viewflow_task_previous' goes backwards? Given the following steps defined

And when I dig into the internal tables, especially viewflow_task_previous table, it seems the from and to are reversed?
pmas=> select * from viewflow_task_previous where from_task_id = 10248;
  id  | from_task_id | to_task_id
------+--------------+------------
 9099 |        10248 |      10247
(1 row)

pmas=> select id, status, flow_task, status from viewflow_task where id = 10248;
  id   |  status  |                                flow_task                                |  status
-------+----------+-------------------------------------------------------------------------+----------
 10248 | ASSIGNED | connect_it/flows.new_circuit.flow.NewCircuit.external_task_installation | ASSIGNED
(1 row)

pmas=> select id, status, flow_task, status from viewflow_task where id = 10247;
  id   | status |                                flow_task                                | status
-------+--------+-------------------------------------------------------------------------+--------
 10247 | DONE   | connect_it/flows.new_circuit.flow.NewCircuit.external_task_provisioning | DONE
(1 row)

Could someone explain why and how this works?

A: viewflow_task_previous table created by models.ManyToManyField previous field of the Task model
https://github.com/viewflow/viewflow/blob/master/viewflow/models.py#L97
Yep, that gives some confusion on the SQL level


text:
Q: Unmanaged Struct Instance in Managed Class I've got a fairly specific problem i've been struggling with for a couple of days.
I'm using a native C++, one of the methods takes a ptr to a struct containing fixed size char arrays.
e.g.
struct userData {
    char data1[10];
    char data2[10];
};

method:
short AddItem(long id, userData* data);

I'm trying to call to call this from Managed VC++ but I need to have an instance of userData I can keep hold of in my managed class.
Can anyone help with how to achieve this?
Thanks

A: I use one of the following two containers when friendly interop with garbage collection is preferred:
template<typename T> ref class GcPlainPtr sealed {
    T*  ptr;
public:
    GcPlainPtr(T*ptr): ptr(ptr) { GC::AddMemoryPressure(sizeof(T)); }

    !GcPlainPtr() {
        GC::RemoveMemoryPressure(sizeof(T));
        delete ptr; ptr = nullptr;
    }

    ~GcPlainPtr() { this->!GcPlainPtr(); } //mostly just to avoid C4461

    T* get() {return ptr;}

    static T* operator->(GcPlainPtr<T>% gcPtr) { return gcPtr.ptr;}
    static operator T*(GcPlainPtr<T>% gcPtr) { return gcPtr.ptr; }
};

The previous container looks sufficient for your needs.  You can use it as follows:
ref class MyManagedClass {
    GcPlainPtr<userData> myUserData;

    MyManagedClass(...bla...)
        : myUserData(new userData(...))
        , ...
    {...}

    AnotherMethod() {
        std::cout << myUserData->data1 << '\n';
        AddItem(1, myUserData.get());
    }
}

The advantage of the previous approach is that even if you forget to dispose of the objects, the memory pressure is reasonably updated so that garbage collection occurs at the appropriate frequency.
If you know the size of the data element you're allocating roughtly, but it's not merely the direct size (i.e. the native struct or class allocates memory internally), the following variant may be more appropriate:
template<typename T> ref class GcAutoPtr sealed {
    T*  ptr;
    size_t  size;
public:
    GcAutoPtr(T*ptr,size_t size) : ptr(ptr), size(size) {
        GC::AddMemoryPressure(size);
    }

    !GcAutoPtr() {
        GC::RemoveMemoryPressure(size);
        size=0;
        delete ptr;
        ptr = nullptr;
    }

    ~GcAutoPtr() { this->!GcAutoPtr();} //mostly just to avoid C4461

    T* get() {return ptr;}

    static T* operator->(GcAutoPtr<T>% gcPtr) { return gcPtr.ptr;}
    static operator T*(GcAutoPtr<T>% gcPtr) { return gcPtr.ptr; }
};

A: You cannot store the instance in the managed class object and generate a pointer to it easily.  That's very incompatible with the garbage collector.  It will move managed objects around when it compacts the heap, that can happen at unpredictable times.  Trying to pass a pointer to a userData member will generate a compiler error.
Some workarounds: allocate the userData instance on the heap with new, store the pointer in the managed object.  That is however pretty inefficient, you'll need to implement a destructor and a finalizer to release it.  Do this only if you expect to have a limited number of instances of the managed class.
Next solution is to generate the pointer at the time of the call, using pin_ptr<>.  That pins the managed object in memory, preventing the garbage collector from moving it.  Not terribly efficient of course.
Finally, you could declare an instance of userData as a local variable in the method that makes the call and copy the one in the managed object into it.  No problem generating pointers to stack variables, they cannot move.  You are now also free to declare the structure in your managed class whichever way you want.  Assuming this struct isn't too large, that's what I would pick.

A: Store a pointer to the data in the managed class, delete it in the destructor.
ref class MyManagedClass
{
    userData *myUserData;

public:
    ~MyManagedClass()
    {
        if (myUserData)
            delete myUserData;
        myUserData = NULL;
    }

    short AddItem(long id, userData* data)
    {
        if (myUserData)
            delete myUserData;
        myUserData = new userData(*data);
    }
}


text:
Q: Can I earn achievements while offline? I will be traveling for 2 days very soon and will not be online. Can I play the single player campaign and earn achievements during this time? (i.e. - do they sync later?)
Or must I always be online when I play X-Com: EU? (that'd be lame!)

A: Yes, it does work. I've been playing XCOM with Steam running in offline mode. I've got achievements, and they got synced to Steam once I got online.

A: I'm not sure if you will automatically get the achievements when you 'reconnect' to steam.
But I do know you can 'save' games and load them later. So if you 'save' your games just before you get a known achievement (i.e. before you finish a specific mission, or research the last item) - then you can just reload those games when you come back, and get that specific achievement.


text:
Q: VBA Scrape table MY GOAL
I'm trying to scrape *5 colums of the table of https://data.goaloong.net/1x2/.
All single row on each single row.
*see screen
MY CURRENT CODE
Set http = New MSXML2.XMLHTTP
Set html = New HTMLDocument

url = "https://data.goaloong.net/1x2/"

http.Open "GET", url, False
http.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
http.send
    While http.readyState <> 4
        DoEvents
    Wend
html.body.innerHTML = http.responseText

With Sheets("table")
    Set HTMLAtab = html.getElementsByTagName("table")(0)

    For Each HTMLArow In HTMLAtab.Rows
        iRow = iRow + 1
        iCol = 0
        For Each HTMLAcel In HTMLArow.Cells
            iCol = iCol + 1
            Cells(iRow, iCol) = HTMLAcel.innerText
        Next HTMLAcel
    Next HTMLArow
End With

UPDATED CODE
    .Cells(i, 1) = html.getElementsByClassName("black-down f-white")(0).innerText
    .Cells(i, 2) = html.getElementsByClassName("en")(0).getAttribute("data-tf")
    .Cells(i, 3) = html.getElementsByClassName("team")(0).innerText
    .Cells(i, 4) = html.getElementsByClassName("td")(2).getElementsByTagName("a")(0).innerText

I tried various methods but I still failing.

A: Is this what you want?
Sub TryThis()
    Dim HTMLDoc As New HTMLDocument
    Dim objTable As Object
    Dim lRow As Long
    Dim lngTable As Long
    Dim lngRow As Long
    Dim lngCol As Long
    Dim ActRw As Long
    Dim objIE As InternetExplorer
    Set objIE = New InternetExplorer
    Dim sht As Worksheet
    Dim LastColumn As Long

    objIE.Navigate "https://data.goaloong.net/1x2/"

    Do Until objIE.ReadyState = 4 And Not objIE.Busy
        DoEvents
    Loop

    Set sht = ThisWorkbook.Worksheets("Sheet1")

    Application.Wait (Now + TimeValue("0:00:01"))
    HTMLDoc.body.innerHTML = objIE.Document.body.innerHTML
    With HTMLDoc.body
        Set objTable = .getElementsByTagName("table")
        For lngTable = 0 To objTable.Length - 1
            For lngRow = 0 To objTable(lngTable).Rows.Length - 1
                For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
                If lngCol = 0 Or lngCol = 1 Or lngCol = 2 Or lngCol = 3 Or lngCol = 11 Or lngCol = 12 Then
                    ThisWorkbook.Sheets("Sheet1").Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
                End If
                Next lngCol
            Next lngRow
            ActRw = ActRw + objTable(lngTable).Rows.Length + 1
        Next lngTable
    End With
    objIE.Quit
End Sub


text:
Q: Pythonic solution to cryptographic agility that avoids violating Liskov's substitution principle I need to write a set of wrappers in python around symmetric ciphers (AES,DES, etc) in various modes of operation that allow for crypto agility. Specifically, the code that is calling the wrappers needs to need no knowledge for what actually is protecting the data so it can be changed out dynamically
Basically the following  should hold ( whether these are methods on an object, separate functions, or something else)
foo = MagicalEncryptor()
foo.ciphertext = foo.encrypt(data)
key = foo.key
bar = MagicalEncryptor()
bar.key = key
data = bar.decrypt(ciphertext)

The problem is that depending on the mode used, the resulting ciphertext will be different. It may be (MODE_CBC,IV,ciphertext) for CBC or (MODE_GCM,IV,ciphertext,mac) for GCM mode.
This very clearly violates the Liskov substitution principle because it makes the argument to decrypt covariant. If the caller is holding an instance of the generic magicalEncryptor interface that happens to be for GCM mode, it cannot hand it an instance of ECB mode.
What's a good pythonic solution to this? (Or is the answer simply not to care?) For what I specifically need to do, it ought to work in both 2.7 and 3.0, but I'm interested in solutions for either.
Also, key must have a short representation as a bitstream (probably 128 or 256 bits max). This is meant to be used in hybrid encryption schemes, where, for example, one might send (RSA_ENC(PublicKey,symetric_key_as_message)||AES(symetric_key_as_message,actual_message).

A: Following Kirk, but peeling off at the last minute, let the polymorphic key take care of choosing the right kind of decryptor:
foo = MagicalEncryptor()
foo.ciphertext = foo.encrypt(data)
key = foo.key

bar = key.decryptor()
data = bar.decrypt(ciphertext)

It can create the appropriate decryptor and pass itself in. Or whatever: the protocol between the key and the creation of decryptors is private.
I might even rearrange things like this:
key = createMagicalKey()

foo = key.encryptor()
ciphertext = foo.encrypt(data)

bar = key.decryptor()
data = bar.decrypt(ciphertext)

And of course then it's only a simple step to:
key = createMagicalKey()

ciphertext = key.encrypt(data)

data = key.decrypt(ciphertext)

A: Method one: strongly type the encrypted data:
class GCMData(object):
    def __init__(self, data): self.data = data

    def __str__(self): return self.data
    __repr__ = __str__

class MagicalGCMEncryptor(object):
    def encrypt(self, data):
        return GCMData(self._encrypt(data))

    def decrypt(self, dataobj):
        if not isinstance(dataobj, GCMData):
            raise ValueError('Only decrypts GCM data')

Method two: invert flow control. Don't make classes that encrypt data. Make data objects that store encrypted data:
class GCMEncryptedData(object):
    def __init__(self, data):
        self.data = [... do something with data]

    def __str__(self): return self.data
    __repr__ = __str__

    def decrypt(self):
        return [... do something with self.data]

A: "This very clearly violates the Liskov substitution principle because it makes the argument to decrypt covariant. If the caller is holding an instance of the generic magicalEncryptor interface that happens to be for GCM mode, it cannot hand it an instance of ECB mode."
Nor should it. Encryption cannot be a mode-independent black-box. Yes, you can swap TDES with AES-256 without changing a lot of higher level logic, but that is not true for changing encryption modes. Think of a mode as a protocol, and an algorithm as an engine. A protocol is complicated, as it requires its own special error reporting, failure mechanism, initialization procedures, associated data, state information, etc. By contrast, swapping the algorithm engine is easy.
For example, when using GCM, you need to take care that you do not encrypt too many messages and that you rotate your keys more quickly in order to maintain the cryptographic strength of your mac. That is true whether it is TDES-GCM or AES-256-GCM. That means you should keep track of how many messages have been encrypted -- even if this is a ballpark estimate such as "rekey every X days when using mode Y" (although you really care about the quantity of data processed.)
You don't have these concerns (at a practical level) with ECB, but you have a whole different set (of much more difficult) concerns regarding information leakage.
CBC mode has its own usage pitfalls, particularly if you are also using CBC-MAC. Depending on the authentication method used, you need to be careful about reporting error messages when the MAC fails -- in some cases, the failure of the MAC should result in destruction of the key (e.g. session keys), but in other cases failure of the MAC should only result in resetting the protocol run (keeping your authentication key sets). Or perhaps you can replay the message -- it depends on how you are building your protocol and what algorithms you are using.
If you are using a tweak encryption mode for stored data, you care about where the data resides on disk, and you will re-use the same tweak key and positional value if you are overwriting a block in place. But you would never reuse a message counter with the same session key if you were encrypting a channel. The encryption modes suitable for encrypting data-in-place have no overlap with the encryption modes suitable for encrypting a channel. They are not swappable with each other.
All of that violates the Liskov substitution principle unless you attempt to implement a generic "security" object that can specialize to every conceivable data protection protocol.
Moreover you would never *ever* use the same key in two different modes or two different algorithm engines.
So why design the code in a such a way that allows an instance of a key object to be specialized to more than one algorithm implementation? Now your security team is going to have go back over your code and ensure that this generality isn't opening any holes for an attacker to get your application to abuse a key by using it in the wrong way. You will need to go back and ensure that when you instantiate your key, you fully specify the mode and algorithm with which it will be used in the key's constructor, which goes back to the issue of key length. Any subsequent attempts to use the key in a with a different algorithm or mode with which it was instantiated should result in an critical error.
But in that case, what does "algorithm agility" mean if users or the application needs to create new keys and/or rekey existing data in place each time the underlying system adopts a new algorithm?


text: Q: Search_tabs.json - Yammer API Yammer search returns results because they are part of the replies and not in an intial message of the conversation. I want to retrive them using REST API and reading that search/search_tabs.json (not documented) can be used to understand why they are included in the search result. Does anyone know what input parameters it accepts ?


text:
Q: How to debug where scrapy-splash freezes? I am using splash + lua script to parse Client-side rendering site.
Site is complicated, I need use a lot of splash:wait() stuff in loops. Example:
      while splash:select('#x-widget-1-label') ~= nil do
        splash:wait(0.1)
      end

And I see, that sometimes I am getting result, but in other times Lua script just "stuck" somewhere in my "wait" blocks. It happens rarely, but it shouldn't be happened at any circumstances.
How to debug in what block my script stucks?


text:
Q: xmllint validation error for ID attribute I'm trying to validate this XML document:
<?xml version="1.0"?>
<CONTACTS>
    <CONTACT CONTACT_NUM = "1">
    <NAME>Alice</NAME>
    </CONTACT>

    <CONTACT CONTACT_NUM = "2">
    <NAME>Bob</NAME>
    </CONTACT>
</CONTACTS>

against the following DTD:
<!ELEMENT CONTACTS ANY>
<!ELEMENT CONTACT (NAME)>
<!ELEMENT NAME (#PCDATA)>
<!ATTLIST CONTACT CONTACT_NUM ID #REQUIRED>

running
xmllint --dtdvalid test.dtd test.xml
produces:
test.xml:3: element CONTACT: validity error : Syntax of value for attribute CONTACT_NUM of CONTACT is not valid
test.xml:7: element CONTACT: validity error : Syntax of value for attribute CONTACT_NUM of CONTACT is not valid
Document test.xml does not validate against test.dtd

Anybody spot what's wrong with the syntax of attribute CONTACT_NUM?

A: The value of an attribute of type ID cannot start with a digit. It must match the Name production in the XML specification, which rules out initial digits.
<CONTACT CONTACT_NUM = "_1"> or <CONTACT CONTACT_NUM = "ID1"> would be OK, for example.
References:

*

*http://www.w3.org/TR/xml/#sec-attribute-types

*http://www.w3.org/TR/xml/#sec-common-syn


text:
Q: create unlimited ul li tag from fetch Array (for list) I'm going to make a unlimited list use li and ul tags from my Array results of PDO(fetched)
my Array  :
Array (
 [0] => Array ( [category_label] => catLevel4 [category_id] => 22 [category_owner] => 21 )
 [1] => Array ( [category_label] => catLevel3 [category_id] => 21 [category_owner] => 20 )
 [2] => Array ( [category_label] => catLevel2 [category_id] => 23 [category_owner] => 8 )
 [3] => Array ( [category_label] => catLevel2 [category_id] => 24 [category_owner] => 8 )
 [4] => Array ( [category_label] => catLevel2 [category_id] => 20 [category_owner] => 6 )
 [5] => Array ( [category_label] => catLevel1 [category_id] => 6 [category_owner] => 0 )
 [6] => Array ( [category_label] => catLevel1 [category_id] => 7 [category_owner] => 0 )
 [7] => Array ( [category_label] => catLevel1 [category_id] => 8 [category_owner] => 0 )
 )

i want :
catLevel1
 catLevel2
  catLevel3
   catLevel4
catLevel1
catLevel1
 catLevel2
 catLevel2

i made a function for convert :
function getCategory($parentCategoryId,$data)
{
    foreach($data as $row){if($row['category_owner']==$parentCategoryId){?>
    <li catId='<?php echo $row['category_id']?>'><?php echo $row['category_label'];?>

            <?php getCategory($row['category_id'],$data) ;?>

    <?php };}
}

echo getCategory(0,$this->categorysList);

this function is very good working for me , But create null

 for all items !
I appreciate your help to build a standard function ;D

A: You get null
 tags, because you hardcode it without any checks, and output in every iteration. Try something like this:
<?php

function getCategory($parentCategoryId, $data) {
    foreach ($data as $row) {
        if ($row['category_owner'] == $parentCategoryId) {
            $str .= '

' . $row['category_label'] . '' . "\n";
            $res = getCategory($row['category_id'], $data);
            if ($res) {
                $str .= '

' . $res . '

    ' . "\n";
            }
            $str .= '

' . "\n";
        }
    }
    return $str;
}

$str = getCategory(0, $data);
echo $str;

?>

So you get output like this:

     catLevel1

             catLevel2

                     catLevel3

                             catLevel4

     catLevel1

     catLevel1

             catLevel2

             catLevel2


text:
Q: symfony2 - Not able to execute webtestcase on home page I am getting 'InvalidArgumentException: The current node list is empty' on the home page of my symfony2 application when I execute the phpunit test on it.  please help.
The path is /student.  I can access /student/1/edit and /student/1/show in my tests, but cannot access just /student.
Here is the test:
  public function testindexAction(){
        $client = static::createClient();
        $client->followRedirects(true);
        $crawler = $client->request("GET","/student");
       // echo $client->getRequest()->getUri();
      // $this->assertRegExp('/\/student$/', $client->getRequest()->getUri());
       $heading = $crawler->filter('h1')->eq(0)->text();
       $this->assertEquals('Student list',$heading);

    }

And the error is :
StudentBundle\Tests\Controller\StudentControllerTest::testindexAction
InvalidArgumentException: The current node list is empty.
php app/console router:debug -e test | grep /student
 student                         ANY         ANY    ANY  /student/
 student_show                    ANY         ANY    ANY  /student/{id}/show
 student_new                     ANY         ANY    ANY  /student/new
 student_create                  POST        ANY    ANY  /student/create
 student_edit                    ANY         ANY    ANY  /student/{id}/edit
 student_update                  POST|PUT    ANY    ANY  /student/{id}/update
 student_delete                  POST|DELETE ANY    ANY  /student/{id}/delete

A: Is there any redirects on homepage?
try to debug by
var_dump($client->getResponse()->getContent());


text:
Q: Numpy and other library dependencies for Spark application on Kubernetes I am running pyspark application, v2.4.0, on Kubernetes, my spark application depends on numpy and tensorflow modules, please suggest the way to add these dependencies to Spark executors.
I have checked the documentation, we can include the remote dependencies using --py-files, --jars etc. but nothing mentioned about library dependencies.

A: Found the way to add the library dependencies to Spark applications on K8S, thought of sharing it here.
Mention the required dependencies installation commands in Dockerfile and rebuild the spark image, when we submit the spark job, new container will be instantiated with the dependencies as well.
Dokerfile (/{spark_folder_path}/resource-managers/kubernetes/docker/src/main/dockerfiles/spark/bindings/python/Dockerfile) contents:
RUN apk add --no-cache python && \
    apk add --no-cache python3 && \
    python -m ensurepip && \
    python3 -m ensurepip && \
    # We remove ensurepip since it adds no functionality since pip is
    # installed on the image and it just takes up 1.6MB on the image
    rm -r /usr/lib/python*/ensurepip && \
    pip install --upgrade pip setuptools && \
    # You may install with python3 packages by using pip3.6
    pip install numpy && \
    # Removed the .cache to save space
    rm -r /root/.cache


text:
Q: Jquery script works only after opening new window in IE The script below queries a PHP service that returns a JSON response. Buttons are created for each returned record, allowing the user to delete that record from the database. A link is also created below to refresh the data.
This all works fine in IE, Chrome, Safari...IE (tried 8 & 9), however, is having a strange issue.
When the page loads, I am able to refresh the data by clicking the 'refresh' link. After this, clicking has no effect UNLESS I open the same page in a different IE window, click the link in the new window, and return to the original window. The 'refresh' link then works on the new window ONE time. It then turns into a vicous cycle.
Your help is appreciated!
function getNew(){
    $('#new').remove();
    $.getJSON('service.php', function(data) {
        var items = [];

        items.push('
EmplId	ExternalID	Name
');

        $.each(data, function(key, val) {

            var indiv = val.toString().split(",");
            items.push('
');
            var id = indiv[0];

            $.each(indiv, function(index, value) {
                items.push('' + value + '	');
            });

            items.push('Update	');

        });

        items.push('
Refresh
');

        $('
', {
            'id': 'new',
            html: items.join('')
        }).appendTo('body');
    });
}

function update (emplID){
    $.ajax({
        url: "service.php?emplID="+emplID,
        context: document.body,
        success: function(){
            $('#new').remove();
            getNew();
        }
    });
}

I have tried using .live and I get the same results.
$(".refreshButton").live("click" , function() {
    getNew();
    $.ajax({
        url:     "Service.php?emplID=",
        context: document.body,
        success: function(){
            $('#new').remove();
            getNew(); }
    });
});

I have disabled the cache still to no avail. The ONLY way to make the link work is to open the same page in a separate window, click the link, and return to the original window. Is there any solution to this?
$(".refreshButton").live( "click" , function() {
    getNewStudents();
    $.ajax({
        url: "studentService.php?emplID=",
        cache: false,
        context: document.body,
        success: function(){

            $('#newStudents').remove();

            getNewStudents();
        }
    });
});

Thanks for your suggestions. I fixed the tr, but it seems that the solution was to use
 $.ajaxSetup({ cache: false });

It seems all versions of IE treat ajax calls as normal web requests (cacheable), whereas other browsers consider ajax calls as non-cacheable.
Learned something new today, thanks guys!

A: Maybe it's because of cache, have you tried to clear your cache and try again? this may help http://kb.iu.edu/data/ahic.html#ie8

A: Perhaps IE is choking on the malformed HTML that getNew is generating; note that in your .each loop, you are not closing the tr element.  Also, if you're getting a JavaScript error, JS execution may stop, so make sure your browser isn't configured such that it ignores JS errors.  Check the error console.


text:
Q: How to make camera work like scanner in .Net I have created a webapplication. Basically it gets the barcode string from an uploaded Image. Now I am planning of making it more fancy.
Instead uploading an image (either by iphone /ipad to capture the image or upload from library). I just want to scan the image from camera and get the barcode string to my backend database which will further load the pop up with invoice details.
Could someone share some ideas. I have researched all over the google and found that it can be done with own libraries. But I am not quite sure how to do that. Any tutorials or links that actually scans the barcode not just take a picture, upload and decode would be appreciated.


text:
Q: Query to check latest modifications in entire database (fields and structure) In SQL Server, is there a query that shows me the latest modifications in both data (every table) and tables structures?
I need to check if in a database happens some modifications in recent days (data and structure).
Thanks a lot.

A: Unfortunetly, I don't know relible way to track data and structure changes out of the box without additional efforts (like creating DDL triggers, CDC, temporal tables).
With certain assumptions, you can query to the sys.objects table by modify_date field (https://learn.microsoft.com/ru-ru/sql/relational-databases/system-catalog-views/sys-objects-transact-sql?view=sql-server-ver16; see @Charlieface comment) to track structure changes. But keep in mind modify_date also changes when a clustered index created or rebuilt. Is it the changes you would like to consider along the others?
To track data changes, you can check index usage statistics in the sys.dm_db_index_usage_stats table (https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-usage-stats-transact-sql?view=sql-server-ver15). Each data change (insert / update / delete) will update the usage statistics of particular table, but there also some limitations exists (e.g., these statistics are reset every time server is started).
Thus, you can check the changes for some date with the next query, but you should be aware of the existsing limitations:
DECLARE @Date date = DATEADD(DAY, -1, GETDATE())

IF (
    EXISTS (SELECT * FROM sys.objects AS o WHERE o.is_ms_shipped = 0 AND o.modify_date > @Date)
    OR EXISTS (SELECT * FROM sys.dm_db_index_usage_stats AS s JOIN sys.objects AS o ON o.object_id = s.object_id AND o.is_ms_shipped = 0 WHERE s.last_user_update > @Date)
)
BEGIN
    PRINT 'Changed'
END
ELSE
BEGIN
    PRINT 'No changes'
END

It is worth noting that this query doesn't respect changes in system tables (sys.objects.is_ms_shipped = 0) and changes made by internaly generated queries (the sys.dm_db_index_usage_stats.last_system_update field is omitted).


text:
Q: Is there some built-in feature to repel trolls? The (long) story
The question is below, you don't have to read "the story" to get the question.
The more popular SE sites are the more trolls they attract. I cannot (and others too) ask civilized question without request for fairy tales, explaining half of my life, and so on.
Simplified example:
My question:

what is the hex code of html color 'red'?

So called "answers":

why would you like to use red?
red is not good, remember you are doing this on your own risk!
what browser do you use?
dude, don't use hex codes!

and so on and on and on.
From time to time I also fall for honest explanation, because I am fooled by Jeff Atwood posts, how SE teaches us all to ask proper questions.
So keeping this example, let's say I updated my question about why I would like to use red color after all.
10 minutes later, I will get posts from some trolls about my "rant" of colors, and what hater I am.
On the other hand if I add remark next to my question, with sincere begging to stick to the question I will get downvoted (guessed reason: how dare I remind somebody how to answer the question). The worst, after getting suck by trolls into discussion my post was closed as non-constructive and I was toasted -- why it is my fault that I've got not constructive questions for question?
If you need particular example, take a look (watch the dates and times):
How to disable tmpfs on /media in openSUSE?
Ah, that hunger for a good tale... (honestly speaking I suspected that at the time of writing the question)
I am sick and tired of questions for questions just to feed somebody curiosity. Maybe I am naive, but for me what counts is high signal to noise ratio, this means -- answer to question if you know answer, in any other case, move on. If you really have to make the remark...
do this:

you can do this by ... but I would recommend rather ...

don't do this:

why would you like to do this?

Why? Because lifetime is limited, so it is better to show the path and show the alternate way, instead of prolonging the discussion -- because it shortens the life!
Question
Yes, there is question -- is there any tool which would repel the trolls? Remove their questions for questions? General reminder to keep signal to noise ratio high (per question)?
Anything legal/valid which would help sticking to the question and not discussing "meaning of life". I mean it: any, even mini, feature would be helpful.
I think I kill myself, if I read "why would you like to repel trolls"?

A: When you are asking about something that is far from the standard way of achieving a certain goal or is about doing something that is unusual, it is fair to expect people to question it.
Demanding that people stay "on-topic", when they don't understand why one is requesting things that are out of the norm instead of adding the relevant information is simply not constructive.
I don't really know what "tool" you could use apart from flagging comments and answers as not relevant (though the moderators may disagree).
The best way to "repel" trolls is to give a full description of your issue, including motivation for when you are doing things very differently than expected.

A: Before outlining the answers, let's look at your question first:

What is the hex code of html color 'red'?

*

*You are asking for a HEX code, so you should understand how HEX works.

*You are asking for a HTML color, so you should understand what HTML colors work.

*If you would know that, you wouldn't be asking such question.
As a logical consequence, the answers you provided in you example don't represent anything because the problem lies with the question, not with the answers...

So keeping this example, let's say I updated my question about why I would like to use red color after all.

Skipping the fact that your homework was not done and that the question is rherotical, defending a detail is not really the way to go in your question. Consider not mentioning red at all.
On your particular example, you are indirectly mentioning in your question that you are putting files in tmpfs, so that is a perfect valid query for more informaiton, and is not trolling at all.

I can easily turn your quote around

Why? Because lifetime is limited, so if your question is rhetorical or requires more explanation then you better hurry to provide it, otherwise you would most likely not get your answers.

Yes, there is question -- is there any tool which would repel the trolls?

Why are they trolls? You didn't mention that.

Remove their questions for questions?

What defines a "question for question", this is rather vague.

General reminder to keep signal to noise ratio high (per question)? Anything legal/valid which would help sticking to the question and not discussing "meaning of life". I mean it: any, even mini, feature would be helpful.

Even more text? They barely read it now anyway, as you mentioned yourself.

I think I kill myself, if I read "why would you like to repel trolls"?

Why would you like to repel trolls? You don't, they are there to help you write better questions.

A: Answer to your question
Flag the comment. Type "I think its a troll" in the flag reason. Done.
Answer to your situation
That's not really trolling.

you can do this by ... but I would recommend rather ...

A recommendation for an alternate method is only possible when the other party knows exactly what you want to do. So, obviously, the first question that one would ask is

why would you like to do this?

(see the "big picture" section below for more on this)
Breakup of your HTML hex example
Here's a breakup of the simplified examples you gave. First thing: these comments sound stupid, but so does the example question. So we can't use "obviously it's trolling" over here because you purposely simplified them to make a general example. So I'm focussing on the type of comment, not the content:

*

*why would you like to use red?

This is actually quite necessary, as shown above. Sometimes, you're just going on the wrong path.

*

*red is not good, remember you are doing this on your own risk!

Looks troll-y, but not really. There are lots of coding bad-practices which this person wants to warn you of.

*

*what browser do you use?

OK, slightly irrelevant to the question. In this case, it's trolling, but remember that the question itself is oversimplified.

*

*dude, don't use hex codes!

Again, bad coding practices &c.
I can't really show you the difference between trolling and not trolling unless you give nonsimplified, real, examples. You gave only one:
The SUSE example
I don't use unix, so I don't know about the /media/ directory. If it's something you're supposed to put stuff in, then that comment is trolling. Flag it.
If it's some exotic system folder thingythingy which you're not supposed to touch, then its a valid problem. He may be able to find an alternative thing for you to do.
Edit: According to @DanielFischer, the /media directory is not for everyday use. So that comment is not trolling, just a "big-picture" comment (see next section).
Always give the big picture
Remember, a solution to your big-picture problem is better than a solution to a small hurdle in your problem. It's always nice to provide detailed about the big-picture problem so that others can see what you really need. As a slightly crappy, mundane analogy: You need money. But you don't really need money, just the services that money gets you (food, etc). Money is just a hurdle in your path to getting those services. Same here. Your problem is just a hurdle in a bigger problem(usually), and it always helps to know what the big picture is. These guys just want to know what the big picture is.
Conclusion
I think you're getting a bit worked up about people who may be genuinely trying to help. Many times, more details are necessary for solving the problem. Some real world examples would help me analyse this better.


text: Q: Unable to see data from repeating rows I am using SharePoint Online. I have a form library that uses an InfoPath form which includes a repeating section.  Previously, in SharePoint 2010, I was able to view all data entered into the repeating section in the SharePoint view. Now, after I copied the library from 2010 into SharePoint Online, only the first/top row is displayed in the view. The rest of the data entered into subsequent rows in the repeating section are only able to be seen by opening the individual form.   And of course since it is not showing in the view, it also does not get exported into Excel (which also worked in 2010).  I need to be able to export all data including all repeating rows. How can i do this in SharePoint Online?


text:
Q: How to fix InputMismatchException So i have this code:
protected void giveNr(Scanner sc) {
    //variable to keep the input
    int input = 0;
    do {
      System.out.println("Please give a number between: " + MIN + " and " + MAX);
      //get the input
      input = sc.nextInt();
    } while(input < MIN || input > MAX);
}

If the human inputs sth thats not an integer, say a letter or a string, the program crashes and gives the error, InputMismatchException. How can I fix it, so that when a wrong type of input is entered, the human is asked again for the input(and the program does not crash?)

A: You could catch the InputMismatchException, print an error message telling the user what went wrong, and go around the loop again:
int input = 0;
do {
    System.out.println("Please give a number between: " + MIN + " and " + MAX);
    try {
        input = sc.nextInt();
    }
    catch (InputMismatchException e) {
        System.out.println("That was not a number.  Please try again.");
        input = MIN - 1; // guarantee we go around the loop again
    }
while (input < MIN || input > MAX)


text:
Q: Can't update HTML element with Jquery Working on a map application and this is driving me nuts. This works:
var myBounds = map.getBounds();
$("#bounds").html("My bounds are: " + myBounds);

But this just shows blank:
var myBounds = map.getBounds();
$("#bounds").html(myBounds);

No console errors in Chrome. It looks like Jquery doesn't like the return value of map.getBounds(), which in this case are Google map boundaries like ((34.71679866336405, -9.207592500000032), (38.42994070565381, -0.06696750000003249))
What is wrong here?
Update:
Curiously, this works OK too:
var myBounds2 = '((34.71679866336405, -9.207592500000032), (38.42994070565381, -0.06696750000003249))';
$("#bounds").html(myBounds2);

A: The return value of getBounds isn't a string, it's a LatLngBounds object. Apparently passing the object directly into html doesn't work — which is fair enough, html doesn't document that it accepts objects, just strings. I'm a bit surprised it's not ending up calling toString on it, but apparently not.
Since converting it to string works (that's what you're doing when you append it to a string), you can do that by just passing into the String function:
var myBounds = map.getBounds();
$("#bounds").html(String(myBounds));
// ---------------^^^^^^^--------^


text:
Q: Avoid duplicate row in Hibernate Criteria I have an object A in my dataBase that contains a collection C with 2rows.
when i use criteria Hibernate to get my object , i got the some object for each item on collection C . I used :
  Criteria criteria = session.createCriteria(SillonBD.class);
  criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

And
// not work because that retuen only id
 criteria.setProjection(Projections.distinct(Projections.property("id")))

;
But that's not work for me hibernate does not return distinct results for my object  with outer join fetching enabled for a collection

A: Try:
criteria.setProjection(Projections.distinct(Projections.property("id")));


text:
Q: My WEBrick server is nerver deleting PID file for a specifc project, what do i do? I searched a lot already and I didn't find anything useful.
Could someone help me.
When WEBrick server is stopped It should delete the server.pid file from tmp folder, but It is never being erased.
I wonder why it is happing, because it just happens with one and only project, the others is ok, if i create a new one it is ok too. What configuration on that project could cause that problem, any clue?
Thank you for the help.

A: I've found the solution...
I had a custom jasper-rails gem into my ruby gems directory with version 0.0.2, when I created this problem project and run bundle install it installed jasper-rails 1.0.3, because I did'nt set the version on Gemfile.
For some reason the jasper-rails gem was causing the problem.
My fix:
Edited Gemfile = gem 'jasper-rails' to gem 'jasper-rails', '0.0.2'
Uninstalled the newer version of jasper-rails: gem uninstall jasper-rails -v 1.0.3


text:
Q: Access .dll library MODULE function in Excel (VBA) I have a library called PIT_math_tools (written in vb.net) containing math functions which is split up into different modules.
In this case, the function I want to access is located in a Module called geometry_ellipsen_module:
Namespace geometry_ellipsen
    Public Module geometry_ellipsen_module
    ...
         Public Function calc_distanz_ellipse_kreis(...) As Double

Now I want to access the Function calc_distanz_ellipse_kreis() in VBA.
I used the following declare statement to accomplish this:
Private Declare PtrSafe Function calc_distanz_ellipse_kreis Lib "C:\Users\path...\PIT_math_tools.dll" (...) As Double

So far, everything looks fine.
When trying to call that function, however, I get runtime error '453'
"DLL-Entry Point calc_distanz_ellipse_kreis in 'PathToLibrary' not found."
When using the function in other .Net code, it could be found either by using the prefix
PIT_math_tools.geometry_ellipsen.geometry_ellipsen_module.calc_distanz_ellipse_kreis()

or an import statement identical to the prefix above.
Based on that, I tried extending the Function name in the Declare Statement by the same prefix:
Private Declare PtrSafe Function geometry_ellipsen.geometry_ellipsen_module.calc_distanz_ellipse_kreis Lib ...

However, this results in a compiler error "Expected: Lib".
How do I get the vba code to find the function inside the library module?
Thanks in advance.

A: The VBA syntax...
Private Declare Function SomeMethod() Lib "Some.dll"

... is used to prototype standard Win32 DLLs, e.g. Win32 API. Which .NET DLLs (aka "Assemblies") are not.
What you need to do in VB.NET is to make that assembly COM-visible. VB.NET creates a typelib (*.tlb) for the assembly.
In VBA you then add a COM reference (point to that typelib) to your project like you would do with other COM DLLs (ADODB, MSXML etc.). And then you do your standard
Dim myObject As Namespace.ClassName
Set myObject = New Namespace.ClassName
With myObject
   .ThisProperty = 123
   Dim lRet As Long
   lRet = .ThisMethod("abc")
End With


text:
Q: Why is my custom Tailwind CSS utility not applying to React elements? I'm trying to create multiple themes by following this: https://github.com/adamwathan/theming-tailwind-demo
My code:
// tailwind.config.js
module.exports = {
  purge: [],
  theme: {
    backgroundColor: {
      primary: "var(--color-bg-primary)",
    },
    textColor: {
      primary: "var(--color-text-primary)",
    },
    extend: {},
  },
  variants: {},
  plugins: [],
};

// tailwind.css
@tailwind base;

@tailwind components;

@tailwind utilities;

.theme-TCD {
  --color-bg-primary: #411218;

  --color-text-primary: #e8982e;
}

// My HTML

    <Banner />

I have tried "color-bg-primary" and "backgroundColor-primary" in place of "bg-primary" but that does not work.

A: Are you using CRA(Create React App)? If so, you'll have to do some setup.
First, you'll need to install some dependencies
yarn add -D tailwindcss autoprefixer postcss-cli

or
npm install --save-dev tailwindcss autoprefixer postcss-cli

After you'll need to create a postcss.config.js
module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
  ]
}

Lastly, you'll need to add some scripts to compile the styles
{
  //...
  "scripts": {
    //... place these after the four scripts created by CRA
    "build:styles": "postcss src/tailwind.css -o src/styles.css",
    "prebuild": "yarn build:styles",
    "prestart": "yarn build:styles"
  }
}

or
{
  //...
  "scripts": {
    //... place these after the four scripts created by CRA
    "build:styles": "postcss src/tailwind.css -o src/styles.css",
    "prebuild": "npm run build:styles",
    "prestart": "npm run build:styles"
  }
}

Source: Setting up Tailwind With create-react-app


text:
Q: Unable to open a PDF uploaded to SharePoint using the MS Graph API(Python) I am trying to upload a PDF to SharePoint using the MS Graph API and I am able to upload a PDF, but the PDF can't be read/previewed.
I've tried converting the PDF file to Base64 to allow it to be uploaded since it needs to be a binary stream but it doesn't seem to work.
with open(pdf_filename,"rb") as pdf_file:
    pdf_base64 = base64.b64encode(pdf_file.read())

Here is my PUT statement:
response_upload = requests.put(f"https://graph.microsoft.com/v1.0/sites/{site_id}/drive/root:/Document Folder/PDF_Name.pdf:/content", data=pdf_base64, headers=headers)

Here are my headers:
headers = {'Authorization': 'Bearer {}'.format(token), "Content-Type":"application/pdf"}

Any help or guidance is appreciated.
Thanks

A: Apparently you don't need to add a step to convert to Base64 to upload a pdf to SharePoint.
with open(pdf_filename,"rb") as pdf_file:

and then in the API call updating the data field to data=pdf_file.read() to read the file:
response_upload = requests.put(f"https://graph.microsoft.com/v1.0/sites/{site_id}/drive/root:/Document Folder/PDF_Name.pdf:/content", data=pdf_file.read(), headers=headers)


text:
Q: SQL Server default date time stamp? I have a field that when something is inserted I want it to get the current Date & Time and insert this into the database. Is there a way to get the date & time, and set it as the default value?
Currently the default value is: (getdate()) Which sets only the date. How do I also set the time?

A: One easy way is to give the field a default constraint:
create table YourTable
    (
    ... other columns ...
    CreateDt datetime default getdate(),
    ... other columns ...
    )

A disadvantage of this method is that you can overwrite the value by specifying it in an insert clause.

A: Personally I would like to use GETUTCDATE() instead GETDATE() to avoid confusions.

A: GETDATE() is a date and time in SQL Server.
Run SELECT GETDATE() to verify this.
What is the datatype of your field?  If it's DATE then it will not hold time values as well.

A: SYSDATETIME() will get the current date and time.
Make sure the data type of the column is datetime, and not just date or it won't be able to hold a datetime.

A: Most SQL implementations (engines) do have CURRENT_TIMESTAMP function.


text:
Q: ResourceResolverFactory and SlingRepository null in Service class I have a Service class as below which I deployed using Maven and is Active on Sling Web Console. When I am accessing the method getSearchAssetNames() from this bundle it is getting called as per the AEM 6.0 logs on Authoring instance.
But, implicit objects such as repository, resource resolver factory, query builder are all getting null pointer exceptions through how I have derived them using @Reference annotation.
Here is the code for the class. I have tried removing activate, deactivate methods, adding start/stop methods, everything, but still this does not work.
Error logs show:

*01.07.2015 12:05:24.014 INFO [127.0.0.1 [1435732523998] GET /content/test/en/headerfooter/jcr:content/footerpar/testassetfinder..html HTTP/1.1] com.test.example.assetfinder.AssetFinderImpl Query Builder: null
  01.07.2015 12:05:24.014 INFO [127.0.0.1 [1435732523998] GET /content/test/en/fordheaderfooter/jcr:content/footerpar/testassetfinder..html HTTP/1.1] com.test.example.assetfinder.AssetFinderImpl JCR Repository: null
  Caused by: java.lang.NullPointerException: null
      at com.test.example.assetfinder.AssetFinderImpl.getSearchAssetNames(AssetFinderImpl.java:61)*

Can anyone please help me regarding how to solve this ?
            package com.test.example.assetfinder;

            import java.util.ArrayList;
            import java.util.HashMap;
            import java.util.List;
            import java.util.Map;

            import javax.jcr.RepositoryException;
            import javax.jcr.Session;

            import org.apache.felix.scr.annotations.Activate;
            import org.apache.felix.scr.annotations.Component;
            import org.apache.felix.scr.annotations.Deactivate;
            import org.apache.felix.scr.annotations.Reference;
            import org.apache.felix.scr.annotations.Service;
            import org.apache.sling.jcr.api.SlingRepository;
            import org.osgi.service.component.ComponentContext;
            import org.slf4j.Logger;
            import org.slf4j.LoggerFactory;

            import com.day.cq.search.PredicateGroup;
            import com.day.cq.search.Query;
            import com.day.cq.search.QueryBuilder;
            import com.day.cq.search.result.Hit;
            import com.day.cq.search.result.SearchResult;

            /**
             * Example Asset Finder in AEM DAM.
             */
            @Service(value=com.test.example.assetfinder.AssetFinderService.class)
            @Component
            public class AssetFinderImpl implements AssetFinderService {

                @Reference
                private QueryBuilder builder;

                @Reference
                private ResourceResolverFactory resolverFactory;

                @Reference
                private SlingRepository repository;

                private static final Logger LOGGER = LoggerFactory.getLogger(AssetFinderImpl.class);

                @Activate
                protected void activate(final ComponentContext pCtx) throws RepositoryException {
                }
                @Deactivate
                protected void deactivate(ComponentContext pCtx) throws RepositoryException {
                }

                public List<String> getSearchAssetNames() {
                    List<String> assetList = new ArrayList<String>();
                    Session session = null;
                    try {
                        LOGGER.info("Query Builder: "  +builder);
                        LOGGER.info("Resolver Factory: "  +resolverFactory);
                        LOGGER.info("JCR Repository: " +repository);

                        session = repository.loginAdministrative(null);
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("path",         "/content/dam");
                        map.put("type",         "dam:Asset");
                        map.put("nodename",     "*example*.*");
                        map.put("orderby.sort", "asc");
                        Query query = builder.createQuery(PredicateGroup.create(map), session);
                        SearchResult result = query.getResult();

                        // Iterating over the results
                        for (Hit hit : result.getHits()) {
                            assetList.add(hit.getTitle());
                        }
                    } catch(RepositoryException re) {
                        re.printStackTrace();
                    } finally {
                        if(null != session) {
                            session.logout();
                        }
                    }
                    return assetList;
                }
            }

A: The key thing here is that when you use @Reference, that injects a service reference into an instance of your class managed by the Service Component Runtime (SCR) and only into that managed instance. If you create a new (i.e. different) instance of your class, then it won't have the field injected. Which is why you need to use the sling.getService() method to get the managed instance.
A best practice is to avoid having the implementation class be in an exported package. That way, you can't reference the implementation class directly from a JSP; you can only reference the service interface so you could never create a new instance from the JSP and thus not hit the problem of using a non-managed instance of the class.
Regarding @Activate and @Deactivate, you would need those only if your activate/deactivate methods did anything. In this case, they don't (at least in your code example). You can also get away from using them if you name your methods activate and deactivate, but personally I would always recommend using them just to be on the safe side, e.g. if you mistype the name as activte or something like that.


text:
Q: Uniqueness of Riemann surface Note: I'm learning complex analysis from Gamelin and Riemann surfaces appear there in the first chapter as prerequisites. I have no background in Topology/Complex Analysis so please don't use that while answering this.
I don't understand what is actually a Riemann surface (because it's definition involves terms which I don't know), but based on intuitive explanation given in Gamelin I get the following notion of a Riemann surface (I don't know how much  is this correct and this may be very wrong):

Let $f(z)$ be a multivalued complex function.
Let $S \in \mathbb{C}$ be the set of points such that for any "sufficiently" small loop $\gamma$ near a point $P \in S$ it's not possible to define $f$ continiously on $\gamma$.
Now we make a bunch of slits $s_1, \cdots, s_k$ (ray/line segment) in $\mathbb{C}$ such that each point $P \in S$ is adjacent to atleast one slit. Now define $f$ continuously on $T:= \mathbb{C} - \{s_1 \cup s_2 \cup \cdots s_k \}$ as $f_1$. Now consider all such functions $f_1, \cdots, f_n$ and glue the slitted complex plane's ($T$) together to form a surface $S$ such that the value of $f$ on $S$ is continuous.
This $S$ is the required Riemann surface

It's not clear to me why the surface $S$ obtained should be independ of in which way you make the slits or how you define $f$ over the slitted complex plane and glue them up.
Consider $f(z) = \sqrt{z(1-z)}$. Here $S = \{0, 1 \}$. Now I think there're two ways to make a slit: either slit $[0,1]$ or slit both $(-\infty, 0]$ and $[1, \infty)$. Doesn't which way you make the slit changes the resulting Riemann surface ?

Also suppose you make the only slit $[0,1]$. Now consider two small circles $\gamma_0, \gamma_1$ centered at $0$ and $1$ respectively. When you approach the slit $[0,1]$ through a variable point $p \in \gamma_0$ in the counterclockwise direction, the sign of $Re(p)$ either is postive or negative. Similar for $\gamma_2$, so total four ways (I guess) you can define $f$ continuously on $\mathbb{C}-[0,1]$ - i.e w. Among them, why it's not possible to define $f$ on $\mathbb{C} - [0,1]$ so that it's like the either of the cases in the right side ?


text:
Q: deducting conservation of linear momentum in material media Good evening,
I'm  trying to deduce the continuity equation for the fields and particles momentum , something like
$\nabla \cdot (-\Pi) + \frac{\partial \vec{g}}{\partial t}=-f$
I should get that $\vec{g}=\frac{\vec{E} \times \vec{H}}{4\pi c}$, but I'm getting instead $\vec{g}=\frac{\vec{D} \times \vec{B}}{4\pi c}$
I have checked several times but I cannot find any mistake on my procedures (basically, expressing densities of charge/current in terms of the fields using Maxwell equations and replacing them in the force per unit volume formula (Lorentz force per unit volume)).
Are these two cross products equal somehow?

A: No, they are not equal. You have apparently stumbled upon the Abraham-Minkowski debate, which has raged for a century (although the complexion has changed a bit in the last decade or so).  Enjoy!


text:
Q: Laravel 5 - SoftDelete not working I've been searching a lot in the web and StackOverflow itself, however I can't find a solution to the problem.
Soft deleting simply refuses to work. The database has the deleted_at field. User model has everything needed to supposedly work, however data is still hard deleted when I call the Delete() method. I don't know what I'm doing wrong.
Laravel Version: 5.3.31
destroy method
public function destroy($id)
{
    //$this->authorize('delete', User::class);
    $user = User::find($id);

    if (empty($user)) {
        Flash::error('User not found');

        return redirect(route('users.index'));
    }

    $user->Delete();

    Flash::success('User deleted successfully.');

    return redirect(route('users.index'));
}

user model
namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;

    public $table = 'users';

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $dates = ['deleted_at'];

    public $fillable = [
        'name',
        'email',
        'password',
        'role',
        'remember_token'
    ];

    protected $casts = [
        'id' => 'integer',
        'name' => 'string',
        'email' => 'string',
        'password' => 'string',
        'role' => 'string',
        'remember_token' => 'string'
    ];

    public static $rules = [
      'name' => 'required|max:255',
    ];
}

I appreciate anything that can help me to solve this.
Thanks in advance.


text:
Q: Renci.SshNet 2016.0.0.0 throwing file not found System.Security.Cryptography.Algorithms, Version=4.0.0.0 I am trying to use the latest Renci.SshNet 2016.0.0.0 in one of my C# projects with the intent start autosys job from C#. When I try to create an object of SshClient, I am getting the below exception:
Could not load file or assembly 'System.Security.Cryptography.Algorithms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
I downloaded System.Security.Cryptography.Algorithms 4.0.0-beta-23516 and referenced it in the project, but still getting the same exception. Here is the line where the exception is thrown.
SshClient client = new SshClient(server, userName, password);

Console application created in Visual Studio 2013 targeting .Net Framework 4.6.
Looking forward to suggestions.


text:
Q: Amazon SQS long polling returning 0 messages when messages are in the Queue Amazon SQS long polling is returning 0 messages when there are still messages in my queue. I've been able to reproduce this effect multiple times.
I'm aware that it's possible for SQS long polling to yield fewer messages than the max requested even if there are more messages on the queue.
I'm also aware that short polling can yield zero messages even when there are more than zero messages on the queue.
But I did not know that long polling could yield zero messages when there are more than zero messages on the queue. And from what I can tell after reading the docs, this isn't supposed to happen.
Question:
Is it possible for SQS long polling to return 0 messages even when there are messages on the queue? If so, are their specific conditions that make this likely to occur? If not, has anyone else experienced this behavior?

A: Check that the group ID's are unique.
AFAIK, if one message in a group is in-flight, then the entire group is not visible.

A: As far as I know this could be related to any of these queue attributes:

*

*Visibility timeout

*Delay queues
Please rewiew your queue configuration. Bear in mind that it's possible to set specific visibility timeout on a message level, which could not match the value set for the queue.
Hope this may help.
Best regards,


text:
Q: java.lang.IncompatibleClassChangeError inside FirebaseInitProvider.onCreate when starting app with minifyEnabled true Tested Environment / Dependencies

*

*Android Studio: Android Studio Arctic Fox Beta 2 and Bumblebee Canary 1

*AGP: 7.1.0-alpha01

*Firebase Analytics: com.google.firebase:firebase-analytics-ktx:19.0.0

*Firebase Crashlytics: com.google.firebase:firebase-crashlytics-ktx:18.0.0

*minifyEnabled: true

*Proguard Config specifically for Firebase: None

What's happening
When I build my app with minifyEnabled = true and try to start the app, app crashes right after it launches with the following crash log:
2021-05-29 22:30:37.652 16541-16541/com.my.app.package.name E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.my.app.package.name, PID: 16541
    java.lang.IncompatibleClassChangeError: Class j$.util.concurrent.i implements non-interface class e.a (declaration of 'j$.util.concurrent.i' appears in /data/app/~~xxxx==/com.my.app.package.name--xxxxxx==/base.apk!classes2.dex)
        at com.google.firebase.components.x.<init>(:37)
        at com.google.firebase.components.x.b(:44)
        at com.google.firebase.components.n.t(:219)
        at com.google.firebase.components.n.j(:138)
        at com.google.firebase.components.n.<init>(:91)
        at com.google.firebase.components.n.<init>(:45)
        at com.google.firebase.components.n$b.e(:360)
        at com.google.firebase.c.<init>(:427)
        at com.google.firebase.c.p(:299)
        at com.google.firebase.c.o(:267)
        at com.google.firebase.c.n(:252)
        at com.google.firebase.provider.FirebaseInitProvider.onCreate(:51)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:2388)
        at android.content.ContentProvider.attachInfo(ContentProvider.java:2358)
        at com.google.firebase.provider.FirebaseInitProvider.attachInfo(:45)
        at android.app.ActivityThread.installProvider(ActivityThread.java:7242)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:6783)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6700)
        at android.app.ActivityThread.access$1300(ActivityThread.java:237)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7660)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Notes

*

*Configuring minifyEnabled = false fixes the issue and app can start as expected.

*Maybe it is related or dup of: java.lang.IncompatibleClassChangeError caused by R8 (AGP 7.0.0-beta02).

A: We had similar crashes in release since AGP 7.0.0-alpha12. The crashes are gone after updating the desugaring library to version 1.1.5.
dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

More info: https://issuetracker.google.com/issues/189244205


text:
Q: How do I be good? In the ad wherein Steve Martin promotes his master class I note that, at some point, he asks this:
How do  I be good?
Is that usage standard in the English-speaking world? Or is it just some kind of private joke of his? Is this phrase interchangeable with
How do I become good?
Thanks in advance for your attention.

A: "Be good" often has the special meaning of "behave well/properly".
In that sense, it's hard to know how to ask the question Martin is asking, because "How am I good?" would not have that meaning. Probably most people would ask "How will I be good?" or "How should I be good?"But I don't find "How do you/I be good?" strange in that context.
However, looking in various online corpora, I find hardly any examples of it.


text:
Q: Is there a way in Python/Pandas to use a generic variable name with a wildcard to select all similar columns? In Stata, if I typed Week_*, it would select all columns Week_1, Week_2, etc. Is there a similar way to do this in Python/Pandas?
Code example, including last line for what I want to do.
# One-hot Encode Week: Create variables Week_1, Week_2, ... etc.
dt_temp0 = dt_temp0.join(pd.get_dummies(dt_temp0['Week'],prefix='Week'))

# Features to Use
feat_cols = ['lag2_tfk_total','lag3_tfk_total','lag2_Trips_pp','lag3_Trips_pp',
             'ClinicID_fac', 'Week_*']

x_train = dt_temp1.loc[dt_temp1['train'] == 1,feat_cols]

A: You could select your week columns with a list comprehension:
week_cols = [col for col in df_temp1.columns if col.startswith('Week_')]
feat_cols = ['lag2_tfk_total','lag3_tfk_total','lag2_Trips_pp','lag3_Trips_pp',
             'ClinicID_fac', *week_cols]

You can combine these into one line if you want.

A: I actually found another way to do this, as well... using filter(). Then you just have to concatenate the string arrays together. Thanks for all the help!
week_cols = dt_temp0.filter(regex = "Week_" ).columns.tolist()
feat_cols = ['ClinicID_fac','lag2_tfk_total','lag3_tfk_total','lag2_Trips_pp','lag3_Trips_pp'] + week_cols


text:
Q: "What" or "who"? Imagine having to speak about a profession that no longer exits or is no longer called what it used to be (e.g. "beadsman," "friar," "apothecary"). The audience knows that the talk is about a dead profession, but they don't know yet what it is exactly and whether it was performed by a man or woman. Now, you want to ask them a question to ease them into the subject. The question asks if any of the audience knows about the profession.
Do you ask:

a. Does anyone know what an "apothecary" is?
b. Does anyone know who an "apothecary" is?

"What" suggests that "apothecary" could be something not someone, which may throw the audience out of balance (remember that they have very little background; they can get easily confused)
And
"Who" sounds as if I were asking about his identity or something
Please help.

A: A profession is a thing, not a person.
 Q. What is a carpenter?
 A. A person who works with wood.

 Q. Who is the carpenter?
 A. Dave.

By the way, a friar is neither a profession nor obsolete. A friar is a member of a mendicant religious order (Franciscans, for example) and they still exist today. A friar could practice many different professions.

A: If I wanted to ease into a conversation where we'd discuss an obscure profession, I might ask:

Does anyone know what an apothecary does?

This is a rather common way of wording such a question, as was done in a series of articles published by The Guardian:

*

*What does a research analyst do, exactly?

*What does a civil engineer do, exactly?

*What does a music manager do, exactly?

If you are absolutely sure the career is obsolete, I suppose you could change the question to the past tense, if you liked that better:

Does anyone know what a haruspex did?


text:
Q: What is required to get a Connected App whitelisted? This article mentions whitelisting a connected app, but I have not been able to find any resources on how to begin the whitelisting process, and what is required of my application to be successfully whitelisted. Is the security review part of the whitelisting process? How long does the whitelisting process take? What else do you know about whitelisting? (because I have found very little about it online thus far).
It is my understanding that our connected app be whitelisted before Group Edition and Professional Edition SF orgs can install our connected app (and gain REST API access)
Update: here is a precursor to the original article. Based on the url anchor, whitelisting is the same as the security review process, but I would like something a little more concrete than an url anchor.
Another Update: This article is slightly more helpful.

A: The prerequisite to allow API access for a GE/PE org is a managed package that successfully passed security review.
Given that you need to create a Support Case via the Partner Portal and request the appropriate permissions for the connected app contained in the managed package.
The 'appropriate permissions' depend on type of API you want to consume; for example the REST API requires the connected app to get whitelisted while other APIs require a special API token you need to request via the support case.
All details are described here:
https://developer.salesforce.com/docs/atlas.en-us.packagingGuide.meta/packagingGuide/dev_packages_api_access.htm


text:
Q: Checking for alphanumeric characters and getting input from HTML form I'm fairly new to programming in Perl and I have a couple of compilation issues I can't seem to resolve. My program gets input from this HTML form.
Question: Should my form use the post or get method?
<FORM action="./cgi-bin/Perl.pl" method="GET">

     Full name:
<input type="text" name="full_name" maxlength="20">

     Username:
<input type="text" name="user_name" maxlength="8">

     Password:
<input type="password" name="password" maxlength="15">

     Confirm password:
<input type="password" name="new_password" maxlength="15">

I open a CSV file, write the value of user_name into an array and do a number of checks on the user's input.
Problem #1: I need to check that full_name, user_name, password, and new_password are all alphanumeric or a space but I keep getting multiple errors that look like:
Use of uninitialized value $full_name in string eq at Perl.pl line 33

I don't think I've used CGI correctly to get these values from the form. I also believe I'm not correctly checking for alphanumeric characters. How can I resolve this?
Problem #2: I need to redirect the user to a specific webpage if their passwords don't match and if the username is already taken. I used a meta redirect but it's not doing it successfully. How can I display a proper error page?
This is my code:
#!/usr/bin/perl
use CGI qw(:standard);
use strict;
use warnings;

print "Content-type: text/html\n\n";

#opening Members.csv for reading
my $file = '/home/2014/amosqu/public_html/cgi-bin/Members.csv';
open(my $csv, '<', $file)  || die "Could not open your file";

#getting these from HTML form
my $full_name = param('full_name');
my $user_name= param('user_name');
my $password = param('password');
my $new_password = param('new_password');

my @users = ();

#splitting each line of csv file
foreach (<$csv>) {
     chomp;
     my @fields = split (/\,/);
     push @users, $fields[1]; #put all usernames inside of array
}

close $csv;

#opening Members.csv for appending
open(my $fh, '>>', $file) || die "Could not open your file";

#SOURCE OF PROBLEM 1
#checking that all values are alphanumeric
if(($full_name && $user_name && $password && $new_password) eq /\A[[:alnum:]]+\z/) {
      #if passwords don't match, redirect to error page
      if($password ne $new_password){
         print qq(\n);
         print qq(\n);
         print qq(<title> Passwords don't match. </title> \n);
         print qq{<meta http-equiv="refresh"content="5;URL="http://www.cs.mcgill.ca/~amosqu/registration.html">\n};
         print qq(\n);
         print qq(\n);
         print qq( Passwords don't match \n\n);
         print qq(\n);
         print qq(\n);
     }
      #if they do match, check that user name isn't in Members.csv
      else {
          if(grep (/$user_name/, @users)) {
             print qq(\n);
             print qq(\n);
             print qq(<title> Sorry username already taken. </title>\n);
             print qq{<meta http-equiv="refresh"content="5;URL="http://www.cs.mcgill.ca/~amosqu/registration.html">\n};
             print qq(\n);
             print qq(\n);
             print qq( Username already taken. \n\n);
             print qq(\n);
             print qq(\n);
        }
        #if it isn't already in Members.csv append values to the file
        else {
             print $fh "$full_name, $user_name, $password \n";
       }
    }
}

close $fh;

A: This should get you going. There is a number of issues with your code that don't stop it from working, but current wisdom is not to use CGI at all so I will roll with you.

*

*Use GET unless you have a good reason to use POST

*The problem is here
if(($full_name && $user_name && $password && $new_password) eq /\A[[:alnum:]]+\z/) {

You are using a Boolean && operation that combines the truth of the three variables, and checking whether that, as a string, is equal to the result of matching the contents of $_ against that regular expression.
You must check each of the variables individually, and use the binding operator =~ to test them against a regex. It is also bad form to use the POSIX character classes. I suggest you use grep, like this
my $mismatch = grep /[^A-Z0-9]/i, $full_name, $user_name, $password, $new_password;

Now, $mismatch is true if any of the variables contain a non-alphanumeric character. (Strictly, it is set to the number of variables that have a a non-alphanumeric character, which is zero (false) if none of them do.)
Then you can say
if (not $mismatch) { ... }

*It looks like you just need an else that builds a separate page.


text:
Q: How to add Tag into Asp.net Textbox? I am trying to develop an web application in asp.net where my goal is to create a textbox where user can type multiple phone numbers with comma and then it shows as tags. I want is as below:

I can already achieve this with the following code:

            Input Tags

                <input id="tags_1" type="text" class="tags form-control" value="social, adverts, sales" />


text:
Q: Is Stack Exchange network making business with Russians organizations nowadays? Recently in some discussions in SE network I have used the argument that likely SE (actually, it was regarding SO and SE, but I understand that by definition if something refers to SO, then it refers to SE as well) is making money / business with Russians organizations, helping them grow, and these organizations are paying taxes, so the government has money to continue the war.
However, I don't feel really comfortable saying this and adding that it is likely etc. I think it is not 100% ethical. That's why I would like to know.

A: Given that computer programmers in Russia will pay taxes and work for companies that pay taxes, anything that helps a computer programmer in Russia do her/his job is giving money to Putin.
Hence can we at least have clear warnings on all questions that come from Russia?


text:
Q: How to temporarily stop refreshing Primefaces line chart when zooming I am using JSF/Primefaces p:chart to display a dynamic line chart that updates periodically (e.g. with an interval of 3 seconds) via p:poll tag according to the real-time data, and the zoom property is set to true. Now, the problem is that I want the chart to temporarily stop updating when I zoom and resume when I double-click to reset zoom. However, the updated chart always override the zoomed chart that I am watching. How can I configure the chart to let it stop refreshing when zooming?

A: I have solved the problem, it turns out that both Zoom and ResetZoom have events, so I can bind javascript functions to these events in order to stop and start p:poll.
Let me share my solution as the following code snippet.
index.xhtml
<h:form id="dashboardForm">
    <p:poll interval="3" update="chart"  process="@this"  global="false"  ignoreAutoUpdate="true" widgetVar="chartpoll"/>
    <p:chart id="chart" type="line" model="#{chartView.zoomModel}" style="height:300px;" widgetVar="chart" responsive="true"/>
</h:form>
<script type="text/javascript">
function lineChartExtender() {
    $('#dashboardForm\\:chart').bind('jqplotZoom', function(ev, gridpos, datapos, plot, cursor){
        PF('chartpoll').stop();
    });
    $('#dashboardForm\\:chart').bind('jqplotResetZoom', function(ev, gridpos, datapos, plot, cursor){
        PF('chartpoll').start();
    });
}
</script>

ChartView.java
LineChartModel model = new LineChartModel();
model.setZoom(true);
model.setExtender("lineChartExtender");


text:
Q: Magento MegaMenu small column justification logic I installed a Magento module (Web and People Custom Menu) to give us a mega menu (mega navigation) functionality for the navigation of our website. I am trying to correct the justification so that there isn't this huge amount of space under some of the columns. As you can see in the screenshot, the left column has room for more subcategories underneath it.

I've tried CSS changes and changes to the structure of the printed html. It seems I am going to have to change the logic that is applied to the column divs but I can't seem to figure it out.
Below is the function I think I am supposed to be changing somehow under "// --- 2. merge small columns with next ---":
private function _explodeByColumns($target, $num)
{
    if ((int)Mage::getStoreConfig('custom_menu/columns/divided_horizontally')) {
        $target = self::_explodeArrayByColumnsHorisontal($target, $num);
    } else {
        $target = self::_explodeArrayByColumnsVertical($target, $num);
    }
    #return $target;
    if ((int)Mage::getStoreConfig('custom_menu/columns/integrate') && count($target))
    {
        // --- combine consistently numerically small column ---
        // --- 1. calc length of each column ---
        $max = 0; $columnsLength = array();
        foreach ($target as $key => $child)
        {
            $count = 0;
            $this->_countChild($child, 1, $count);
            if ($max < $count) $max = $count;
            $columnsLength[$key] = $count;
        }
        // --- 2. merge small columns with next ---
        $xColumns = array(); $column = array(); $cnt = 0;
        $xColumnsLength = array(); $k = 0;
        foreach ($columnsLength as $key => $count)
        {
            $cnt+= $count;
            if ($cnt > $max && count($column))
            {
                $xColumns[$k] = $column;
                $xColumnsLength[$k] = $cnt - $count;
                $k++; $column = array(); $cnt = $count;
            }
            $column = array_merge($column, $target[$key]);
        }
        $xColumns[$k] = $column;
        $xColumnsLength[$k] = $cnt - $count;
        // --- 3. integrate columns of one element ---
        $target = $xColumns; $xColumns = array(); $nextKey = -1;
        if ($max > 1 && count($target) > 1)
        {
            foreach($target as $key => $column)
            {
                if ($key == $nextKey) continue;
                if ($xColumnsLength[$key] == 1)
                {
                    // --- merge with next column ---
                    $nextKey = $key + 1;
                    if (isset($target[$nextKey]) && count($target[$nextKey]))
                    {
                        $xColumns[] = array_merge($column, $target[$nextKey]);
                        continue;
                    }
                }
                $xColumns[] = $column;
            }
            $target = $xColumns;
        }
    }
    $_rtl = Mage::getStoreConfigFlag('custom_menu/general/rtl');
    if ($_rtl) {
        $target = array_reverse($target);
    }
    return $target;
}

The whole script:
<?php

class WP_CustomMenu_Block_Navigation extends Mage_Catalog_Block_Navigation
{
    const CUSTOM_BLOCK_TEMPLATE = "wp_custom_menu_%d";

    private $_productsCount = null;

    public function showHomeLink()
    {
        return Mage::getStoreConfig('custom_menu/general/show_home_link');
    }

    public function drawCustomMenuItem($category, $level = 0, $last = false)
    {
        if (!$category->getIsActive()) return '';
        $html = array();
        $id = $category->getId();
        // --- Static Block ---
        $blockId = sprintf(self::CUSTOM_BLOCK_TEMPLATE, $id); // --- static block key
        #Mage::log($blockId);
        $collection = Mage::getModel('cms/block')->getCollection()
            ->addFieldToFilter('identifier', array(array('like' => $blockId . '_w%'), array('eq' => $blockId)))
            ->addFieldToFilter('is_active', 1);
        $blockId = $collection->getFirstItem()->getIdentifier();
        #Mage::log($blockId);
        $blockHtml = $this->getLayout()->createBlock('cms/block')->setBlockId($blockId)->toHtml();
        // --- Sub Categories ---
        $activeChildren = $this->_getActiveChildren($category, $level);
        // --- class for active category ---
        $active = ''; if ($this->isCategoryActive($category)) $active = ' act';
        // --- Popup functions for show ---
        $drawPopup = ($blockHtml || count($activeChildren));
        if ($drawPopup) {
            $html[] = '
';
            //$html[] = '
';
        } else {
            $html[] = '
';
        }
        // --- Top Menu Item ---
        $html[] = '
';
        if ($level == 0 && $drawPopup) {
            $html[] = 'getCategoryUrl($category).'">';
        } else {
            $html[] = 'getCategoryUrl($category).'">';
        }
        $name = $this->escapeHtml($category->getName());
        if (Mage::getStoreConfig('custom_menu/general/non_breaking_space')) {
            $name = str_replace(' ', ' ', $name);
        }
        $html[] = '' . $name . '';
        $html[] = '';
        $html[] = '
';
        $html[] = '
';
        // --- Add Popup block (hidden) ---
        if ($drawPopup) {
            // --- Popup function for hide ---
            $html[] = '
';
            //$html[] = '
';
            // --- draw Sub Categories ---
            //CAITLIN added line below
            $html[] = '

getCategoryUrl($category).'">All ' . $this->escapeHtml($category->getName()) . '

';

            if (count($activeChildren)) {
                $html[] = '
';
                $html[] = $this->drawColumns($activeChildren);
                $html[] = '

';
                $html[] = '
';
            }
            // --- draw Custom User Block ---
            if ($blockHtml) {
                $html[] = '
';
                $html[] = $blockHtml;
                $html[] = '
';
            }
            $html[] = '
';
        }
        $html = implode("\n", $html);
        return $html;
    }

    public function drawMenuItem($children, $level = 1)
    {
        $html = '
';
        $keyCurrent = $this->getCurrentCategory()->getId();
        foreach ($children as $child)
        {
            if (is_object($child) && $child->getIsActive())
            {
                // --- class for active category ---
                $active = '';
                if ($this->isCategoryActive($child))
                {
                    $active = ' actParent';
                    if ($child->getId() == $keyCurrent) $active = ' act';
                }
                // --- format category name ---
                $name = $this->escapeHtml($child->getName());
                if (Mage::getStoreConfig('custom_menu/general/non_breaking_space'))
                    $name = str_replace(' ', ' ', $name);
                $html.= 'getCategoryUrl($child) . '">' . $name . '';
                $activeChildren = $this->_getActiveChildren($child, $level);
                if (count($activeChildren) > 0)
                {
                    $html.= '
';
                    $html.= $this->drawMenuItem($activeChildren, $level + 1);
                    $html.= '
';
                }
            }
        }
        $html.= '
';
        return $html;
    }

    public function drawColumns($children)
    {
        $html = '';
        // --- explode by columns ---
        $columns = (int)Mage::getStoreConfig('custom_menu/columns/count');
        if ($columns < 1) $columns = 1;
        $chunks = $this->_explodeByColumns($children, $columns);
        // --- draw columns ---
        $lastColumnNumber = count($chunks);
        $i = 1;
        foreach ($chunks as $key => $value)
        {
            if (!count($value)) continue;
            $class = '';
            if ($i == 1) $class.= ' first';
            if ($i == $lastColumnNumber) $class.= ' last';
            if ($i % 2) $class.= ' odd'; else $class.= ' even';
            //$html.= '
';
            $html.= $this->drawMenuItem($value, 1);
            //$html.= '
';
            $i++;
        }
        return $html;
    }

    protected function _getActiveChildren($parent, $level)
    {
        $activeChildren = array();
        // --- check level ---
        $maxLevel = (int)Mage::getStoreConfig('custom_menu/general/max_level');
        if ($maxLevel > 0)
        {
            if ($level >= ($maxLevel - 1)) return $activeChildren;
        }
        // --- / check level ---
        if (Mage::helper('catalog/category_flat')->isEnabled())
        {
            $children = $parent->getChildrenNodes();
            $childrenCount = count($children);
        }
        else
        {
            $children = $parent->getChildren();
            $childrenCount = $children->count();
        }
        $hasChildren = $children && $childrenCount;
        if ($hasChildren)
        {
            foreach ($children as $child)
            {
                if ($this->_isCategoryDisplayed($child))
                {
                    array_push($activeChildren, $child);
                }
            }
        }
        return $activeChildren;
    }

    private function _isCategoryDisplayed(&$child)
    {
        if (!$child->getIsActive()) return false;
        // === check products count ===
        // --- get collection info ---
        if (!Mage::getStoreConfig('custom_menu/general/display_empty_categories'))
        {
            $data = $this->_getProductsCountData();
            // --- check by id ---
            $id = $child->getId();
            #Mage::log($id); Mage::log($data);
            if (!isset($data[$id]) || !$data[$id]['product_count']) return false;
        }
        // === / check products count ===
        return true;
    }

    private function _getProductsCountData()
    {
        if (is_null($this->_productsCount))
        {
            $collection = Mage::getModel('catalog/category')->getCollection();
            $storeId = Mage::app()->getStore()->getId();
            /* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
            $collection->addAttributeToSelect('name')
                ->addAttributeToSelect('is_active')
                ->setProductStoreId($storeId)
                ->setLoadProductCount(true)
                ->setStoreId($storeId);
            $productsCount = array();
            foreach($collection as $cat)
            {
                $productsCount[$cat->getId()] = array(
                    'name' => $cat->getName(),
                    'product_count' => $cat->getProductCount(),
                );
            }
            #Mage::log($productsCount);
            $this->_productsCount = $productsCount;
        }
        return $this->_productsCount;
    }

    private function _explodeByColumns($target, $num)
    {
        if ((int)Mage::getStoreConfig('custom_menu/columns/divided_horizontally')) {
            $target = self::_explodeArrayByColumnsHorisontal($target, $num);
        } else {
            $target = self::_explodeArrayByColumnsVertical($target, $num);
        }
        #return $target;
        if ((int)Mage::getStoreConfig('custom_menu/columns/integrate') && count($target))
        {
            // --- combine consistently numerically small column ---
            // --- 1. calc length of each column ---
            $max = 0; $columnsLength = array();
            foreach ($target as $key => $child)
            {
                $count = 0;
                $this->_countChild($child, 1, $count);
                if ($max < $count) $max = $count;
                $columnsLength[$key] = $count;
            }
            // --- 2. merge small columns with next ---
            $xColumns = array(); $column = array(); $cnt = 0;
            $xColumnsLength = array(); $k = 0;
            foreach ($columnsLength as $key => $count)
            {
                $cnt+= $count;
                if ($cnt > $max && count($column))
                {
                    $xColumns[$k] = $column;
                    $xColumnsLength[$k] = $cnt - $count;
                    $k++; $column = array(); $cnt = $count;
                }
                $column = array_merge($column, $target[$key]);
            }
            $xColumns[$k] = $column;
            $xColumnsLength[$k] = $cnt - $count;
            // --- 3. integrate columns of one element ---
            $target = $xColumns; $xColumns = array(); $nextKey = -1;
            if ($max > 1 && count($target) > 1)
            {
                foreach($target as $key => $column)
                {
                    if ($key == $nextKey) continue;
                    if ($xColumnsLength[$key] == 1)
                    {
                        // --- merge with next column ---
                        $nextKey = $key + 1;
                        if (isset($target[$nextKey]) && count($target[$nextKey]))
                        {
                            $xColumns[] = array_merge($column, $target[$nextKey]);
                            continue;
                        }
                    }
                    $xColumns[] = $column;
                }
                $target = $xColumns;
            }
        }
        $_rtl = Mage::getStoreConfigFlag('custom_menu/general/rtl');
        if ($_rtl) {
            $target = array_reverse($target);
        }
        return $target;
    }

    private function _countChild($children, $level, &$count)
    {
        foreach ($children as $child)
        {
            if ($child->getIsActive())
            {
                $count++; $activeChildren = $this->_getActiveChildren($child, $level);
                if (count($activeChildren) > 0) $this->_countChild($activeChildren, $level + 1, $count);
            }
        }
    }

    private static function _explodeArrayByColumnsHorisontal($list, $num)
    {
        if ($num <= 0) return array($list);
        $partition = array();
        $partition = array_pad($partition, $num, array());
        $i = 0;
        foreach ($list as $key => $value) {
            $partition[$i][$key] = $value;
            if (++$i == $num) $i = 0;
        }
        return $partition;
    }

    private static function _explodeArrayByColumnsVertical($list, $num)
    {
        if ($num <= 0) return array($list);
        $listlen = count($list);
        $partlen = floor($listlen / $num);
        $partrem = $listlen % $num;
        $partition = array();
        $mark = 0;
        for ($column = 0; $column < $num; $column++) {
            $incr = ($column < $partrem) ? $partlen + 1 : $partlen;
            $partition[$column] = array_slice($list, $mark, $incr);
            $mark += $incr;
        }
        return $partition;
    }
}

HTML output of one menu:

Baseball

Baseball BasesBaseballsBaseball Gloves

Basketball

Basketball AccessoriesBasketballs

Field & Ice Hockey

Hockey BallsHockey GoalsHockey PucksHockey Sticks

First Aid

Heart Rate MonitorsAthletic Tape

Fitness

Exercise Training Bands

Football

Football AccessoriesFootballs

GolfGymnasticsLacrossePhysical Education

Exercise Training BandsHurdlesMarkers

Playground

DodgeballsFoursquare BallsHandballsJump RopesKickballsPlayground BallsTetherballs

Rugby

Rugby Balls

Soccer

Soccer Balls

Softball

Softballs

Sport Accessories

Ball Bags

SwimmingTennisTimers & Pedometers

Stop Watches

Track & FieldVolleyball

Misc AccessoriesVolleyballs

WhistlesWrestlingOther Sports

Any ideas or hints as to how to justify these columns would be very appreciated!


text:
Q: A substitution for a function of a vector with variable dimension I have to define a function with a recurring pattern like
$u[\mathbb{x}] = x_1^{\alpha_1} x_2^{\alpha_2} \cdots x_n^{\alpha_n}$
With the help of an older post, it is easily done
 u[x : {__}, α : {__}] := Times @@ (x^α)
u[{u, v, x, y,
  z}, {α, β, γ, ϵ, θ}]
xx = Table[Subscript[x,
  i], {i, 1,
   5}](*{Subscript[x, 1],Subscript[x, 2], Subscript[x, 3], \
Subscript[x, 4], Subscript[x, 5]}*)
αα =
 Table[Subscript[α,
  i], {i, 1,
   5}](*{Subscript[α, 1],Subscript[α, 2], Subscript[\
α, 3],Subscript[α, 4], Subscript[α, 5]}*)
u[xx, αα]

Now I want to write the gradient  Grad[] of U. One more time, it is fairly easy:
grad[u_]:= Grad[u[xx, αα], xx]

Now comes my problem: whichever be the dimension of xx, each derivative, which is an element of grad[u], incorporate a pattern of the form
$u_{x_i}[\mathbb{x}] = x_1^{\alpha_1} x_2^{\alpha_2} \cdots \alpha_i x_i^{\alpha_i-1} \cdots x_n^{\alpha_n} = \alpha_i\frac{u}{x_i}$
So I want to substitute this pattern in grad[u] simplify the representation of the gradient. If Dimensions[xx] is always the same, it is not too complicated to do the substitution. For instance if Dimensions[xx]= 3, I would use the vectors ${x, y, z}$ and ${\alpha, \beta, \gamma}$ and  do  the substitution:
//.{α_ x_^(α_-1) y_^β_ y_^γ_ -> α (u/x)}

but
1) I want to keep the indexed variables and  the indexed  parameters;
2) the process must work whichever be the Dimensions[xx].
Perhaps the good idea would be to write a substitution formula of the type
$\forall i$ grad[u][[i]]-> $\alpha_i u/x_i$
I use here a mix of Mathematica and Latex since I do not know how to encode this.