Q:

Python SUBPROCESS.RUN says file is not in place although it is

So when i try to open a .bat file:
Traceback (most recent call last):
  File "accorddownload.py", line 31, in <module>
    subprocess.run(["Tools\aAIvwb.bat"], creationflags=0x08000000)
  File "C:\Program Files\Python37\lib\subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Program Files\Python37\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Program Files\Python37\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

I am running it using
subprocess.run(["tools\aAIvwb.bat"], creationflags=0x08000000)

but the thing is I checked the location 20 times and keep trying to fix, but the same thing is happening. Here is file structure
AB
|
|--Tools--|
|         |--aaitp.bat
|         |--aAIvwb.bat
|         |--mdfa.bat
|
|--basefile.py

EDIT 1: The current working directory NEVER changes throughout the file

A:

I am suspicious of \ escaping. Have you considered calling like this:
subprocess.run([r"tools\aAIvwb.bat"], creationflags=0x08000000)

Note that I put an 'r' before the double quote.


Q:

Add windows commands in python

Can anyone tell me how to add the shutdown.exe to python and how . i also want to set and variables like shutdown.exe -f -s -t 60

A:

The subprocess module allows you to run external programs from inside python. In particular subprocess.call is a really convenient way to run programs where you don't care about anything other than the return code:
import subprocess
subprocess.call(["shutdown.exe", "-f", "-s", "-t", "60"])

Update:
You can pass anything you want as part of the list so you could create a shutdown() function like this:
import subprocess

def shutdown(how_long):
    subprocess.call(["shutdown.exe", "-f", "-s", "-t", how_long])

So if we wanted to get user input directly from the console, we could do this:
dt = raw_input("shutdown> ")
dt = int(dt) #make sure dt is actually a number
dt = str(dt) #back into a string 'cause that's what subprocess.call expects
shutdown(dt)


Q:

How to factorize $n^5+n+1$?

How to factorize $n^5+n+1$ ?
I think I should break $a^5$ and use a factorization formula. but how is it done?

A:

Not sure if my answer can satisfy:
$$\begin{aligned} n^5+n+1&=(n^5-n^2)+(n^2+n+1)\\&=n^2(n-1)(n^2+n+1)+(n^2+n+1)\\&=(n^3-n^2+1)(n^2+n+1)\end{aligned}$$

A:

By trial and error, knowing that there must be a simple solution.

Factoring $n^5+1$ leads nowhere.
$$n^5+n+1=(n+1)(n^4-n^3+n^2-n+1)+n.$$
Factoring $n^5+n$ leads nowhere.
$$n^5+n+1=n(n+1)(n^3-n^2+n-1)+1.$$
Factoring $n^5+n^2$ with an artifice fails, but shows some hope
$$n^5+n^2-n^2+n+1=n^2(n+1)(n^2-n+1)-n^2+n+1.$$
Factoring $n^5-n^2$ instead works !
$$n^5-n^2+n^2+n+1=n^2(n-1)(n^2+n+1)+n^2+n+1.$$

A:

Your coefficients are $(1,0,0,0,1,1)$. That suggests to me that $(1,1,1,1,1,1) + (0,-1,-1,-1,0,0)$ will be useful, to form the pattern with blocks of 3 unit coefficients, i.e. that $(x^2+x+1)$ is a factor.


Q:

Squid : Reverse proxy with IIS 10

There is a website on ISS 10 on windows server 2019.
Default web site and one other.
I have not made any configuration of thoses websites and IIS. It's a crm product, all default settings.
I made a bind with https port and certificate on two websites.
On local network, when i go to https://local_net_adress, it redirect from default website to other site.
From Internet, when i go to https://public_adress, i m not redirected, it shows me default IIS webpage.
Here's my squid configuration from this website :
(squid in reverse proxy is operationnal for exchange webmail and many other apache websites.)
    # ----- xxxxxx -----
cache_peer xx.xx.xx.xx parent 443 0 no-query originserver ssl sslflags=DONT_VERIFY_PEER login=PASS name=srv-xxx

acl myacl url_regex -i ^https://public_url/.*$

cache_peer_access srv-xxx allow myacl
cache_peer_access srv-xxx deny all

http_access allow myacl
never_direct allow myacl
miss_access allow myacl

Is issue on squid or IIS?

A:

Ok It's working now.
It was on IIS bindings.
To work, i had to delete binding from default website AND DO NOT PUT hostname on binding for the other website.
Problem solved.


Q:

Storing subcollections (filtered versions of the main collection) inside the collection as cache?

Is it good practice to store sub-collections of item X inside a parent collection of item X for caching 'filter-queries' which are performed on the parent collection? (They won't be used together (as in color AND type).) Or is it also ok to just Loop over the collection and return the correct entities in a temporary collection?
Class ItemCollection : Inherits Collection(Of Item)
    Private _types as New List(Of ItemCollection) //Cache

    Function FilterByType(type) As ItemCollection
        If Not _types.KeyExists(type) Then
            _types.Add(type, New ItemCollection())
            For Each i in Me
                If i.Type = type Then _types(type).Add(i)
            Next
        End If
        Return _types(type)
    End Function

    //Same for FilterByColor(color)
End Class

Class Item
    Public Color = "Blue"
    Public [Type] = "One"
End Class

A:

I would recommend keeping it simple to start with and then add caching if testing shows that regenerating the filtered lists is a performance problem.  Besides that, the filtering code can be greatly simplified by using filtering methods built into List or using LINQ extensions.
filtered = Me.Where(i => i.Type = type)

(I could be off on the exact syntax, I've never done LINQ in VB.NET, I'm a C# guy.)


Q:

How can I Regex.Replace

How can I use Regex.Replace to achieve the flowing:
Given the input string:
"DV_DHW dv_DWH dv_dwh Dv_Dwh some more text dv_dwhtest"

I want to change it to :
"Test_DV_DHW Test_DV_DHW Test_DV_DHW Test_DV_DHW  some more text dv_dwhtest"

I tried this:
Regex.Replace("Test_DV_DHW Test_DV_DHW Test_DV_DHW Test_DV_DHW  some more text dv_dwhtest", "DV_DHW", "Test_DV_DHW", RegexOptions.IgnoreCase);

But it replace just the first instance of DV_DHW (case sensitive)

A:

Your input contains "DV_DHW" and "DV_DWH". Those aren't the same string. Notice that the first is D-H-W, where "H" is before "W", and the second has "W" before "H."
Since they're not the same, only the first occurrence of "DV_DHW" gets replaced. The correct output is:

Test_DV_DHW dv_DWH dv_dwh Dv_Dwh some more text dv_dwhtest

If your intention was to replace both of the strings, expect the last one since it isn't a whole word, you could use this pattern: @"\bDV_D(?:HW|WH)\b"
The \b metacharacter matches a word-boundary and then the pattern uses (?:...) for a non-capturing group that will match either "HW" or "WH" text.
The above pattern would produce this output:

Test_DV_DHW Test_DV_DHW Test_DV_DHW Test_DV_DHW some more text
  dv_dwhtest

Notice that the last word, "dv_dwhtest," hasn't been modified since the "dv_dwh" wasn't a whole word and was a part of a word instead.


Q:

What is the difference between kosoto-gari and kosoto-gake?

Kosoto-gari and kosoto-gake are superficially similar techniques. I have seen many high level judoka call what I would have called -gari -gake and vice versa - what distinguishes these techniques?

A:

Excerpt of Canonical Answer
This quotation is attributed to Kyuzo Mifune on page 162 of Kodokan Judo: Throwing Techniques by Toshiro Daigo.

Sweeping is similar to brushing an extremely light object away.
When hooking, you execute the technique as if pulling a rooted plant out from the ground.
Reaping is similar to the movement of reaping and cutting off a plant at its root with a sickle.

A kosoto gari is reap, where the side of tori's foot maintains contact with the mat. A kosoto gake is a hooking, where tori's leg bends and tori's foot comes off the mat.
As a strict classification issue, the key point is the action of tori's attacking leg. Does it leave the mat? Then it's a gake. Otherwise it's a gari.
Personal thoughts
I find kosoto gake to be most effective as a counter technique. The opponent enters for a throw where they are turning their back and standing on one leg (for example: harai goshi, hane goshi, uchi mata, ashi guruma), and you disrupt their balance and attack the far leg. As a strict Kodokan classification, this throwing action may unfortunately be classified as a harai goshi gaeshi, hane goshi gaeshi, or uchi mata gaeshi. Note that this does not apply to all throws, only these three. A counter to ashi guruma is not an ashi guruma gaeshi because this is not recognized as a distinct throw.
At the close distance for the counter and uke's weight firmly on the supporting foot, I find timing of kuzushi with the body and a strong hooking action necessary to successfully counter. For kosoto gari, the action of the hands becomes more important to break uke's balance over the heels to setup the reap.


Q:

Jquery .click() function selector issue

I'm currently building a PHP web-page that retrieves data from a SQL server and outputs the retrieved data as a table. Each
 has its own class kind of like this:
"

          $pages->title

          Type:
          $pages->type
          Written by:
          $pages->author

          $pages->article

             <button type='button' class='more'>
                  See more
             </button>
             <button type='button' class='less'>
                  See less
             </button>

"

As there are multiple articles and as they are quite long, I want to hide the articles using display: none; until the user clicks on the "see more" button.
I did this with the following jQuery code:
var main = function() {
$('#search_container .preview').hover(function(){
    $(this).toggleClass('active');
});

$('#search_container .active .more').click(function(){
    console.log('click');
    $('#search_container .active .less').show();
    $('#search_container .active .article').show();
    $('#search_container .active .more').hide();
    $('#search_container .active .info').hide();
});

$("#search_container .active .less").click(function(){
    $('#search_container .active .less').hide();
    $('#search_container .active .article').hide();
    $('#search_container .active .more').show();
    $('#search_container .active .info').show();
});
};
$(document).ready(main);

As only the selected article needs to be revealed, I decided to add the first function. However the selector for .active .more and .active .less do not seem to be working since, when I execute the exact same code without the .active selector, it works and ALL the articles and buttons are revealed or hidden.
Any idea how I can fix that ?

A:

Good question. This has to do with the scope of the selectors being used. In your javascript what happens is you provide a mechanism for toggling a class, but when you change the class you must re-run your jQuery selectors to find the newly added active class. A few small changes to your javascript code should get you headed in the right direction:
var main = function() {
    $('#search_container .preview').hover(
        function(){
            // Keeping this for your targeting
            $(this).addClass('active');
            $(this).find('.more').click(
                function(){
                    $('#search_container .active .less').show();
                    $('#search_container .active .article').show();
                    $('#search_container .active .more').hide();
                    $('#search_container .active .info').hide();
                }
            );
            $(this).find('.less').click(
                function(){
                    $('#search_container .active .less').hide();
                    $('#search_container .active .article').hide();
                    $('#search_container .active .more').show();
                    $('#search_container .active .info').show();
                }
            );
        },
        // When exiting hover, unbind the click bindings
        function(){
            // Keeping this for your targeting
            $(this).removeClass('active');
            // These keep only one .preview container bound to the commands
            // at a given moment
            $(this).find('.more').unbind('click');
            $(this).find('.less').unbind('click');
        }
    );
};

$(document).ready(main);

This implementation has a couple of drawbacks. Each time you hover the click event is registered. Each time you blur off of it the click bindings are unset to prevent a subsequent hover double-binding the click event. Since all of your targeted classes are contained within .preview I would go as far as to do something like this:
var main = function() {
    var previews = $('#search_container .preview');

    $.each(
        previews,
        function(){

            // Reference stored for the .preview container
            var ref = $(this);

            ref.find('.more').click(
                function(){
                    ref.find('.less').show();
                    ref.find('.article').show();
                    ref.find('.more').hide();
                    ref.find('.info').hide();
                }
            );

            ref.find('.less').click(
                function(){
                    ref.find('.less').hide();
                    ref.find('.article').hide();
                    ref.find('.more').show();
                    ref.find('.info').show();
                }
            );
        }
    );
};

$(document).ready(main);

Now all of the previews will have their .more and .less items bound to a click event and the click event operates within the scope of the .preview allowing them all to be registered at once. Hope this helps.


Q:

If I start the Windows Firewall/ICS service will it automatically turn on the firewall

I have a new 2003 server up and running at a data center. I want to turn on the windows firewall, but I have to start the Windows Firewall/ICS service to do it. I don't want to turn it on and then have it block the remote desktop service.
If i turn on the service will it give me the opportunity to configure the firewall before I turn on the firewall itself?

A:

If you enable both the firewall and remote desktop, Windows Firewall will automatically make exceptions for remote desktop.
If you are cautious about blocking RDP, set the Firewall service startup type to manual then set up a scheduled task to reboot the server in 10 minutes. If you can't RDP in after enabling the firewall, go grab a coffee then come back in 10 minutes and it will fix itself. If you can RDP in, simply delete the task. I would not recommend this if the server is in production already, however.


Q:

SQL - why is this 'where' needed to remove row duplicates, when I'm already grouping?

Why, in this query, is the final 'WHERE' clause needed to limit duplicates?
The first LEFT JOIN is linking programs to entities on a UID
The first INNER JOIN is linking programs to a subquery that gets statistics for those programs, by linking on a UID
The subquery (that gets the StatsForDistributorClubs subset) is doing a grouping on UID columns
So, I would've thought that this would all be joining unique records anyway so we shouldn't get row duplicates
So why the need to limit based on the final WHERE by ensuring the 'program' is linked to the 'entity'?

(irrelevant parts of query omitted for clarity)
SELECT  LmiEntity.[DisplayName]
        ,StatsForDistributorClubs.*
FROM    [Program]
LEFT JOIN
        LMIEntityProgram
ON      LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
    SELECT  e.LmiEntityUid,
            sp.ProgramUid,
            SUM(attendeecount) [Total attendance],

        FROM    LMIEntity e,
                Timetable t,
                TimetableOccurrence [to],
                ScheduledProgramOccurrence spo,
                ScheduledProgram sp
        WHERE
                t.LicenseeUid = e.lmientityUid
        AND     [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
        AND     sp.ScheduledProgramUid = spo.ScheduledProgramUid

        GROUP BY e.lmientityUid, sp.ProgramUid
    ) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
       [Program].LicenseeUid = LmiEntity.LmiEntityUid
       OR
       [LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
      )

A:

If you were grouping in your outer query, the extra criteria probably wouldn't be needed, but only your inner query is grouped.  Your LEFT JOIN to a grouped inner query can still result in multiple records being returned, for that matter any of your JOINs could be the culprit.
Without seeing sample of duplication it's hard to know where the duplicates originate from, but GROUPING on the outer query would definitely remove full duplicates, or revised JOIN criteria could take care of it.


Q:

Loading product view in category list with AJAX

Im trying to load the product view block in the category list page with AJAX using Ajaxify.
Everything works fine the only issue being that the options box (childhtml "container1") is not loaded correctly. It does not show the options.
Does anyone have experience with this, maybe tried something like this?
I set the active product in the controller using
$productId  = (int) $this->getRequest()->getParam('product_id');
Mage::helper('catalog/product')->initProduct($productId, $this);

before rendering the layout.
I think it has something to do with the fact that the options are added to the view in an other part of the catalog.xml
[...]
<PRODUCT_TYPE_configurable translate="label" module="catalog">
   Catalog Product View (Configurable)
   <reference name="product.info">
      <block type="catalog/product_view_type_configurable" name="product.info.configurable" as="product_type_data" template="catalog/product/view/type/default.phtml">
         <block type="core/text_list" name="product.info.configurable.extra" as="product_type_data_extra" translate="label">
            Product Extra Info
         </block>
      </block>
   </reference>
   <reference name="product.info.options.wrapper">
      <block type="catalog/product_view_type_configurable" name="product.info.options.configurable" as="options_configurable" before="-" template="catalog/product/view/type/options/configurable.phtml"/>
   </reference>
</PRODUCT_TYPE_configurable>
[...]

but I'm not sure what the precise issue is.
I hope someone can point me in the right direction.
Regards,
Sander Mangel

A:

We have had a similar issue in the past when trying to introduce a quick view popup onto a category list page. Here are a few of the issues we encountered: -

/js/varien/product.js & /js/varien/configurable.js are not included on the category list page by default which are required for configurable dropdowns to be generated. The inline JS below requires this.

Another issue we had was when trying to include more than one of these per page, we were getting issues with duplicate ID's, in any case this might not apply to yourself but make sure if you have multiple you destroy them when closed.

The way we have done this is by creating a blank controller file which allows us to use the unique layout handle e.g. ''. Which you can use the following xml.
 <custom_catalog_product_ajax_view>
        <update handle="catalog_product_view" />
        <remove name="html_calendar" />
        <reference name="root">
                <action method="setTemplate"><template>custom/catalog/ajax/product/response.phtml</template></action>
        </reference>
        <reference name="product.info">
                <action method="setTemplate"><template>custom/catalog/ajax/product/view.phtml</template></action>
                <action method="append">
                    <block>breadcrumbs</block>
                </action>
        </reference>
        <reference name="product.info.media">
                <action method="setTemplate"><template>custom/catalog/ajax/product/view/media.phtml</template></action>
        </reference>
        <reference name="product.info.options.configurable">
                <action method="setTemplate"><template>custom/catalog/ajax/product/view/type/options/configurable.phtml</template></action>
        </reference>
</custom_catalog_product_ajax_view>

This meant we could include the relevant blocks and customise certain aspects of the regular product page.
We also added this to the  handle to include the necessary JS files.
<catalog_category_default>
    <update handle="required_for_catalog_ajax_product_view" />
</catalog_category_default>

<required_for_catalog_ajax_product_view>
        <reference name="head">
                <action method="addJs"></action>
                <action method="addJs"></action>
        </reference>
</required_for_catalog_ajax_product_view>

Our response.phtml file also looks like so
<?php echo Zend_Json::encode(array(
'success' => true,
'html' => $this->getChildHtml('content'),
'optionsPrice' => $this->getOptionsPrice(),
'spConfig' => $this->getSpConfig()
));

Hopefully that can help shed some light on where your going wrong


Q:

Setting default gVim font via `vimrc`, conditional on the operating system

I can place the following code into my _vimrc file on Windows 7/10 and the font will default to 'Consolas - size 11' when I launch gVim.
if has("gui_running")
  if has("gui_gtk2")
    set guifont=Ubuntu Mono\ 15
  elseif has("gui_macvim")
    set guifont=Menlo\ Regular:h14
  elseif has("gui_win32")
    set guifont=Consolas:h11:cANSI
  endif
endif

If I place this same code into my Ubuntu 18.04 vimrc file I don't get the expected 'Ubuntu Mono - size 15'. I just get the default font and size, as if my new vimrc code did nothing.
What do I need to change in my code?

A:

I don't have a Linux machine with graphical interface here to test it, but I'd say the correct syntax for that line would be something like:
set guifont=Ubuntu\ Mono\ 15


Q:

Python: Merge strings and convert to list of floats

I have several messy lists that contains numbers as strings.  A typical list looks like this:
example = ['2', '0', '1', '3', ' ', '=', ' ', '[', '3', '2', '.', '9', '8', ',', ' ', '3', '2', '.', '9', '7', ',', ' ', '3', '2', '.', '5', '9', ']', '\n']

I want to convert this into a single "comma" separated list of floats. Using the list example above, the ideal cleaned up list should be:
cleanedExample = [32.98, 32.97, 32.59]

The length of the floats are not fixed, so sometimes a three decimal might appear.
How can I achieve this?

A:

First you need to extract the bits between the brackets, then join the strings together so you can split by comma, then finally map float to get a list of floats.
firstBracketIndex = example.index('[') + 1
secondBracketIndex = example.index(']')
numberStrings = ''.join(example[firstBracketIndex:secondBracketIndex]).split(', ')
numbers = list(map(float, numberStrings))
print(numbers)

View in action here -> https://repl.it/@LukeStorry/63014174


Q:

Manga with life burning power

I am trying to find a manga i read about 10-15 years ago. A lot of the details are barely remembered, but the final chapter or so stands out in my memory.
In the final chapters the main character fights with the main enemy who i think was his former best friend.  The main character loses an arm.  The fight ends with both still alive, i think. All the people with powers the main character and friends were fighting against end up leaving or stopping, i forget if this was somehow leaving the planet, moving to a new country, or something was happening that would merely make everyone lose their powers.
The main character then talks to someone else, i think the love interest, and explains that he figured out his own power isn't what was thought all along. He could cause burns, but he reveals that recently he figured out his power is actually regeneration, or some form of life manipulation. the burns were caused either by extreme heat of replicating cells, or his touch could stop the regeneration of cells, one of the two.  He also reveled this meant he could restore his arm, but he wouldn't. It was something along the lines of that would disrespect or anger the friend/enemy.
I think there was a chapter where the main character ended up getting separated and traveling through snow and comes across a cabin. It then turns out one of the enemies is in the cabin. though this might be me mixing it up with another manga.
I believe all the characters were human and some event at the start of the manga gave a large number of people powers, but i don't think everyone got powers. I think the characters were high school students.

A:

This is Alive: The Final Evolution (アライブ -最終 進化的 少年).

Taisuke's ability is destruction and reconstruction. Though unable to fully use his reconstruction abilities, Taisuke is able to manifest his destruction abilities by emitting fire which permanently damages cells.

Toward the end, the main character's friend loses his arm.


Q:

Isometries between Hilbertian homogeneous finite dimensional operator spaces

We know that if $i:R_n\rightarrow C_n$ is an isometry then for any $n$-dimensional operator space E, there is a factorization $i=uv$ with $v:R_n\rightarrow E$, $u:E\rightarrow C_n$ such that $\|u\|_{cb}\|v\|_{cb}=n^{1/2}$. The question is, if E is a homogeneous Hilbertian operator space can we find $u$ and $v$ such that they are isometries?

A:

Yes. See the proof of Proposition 10.1 in Pisier's book.
The idea is simple: if you start from any factorization $uv$, by the polar decomposition you can assume that both maps are diagonal in an orthonormal basis. Averaging these diagonal maps over all permutations of the basis does not increase the cb norm, and yields maps that are multiple of the identity.


Q:

use durandal.js for single page application in sharepoint 2013

I am developing single page application in sharepoint 2013. I have some doubts about implementation

I should have something which can be use to maintain history and use for navigation ( as it is single page application)
It should bind the data (can do with knockout.js)
It should give me backend some notification (eg. Data has been saved etc this thing also can be done by knockout.js)

But when I searched about this I get to know that we can do all this things with Durandal.js http://durandaljs.com/
Please tell me it is feasible to use such frameworks in the sharepoint or not?
Is anybody implemented such kind of scinarioes?

A:

From the article Durandal meets SharePoint 2013, one can read:

Let me introduce you to Durandal, a pretty young SPA framework, which is named after a famous French sword. As it states on the web site
Your search for a SPA framework ends here.
Durandal claims to be comfortable
We didn’t try to re-invent the wheel. Durandal is built on libs you know and love like jQuery, Knockout and RequireJS. There’s little to learn and building apps feels comfortable and familiar. Dive in and enjoy.
Durandal claims to run Anyone and Everyone
In the end, Durandal is just a collection of JavaScript libraries, so you don’t need anything special to use it. Hop on over to our github repo and fork away. You can just grab the contents of the App folder and use it to kickstart your own project.

Where they actually test if it is possible, and come to this conclusion:

I’d say that Durandal can fulfill the promise of Your search for a SPA framework ends here.

Conclusion
Yes, it is possible.


Q:

A decimal die is tossed 4 times, thus producing a series of 4 random digits...?

A decimal die is tossed 4  times, thus producing a series of 4 random digits.
The series is said to be increasing if from the second digit onward, each digit stands for a larger number than the previous digit.
For example: $1569,\space 1234,$ and $2579$ are increasing.
The question is: what is the probability of obtaining an increasing series?

A:

Every increasing sequence of four digits corresponds to a four-element subset of $\{0,1,2,\dots,9\}$. This means that the number of successful results is $$\binom{10}{4}$$
The total number of possibilities is just $10^4$, so our final probability is
$$\frac{\binom{10}{4}}{10000}=\frac{\frac{10\cdot 9 \cdot 8 \cdot 7}{4 \cdot 3 \cdot 2}}{10000}=\frac{21}{1000}=0.021$$


Q:

What is the best way to implement a REST service that query the database using like statement using Spring Boot and JPA?

I want to query database for the items that are similar(sql like) to the given string which is later is going to be used for auto complete feature in my app. I want to use REST services but I wondering what is the best approach to implement it. I am also considering that might be later I need to introduce multiple parameters such as the way to sort(asc, desc) or search by multiple fields. Here is my current solution but I am not sure if it is the best way. My Rest service url looks something like this. I didn't want to use RequestParam in this case because it was not showing that this is going to be "like" operator instead of "equal":
https://localhost/rest/device/serial/like/lac

Looking for recommendations regarding best REST Resource Naming convention and ways to implement it in spring mvc.
@RestController
@RequestMapping({"rest/device"})
public class DeviceController {
    private final ServiceManager serviceManager;

    @GetMapping("/serial/like/{serial}")
    @ResponseBody
    public Iterable<Device> searchDevicesBySerialNumber(@PathVariable(value = "serial") String serial){
        return this.serviceManager.getDeviceRepository().findBySerialNumberLike(serial);
}

}
This is also another way I can accomplish the same thing:
https://localhost/rest/device?serial-prefix=lac

@GetMapping("")
@ResponseBody
public  Iterable<Device> searchDevice(@RequestParam(value = "serial-prefix",required = false) String serialPrefix){
    if (serialPrefix!=null) {
        return this.serviceManager.getDeviceRepository().findBySerialPrefix(serialPrefix);
    }
    return this.serviceManager.getDeviceRepository().findAll();

}

A:

Your 2nd version is far better. Parameters for sorting, pagination or filtering should appear as request parameters in REST request.
You should also consider using Spring Data Rest. It has out-of-the-box solutions for standard REST endpoints for your entities, which includes paging and sorting too!
The search-feature you need can be implemented in literally 2 lines under Spring Data Rest.


Q:

Single query to get events based on criteria AND singular events that come AFTER each one?

We have a table which stores events (alerts based on machine learning). Each alert provides some information about future possible failures that might happen. Alerts that meet some criteria are special and planned maintenance is scheduled to avoid future failure based on information from such alert.
The table schema is similar to:
|id|fin|datetime|failure|
-------------------------
|1 |fin1|2016-04-02|0|
|2 |fin1|2016-05-02|1|
|3 |fin2|2017-05-02|0|
|4 |fin2|2017-05-12|0|
|5 |fin2|2017-05-01|1|
|6 |fin3|2017-12-01|1|

where fin describes the part which failed or may fail in near future and failure is binary and indicates whether the event is an alert or an actual failure (we need both in same table).
Now what we want is to get all alerts which are labeled as planned maintenance and also the next failure after each such alert (for same FIN of course as the FIN of the alert).
Note we have the ids of those alerts that are labeled as planned maintenance from another table based on another evaluation process. You can consider this as given eg in a list of planned_ids (for example this list may be [1,3] to match the sample data above)
Right now we solve this problem by making multiple requests in DB (mysql but not that important), first to get all events that are labeled as planned maintenance (we have the ids of those events) by using, for example,
select *
from events
where id in [planned_ids]
order by datetime asc -- we dont mind if this is ordered desc as well

Then for each such alert we fetch the next failure for same FIN (functional part) that comes immediately AFTER that event and is a failure. For example by using:
-- using $alert as kind of variable here to denote that the query
-- runs for each alert based on that same alert data i.e datetime and fin part
select *
from events
where fin=$alert.fin and datetime>=$alert.datetime and failure=1
order by datetime desc
limit 0,1

This works but is a kind of N+1 problem.
Can we fetch the alerts and also single next failure for each alert in a single sql query?

A:

A correlated subquery, perhaps:
select e.*,
       (select e2.id
        from events e2
        where e2.fin = e.fin and e2.datetime > e.datetime
        order by e2.datetime desc
        limit 1
       ) as next_event_id
from events e
where e.id in ( . . . )

If you want additional information, you can use this as a subquery and join back to the events table.
select p.*, nexte.*
from (select e.*,
             (select e2.id
              from events e2
              where e2.fin = e.fin and e2.datetime > e.datetime
              order by e2.datetime desc
              limit 1
             ) as next_event_id
      from events e
      where e.id in ( . . . )
     ) p left join
     events nexte
     on nexte.id = p.next_event_id;

According to MySQL documentation on performance of correlated queries it is stated:

For certain cases, a correlated subquery is optimized. For example:
val IN (SELECT key_val FROM tbl_name WHERE correlated_condition)

Otherwise, they are inefficient and likely to be slow. Rewriting the
  query as a join might improve performance.

Also according to this article:

We have shown that under some circumstances, correlated subqueries can
  be better than bulk aggregation. In Oracle. With small-medium sized
  data sets. In other cases, that’s not true as the size of M and N, our
  two algorithmic complexity variables increase, O(M log N) will be much
  worse than O(M + N).

Also it seems a kind of N+1 problem still exists (although less severe performance-wise than having N separate queries) even if using correlated subqueries to construct a single query to fetch our data.


Q:

Strichartz estimates for the heat equation

Consider the heat flow $e^{t\Delta}$, $t>0$, on an Euclidean domain (say $\mathbb{R}^3$). I expect, in analogy with the Strichartz estimates for the Schrodinger equation, that the following estimates hold:
$$\Vert e^{t\Delta}f\Vert_{L^s(\mathbb{R}^+,L^p(\mathbb{R}^3))}\lesssim \Vert f\Vert_{L^2(\mathbb{R}^3)},$$
where $(s,p)$ is a Strichartz pair. Is this fact actually true? In such a case, there exists a reference where it is stated explicitly?

A:

Sure. Actually you have in addition the maximum principle (i.e. an $L^\infty$--$L^\infty$ estimate) which combined with the others gives a full triangle of indices for the Strichartz type estimates in your question. Even more, the strong decay of the symbol $e^{-t|\xi|^2}$ can be exploited for some gains in regularity. A short account is in the book by Wang, Huo, Hao, Guo "Harmonic analysis method for nonlinear evolution equations" (around p.35) link


Q:

Where are my Application Settings when running on IIS

I have a deployed WCF application running on IIS 7.5 as a site.  One of the business dll's of that application (ABC.dll) has an application setting of type "connection-string".
I would like to change that DB connection string but can't find the right place to do it.
The ABC.dll.config in the Bin folder where the application dll's are deployed does not contain the actual connection string the application use at run-time.
How do I find that connection string?

A:

If you have a WCF service running in IIS, you put the configuration in a web.config file in the root folder. This will contain all the settings that apply to your service. It is most likely that the connection string is being used from this file.
It is theoretically possible that if the settings are not in the web.config either, then they might be in the machine.config of the server on which you are hosting your WCF service. It is highly unlikely though that someone would store app-specific connection strings in this file but u never know sometimes.


Q:

Symfony2 cloned routed

I am trying to make 1 resource accessible by 2 different routes:
api_v1:
    type:     rest
    prefix:   /api/v1
    resource: "@AppBundle/Resources/config/routing.yml"

app:
    type:     rest
    prefix:   /
    defaults: { _format: html }
    resource: "@AppBundle/Resources/config/routing.yml"

But forever reason second route overrides the first. When I debug:router I get:
get_products    GET      ANY    ANY  /products.{_format}
post_products   POST     ANY    ANY  /products.{_format}
//etc...

But I am expecting
get_products    GET      ANY    ANY  /api/v1/products.{_format}
post_products   POST     ANY    ANY  /api/v1/products.{_format}
//etc...

get_products    GET      ANY    ANY  /products.{_format}
post_products   POST     ANY    ANY  /products.{_format}
//etc

What could I be doing wrong?

A:

You can't have 2 routes with the same name. In such cases, the second route overrides the previous defined route with the same name, exactly the behaviour you're describing.
It also seems very wrong to have 2 URLs point to exact the same resource. Use a (permanent) redirect to handle such cases.


Q:

Is "extend self" the same as "module_function"?

extend self and module_function are two ruby ways to make it so you can call a method on a module and also call it if you include that module.
Are there any differences between the end results of those ways?

A:

module_function makes the given instance methods private, then duplicates and puts them into the module's metaclass as public methods. extend self adds all instance methods to the module's singleton, leaving their visibilities unchanged.
module M
  extend self

  def a; end

  private
  def b; end
end

module N
  def c; end

  private
  def d; end

  module_function :c, :d
end

class O
  include M
  include N
end

M.a
M.b  # NoMethodError: private method `b' called for M:Module
N.c
N.d
O.new.a
O.new.b  # NoMethodError: private method `b' called for O
O.new.c  # NoMethodError: private method `c' called for O
O.new.d  # NoMethodError: private method `d' called for O


Q:

How do I access the XMLHttpRequest object of the current web page?

I am writing a firefox extension that intercepts the XMLHttpRequest before the page gets loaded in the browser. What I have found so far requires me to create a new instance of XMLHttpRequest.
Any advice on this? Any help will be greatly appreciated!

A:

Override the prototype of the XHR object, eg:
//Capture the original XHR.open method
var _XMLHTTPRequest_open = XMLHttpRequest.prototype.open;

//Overwrite the XHR.open method
XMLHttpRequest.prototype.open = function(){
    //Do something, checks, etc.
    //If permitted:
    _XMLHTTPRequest_open.apply(this, arguments);
}


Q:

Loop to save and close each open email leaves one open

I often have many windows open and it becomes tedious to close Outlook.
I've written two versions of this QuickClose procedure, they tend to leave an email open.
This one throws an index array out of bounds error:
Sub QuickClose()

Dim Inspector As Outlook.Inspector
Dim InspectorCount, i As Integer
Dim myItem As Object
'On Error Resume Next
If Application.Inspectors.count > 0 Then
    InspectorCount = Application.Inspectors.count

    For i = 1 To InspectorCount
        Set myItem = Application.Inspectors.Item(i)

        myItem.Activate

        If TypeName(myItem) = "Message" Then

            myItem.Close olSave

        End If

        If TypeOf ActiveInspector.CurrentItem Is MailItem Then

            ActiveInspector.CurrentItem.Close olSave

        End If

    Next i

End If

End Sub

No errors from this one, but it also tends to leave an email open (and not saved):
Sub QuickClose1()

Dim Inspector As Outlook.Inspector
Dim InspectorCount As Integer
Dim myItem As Object

If Application.Inspectors.count > 0 Then

    For Each Inspector In Application.Inspectors
        Inspector.Activate
        Inspector.CurrentItem.Close olSave
    Next Inspector

End If
End Sub

Once I get this section working, it will go on to close Outlook.

A:

There is no need to get an item from the active inspector window. You can use the Inspector.Close method which closes the Inspector and optionally saves changes to the displayed Outlook item.
Sub QuickClose()

Dim inspectors As Outlook.inspectors
Dim inspector As Outlook.inspector

Set inspectors = Application.inspectors

Do While inspectors.Count > 0
  Set inspector = inspectors.Item(1)
  inspector.Close olSave
Loop

End Sub


Q:

Find the tangent and the normal to an implicit function

Find the implicit function for $xy^2+4x^2y-12=0$ at $(1,2)$. Then find
  the tangent and the normal to $y=\varphi(x)$ at $x=1$.

Let $y=\varphi(x)$ (1)
Now: $x\varphi(x)^2+4x^2\varphi(x)-12=0$ $\Rightarrow \frac{d}{dx} = \varphi^2(x)+2x\varphi'(x)\varphi(x)+8x\varphi(x)+4x^2\varphi'(x)=0$
Using again (1) $\Rightarrow 4+4x\varphi'(x)+16x+4x^2\varphi'(x)=0$
$\Rightarrow \varphi'(x)=\frac{-4x-1}{x+x^2}$
Now, I don't know how to find neither the tangent nor the normal. How'd I find them?

A:

I am assuming the problem wants the tangent line to the graph of $xy^{2} + 2x^{2}y - 12 = 0$. As you calculated, $\frac{d}{dx} (xy^{2} + 2x^{2}y - 12) = y^{2} + 2xy y' + 4x^{2} y' + 8xy = 0 \implies y' = \frac{-8xy-y^{2}}{2xy+4x^{2}}$. To find the tangent line at $(1,2)$, we need to find the slope, which is given by $y'(1,2) = -\frac{5}{2}$. Knowing that the tangent line has a point of $(1,2)$, we have that using point slope form $(y-2) = -\frac{5}{2}(x - 1) \implies y = -\frac{5}{2}x + \frac{9}{2}$. For the normal line, it is perpendicular to the tangent line and intersects it at $(1,2)$. Performing a similar calculation yields that $y = \frac{2}{5} x  +\frac{8}{5}$. Hence the lines are:
$$
y_{T} = -\frac{5}{2}x + \frac{9}{2} \\
y_{N} = \frac{2}{5} x  +\frac{8}{5}
$$
A graphic of this problem can be found below:
Which curve is the tangent line, normal line and the given function?


Q:

Como formatar um Double trocando o ponto por vírgula e mantendo 2 casas decimais em VB.NET

Preciso transformar o resultado de um valor de As Double para o padrão numérico brasileiro que usa vírgula ao invés de ponto (e também manter somente 2 casas decimais), Assim:
' variaveis de teste                       ' valores esperados de saida
Dim t1 as double = 123                     ' ~> 123,00
Dim t2 as double = 123.123                 ' ~> 123,12
Dim t3 as double = 123123132112321321.123  ' ~> 123123132112321321,12
Dim t4 as double = 0.123                   ' ~> 0,12
Dim t4 as double = 0.158123                ' ~> 0,16

A:

O método ToString tem uma sobrecarga que aceita um CultureInfo como parâmetro. Passe este parâmetro usando a cultura que desejas.
Dim valor = 5.89d
valor.ToString(new CultureInfo("pt-br"))

Veja funcionando no .NET Fiddle


Q:

"Why and for what reasons"

I saw "Why and for what reasons […]" here and it seems to be present in other places.
Is it pure redundancy, or does the asker expect an anwer in two parts ("why" and "for what reasons")?
If it is redundant, why would someone use this expression instead of just "why"? Is it just showiness?

A:

It's called pleonasm.

"Let me tell you this, when social workers offer you, free, gratis and
for nothing, something to hinder you from swooning, which with them is
an obsession, it is useless to recoil ..."
—Samuel Beckett, Molloy.

Sometimes figures of speech like this one are used to achieve some particular effect, in this case it's just an idiom being used by imitation, or habit.


Q:

How to combine arithmetic expansion and brace expansion?

Can peoples combine arithmetic expansion and brace expansion?
$ for i in {$((1 + 1))..5}; do echo $i; done;
{2..5}
$ echo "bash laughs at me"

A:

See man bash for explanation:

The  order  of  expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and  pathname expansion.

Brace expansion happens before arithmetic expansion, so you can't combine them in the way you tried.
Use seq instead:
for i in $(seq $((a+4)) 12) ; do echo $i ; done


Q:

White ceramic- irrespective of lighting

In blender, we can get a green reflective color irrespective of the lighting:

or a yellow ceramic :

But I've been thinking of a way to get white ceramic like these cups, irrespective of the lighting. We could fake through the use of HDR lighting or using the compositor, to seperately render out the cups and use a background. But, what would be a way to do so irrespective of the lighting.So, that we could take the same cup(or objects), to a bunch of different scenes and not get bugged with making adjustments. In a single scene, too much of lighting would occlude out the details. So, I'm really confused how to get this results.
All I get is a dull gray :

Please note that the main point of it is to be irrespective of lighting.

A:

Environment texture:
First of all you'll need some Environment Map. I suggest to use HDRI imitating photo studio setup. You can find many of them, even for free.

After selecting one change Strenght accordingly to your needs. And you can see our environment.

Background:
To get gray background, or any other color create plane and extrude it with nice subtle curve.

Material:
I'm using simple Diffuse/Glossy mixed by Fresnel but you can go with any other setup. Remember that default color in Blender isn't pure white.
Blend file:
Here it's my blend file with HDRI map packed.


Q:

MPMediaQuery wait until Media dialog is complete before callback

My goal is to establish a bridge between iOS and react-native and return back all the podcast titles. The bridge seems to be working, and the podcast titles get returned however the callback I've set up gets called immediately and not after the user has accepted the Media permissions prompt ( The prompt below )

So the callback will return no podcast titles since I'm not authorized, however if I invoke the function after the user has clicked "OK" meaning I'm authorized then the podcast titles return properly. Because I don't have to wait for the dialog to be answered. So my question is how do I wait for the dialog to be answered before calling my callback with the podcast titles.
Here is my function to retrieve the podcast titles:
RCT_EXPORT_METHOD(requestPodcastTitles: (RCTResponseSenderBlock)callback)
{
    MPMediaQuery *query = [[MPMediaQuery alloc] init];
    [query setGroupingType: MPMediaGroupingPodcastTitle];
    NSArray *podcasts = [query collections];
    NSMutableArray *mutablePodcastsToSerialize = [NSMutableArray array];

    for (MPMediaItemCollection *podcast in podcasts) {
      MPMediaItem *representativeItem = [podcast representativeItem];
      NSString *podcastTitle =
      [representativeItem valueForProperty: MPMediaItemPropertyPodcastTitle];\
      NSLog (@" Podcast Title: %@", podcastTitle);
      NSDictionary *podcastDictionary = @{@"podcastTitle": podcastTitle};
      [mutablePodcastsToSerialize addObject:podcastDictionary];

    }

    callback(@[[NSNull null], mutablePodcastsToSerialize]);
    return;
}

Any idea what needs to be done to wait for the prompt to end before returning the callback?

A:

The problem is that you did not call MPMediaLibrary.requestAuthorization().  If you did, it would call you back when the dialog is gone, and now you can proceed.


Q:

Spray routing multiple depth paths

I have 4 levels of response based on URL. So for:
* GET on /abc -> response should be abc
* GET on /abc/def -> response should be def
* GET on /abc/def/ghi -> response should be ghi
* GET on /abc/def/ghi/jkl -> response should be (surprisingly) jkl
So my question is how to design that kind of request-response property with Spray.io?
I know that using pathPrefix with path is possible but that is only for two levels?
With that kind of approach it should look something like:
val route = {
  path("/abc") {
    // complete with response 'abc'
  } ~
  path("/abc/def") {
    // complete with response 'def'
  } ~
  path("/abc/def/ghi") {
    // complete with response 'ghi'
  } ~
  path("/abc/def/ghi/jkl") {
    // complete with response 'jkl'
  }
}

Is there  any way to "nest paths"? I know this is not working but just an idea like:
val route = {
  path("/abc") {
    // complete with response 'abc'
    'sub'path("/def") {
      // complete with response 'def'
      'sub'path("/ghi") {
        // complete with response 'ghi'
        'sub'path("/jkl") {
          // complete with response 'jkl'
        }
      }
    }
  }
}

Or any other proper way of nesting paths?
Best,
zmeda

A:

I think the question is about how to do both, complete with something on one level if the path is finished or go one level deeper if there's still more path available.
Try this:
val route = {
  pathPrefix("abc") {
    // complete with response 'abc'
    pathEnd { complete("abc") } ~ // don't forget the twiggles
    pathPrefix("def") {
      pathEnd { complete("def") } ~
      pathPrefix("ghi") {
        pathEnd { complete("ghi") } ~
        path("jkl") { // path already includes pathEnd, path(x) = pathPrefix(x ~ PathEnd)
          complete("jkl")
        }
      }
    }
  }
}

Btw. this doesn't match "/abc/" etc., i.e. a path with a trailing slash. If you want to match trailing slashes mandatorily or optionally use pathSingleSlash or pathEndOrSingleSlash instead of pathEnd.


Q:

How to pass strings from C# to C++ (and from C++ to C#) using DLLImport?

I've been trying to send a string to/from C# to/from C++ for a long time but didn't manage to get it working yet ...
So my question is simple :
Does anyone know some way to send a string from C# to C++ and from C++ to C# ?
(Some sample code would be helpful)

A:

in your c code:
extern "C" __declspec(dllexport)
int GetString(char* str)
{
}

extern "C" __declspec(dllexport)
int SetString(const char* str)
{
}

at .net side:
using System.Runtime.InteropServices;

[DllImport("YourLib.dll")]
static extern int SetString(string someStr);

[DllImport("YourLib.dll")]
static extern int GetString(StringBuilder rntStr);

usage:
SetString("hello");
StringBuilder rntStr = new StringBuilder();
GetString(rntStr);

A:

Passing string from C# to C++ should be straight forward. PInvoke will manage the conversion for you.
Geting string from C++ to C# can be done using a StringBuilder. You need to get the length of the string in order to create a buffer of the correct size.
Here are two examples of a well known Win32 API:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
 static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static string GetText(IntPtr hWnd)
 {
     // Allocate correct string length first
     int length       = GetWindowTextLength(hWnd);
     StringBuilder sb = new StringBuilder(length + 1);
     GetWindowText(hWnd, sb, sb.Capacity);
     return sb.ToString();
 }

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern bool SetWindowText(IntPtr hwnd, String lpString);
SetWindowText(Process.GetCurrentProcess().MainWindowHandle, "Amazing!");


Q:

Losing Focus From A JTextField

After I use my textfield I can't get a jpanel that click on back into focus for my keylistener. It works for the mouselistener but all other keystrokes keep being detected by the textfield not the jpanel.
The panel has been setFocusable(true) and works fine until i give the textfield the keyboard focus. It's like the textfield won't release the focus.
Any suggestions?

A:

The answer was to call requestFocus() on the panel after the text action was performed


Q:

How my website should use its own API?

Im building small web-service which will provide my users with data through API.
Also, some data will be available right on my website.
The question is about how to use my own API? Should my website make a query to, for example, http://website.com/api/users/?format=json and then render data? Because I can use standard Django ORM features, but this is not corresponding with using of own API.
update:
Imagine that I have a database full of games with release date, game name, game platform etc. And on my own website I will show this games as a list or a grid. Also, this data can be reached through API in JSON format, this data can be updated through API and even deleted. And on my own website I have html forms that allow me to do this actions in a user-friendly way. So how should I access my own API? Via POST request to my API or via django ORM directly to database?

A:

Unless the performance overhead of using the web service is an issue, you should definitely use your public API.
This will help you get a consistent behavior between your application and the consumers. It will also avoid code duplication and the best part - if you break your web service you will most likely be the first one to notice it.
The concept is usually referred to as "dogfooding" and Twitter is one example of an application, that dogfoods it's own API.


Q:

API naming and namespacing

Is it right or more beautiful to name the functions with an prefix, like in Qt? Or using "many" namespaces, but 'normal' names for functions?
For example,

slOpenFile(); //"sl" means "some lib"
vs
some_lib::file_functions::openFile();

Update:  I've read somewhere that the first variant(using some prefix) is better, because the API users can perform 'fast' search among the documentation and in the Internet. E.g. by typing the magic prefix search engine starts to advice the exact functions. Is it enough to use the first variant?

A:

The latter is better, if possible.

In many languages (including C++), you can simply use/import packages/namespaces, so that you don't have to spell out the whole path repeatedly. In contrast to that, prefixes always have to be used.
Namespaces make it easier to avoid collision. Many libraries are simply prefixed by the domain of the library creators (e.g. com.google.android.maps). There's only 676 possible two-letter-prefixes, but there's definitely more than 676 libraries out there. Damned is he who needs two with the same prefix.
Namespaces allow nesting, so you can have some_lib::file_functions::openFile and some_lib::file_functions::closeFile and some_lib::sound_functions::beep, while you can't do that with prefixes: slOpenFile, slCloseFile, slBeep. Nested namespaces allow you to communicate structure.

As for the claim, that prefixes make searching easier. Even assuming it is true (which IMHO is bs): You want to design a good API. Well, a good API comes with expressive, self-explaining function names and enough documentation to cover any ambiguity.


Q:

Return array in stored function

I am trying to use the result of a stored function in a WHERE statement in MySQL (5.x), but it fails because in the function I am selecting values from a table into an INT variable and then returning them/it, which obviously doesn't work if the SELECT returns more than 1 row. I've tried returning a TABLE (as I understood TABLE means array in MySQL) but that didn't work either.
Is there any way that I could do something like:
SELECT ID FROM myTable WHERE ID IN my_function(params);

Thank you.

A:

This cannot be done...
First, you cannot use a stored function to return multiple results - you would need to use a stored procedure.
The MySQL docs state:

Statements that return a result set can be used within a stored procedure but not within a stored function.

Second, you cannot use a stored procedure in a query - see this SO question.
Have you considered using 'HAVING ...' at the end of your query?


Q:

the use of combining max, xrange and lambda function in python

I have found a code that pivotize a square matrix for LU decomposition, but I can't understand some of them.
def pivotize(m):
    """Creates the pivoting matrix for m."""
    n = len(m)
    ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
    for j in xrange(n):
        row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
        if j != row:
            ID[j], ID[row] = ID[row], ID[j]
    return ID

First, isn't the line for ID simply the identity matrix? any advantage doing this?
Second, I can't really understand the line for row. I know lambda is used to define a function in the text, and it simply returns the value of M_ij once the value of i is supplied (and the value of j depends on the for loop), but what is i?
And isn't xrange similar to range? But what does it return here?
And when combined with the function max, what happens? I just don't know what are the things inside the max function that are being compared.
Sorry if this question sounds stupid. I'm pretty new to programming

A:

First, isn't the line for ID simply the identity matrix?

Yes.

Second, I can't really understand the line for row....

See this for a discussion about the max/key/lambda interaction.  To answer "what is i?", its the argument to the lambda function, i could equivalently be x for foo.  (For clarity, yielding abs(m[x][j]) and abs(m[foo][j]), respectively).

And isn't xrange similar to range?

Yes.  In Python 2 xrange returns a sequence object that lazily computes the next value, only when needed.  See this for more info.  When looped through in entirety, range and xrange will produce the same results, with different implementations.

But what does it return here?

Line 5's xrange(n) will return the integer values from 0 to (n-1) while Line 6's xrange(j, n) will return the integer values from j to (n-1).
EDIT
More on lambda:
Consider how you might take a given sequence of numbers, and double each of them.  First define a function that doubles a number x and returns that value.  Then map that function to each element of a sequence.
# Traditional
def double(x): return x*2
print map(double, [1,2,3,4])         # [2, 4, 6, 8]

You could have alternatively used an anonymous (lambda) function to do the same thing:
# Lambda
print map(lambda i: i*2, [1,2,3,4])  # [2, 4, 6, 8]

Note that everything is the same, except the definition of the double function is gone and the reference to the function in the call to map is replaced by the "inline" lambda function.
EDIT 2

And when combined with the function max, what happens?

This line row = max(xrange(j, n), key=lambda i: abs(m[i][j])) can be broken down as follows:

xrange(j,n) generates a sequence of integers from j (inclusive) to n (exclusive).
Each of those integers are then "passed" as arguments to the function in the key argument.  In other words, they're each used as the i in the lambda function.  The lambda function "returns" the absolute value of the ith row and jth column.[1]
The max function then finds the greatest value of these "lambda outputs" and sets row equal to it.

This could have alternatively been written as a max of a list comprehension:
row = max( [abs(m[i][j]) for i in xrange(j,n)] )

Or as Dan D. points out in his comment, written as a generator expression (without creating an intermediary list) as simply:
row = max( abs(m[i][j]) for i in xrange(j,n) )

Notes:
[1] Some assumptions here, but row-column is a standard way of expressing matrices.


Q:

Python end parent process from thread

My aim is to create a new process which will take a number as input from user in a loop and display the square of it. If the user doesn't enter a number for 10 seconds, the process should end (not the main process). I'm using threading.Timer with multiprocessing.
Tried Code
from threading import Timer
import multiprocessing as mp
import time

def foo(stdin):
    while True:
        t = Timer(10, exit, ())
        t.start()
        print 'Enter a No. in 10 Secs: ',
        num = int(stdin.readline())
        t.cancel()
        print 'Square of', num, 'is', num*num

if __name__ == '__main__':
    newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
    proc1 = mp.Process(target = foo, args = (newstdin, ))
    proc1.start()
    proc1.join()
    print "Exit"
    newstdin.close()

But it's not working. Instead of exit I tried with sys.exit, Taken proc1 as global and tried proc1.terminate, But still no solution.

A:

Replaced exit with os._exit and it's working as expected.
t = Timer(10, os._exit, [0])

os._exit takes exactly 1 argument, hence we have to mention 0 in a list. (In threading.Timer to pass arguments to the function, the arguments should be in a list.)


Q:

How to change color of linkbutton when clicked(visited link)?

I'm trying to change on of my linkbutton's text color to red when a user clicks on the link. Therefore, as a user I can identify that I've already clicked on this link.
<body>
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="FileGrid" runat="server" AutoGenerateColumns="False" OnRowCommand="FileGrid_RowCommand">
            <Columns>
                <asp:BoundField DataField="OriginalFileName" HeaderText="OriginalFileName" SortExpression="OriginalFileName" />
                <asp:BoundField DataField="AttachmentGUID" HeaderText="AttachmentGUID" SortExpression="AttachmentGUID" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="Generate_PDF" runat="server" Text="Generate PDF" CommandName="GeneratePDF_Click" CommandArgument="<%#Container.DataItemIndex %>" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

    </div>
</form>

This is what I've tried using javascript.
<script>
    document.getElementById('Generate_PDF').onclick = function () {
        this.style.backgroundColor = '#ff0000';
    };
</script>

A:

Use this:
    document.getElementById('Generate_PDF').onclick = function () {
        this.style.color= '#ff0000';
    };

Because you need to change the color of text, not the background.


Q:

What does "bordered on narcoleptic" mean?

What does bordered on narcoleptic mean in the following passage?

But if an explanation is where the mind comes to rest, the mind that stopped at “lucky” when it sought to explain the Oakland A’s recent pitching success bordered on narcoleptic.

A:

I'm working without context here.

Narcolepsy is a sleep disorder that causes excessive sleepiness and frequent daytime sleep attacks.

Here the writer is using hyperbole for effect. In the opening clause you have

...if an explanation is where the mind comes to rest

"Comes to rest" here is used to mean "settle" or "reach destination". However, "rest" can also mean to "relax" or "cease activity in order to refresh oneself".
The implication, then, is that the explanation "lucky" is so lazy, so without thought, that the mind that came up with it must be so very much in need of rest that it's practically abnormal.
But then, that's sports writing for you.


Q:

QGraphicsItem does not show

I wrote a simple application that displays QGraphicsPixmapItems in a QGraphicsScene. The application should be portable without installing Qt on the operating system. I managed to copy only the needed dll files to start the application. Everything works except the QGraphicsItems are not displayed at all, although they are in the scene (wrote a logfile that counts the items).
I figured out that the items are shown correctly, if I copy my "portable" exe file into Qt\Qt5.2.1\5.2.1\mingw48_32\bin folder.
The opposite does not work: If I copy all of the bin-folder to my portable application folder, it does not work. How can I use a QGraphicsItem in a portable Qt application?

A:

I found the reason: I needed to add the folder Qt\Qt5.2.1\5.2.1\mingw48_32\plugins\imageformats to my "portable-app"-folder. In particular, the needed dll was qjpeg.dll.


Q:

Why is the store state of the vuex not stored in localStorage?

When I refresh the page, the store's state is all gone.
This is very inconvenient when programming.
When I looked up, there was a module called vuex-persist, which stores the state of vuex in localStorage.

Why doesn't vuex store the state of vuex by default in cookie or localStorage?
And, will there be any side effects of storing the state of the store using the vuex-persist module?

A:

Why doesn't vuex store the state of vuex by default in cookie or localStorage?

Vuex is a state management library. It most of the cases, the state will be partially filled from an API or a database. It's not Vuex's responsibility to persist that state.

Will there be any side effects of storing the state of the store using the vuex-persist module?

It depends on what your application is, but it should not
Just be careful about the size of the local storage, which is quite large but not infinite.


Q:

Is it ok to create a tag to help readers ask programming questions related to my book?

My publisher has this old-school forum for readers of my book to ask programming questions related to its content and code samples.
I'd like to direct them over to Stack Overflow, but want a good way to identify them so I can proactively answer them. The book is on Android, so tagging them as such isn't going to help me narrow it down any.
Is it ok to create a tag specifically for the book? The book's title is Professional Android 4 Application Development -- I was going to suggest readers tag their related questions PA4AD.

A:

There's a considerable chance that someone finding SO through your invitation will not have sufficient reputation to apply the tag if it does not yet exist. I don't see anything wrong with you applying it to the first question because:

It describes the question
It's not a meta tag
It's not like we don't have questions tagged with book titles to begin with (e.g., sicp, clrs, kr-c)
It's not like we don't have popular authors that sometimes answer questions about their books here.
Saving people from cruddy forums is an act of kindness and such questions would probably be on topic.
You have the rep to do it
Thanks for promoting SO

If you don't feel comfortable applying the tag, and it should be applied, flag for it.
Just remember, moderation is up to us. Also, I'm not an employee of Stack Exchange, so a subsequent answer from someone that IS an employee takes precedence over this answer.


Q:

User routing in ASP.NET MVC for urls like www.website.com/users/jeffAtwood

I am trying to show user details at the following url :
www.website.com/users/yasser
where the last entry yasser is the username I have tried a couple of routes but it just does nt work.
My User controller is as shown below.
public class UserController : Controller
{
    public ActionResult Index(string username)
    {
        var model = _service.GetUserDetails(username);
        return View(model);
    }
}

I have reffered this and couple of other links, but I really could not figure out how it worked.
Can some one help me out on this. Thanks
Edit :
My current route config is below
public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

A:

Routes executes from top to the bottom:
routes.MapRoute("UserProfile",
     "Users/{username}",
     new { controller = "User", action = "Index", username = string.Empty }
);

routes.MapRoute("Default",
     "{controller}/{action}/{id}",
     new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);


Q:

SQL query to calculate the sum of previous record in each record

I would like to get the calculated field (previous balance which equal to (sum of all the previous debit) - (sum of all previous credit))  in each row
for example :
for ID =5   , i want to get the previous balance of this record = (sum of debit amount) - (sum of credit amount) from ID=1 to ID =4
any suggestion please ?
i tried the LAG function but still didn't get what i want
thank you

A:

Hi if i understand your wall query and if you have SQL Server version greater or equal than 2008 you can use this query example  ::
Create table #tblVal
(
Id int identity(1,1),
Val int
)
--Inserting Records--
Insert into #tblVal values(720)
Insert into #tblVal values(720)
Insert into #tblVal values(500)
Insert into #tblVal values(720)
Insert into #tblVal values(539)
Insert into #tblVal values(341)

select * from #tblVal

SELECT *, SUM(Val) OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - Val as 'TotalSumPrevious',
     SUM(Val) OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as 'TotalSumCurrent'
FROM #tblVal

drop table #tblVal

AND take look at this link : https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-2017
Code edit with example picture :
Create table #tblVal
(
Id int identity(1,1),
Debit int,
Credit int
)
--Inserting Records--
Insert into #tblVal values(10,0)
Insert into #tblVal values(0,5)
Insert into #tblVal values(20,0)
Insert into #tblVal values(0,30)
Insert into #tblVal values(10,0)
Insert into #tblVal values(0,30)
Insert into #tblVal values(10,0)

select * from #tblVal

SELECT *,
     SUM(Debit - Credit)  OVER(ORDER BY Id Asc
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - (Debit - Credit) as 'PreviousBalance'
FROM #tblVal

drop table #tblVal


Q:

degradation of parallel loop performance

I am currently optimizing data processing logic for parallel execution.
I have noticed, that as the core count increases - data processing performance does not necessary increases the way I suppose it should.
Here is the test code:
Console.WriteLine($"{DateTime.Now}: Data processing start");
double lastElapsedMs = 0;
for (int i = 1; i <= Environment.ProcessorCount; i++)
{
    var watch = System.Diagnostics.Stopwatch.StartNew();
    ProccessData(i); // main processing method
    watch.Stop();
    double elapsedMs = watch.ElapsedMilliseconds;
    Console.WriteLine($"{DateTime.Now}: Core count: {i}, Elapsed: {elapsedMs}ms");
    lastElapsedMs = elapsedMs;
}
Console.WriteLine($"{DateTime.Now}: Data processing end");

and
public static void ProccessData(int coreCount)
{
    // First part is data preparation.
    // splitting 1 collection into smaller chunks, depending on core count
    ////////////////
    // combinations = collection of data
    var length = combinations.Length;
    int chuncSize = length / coreCount;
    int[][][] chunked = new int[coreCount][][];
    for (int i = 0; i < coreCount; i++)
    {
        int skip = i * chuncSize;
        int take = chuncSize;

        int diff = (length - skip) - take;
        if (diff < chuncSize)
        {
            take = take + diff;
        }

        var sub = combinations.Skip(skip).Take(take).ToArray();
        chunked[i] = sub.ToArray();
    }

    // Second part is itteration. 1 chunk of data processed per core.
    ////////////////
    Parallel.For(0, coreCount, new ParallelOptions() { MaxDegreeOfParallelism = coreCount }, (chunkIndex, state) =>
    {
        var chunk = chunked[chunkIndex];
        int chunkLength = chunk.Length;

        // itterate data inside chunk
        for (int idx = 0; idx < chunkLength; idx++)
        {
            // additional processing logic here for single data
        }
    });
}

The results are following:

As you can see from the result set - by using 2 cores instead of 1 - you can get almost ideal increase of performance (given the fact, that 1 core is running at 4700Mhz, but 2 cores run at 4600Mhz each).
After that, when the data was supposed to be processed in parallel on 3 cores, I was expecting to see the performance increase by 33% when compared to 2 core execution. The actual is 21.62% increase.
Next, as the core count increases - the degradation of "parallel" execution performance continues to increase.
In the end, when we have 12 cores results - the difference between actual and ideal results is more than twice as big (96442ms vs 39610ms)!
I have certainly not expected the difference to be as big. I have an Intel 8700k processor. 6 physical cores and 6 logical - total 12 Threads. 1 core running at 4700Mhz in turbo mode, 2C 4600, 3C 4500, 4C 4400, 5-6C 4400, 6C 4300.
If it matters - I have done additional observations in Core-temp:

when 1 core processing was running - 1 out of 6 cores was busy 50%
when 2 core processing was running - 2 out of 6 cores were busy 50%
when 3 core processing was running - 3 out of 6 cores were busy 50%
when 4 core processing was running - 4 out of 6 cores were busy 50%
when 5 core processing was running - 5 out of 6 cores were busy 50%
when 6 core processing was running - 6 out of 6 cores were busy 50%
when 7 core processing was running - 5 out of 6 cores were busy 50%, 1 core 100%
when 8 core processing was running - 4 out of 6 cores were busy 50%, 2 cores 100%
when 9 core processing was running - 3 out of 6 cores were busy 50%, 3 cores 100%
when 10 core processing was running - 2 out of 6 cores were busy 50%, 4 cores 100%
when 11 core processing was running - 1 out of 6 cores were busy 50%, 5 cores 100%
when 12 core processing was running - all 6 cores at 100%

I can certainly see that the end result should not be as performant as ideal result, because frequency per core decreases, but still.. Is there a good explanation why my code performs so badly at 12 cores? Is this generalized situation on every machine or perhaps a limitation of my PC?
.net core 2 used for tests
Edit: Sorry forgot to mention that data chunking can be optimized since I have done it as a draft solution. Nevertheless, splitting is done within 1 second time, so it's maximum 1000-2000ms added to the result execution time.
Edit2: I have just got rid of all the chunking logic and removed MaxDegreeOfParallelism property. The data is processed as is, in parallel. The execution time is now 94196ms, which is basically the same time as before, excluding chunking time. Seems like .net is smart enough to chunk data during runtime, so additional code is not necessary, unless I want to limit the number of cores used. The fact is, however, this did not notably increase the performance. I am leaning towards "Ahmdahl's law" explanation since nothing of what I have done increased the performance outside of bonds of an error margin.

A:

Yeah Ahmdahl's law. Performance speedup is never linear with the number of cores thrown at the problem.
Also reciprocals...


Q:

Why does lsof exceed kern.maxfiles?

Running Mojave 10.14.3 I notice there are currently more files open than the maxfiles allowed.  How is this possible?  In this case I do not have any symptoms or error messages, but in the past I have seen an error message about too many open files, and that time when I checked, lsof was exactly 10000.
Side node: Is there any harm in increasing maxfiles?
$ sysctl kern.maxfiles
kern.maxfiles: 10000
$ lsof | wc
   13242  124035 1982117

A:

lsof lists more than just file handles. Most notably, it includes program text mapped into all processes (e.g, the executable and all libraries it's using). There are a lot of these mappings in most GUI processes -- I count over 270 for the Finder, for instance -- and they don't consume file handles.
If you believe you are hitting the system's open file limit, go ahead and change kern.maxfile. However, it's more likely that you're hitting the per-process open file limit, which defaults to a lower number (7168 on my system) and can be changed using ulimit.


Q:

Convert a date vector into Julian day in R

I have a column of dates in the format:
16Jun10
and I would like to extract the Julian day.
I have various years.
I have tried the functions julian and mdy.date and it doesn't seem to work.

A:

Try the following to convert from class character(i.e. text) to class POSIXlt, and then extract Julian day (yday):
tmp <- as.POSIXlt("16Jun10", format = "%d%b%y")
tmp$yday
# [1] 166

For more details on function settings:
?POSIXlt
?DateTimeClasses

Another option is to use a Date class, and then use format to extract a julian day (notice that this class define julian days between 1:366, while POSIXlt is 0:365):
tmp <- as.Date("16Jun10", format = "%d%b%y")
format(tmp, "%j")
# [1] "167"

A:

Similarly:
require(lubridate)
x = as.Date('2010-06-10')
yday(x)

[1] 161

Also note, using lubridate:
> dmy('16Jun10')
[1] "2010-06-16 UTC"

A:

You can use R's insol package which has a JD(x, inverse=FALSE) function which converts POSIXct to Julian Day Number (JDN).
insol package also has JDymd(year,month,day,hour=12,minute=0,sec=0) for custom dates.
To display the whole Julian Date (JD) you possibly have to set options(digits=16).


Q:

How can I classify policy gradient methods in RL?

In the book of Barto and Sutton, there are 3 methods presented that solve an RL problem: DP, Monte Carlo, and TD. But which category does policy gradient methods (or actor-only methods) classify in? Should I classify them as the 4th method of solving a reinforcement learning problem?

A:

DP, Monte Carlo, and TD are methods of estimating returns. Policy gradient describes methods of learning a policy. So policy gradients serve a different purpose than the other things you mentioned. For clarity, you can use Monte Carlo or TD methods to estimate returns to construct the loss that you get your policy gradient from.


Q:

Find Word with Vowels in order C

So for a lab at uni... Ive been challenged to find all words in the usr/share/dict/linux.words
file using fopen, fgets etc with every vowel only once, in order.
i.e. facetious
So far I have the following code... but its flawed somewhere...
int all_vowels( char *s )
{
    const unsigned char *p = (const unsigned char *)s;

    char *v = malloc(sizeof(char *));
    char *vowel = v;

if(*p == '\0') return -1;

while( *p != '\0' )
{
        if( *p == 'a' || *p =='e' || *p =='i'|| *p =='o' || *p =='u' )
        {
            *v = *p;
            v++;
        }
        p++;
    }

    if ( *vowel == 'a' && (*vowel + 1) == 'e' && (*vowel + 2) == 'i' && (*vowel + 3) ==     'o' && (*vowel + 4) == 'u' )
    {
        return 1;
    }

    return -1;
}

int main (int argc, char *argv[])
{
    FILE *file;
    char line[BUFSIZ];

    if (( file = fopen("/usr/share/dict/words", "r") ) == NULL)
    {
        fprintf(stderr, "cannot open %s\n", "/usr/share/dict/words");
        exit(1);
    }

    while ( !feof(file) )
    {
        fgets(line, sizeof(line), file);
        if ( all_vowels(line) == 1 )
        {
            printf("%s\n", line);
        }
    }
    fclose(file);
    return 0;

}

Any tips would be great!!!
Im really confused at the moment...

A:

You are accessing v as if it were pointing to a location holding a number of characters, when indeed you only reserve space for one single char * (usually 4 byte on a 32 bit machine and 8 byte on a 64 bit machine):
char *v = malloc(sizeof(char *));

That might or might not be enough for what you are trying to store in it; in your case, the number of vowels, in any given word.
Whenever possible, you should avoid dynamic allocations; in your case, you don't need them, you can declare an array of fixed size instead of a char*:
char v[5];

In addition to that, you have to check if you have read 5 vowels already, so that you don't exceed the array size; if, after 5 vowels, you encounter another one, you can stop the check anyway; the currently encountered one has to be a duplicate vowel, the word will therefore not qualify.
The way you address characters is also a problem. Check again what * does: it dereferences the expression immediately to the right. In your case, it will always dereference v, then add something to it (which is also legal, since the result of dereferencing is a char). So if the first character where v points to is an a, the second an e, then *v will yield 'a', (*v + 1) will yield 'b', (*v +2) will yield 'c' and so on - you see, the result is an addition to the letter a by the given number; it doesn't matter at all what comes after the first character because you never access the value there. To achieve what you want with pointer arithmetic, you'd have to use parenthesis: *(v+1) - i.e., add 1 to the pointer v, then dereference it. This would yield the second character in the c string starting at v, i.e. 'e'.
Note that with v declared as above you can simply write v[0], v[1], v[2] and so on to address each character.
Aside from that, check the last comparison in your if condition, you had an 'e' instead of an 'u' there.
By the way, as a side note, and something to think about: There is a solution to your problem which does not require the v/vowel variables at all... only a single integer variable!


Q:

It is so clear for what am I

I am common, but special
I am everywhere
What special is, I expand when cooled
Shrink when heated
You will need me or you will die

Isn't it clear now what am I?

A:

 Water

I am common, but special
I am everywhere

 on Earth there is a lot of water so it's common
 But it is special because it facilitates life

What special is, I expand when cooled
Shrink when heated

 The density of ice is smaller than the density of liquid water

You will need me or you will die

 Try going a few weeks without water.


Q:

Color saturation cm 13

I have the nvidia shield k1 tablet. It's running cyanogenmod 13 nightly release. On the stock os there was options for color management. Is there any options for this on cm 13?

A:

You can manage color temperature under Settings - Display - LiveDisplay. Other than that there's no built-in option.

If the kernel supports it, some kernel management apps can also fine-tune color, although that's not universal across devices.


Q:

About saturated sets

The above paragraph claims that $C=p^{-1}(D)$ for some $D\subset Y$. I think $D=\{y\in Y| p^{-1}(y)\cap C\ne \emptyset\}$. Is this correct? Even if so, I can't prove it.
Is the converse true? That is, if $C$ is saturated, then $C=p^{-1}(D)$. I think I managed to prove one inclusion. If $y\in D$, then I must prove that $p^{-1}(y)\in C$. Let $x\in p^{-1}(y)$. Then $p(x)=y\in D$ and so $x=p^{-1}(y)$. Since $y\in D$, $x\cap C\ne \emptyset$, and since $C$ is saturated, $x\in C$. This proves $p^{-1}(D)\subset C$

A:

Suppose that $C$ is saturated. I claim that $p^{-1}[p[C]] = C$ and so $C$ is the pre-image of a subset of $Y$, as claimed (so we can take $D = p[C]$).
Note that by definition we always have $p^{-1}[p[C]] \supseteq C$, because $c \in C$ implies $p(c) \in p[C]$ and so $c \in p^{-1}[p[C]]$. Now suppose that $x \in p^{-1}[p[C]]$. This means that $p(x) \in p[C]$ or there is a $c \in C$ such that $p(c) = p(x)$.
So $C$ intersects $p^{-1}[\{p(x)\}$ and by being saturated, $p^{-1}[\{p(x)\}] \subseteq C$ ($C$ contains every fibre it intersects). And in particular, $x \in p^{-1}[\{p(x)\}] \subseteq C$, showing the reverse inclusion.
Reversely it's easy to check that $C = p^{-1}[D]$ is indeed always a saturated subset of $X$.


Q:

Laravel 4 PHP: Routes Order Issue

EDIT:
I am using Laravel 4 PHP and initially I thought this problem was related to the 'link_to_route' method on a webpage so you can simply link to another webpage that does not contain any dynamic data.
However, I am discovering that the order you list your Routes will ultimately determine if your routes are successfully reached or not.
Authors2.php (Controller)
class Authors2_Controller extends BaseController {

public $restful = true;

public function contact() {

    return View::make('authors2.index')
    ->with('title','Authors and Books')
    ->with('authors2', Author2::orderBy('name')->get());
}

public function getnew() {

    return View::make('authors2.new')
        ->with('title', 'Add New Author');
}

Routes.php
Route::get('authors2', array('as'=>'authors2', 'uses' =>'Authors2_Controller@contact'));

Route::get('authors2/new', array('as'=>'new_author', 'uses'=>'Authors2_Controller@getnew'));

index.blade.php (view)
@extends('layouts.default')

@section('content')

Authors2 Home Page

@foreach($authors2 as $author2)

{{ link_to_route('author2', $author2->name, $parameters = array($author2->id)) }}

@endforeach

{{ link_to_route('new_author', 'Add Author') }}

@endsection

When I click on the 'Add Author' link, I get the error 'Trying to get property of non-object' error.
EDIT:
So now when I change the order of the routing where if I list the 'authors2/new' route BEFORE the 'authors2' route, the route will actually work:
Route::get('authors2/new', array('as'=>'new_author', 'uses'=>'Authors2_Controller@getnew'));
Route::get('authors2', array('as'=>'authors2', 'uses' =>'Authors2_Controller@contact'));

Does this have to deal with how Routes are first received and if so, why does this happen?

A:

As mentioned by @Barry_127, Laravel will match routes based from most specific to least specific.  So its good practice to list your routes in that order.


Q:

match algorithm javascript without regex

I need an algorithm for solving this problem withou using regEx
"Does a string follow a 123-456-7890 pattern like a phone number?
This problem asks you to create a function that can accept a string and then
determine if that string follows the pattern presented. For example, if you pass
the string “123-45-67”, this would not match the pattern. But, if you passed the
string “407-695-0100”, this would match the pattern. The only value returned
from the function should be a Boolean; that is, true if the string matches the
pattern or false if it does not"

A:

Since you want an algorithm:
function matchTele(txt, i){
    i = i || 0;
    if(txt.length != 12) return false;
    if(i == txt.length) return true;
    if(i == 3 || i == 7){
        return txt[i] == "-" ? matchTele(txt, ++i) : false;
    }
    return isNaN(parseInt(txt[i], 10)) ? false : matchTele(txt, ++i);
}

matchTele("000-000-0000")  //true
matchTele("aaa-aaa-aaaa")  //false - not a valid digit
matchTele("000-00-0000")   //false - length not match


Q:

fail2ban couriertcpd: LOGIN FAILED not banning

My fail2ban is not banning as I expect.
An example of my log entries are :-
Jul 26 07:11:29 mail couriertcpd: LOGIN FAILED, user=sally, ip=[::ffff:54.191.110.169]
Jul 26 07:13:22 mail couriertcpd: LOGIN FAILED, user=ddos, ip=[::ffff:54.193.13.22]
Jul 26 07:14:45 mail couriertcpd: LOGIN FAILED, user=sally, ip=[::ffff:54.191.110.169]

My courierstmp setting is
more /etc/fail2ban/filter.d/courierlogin.conf
[INCLUDES]
before = common.conf
[Definition]
_daemon = (?:courier)?(?:imapd?|pop3d?)(?:login)?(?:-ssl)?
failregex = ^%(__prefix_line)sLOGIN FAILED, user=.*, ip=\[<HOST>\]$

ignoreregex =

Running a test yields no results.
 fail2ban-regex -v  /var/log/mail.log /etc/fail2ban/filter.d/courierlogin.conf

Running tests
=============

Use   failregex file : /etc/fail2ban/filter.d/courierlogin.conf
Use         log file : /var/log/mail.log

Results
=======

Failregex: 0 total
|-  #) [# of hits] regular expression
|   1) [0] ^\s*(<[^.]+\.[^.]+>)?\s*(?:\S+ )?(?:kernel: \[\d+\.\d+\] )?(?:@vserver_\S+ )?(?:(?:\[\d+\])?:\s+[\[\(]?(?:courier|couriertcpd)?(?:imapd?|pop3d?)(?:login)?(?:-ssl)?(?:\(\S+\))?[\]\)]?:?|[\[\(]?(?:courier|couriertcpd)?(?:imapd?|pop3d?)(?:login)?(?:-ssl)?(?:\(\S+\))?[\]\)]?:?(?:\[\d+\])?:?)?\s(?:\[ID \d+ \S+\])?\s*LOGIN FAILED, user=.*, ip=\[<HOST>\]$
`-

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
|  [296708] MONTH Day Hour:Minute:Second
|  [0] WEEKDAY MONTH Day Hour:Minute:Second[.subsecond] Year
|  [0] WEEKDAY MONTH Day Hour:Minute:Second Year
|  [0] WEEKDAY MONTH Day Hour:Minute:Second
|  [0] Year/Month/Day Hour:Minute:Second
|  [0] Day/Month/Year Hour:Minute:Second
|  [0] Day/Month/Year2 Hour:Minute:Second
|  [0] Day/MONTH/Year:Hour:Minute:Second
|  [0] Month/Day/Year:Hour:Minute:Second
|  [0] Year-Month-Day Hour:Minute:Second[,subsecond]
|  [0] Year-Month-Day Hour:Minute:Second
|  [0] Year.Month.Day Hour:Minute:Second
|  [0] Day-MONTH-Year Hour:Minute:Second[.Millisecond]
|  [0] Day-Month-Year Hour:Minute:Second
|  [0] Month-Day-Year Hour:Minute:Second[.Millisecond]
|  [0] TAI64N
|  [0] Epoch
|  [0] ISO 8601
|  [0] Hour:Minute:Second
|  [0] <Month/Day/Year@Hour:Minute:Second>
|  [0] YearMonthDay Hour:Minute:Second
|  [0] Month-Day-Year Hour:Minute:Second
`-

Lines: 296708 lines, 0 ignored, 0 matched, 296708 missed

I have tried replacing courier with couriertcpd without avail. I am not not sure what else I can do to get this working.

A:

After much searching, I eventually realised that the supplied filter regex was all-things-to-all-people. I didn't need that, so I changed the regex for my specific situation.
# OLD
# failregex = ^%(__prefix_line)sLOGIN FAILED, user=.*, ip=\[<HOST>\]$
# NEW
failregex = couriertcpd: LOGIN FAILED, user=.*, ip=\[<HOST>\]$

That worked and I am happily banning away those pests.


Q:

centos ruby 1.8.7 repository

I can't find a repository that contains ruby 1.8.7.  All repos only contain 1.8.5 or 1.8.6 versions.
Does anyone know of any repos with ruby-1.8.7?

A:

RBEL Repo provides Ruby packages for RHEL based distro's.


Q:

Which is faster — sorting or multiplying a small array of elements?

Reading through Cactus Kev's Poker Hand Evaluator, I noticed the following statements:
At first, I thought that I could always simply sort the hand first before passing it to the evaluator; but sorting takes time, and I didn't want to waste any CPU cycles sorting hands. I needed a method that didn't care what order the five cards were given as.

...

After a lot of thought, I had a brainstorm to use prime numbers. I would assign a prime number value to each of the thirteen card ranks... The beauty of this system is that if you multiply the prime values of the rank of each card in your hand, you get a unique product, regardless of the order of the five cards.

...

Since multiplication is one of the fastest calculations a computer can make, we have shaved hundreds of milliseconds off our time had we been forced to sort each hand before evaluation.
I have a hard time believing this.
Cactus Kev represents each card as a 4-byte integer, and evaluates hands by calling eval_5cards( int c1, int c2, int c3, int c4, int c5 ). We could represent cards as one byte, and a poker hand as a 5-byte array. Sorting this 5-byte array to get a unique hand must be pretty fast. Is it faster than his approach?
What if we keep his representation (cards as 4-byte integers)? Can sorting an array of 5 integers be faster than multiplying them? If not, what sort of low-level optimizations can be done to make sorting a small number of elements faster?
Thanks!
Good answers everyone; I'm working on benchmarking the performance of sorting vs multiplication, to get some hard performance statistics.

A:

Without testing, I'm sympathetic to his argument.  You can do it in 4 multiplications, as compared to sorting, which is n log n.  Specifically, the optimal sorting network requires 9 comparisons.  The evaluator then has to at least look at every element of the sorted array, which is another 5 operations.

A:

Of course it depends a lot on the CPU of your computer, but a typical Intel CPU (e.g. Core 2 Duo) can multiply two 32 Bit numbers within 3 CPU clock cycles. For a sort algorithm to beat that, the algorithm needs to be faster than 3 * 4 = 12 CPU cycles, which is a very tight constraint. None of the standard sorting algorithms can do it in less than 12 cycles for sure. Alone the comparison of two numbers will take one CPU cycle, the conditional branch on the result will also take one CPU cycle and whatever you do then will at least take one CPU cycle (swapping two cards will actually take at least 4 CPU cycles). So multiplying wins.
Of course this is not taking the latency into account to fetch the card value from either 1st or 2nd level cache or maybe even memory; however, this latency applies to either case, multiplying and sorting.

A:

Sorting is not intrinsically harder than multiplying numbers.  On paper, they're about the same, and you also need a sophisticated multiplication algorithm to make large multiplication competitive with large sort.  Moreover, when the proposed multiplication algorithm is feasible, you can also use bucket sort, which is asymptotically faster.
However, a poker hand is not an asymptotic problem.  It's just 5 cards and he only cares about one of the 13 number values of the card.  Even if multiplication is complicated in principle, in practice it is implemented in microcode and it's incredibly fast.  What he's doing works.
Now, if you're interested in the theoretical question, there is also a solution using addition rather than multiplication.  There can only be 4 cards of any one value, so you could just as well assign the values 1,5,25,...,5^12 and add them.  It still fits in 32-bit arithmetic.  There are also other addition-based solutions with other mathematical properties. But it really doesn't matter, because microcoded arithmetic is so much faster than anything else that the computer is doing.


Q:

Grails spring security authentication provider and custom filter

I'm new to the grails language and am using grails 2.5.6 with spring-security-core 2.0.0 plugin at work.
I've defined my provider as this in the config.groovy file:
grails.plugin.springsecurity.providerNames = [
    'myCustomAuthenticationProvider',
    'anonymousAuthenticationProvider',
    'rememberMeAuthenticationProvider'
]

and my filter as:
grails.plugin.springsecurity.filterChain.filterNames = [
    'securityContextPersistenceFilter',
    'myCustomFilter',
    'exceptionTranslationFilter',
    'anonymousAuthenticationFilter',
    'filterInvocationInterceptor'
]

My resources.groovy file:
myCustomAuthenticationProvider(MyCustomAuthenticationProvider)
myCustomFilter(myCustomFilter)

Both my filter and provider are java classes provided by a jar. The filter extends OncePerRequestFilter and has the AuthenticationManager and AuthenticationEntryPoint injected. My provider implements AuthenticationProvider
The problem is when I put a debug point in my filter to see the AuthenticationManager and see the `AuthenticationProviders that are in it's list, I don't see my custom provider at all. I still see the default spring-security-core plugin providers.
I also don't understand why my custom filter gets initiated even if I remove it from the list of filters. It seems like just defining it in the resources.groovy file is enough for it to get initiated.
Just realized that the reason it gets initiated is because on startup it is being added to the spring container.
Thanks

A:

Figured it out. I ended up not defining the filterNames and in my resources.groovy file I have this:
authenticationProcessingFilter(MyCustomFilter) {
    ...args
}

And the issue with my provider on construction getting the providers doesn't matter. Turns out spring security core doesn't change it until after that.


Q:

How to I read several lines in a file faster using python?

As of now I use the following python code:
file = open(filePath, "r")
lines=file.readlines()
file.close()

Say my file has several lines (10,000 or more), then my program becomes slow if I do this for more than one file. Is there a way to speed this up in Python? Reading various links I understand that readlines stores the lines of file in memory thats why the code gets slow.
I have tried the following code as well and the time gain I got is 17%.
lines=[line for line in open(filePath,"r")]

Is there any other module in python2.4 (which I might have missed).
Thanks,
Sandhya

A:

for line in file:

This gives you an iterator that reads the file object one line at a time and then discards the previous line from memory.

A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. However, using seek() to reposition the file to an absolute position will flush the read-ahead buffer. New in version 2.3.

Short answer: don't assign the lines to a variable, just perform whatever operations you need inside the loop.