text:
Q: change enter key behavior in jquery autocomplete I'm using jquery's autocomplete widget and I want the enter key to serve two purposes:

*

*If the user hits the enter key when focus is on the search box, it should open a form (regardless of current matches).

*If the system finds a match and the user selects it from the list by pressing enter, it should display a different dialog.

The problem is I haven't been able to tell events apart, as it seems that when I choose an option from the autocomplete list of matches, the text box retains focus.
This is where I'm at right now:
My autocomplete function:
jQuery('#nom_id_busqueda').autocomplete({
    source: function(request, response) {
        jQuery.ajax({
            url: myUrl,
            dataType: "json",
            data: {term: encodeURI(request.term)},
            success: function (answer) {
               if (answer.length == 0) {
                  jQuery("#encontrada").hide();
                  jQuery("#no_encontrada").show();
               }
               else {
                  jQuery("#no_encontrada").hide();
                  response(answer);
               }
            },
            error : function(){ alert("Something went wrong."); },
        });
    },
    minLength:2,
    delay:400,
    select: function(event, ui) {
        if (ui.item){
            jQuery("#nom_id_busqueda").val(ui.item.label);
            jQuery("#per_busq").val(ui.item.value);
            event.preventDefault();
            jQuery("#encontrada").show();
        }
    },
});

and my event listener for the keystroke:
jQuery('#nom_id_busqueda').keydown(function (e){
    if(e.keyCode == 13){
        if(jQuery("#nom_id_busqueda").is(":focus")) {
            jQuery("#no_encontrada").hide();
            jQuery("#encontrada").hide();
            jQuery("#div_formu_busq").dialog("close");
            jQuery("#div_formu_per").dialog("open");
        }
    }
});

Any ideas? Thanks.
Update:
Here's my DOM:
<div id="div_formu_busq" class="formu_fs" title="<?php echo JText::_('COM_BUSQUEDA_PERSONA');?>">
<form name="formu_busq" onsubmit="return false;">
    <fieldset>
        <legend><?php echo JText::_('COM_BUSCAR_EN_EXISTENTES');?></legend>
        <?php echo JText::_("COM_ESCRIBA_EL_NOMBRE_O_EL_NUMERO_DE_IDENTIFICACION_PARA_BUSCAR_EN_EL_SISTEMA").' '. JText::_("COM_ENTER_LO_LLEVA_AL_FORMULARIO") ;?>

            <?php echo JText::_("COM_NOMBRE_O_NUMERO_DE_DOCUMENTO");?>
            <input type="text" name="nom_id_busqueda" id="nom_id_busqueda" />

    <input type="hidden" name="per_busq" id="per_busq" />
</form>

    <fieldset>

<?php echo JText::_("COM_SE_ENCONTRO_UNA_PERSONA_CON_EL_MISMO_NOMBRE_Y_O_IDENTIFICACION");?> <?php echo JText::_('COM_IR_A_PERSONA'); ?>

    </fieldset>

    <fieldset>

            <?php echo JText::_("COM_NO_SE_ENCONTRARON_RESULTADOS_SIMILARES");?>
            <?php echo JText::_('COM_AGREGAR_USUARIO'); ?>

    </fieldset>

A: Okay, I found the way! In the event listener I added the !jQuery(this).data( "ui-autocomplete" ).menu.active condition, so my keystroke listener now looks like this:
jQuery('#nom_id_busqueda').keydown(function (e){
    if(e.keyCode == 13 && !jQuery( this ).data( "ui-autocomplete" ).menu.active){
        if(jQuery("#nom_id_busqueda").is(":focus")) {
            jQuery("#no_encontrada").hide();
            jQuery("#encontrada").hide();
            jQuery("#div_formu_busq").dialog("close");
            jQuery("#div_formu_per").dialog("open");
        }
    }
});

Thanks anyway.
Edit:
I tried using keyup instead of keydown, but it seems it somehow breaks the behavior I worked so hard to get.
Warning:
For this to work you need to place the keydown(...) code so that it gets executed before the autocomplete(...) initialization, otherwise the autocomplete will handle the event and it won't work.


text:
Q: Is it possible to debug UI App and AAR simultaneously? we are working on an android project and want to develop two binaries that work together: a UI App, and an AAR library back end.  The idea is that the AAR may be used in the future with other UIs.
So, we have one developer working on the AAR project, and another developer working on a UI project.  Is there any way to debug the two simultaneously; i.e., run the UI+AAR and trace execution back and forth between the two, setting breakpoints and watches on either side, etc.?
I've done the analogous thing in .NET, develop a UI EXE+DLL back end with multiple "projects" in a single "solution", debugging the whole thing at once; it's a really nice way to develop.  Is there any way to achieve this with android studio?
Thanks.

A: You can add both parts to one project as modules. Then you add a direct dependency in your UI module to the second module. Now you can debug both at the same time.
This is the best solution if you also want to be able to make changes in both parts.

If you want to debug any library in combination with your code, Android Studio also supports breakpoints in decompiled files (or in the attached source if there is one).

redpajama_set_name: RedPajamaStackExchange


text:
Q: AttributeError: 'module' object has no attribute python I am fairly new to python and have tried installing python 2.7.9 following the steps described here. The installation failed with the following error:
python make: *** [libinstall] Error 1

I tried reinstalling the previous version of python:
sudo apt-get install --reinstall  python2.7-dev

The installation proceeded normally. However, now, when trying to import hashlib I get the following errors:
Traceback (most recent call last):
  File "./server.py", line 5, in <module>
    import hashlib
  File "/usr/lib/python2.7/hashlib.py", line 138, in <module>
    _hashlib.openssl_md_meth_names)
AttributeError: 'module' object has no attribute 'openssl_md_meth_names'

I am also unable to install any packages using pip as the only output provided is the following:
Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

I installed python-setuptools:
sudo apt-get install python-setuptools

pip still provides the same output regardless of the input. Following this question I ran:
curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
chmod +x ez_setup.py
python ez_setup.py

The output is:
Traceback (most recent call last):
  File "ez_setup.py", line 19, in <module>
    import tempfile
  File "/usr/lib/python2.7/tempfile.py", line 35, in <module>
    from random import Random as _Random
  File "/usr/lib/python2.7/random.py", line 49, in <module>
    import hashlib as _hashlib
  File "/usr/lib/python2.7/hashlib.py", line 138, in <module>
    _hashlib.openssl_md_meth_names)
AttributeError: 'module' object has no attribute 'openssl_md_meth_names'

Where is the issue?
Edit #1:
The output of sudo apt-get install --reinstall  python2.7-dev seems normal:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libjs-sphinxdoc linux-headers-generic linux-image-generic
Use 'apt-get autoremove' to remove them.
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 310 not upgraded.
Need to get 0 B/269 kB of archives.
After this operation, 0 B of additional disk space will be used.
(Reading database ... 219657 files and directories currently installed.)
Preparing to unpack .../python2.7-dev_2.7.6-8_amd64.deb ...
Unpacking python2.7-dev (2.7.6-8) over (2.7.6-8) ...
Processing triggers for man-db (2.6.7.1-1) ...
Setting up python2.7-dev (2.7.6-8) ...

Edit #2:
I have found this question which tackles a similar issue. It points to this thread which uses a checkinstall in order to retrieve all written files and creating a .deb package from them:
sudo apt-get install checkinstall  # install the checkinstall package
cd /home/user/Python-2.7.9
sudo checkinstall -D --fstrans=no make install   # make the deb package

Upon running the last command the output provided is identical with the one given by make install:
...
Listing /usr/lib/python2.7/xml/parsers ...
Compiling /usr/lib/python2.7/xml/parsers/__init__.py ...
Compiling /usr/lib/python2.7/xml/parsers/expat.py ...
Listing /usr/lib/python2.7/xml/sax ...
Compiling /usr/lib/python2.7/xml/sax/__init__.py ...
Compiling /usr/lib/python2.7/xml/sax/_exceptions.py ...
Compiling /usr/lib/python2.7/xml/sax/expatreader.py ...
Compiling /usr/lib/python2.7/xml/sax/handler.py ...
Compiling /usr/lib/python2.7/xml/sax/saxutils.py ...
Compiling /usr/lib/python2.7/xml/sax/xmlreader.py ...
Compiling /usr/lib/python2.7/xmllib.py ...
Compiling /usr/lib/python2.7/xmlrpclib.py ...
Compiling /usr/lib/python2.7/zipfile.py ...
make: *** [libinstall] Error 1

Edit #3:
It appears that all scripts are unable to run. I am working on signing algorithms(used in bitcoin) and the tools mentioned here(bu, tx) are all outputting the same error:
 Traceback (most recent call last):
  File "/usr/local/bin/bu", line 5, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

Edit #4:
I have also tried the approach mentioned here. The output of python get-pip.py
is the following:
Traceback (most recent call last):
  File "get-pip.py", line 28, in <module>
    import tempfile
  File "/usr/lib/python2.7/tempfile.py", line 35, in <module>
    from random import Random as _Random
  File "/usr/lib/python2.7/random.py", line 49, in <module>
    import hashlib as _hashlib
  File "/usr/lib/python2.7/hashlib.py", line 138, in <module>
    _hashlib.openssl_md_meth_names)
AttributeError: 'module' object has no attribute 'openssl_md_meth_names'

If I comment the line:
import tempfile

then execution continues up to line 141:
Traceback (most recent call last):
  File "get-pip.py", line 19892, in <module>
    main()
  File "get-pip.py", line 141, in main
    tmpdir = tempfile.mkdtemp()
NameError: global name 'tempfile' is not defined

meaning that the import of the following libraries:
import os.path
import pkgutil
import shutil
import sys
import struct
# import tempfile

succeeds. This makes me believe that the installation of python2.7.9 is only partially complete(as wisely suggested in the comments to this question).
Edit #5:
I have reran the configuration and compilation steps:
./configure --prefix=/usr       \
            --enable-shared     \
            --with-system-expat \
            --with-system-ffi   \
            --enable-unicode=ucs4 &&
make

The builds terminates with:
Python build finished, but the necessary bits to build these modules were not found:
bsddb185           dl                 imageop
sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

running build_scripts

Are these modules essential?

A: It's an old thread, but my answer might help others in the future.
Step 1. check _hashlib.openssl_md_meth_names through the following, and no error shows up.
$ python
Python 2.7.9 (default, Oct 20 2016, 07:39:46)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import _hashlib
>>> _hashlib.openssl_md_meth_names
frozenset(['SHA256', 'SHA512', 'dsaWithSHA', 'md4', 'sha256', 'sha512', 'RIPEMD160', 'md5', 'whirlpool', 'SHA1', 'SHA224', 'SHA', 'SHA384', 'ecdsa-with-SHA1', 'MD4', 'DSA', 'sha1', 'DSA-SHA', 'sha224', 'dsaEncryption', 'ripemd160', 'sha', 'MD5', 'sha384'])
>>>

Step 2:
change the followng line:
File "/usr/lib/python2.7/random.py", line 49, in <module>
import hashlib as _hashlib

into:
import _hashlib

Then it's done.

A: in my case, i am using virtualenv just copied virtualenv folder from old machine into new ... in my new when i tried to install pip packages it threw this error..
i resolved this issue by creating new virtualenv reinstalled pip packages once again...

A: File "/usr/lib/python2.7/hashlib.py", line 138, in
    _hashlib.openssl_md_meth_names)
AttributeError: 'module' object has no attribute 'openssl_md_meth_names'
Can be fixed by running:
pip install hashlib

or
easyinstall hashlib

or
easy_install-2.7 hashlib


text:
Q: "Cannot read property 'hub' of undefined" in aspx page with declare SignalR Library I have added SignalR script in my ASPX page. But when the page loads:, it gets error in console: Cannot read property 'hub' of undefined. Here my code: ( all of this code is placed in "asp:Content" tag)

<script src="/Js/jquery-1.10.2.min.js"></script>
    <!--Reference the jQuery library. -->
<script src="/Js/jquery.signalR-2.1.2.min.js"></script>

    <!--Reference the autogenerated SignalR hub script. -->
<script src="http://myhost/signalr/hubs"></script>

<script type="text/javascript" src="../Js/tooltip.js"></script>
    <script type="text/javascript">
        $(function () {
            console.log($.connection);
            $.connection.hub.url = 'http://myhost/signalr';
            // Declare a proxy to reference the hub.
            var chat = $.connection.myHub1;
        });

    </script>

When I declare this script in plain html page, it works successfully.
Anyone have idea. Thanks.
Code: enter image description here
Error: enter image description here

A: This problem happens, because your addressing is mismatch.
change
<script src="/Js/jquery-1.10.2.min.js"></script>
    <!--Reference the jQuery library. -->
<script src="/Js/jquery.signalR-2.1.2.min.js"></script>

to
<script src="~/Js/jquery-1.10.2.min.js"></script>
    <!--Reference the jQuery library. -->
<script src="~/Js/jquery.signalR-2.1.2.min.js"></script>

And be sure that the "jquery.signalR-2.1.2.min.js" and "jquery-1.10.2.min.js" files are in the "js" folder in root directory of your site.


text:
Q: Integrate wordpress blog with joomla website I have a website which I developed  in joomla and a blog in wordpress. I would like to integrate that blog with my Joomla website without using wrappers or CorePHP component.
Is there any way to do this?

A: I think the best thing you can hope for in this situation is going to be to have one be a subdomain of the other, and when you want one system to reference the other you'll need to link to it.  Also, if you could move one of the systems to be a subfolder of the other system, you'll probably get away with having relative links.
The only other option would be to literally migrate all of your content from one system to the other manually.

A: What about using a feed reader in your Joomla website to show your Wordpress posts?


text:
Q: Summarize by year and create a new variable containing a vector / list of unique values for each row I have a dataset with all natural disaster that occured over a certain time period. I would like to summarize them by year and state. When summarizing I would like to create a variable (= d_disasters) that shows me the unique types of natural disasters, e.g. for Texas, I would expect to only show Hurricane.
I am currently using dplyr:group_by and dplyr::summarize to summarize my data by year and by state & dplyr::mutate and dplyr:map_int to create new variables with the total number of natural disasters per year ($n_disasters using length) and the unique number of natural disasters ($n_distinct using n_distinct()).
Starting dataset:
structure(list(year = c(1998, 1998, 1998, 1998, 1998), country = c("US",
"US", "US", "US", "US"), state = c("Texas", "Texas", "California",
"New York", "New York"), deaths = c(12, 5, 9, 10, 18), injured = c(3,
1, 3, 5, 9), disastertype = c("Hurricane", "Hurricane", "Wild fire",
"Flood", "Epidemic")), class = "data.frame", row.names = c(NA,
-5L))

Result dataset:
structure(list(year = c(1998, 1998, 1998), state = c("California",
"New York", "Texas"), u_disastertype = c("Wild fire", "Flood, Epidemic",
"Hurricane"), disastertype = c("Wild fire", "Flood, Epidemic",
"Hurricane, Hurricane"), deaths = c(9, 28, 17), injured = c(3,
14, 4), n_distinct = c(1L, 2L, 1L), n_disasters = c(1L, 2L, 2L
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-3L), groups = structure(list(year = 1998, .rows = structure(list(
    1:3), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
"list"))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-1L), .drop = TRUE))

EDIT: Edited for clarification.

A: Try aggregate. This takes the output of 2 3 aggregates and puts them together.
list2 <- function(x){ c(unique(x),length(table(x))) }

lt <- list(year=dat$year, county=dat$country, state=dat$state )

data.frame( aggregate( dat[,c(4,5)], lt, sum ),
  setNames( aggregate( dat$disastertype, lt, list2 )[,4, drop=F], colnames(dat)[6] ),
  setNames( aggregate( dat$disastertype, lt, length )[,4, drop=F], "n_disasters") )

  year county      state deaths injured       disastertype n_disasters
1 1998     US California      9       3       Wild fire, 1           1
2 1998     US   New York     28      14 Flood, Epidemic, 2           2
3 1998     US      Texas     17       4       Hurricane, 1           2

Not sure if you want to keep the n_... columns or not though...
EDIT: added "n_disasters"
EDIT2: added suggestion to include "distinct disasters"

A: The solution using dplyr with group_by and summarize. The key part is to run u_disastertype = toString(unique(disastertype)), before disastertype = paste(disastertype, collapse = ', '),
naturaldisaster2 <- naturaldisaster %>%
  group_by(year, state) %>%
  summarise(
    u_disastertype = toString(unique(disastertype)),
    disastertype = paste(disastertype, collapse = ', '),
    deaths=sum(deaths),
    injured=sum(injured)
    )

The answer is based on this Stackoverflow answer to a similar question, where only one operation was run on the column whereas I am running two operations on the same column: https://stackoverflow.com/a/46367425/11045110


text:
Q: AS3 - Make object obscure specific objects Right, so here's the scenario: I have 4 objects, A, B, C and D. What I want is that C obscures A, but not B. Similarly, I want D to obscure B, but not A. A and B can overlap each other in any order, it doesn't matter.
In other words, what I want is an object (C) to be able to cover one object (A) but not another (B), even if it comes into contact with it. Same with D, which can cover B but not A, even if it comes into contact with it. The problem is that I can't think of a layer configuration that allows this: D will always be higher than both A and B, and thus will obscure both.
I'm not expecting anyone to come up with some unfathomably clever configuration, but I'm wondering if there's some kind of ActionScript that can do this. In particular, I would like A and B to be dynamic TextFields, and C and D to be MovieClips of any shape (i.e. not a rectangle).
Hope this is possible!

A: The order in which you add them to the stage determines what shows up in front of what. Basically, whatever is added last is on top, whatever is added first is on the bottom.
If you want C to cover A but not B and D to cover B but not A, you have a problem. Think about what would happen if all four were overlapping each other. C would be trying to cover A and let B show through, while D would be trying to cover B and let A show through. Not possible.

A: You could use blitting, where you're not actually adding the items to the stage, but instead are using copyPixels() or draw() to draw the pixels. If you did this, then you could determine what parts of the objects would or would not be drawn. Check out this blog post for an overview of the technique http://www.developria.com/2010/02/dealing-with-bitmapdata.html.

A: Assuming I understood what you want, use the setChildIndex() function of the parent/containing MovieClip. If all of your ABCD objects were contained in a MovieClip named parent_mc, you can do something like:
parent_mc.setChildIndex(a_mc, parent_mc.numChildren-1); // Throw "a_mc" on top
parent_mc.setChildIndex(b_mc, parent_mc.numChildren-1); // Throw "b_mc" on top

This wouold result in b_mc being on top of a_mc, etc...
You chould also throw something on the very bottom of the display list:
 parent_mc.setChildIndex(b_mc, 0);

documentation here: DisplayObjectContainer.setChildIndex()


text:
Q: Scrape wikipedia "prop=linkshere" more efficiently? My scraping code works, but it seems inefficient: I have to send a bazillion "continue" requests to get it all.  Here's the initial request:
https://en.m.wikipedia.org/w/api.php?action=query&prop=linkshere&format=json&maxlag=2&titles=Korn

and I get back a continuation number, so I follow with:
https://en.m.wikipedia.org/w/api.php?action=query&prop=linkshere&format=json&maxlag=2&titles=Korn&lhcontinue=20653

over and over and over until the end. Each request gives a tiny amount of the total data.
Am I missing something simple to get more data on each request?  Thanks!

A: The default lhlimit for each response is 10. Change it to max, e.g. https://en.m.wikipedia.org/w/api.php?action=query&prop=linkshere&format=json&maxlag=2&titles=Korn&lhlimit=max .


text:
Q: Why can't customize sshd log info as sshd.log? My os info:
cat /proc/version
Linux version 2.6.32-042stab127.2 (root@kbuild-rh6-x64.eng.sw.ru) (gcc version 4.4.6 20120305 (Red Hat 4.4.6-4) (GCC) ) #1 SMP Thu Jan 4 16:41:44 MSK 2018

I want to customize sshd log into a specified file--/var/log/sshd.log.
vim /etc/ssh/sshd_config
SyslogFacility local0

vim /etc/rsyslog.conf
local0.*    /var/log/sshd.log

systemctl restart sshd
systemctl restart rsyslog

Login in the vps with ssd.
cat /var/log/sshd.log
Nothing in /var/log/sshd.log.
How to customize sshd log info as  sshd.log


text:
Q: why does a dropdown combobox list (select html tag) disappear very quickly in IE 7 but works fine in firefox i have a combobox and its on a narrow part of a webpage. below is my dropdown html.
THe issue is that in IE 7 only (works fine in firefox) after i click on the dropdown, the list of items pops up and i go to click on an item in the list and it disappears before i get a chance to click.
It seems to work fine in IE8 as well but in IE7 (most of my users) no one has time to click before the list disappears.
      <select id="staticData">
          <option value="">(Please select)</option>
             <optgroup label="Geographical">
                <option value="B">United states of AMerica</option>
                <option value="C">Europe</option>
                <option value="D">Asia</option>
             </optgroup>
             <optgroup label="Related">
                 <option value="RoadmapItem">Roadmap items</option>
             </optgroup>
     </select>

A: This fixed it.
http://css-tricks.com/select-cuts-off-options-in-ie-fix/


text:
Q: `prependToContext` in TinyMCE Here is a piece of code from TinyMCE Link plugin:
editor.addMenuItem('link', {
    icon: 'link',
    text: 'Insert/edit link',
    shortcut: 'Meta+K',
    onclick: createLinkList(showDialog),
    stateSelector: 'a[href]',
    context: 'insert',
    prependToContext: true
});

What does prependToContext: true mean? I can't find it in the documentation.

A: Taken from the tinymce core (theme.js):
// Added though context
if (!isUserDefined) {
    each(editor.menuItems, function(menuItem) {
        if (menuItem.context == context) {
...
            if (menuItem.prependToContext) {
                menuItems.unshift(menuItem);
            } else {
                menuItems.push(menuItem);
            }
...
        }
    });
}

So, your MenuItem gets reinserted at the beginning of the internal MenuItems array.


text:
Q: Player facing away from the wall should not collide I'm working on my first Javascript game. It is a top down 2D view (think GTA 1/2). Now I'm having trouble with collision detection. I have multiple entities where one is the player and the other is a static object (let's say a wall for simplicity).
Each object has X/Y coordinates and the player also has a velocity and an angle (which way the player is facing from 0-360 degrees). The collision detection against the wall works fine and I stop velocity on one of the axis if the player collide having as result the player can "slide" agains the wall.
Now to the issue: Once the player collides agains the wall the movement on one of the axis is stopped. If the player after that turns around and facing away from the wall the movement of that axis is still stopped since ha collided.
I would like the player, if facing away from the object, is free to move how he want's how do I achieve this? I guess I need to figure out which way the player is facing and if he is facing against or away from the object?
for( var i = 0; i < GAME.entities.length; i++ ) {
            if( this._collision( GAME.entities[i] ) ) {

                var distanceX = GAME.entities[i].x - this.x;
                var distanceY = GAME.entities[i].y - this.y;

                if( distanceX < 0 )
                    distanceX *= -1;

                if( distanceY < 0 )
                    distanceY *= -1;

                if( !stopX ) {
                    stopX = ( distanceX > distanceY );
                }

                if( !stopY ) {
                    stopY = ( distanceX < distanceY );
                }
            }
        }

A: I figured out how to do this:
var degrees = ( Math.atan2( GAME.entities[i].x - this.x, GAME.entities[i].y - this.y ) * 180 / Math.PI ) + this.angle


text:
Q: X axis should have a space in Line chart- Chart JS I was trying to create a line chart and it is working as expected, except for one small design improvement.
The line chart created starts by touching the first point from the Y-axis but I would like it to have a bit of a space before it.
Chart I am generating:

Chart I want to generate:

I was unable to find the exact keyword to search it up within the documents.
Here attached is the code I have been working with:
Stack Blitz

A: You can define xAxes.offset: true and it should work as expected.
xAxes: [
    {
      offset: true,
      ...
    }
  ]

offset: If true, extra space is added to both edges and the axis is scaled to fit into the chart area.

Please take a look at your amended StackBlitz.


text:
Q: How can I get my Realtek RTL8111/8168B NIC working? I've come to a dead end with another Linux distro due to the difficulty of obtaining or compiling device drivers for a Realtek RTL8111/8168B NIC that is onboard a new server mobo I was planning to use in a render farm project.  I can live with downloading and installing pre-compiled proprietary drivers (e.g. Nvidia) but was hoping to avoid having to compile them and learn how to install them then hope they were not broken in a future kernel upgrade which seems to happen.  Though an experienced developer, I have scant experience with Linux and no time to plough through the learning curve.  Is there any joy for me by way of out-of-the box support for an r8168 NIC?  There are no spare PCI slots and it's either find a ready solution or give up on Linux (which I really am loath to do).  Grateful for any constructive comment.

A: For Ubuntu Server 20.04, you can do this with a little help of the universe repository. Here's how:

*Open your /etc/apt/sources.list file:
sudo vi /etc/apt/sources.list

Note: Feel free to use a different editor if you're not keen on vi. This is more muscle memory than an implicit recommendation.

*Find this line:
deb http://jp.archive.ubuntu.com/ubuntu/ focal main restricted

Note: You're probably not pulling from the Japanese mirror, so do not use jp unless you're on the same side of the globe.
Add universe, so the line becomes:
deb http://jp.archive.ubuntu.com/ubuntu/ focal main restricted universe

*Save the file

*Update apt for the new repository:
sudo apt update

*Pull down the r8168-dkms package:
sudo apt-get install r8168-dkms

Note: This may take some time, as dkms will compile the driver after pulling it down. Once the driver is compiled, the network adapter should start up immediately. If it doesn't, then you may need to restart the system.
That's all there really is to it. For the server I was using, I had a USB⇢Ethernet adapter that allowed me to connect the machine to the network so that I could download the drivers (and other updates). Once everything was good, the USB adapter was thrown back into the "Bag of Useful Adapters" that I keep handy.
Hope this helps you should you replace Fedora with Ubuntu


text:
Q: How to display object's keys and values in react component I have ControlSection component that one of it's props is statistics object prop. I want to display with
 all the key and values of the object. How can I do it?
ControlSection:
const ControlSection = ({ statistics }) => {
    return (

            {
                Object.keys(statistics).forEach(key =>

key: statistics[key]

                )
            }

    )
}

Statistics example:
const statistics = {
    Score: score,
    Level: level,
    Best: bestScore,
};

A: forEach returns undefined. Use Array#map, which returns the JSX for each item in a new array.
JSX also requires the { } braces to evaluate text as JS.
Since you're creating a series of
 elements, React needs a key property to be set on the elements. Using keys from the object is sufficient since they're guaranteed to be unique strings. However, you might consider using a list (
 or
 parent element with
 children) as an alternative to the header elements.
Also, you can use Object.entries to access both the key and value for each pair in an object in a slightly more intuitive way than statistics[key]:
const ControlSection = ({ statistics }) => {
    return (

            {
                Object.entries(statistics).map(([key, val]) =>

{key}: {val}

                )
            }

    );
};


text:
Q: Sitecore 6.5 DMS - Registering a goal completion via the API I want to register a goal/conversion on my Sitecore 6.5 site using the API rather than a 'thank-you' page.
I've seen this question about how to do it Sitecore OMS - achieving a goal on a form submission but the answer relates to the API prior to Sitecore 6.5 where it was overhauled quite significantly.
Has anyone done this? Or has this functionality been intentionally removed?

A: Have you tried something like
protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (Sitecore.Analytics.Tracker.IsActive && Sitecore.Analytics.Tracker.CurrentPage != null)
    {
        PageEventData eventData = new PageEventData("My Goal Name");
        eventData.Data = "this is some event data.";
        VisitorDataSet.PageEventsRow pageEventsRow = Sitecore.Analytics.Tracker.CurrentPage.Register(eventData);
        Sitecore.Analytics.Tracker.Submit();
    }
}

That should register the goal on the currentpage, but not before you decide to in your code

A: You can also use a modified version of the code which references the Goal Item by its GUID:
if (Sitecore.Analytics.Tracker.IsActive && Sitecore.Analytics.Tracker.CurrentPage != null)
{
PageEventItem goal = new PageEventItem(Sitecore.Context.Database.GetItem("GOALGUID"));
VisitorDataSet.PageEventsRow pageEventsRow = Sitecore.Analytics.Tracker.CurrentPage.Register(goal);
Sitecore.Analytics.Tracker.Submit();
}

Make sure you have deployed and published your goal and or goal category too as the code will fail otherwise.


text:
Q: Does the first derivative test always work for finding minima and maxima? Suppose you want to find the max of the function $\ f(x)=\sqrt{x} - x$.
Using the first derivative test you get, $f'(x)= \frac{1}{2\sqrt{x}} - 1$ .
If we equate this to $0$ we get $x =\frac{1}{4}$. Taking as $x$ as $0.20$ and $0.30$, we get that the first derivative doesn't change signs (remains positive). However, if x is taken as $x > 1$, then the first derivative becomes negative.
Graphing the function reveals that $x =\frac{1}{4}$ is indeed the maximum point.
Taking the second derivative $\ f\prime\prime(x)= \frac{-1}{4x^\frac{3}{2}}$ and using the second derivative test at the point $x =\frac{1}{4}$ shows the second derivative is negative, indicating a maximum.
My question therefore is does the first derivative test necessarily always show the maximum? Both the graphs and second derivatives indicate a maximum; however if the first derivative is taken with $x < 1$ then the first derivative test fails. Can someone explain how this could happen?

A: As I said in a comment, your calculations are wrong. $f'(0.2)$ is indeed positive, but $f'(0.3)$ is negative.
The first derivative test (checking how $f'$ changes sign at a critical point) and the second derivative test (checking the sign of $f''$ at a critical point) will never give contradictory conclusions, as you thought they did here. (You thought the first derivative was indicating a non-extremum whereas the second derivative was indicating a maximum. But your evidence was wrong, because $f'(x)$ does indeed change sign at the critical point.)
The second derivative test may be inconclusive (this happens precisely when $f''$ vanishes at a critical point), but you will never get contradictory results.

A: Before attempting to find maxima or minima of a function, you must remember that a function is not just a formula. A function may be expressed by a formula, but even in that particular case you need to add an important specification: the domain. If we are dealing with functions defined in the reals, often it's assumed that the domain are all the values where the formula can be evaluated (natural domain) - but, even then, make that explicit before findind maxima-minima.
In this case, the natural domain is $D=[0,+\infty)$, so we are only interested in the points that make null the derivative in the region. (It might happen that the derivative you get -as a mere formula- can be evaluated outside the domain - but you must exclude that values)
But that's not all. Even after you have found the points where the derivative is zero, and have found that the second derivative is positive or negative, you might still miss some minima-maxima (and, perhaps, the global maximum or minimum).
You also need to ask yourself:

*

*Is the function derivable in all its domain? If not, check for the non-derivable points

*Is the domain open? If not, check for the extremal points (in this
case, $x=0$)


text:
Q: Requirejs reading from different modules cannot ready properly of undefined I am experimenting with require.js and am having trouble accessing module components inside of other modules. In the below example i am trying to access my junk function from my sandbox.js module inside of main. can someone help point out what i am doing wrong?
main.js
require.config({
     baseUrl: "assets/js",
     paths: {
        jquery: ['https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min'],
        bootstrap: ['https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js']
     }
});

require(["jquery", "sandbox"], function($, sandbox){

console.log( sandbox.junk );

});

Sandbox.js
define(['jquery'], function($){
    console.log("firebase.js is online");

    var junk = function(){
        return "tinoy";
    }

});

A: After looking into it further i did the following which allows me to communicate between modules:
main.js
require.config({
     baseUrl: "assets/js",
     paths: {
        jquery: ['https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min'],
        bootstrap: ['https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js']
     },

     shim: {
        /* Set bootstrap dependencies (just jQuery) */
        'bootstrap' : ['jquery'],
        'firebase': {
                  exports: 'firebase'
              }
    }
});

require(["jquery", "sandbox"], function($, sandbox){

console.log( junk() );

}); //close main require

sandbox.js
define(['jquery'], function($){

    this.junk = function(){
        return "tinoy";
    }

});


text: Q: Banana PI M1 built-in microphone features i would like to obtain information about Banana PI M1 built-in microphone features. It would be nice to know its maximum sampling frequency (I know it samples at 44100 Hz, could it get any highter?) and i also require (if existing) some frequency response charts. Is there such a thing like an expansion (addon board) microphone for this device. Could an usb microphone work? If I install Android on this device, could i access to the microphone features with a customized app for this purpose? Thanks


text:
Q: Solidity error: Unexpected token h in JSON at position Hey I'm developing a simple smart contract on solidity and I crashed into a problem. Everytime I try to run setWord function I get an error "transact to HelloWorldContract.setWord errored: Error encoding arguments: SyntaxError: Unexpected token h in JSON at position 2" What could be the problem?
pragma solidity ^0.4.0;
contract HelloWorldContract{
string word = "Hello World";
address issuer;
function HelloWorldContract(){
    issuer = msg.sender;
}
function getWord() constant returns(string) {
    return word;
}
function setWord(string newWord) returns(string) {
    if(issuer != msg.sender){
        return "this is not the creator!";
    }
    else{
     word = newWord;
     return "this is the creator!";
    }
}
}

A: My guess would be that you're using Remix IDE.
Don't forget to add double quotes around the arguments you're passing:

A: You need to pass argument string in double quotes - "helloWorld" instead of just helloWorld.


text:
Q: Calculate HANA global allocation limit How can I calculate the global_allocation_limit parameter? When I have SAP Netweaver and SAP HANA DB installed on a server. And the current database size in RAM is 300 GB.
Many thanks

A: As you correctly mentioned, the Global Allocation Limit is a parameter, which can be set by the administrator. If the administrator has set this to an arbitrary value, there is no way for you to "calculate" it.
However, if your question is referring to the default value, the official documentation may be helpful:

The default value is 0 in which case the global allocation limit is
calculated as follows: 90% of the first 64 GB of available physical
memory on the host plus 97% of each further GB. Or, in the case of
small physical memory, physical memory minus 1 GB.


text:
Q: Tmux bind-key not working for split-window I have following configuration in my tmux config file:
unbind C-b
set -g prefix C-s

bind-key - split-window -v
bind-key \ split-window -h

When I am in tmux, if I try
Ctrl+s : split-window -v

it works. If I try
Ctrl+s -

it does not work. It says No Buffer, and tmux does not do anything.
Any help on how can I debug this behaviour?

A: The - key is already bound to the delete-buffer command. You can check this by executing tmux list-keys. You must unbind it and then apply your binding:
unbind -
bind-key - split-window -v


text:
Q: Correlation of two random variables A random sample of $100$ variables is given. Each of them is independent and identically distributed with $N(0,1)$. What is the correlation between sum of $98$ variables and sum of $100$ variables?

A: Let $X_i \sim N(0,1)$ for $i \in \{1,\dots,100\}$ denote the random variables described in the question.
Next, define
$$ Y \equiv \sum_{i=1}^{98} X_i \;\;\;\;\; \text{and} \;\;\;\;\; Z \equiv \sum_{i=1}^{100} X_i $$
The correlation between $Y$ and $Z$ is given by
$$ \frac{\mathbb E [(Y-\mathbb E [Y])(Z-\mathbb E [Z])]}{ \sqrt{\mathbb E [(Y-\mathbb E [Y])^2] \mathbb E [(Z-\mathbb E [Z])^2]}} $$
Notice that $\mathbb E [Y] = \mathbb E [Z] = 0$, $\; \mathbb E[X_i X_j]=0$ for all $i\neq j, \;$ and $\mathbb E[X_i^2]=1$ for all $i\;$ which implies that
\begin{align}
\mathbb E [(Y-\mathbb E [Y])(Z-\mathbb E [Z])]  &= \sum_{i=1}^{98} \mathbb E[X_i^2]=98 \\[1.5ex]
\mathbb E [(Y-\mathbb E [Y])^2] &= \sum_{i=1}^{98} \mathbb E[X_i^2]=98 \\[1.5ex]
\mathbb E [(Z-\mathbb E [Z])^2] &= \sum_{i=1}^{100} \mathbb E[X_i^2]=100
\end{align}
and, therefore,
$$ \frac{\mathbb E [(Y-\mathbb E [Y])(Z-\mathbb E [Z])]}{ \sqrt{\mathbb E [(Y-\mathbb E [Y])^2] \mathbb E [(Z-\mathbb E [Z])^2]}} = \frac{98}{\sqrt{98*100}} $$


text:
Q: React Native xcode project "Header Search Path" Following the steps from React Native official tutorial, the xcode project created by "react-native init MyFirstRNProject" won't compile. It complains "React/xxxxx.h" can't be found.
After further investigation of this xcode project, I figured the "React" target contains a build phase "Copy Headers" which copies all exposed headers into a weird location:
"MyFirstRNProject/node_modules/react-native/React/build/Debug-iphonesimulator/include/React"
OK, cool, at least we got the header location. We can change the copied location to somewhere else that better than this. So whichever the project that do "#import < React/xxxxx.h >" should have above path in "Header Search Path" in build settings. Unfortunately, all projects have "Header Search Path" empty. And that's why I'm getting tons of header not found error.
OK, let's add it. Now it finds headers, but compilation still failed, see reference below:
https://github.com/facebook/react-native/issues/21482
The discussion above saying that removing the "Header Search Path" of the projects will solve the problem. But we know that without header search path, it again can't find React headers.
Just curious now, I don't think my setup is wrong, does anyone has the same issue?

A: I had the same problem on fresh install of Xcode 10.1
There are few steps to follow to compile the new project after react-native init appName

*

*In Xcode, Select File -> Project/Workspace Settings. You will see a Build System option to select the Legacy Build System as shown below

*Change Advanced settings, and set Build Location to Custom and change paths to Relative to Workspace and Build/ to build/Build/ as showed.

 3. User Debug for command-line builds(for react-native run-ios to work properly)

*Clear your project

After this manipulations(don't need set header search paths) you'll be able to build and run empty project via Xcode or CLI


text:
Q: MySQL 150: Foreign key constraint is incorrectly formed When I import the file to phpmyadmin I'm getting this err :

#1005 - Can't create table `test_db`.`part_order` (errno: 150
  "Foreign key constraint is incorrectly formed")

I checked the syntax many times but I can't see what's wrong. I tried to use INDEX and CONSTRAINT but no success. Any help will be appreciated.
CREATE TABLE IF NOT EXISTS `all_products` (
  `product_id` int(10) NOT NULL AUTO_INCREMENT,
  `product_name` VARCHAR(100)  NOT NULL,
  `product_price` decimal(10,2) NOT NULL,
  `product_description` VARCHAR(1000) NOT NULL,
  PRIMARY KEY(`product_id`, `product_name`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

CREATE TABLE IF NOT EXISTS `product_color` (
  `color_id` int(10) NOT NULL AUTO_INCREMENT,
  `product_id` INT(10) NOT NULL,
  `color_name` VARCHAR(100) NOT NULL,
  PRIMARY KEY(`color_id`, `color_name`),
  FOREIGN KEY(`product_id`) REFERENCES all_products(`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` INT(10) NOT NULL AUTO_INCREMENT,
  `first_name` VARCHAR(100) NOT NULL,
  `last_name` VARCHAR(100) NOT NULL,
  `email` VARCHAR(100) NOT NULL,
  `password` VARCHAR(200) NOT NULL,
  `address` VARCHAR(200) NOT NULL,
  `city` VARCHAR(100) NOT NULL,
  `post_code` VARCHAR(8) NOT NULL,
  PRIMARY KEY(`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

CREATE TABLE IF NOT EXISTS `part_order` (
  `order_number` INT(10) NOT NULL ,
  `product_name` VARCHAR(100) NOT NULL,
  `color_name` VARCHAR(100) NOT NULL,
  `qty` INT(10) NOT NULL,
  PRIMARY KEY(`order_number`),
  INDEX(`order_number`),
  CONSTRAINT FOREIGN KEY(`product_name`) REFERENCES
    all_products(`product_name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT FOREIGN KEY(`color_name`) REFERENCES
    product_color(`color_name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

CREATE TABLE IF NOT EXISTS `orders` (
  `order_number` INT(10) NOT NULL,
  `user_id` INT(10) NOT NULL,
  Date DATETIME DEFAULT CURRENT_TIMESTAMP,
  `total_cost` INT(10) NOT NULL,
  `status` VARCHAR(50) NOT NULL,
  PRIMARY KEY(`status`),
  CONSTRAINT FOREIGN KEY(`order_number`) REFERENCES
    part_order(`order_number`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES
    users(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
)

A: MySQL requires indexes on the referenced columns (product_name and color_name). Add INDEX(product_name) to the all_products table and INDEX(color_name) to the product_color table
CREATE TABLE IF NOT EXISTS `all_products` (
  `product_id` int(10) NOT NULL AUTO_INCREMENT,
  `product_name` VARCHAR(100)  NOT NULL,
  `product_price` decimal(10,2) NOT NULL,
  `product_description` VARCHAR(1000) NOT NULL,
  PRIMARY KEY(`product_id`, `product_name`),
  INDEX(`product_name`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

From the docs:

MySQL requires indexes on foreign keys and referenced keys so that
  foreign key checks can be fast and not require a table scan. In the
  referencing table, there must be an index where the foreign key
  columns are listed as the first columns in the same order. Such an
  index is created on the referencing table automatically if it does not
  exist. This index might be silently dropped later, if you create
  another index that can be used to enforce the foreign key constraint.
  index_name, if given, is used as described previously.


text:
Q: How can I support anonymous users with my application? I need to implement a user authentication system that supports anonymous users, like how this site works. Can it be done with the default asp.net membership provider? if not, what are some of the things I need to do?

A: Yes, it can be done. There's even a special event to migrate anonymous user details once the user logs in:
http://msdn.microsoft.com/en-us/library/system.web.profile.profilemodule.migrateanonymous.aspx


text:
Q: I can not call a method with varargs from JSP page I have class DBBase defined as follow in my application:
public class DBBase {
    public static void close(Statement stmt) {
        try {
            if (stmt != null) stmt.close();
        } catch (Exception ex) {
            logger.error("Exception:(", ex);
        }
    }

    public static void close(ResultSet resultSet) {
        try {
            if (resultSet != null) resultSet.close();
        } catch (Exception ex) {
            logger.error("Exception:(", ex);
        }
    }

    public static void close(Connection con) {
        try {
            if (con != null) con.close();
        } catch (Exception ex) {
            logger.error("Exception:(", ex);
        }
    }

    public static void close(Object... closeable) {
        for (Object obj : closeable) {
            if (obj != null) {
                if (obj instanceof Connection) close((Connection) obj);
                else if (obj instanceof ResultSet) close((ResultSet) obj);
                else if (obj instanceof Statement) close((Statement) obj);
            }
        }
    }
}

When I call the close method DBBase.close(con, stmt, resSet) from another class, everything works fine but when I call this method from a JSP page I got the following error:
An error occurred at line: 20 in the jsp file: /admin/test.jsp
Generated servlet error:
The method close(Statement) in the type DBBase is not applicable for the arguments (Connection, Statement, ResultSet)

And this is my JSP page:
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="db.DBBase" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    Connection con = null;
    Statement stmt = null;
    ResultSet resSet = null;

    try {
        // Some code here
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        DBBase.close(con, stmt, resSet);
    }
%>
<html>
<head>
    <title>Test JSP File</title>
</head>
<body>

</body>
</html>

My JDK version is 1.7.0._51 with language level 7
What is the problem?
UPDATE
This is my server and jsp configs:
Server Version: Apache Tomcat/5.5.17
Servlet Version: 2.4
JSP Version: 2.0

Actually I have JBoss 4.0.4 GA
UPDATE
Regarding to @AlexC's comments I have to change my JBoss version to use varargs.

A: JSR-245 for JSP 2.1 defined usage of varargs in JSP and in Tomcat this was done during 7.x release cycle. (See http://alex-perevalov.livejournal.com/30156.html and https://wiki.apache.org/tomcat/Specifications )
In in web.xml (see http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html ) you can specify the JSP version to support if you need to limit it.
Upgrading your app server to JSP 2.1 compatible one should allow varargs.


text:
Q: Time derivative of the state vector as expressed in abstract Hilbert space vs. as a wavefunction The Schrodinger equation in Hilbert space is expressed as : $$\frac{\partial}{\partial t} \psi(t) = \frac{-i}{\hbar}H\psi(t). $$
Here $\frac{\partial}{\partial t} \psi(t) \equiv \psi'(t) \equiv\lim \limits_{h \to 0} [\frac{\psi(t+h)-\psi(t)}{h}]$, and because $\psi(t)$ is a Hilbert space vector, the limit is defined using convergence via the norm. (In other words, for any $\epsilon>0$ there exists an $h_\epsilon>0$, such that $\big|\big|\psi'(t)-(\frac{\psi(t+h)-\psi(t)}{h})\big|\big| < \epsilon $ for all $|h|<h_\epsilon$). So the convergence depends on the vector as a whole.
But in the wavefunction realization (for a single particle), the Schrodinger equation is expressed as
$$\frac{\partial}{\partial t} \psi(x;t) = \frac{-i}{\hbar}\left [ - \frac{\hbar^2}{2 m} \frac{\partial^2}{\partial x^2} + V \right ] \psi(x;t).
$$
Here, however, $\frac{\partial}{\partial t} \psi(x;t)$ is a pointwise partial derivative with respect to $t$, and so the convergence depends only on each individual point $x$ of $\psi(x)$ separately.
If we take the abstract Hilbert space expression as definitive (axiomatically), then how can it be shown that the wavefunction realization actually expresses the same thing, given the different meanings of $\frac{\partial}{\partial t}$?

A: I henceforth assume $\hbar=1$. The correct way to think of Schroedinger equation in a Hilbert space $\cal H$ (referring to a self adjoint Hamiltonian $H : D(H) \to \cal H$, with $D(H)\subset \cal H$ a dense subspace) is the one where the time derivative refers to the topology of the Hilbert space (as correctly noticed at the beginning of the posted question):
$$\frac{d}{dt} \psi_t = -i H \psi_t\tag{1}\:.$$
Above $\psi_t := e^{-itH} \psi$ and $\psi \in D(H)$. This last requirement guarantees that $\psi_t \in D(H)$ for every $t \in \mathbb R$ and that the $t$-derivative $\frac{d}{dt} \psi_t$ exists in the sense of the topology of the Hilbert space, and, finally, that (1) holds true.
However, a naive interpretation of Schroedinger equation assumes that the $t$-derivative is in the standard sense for a wavefunction $\psi=\psi(t,x)$ sufficiently smooth in both variables, and the equation itself is interpreted in the sense of standard PDE, supposing that $H$ is the (hopefully unique) self-adjoint extension of a differential operator
$H_x = -\frac{1}{2m} \Delta_x + V(x)$ with $V$ at least continuous:
$$\frac{\partial}{\partial t} \psi(t,x) = -i H_x \psi(t,x)\tag{2}\:.$$
This second interpretation is untenable in the general case for various reasons.
In particular it is false that all solutions of (1) solve (2), because the  wavefunctions solving (1) are elements of $D(H) \subset {\cal H} = L^2(\mathbb R^3, dx)$  and thus (a) they  are defined up to zero measure set and (b), in general, it is not possible to obtain a continuous function changing the initial one on a zero measure set. (The reason is that the self-adjoint extension $H$ of $H_x$
ceases to be a differential operator.)
However it could happen that one finds a solution of (2) $\psi=\psi(t,x)$ which is differentiable in $t$ for every $x$ and sufficiently regular in $x$ depending on the regularity of $V$ in order to belong to $D(H_x)\subset D(H)$.
Does $\psi$ solve (1)?
The only thing to check is if, almost everywhere in $x$ and for a given $t \in \mathbb R$,
$$\left(\frac{d}{dt} \psi_t\right)(x) = \frac{\partial}{\partial t} \psi(t,x)\:.\tag{3}$$
We have a pair of elementary facts:
(A) If both sides of (3) exist, and the right hand side belongs to $L^2(\mathbb R^3, dx)$, (3) holds.
(B)  If there are $\epsilon>0$ and
$g_{t} \in L^2(\mathbb R^3, dx)$, with
$$\left|\frac{\partial}{\partial \tau} \psi(\tau,x)\right| \leq |g_{t}(x)|\quad  \mbox{almost everywhere in $x$, } \forall \tau \in (t-\epsilon, t+\epsilon)$$
then the left-hand side of (3) exists (and (3) holds true for (A)).
ADDENDUM.
SKETCH OF PROOF
Regarding (A), since the $t$ derivative exists in the sense of the Hilbert space topology,  we know that
$$\lim_{h\to 0} \int \left| \frac{1}{h}(\psi_{t+h}(x)-\psi_t(x))  - \frac{d \psi_t(x)}{dt}\right|^2 dx=0$$
A know result of $L^p$ spaces theory says that if $f_n \to f$ as $n\to +\infty$ in $L^p$, there is a subsequence with $f_{n_k} \to f$ almost everywhere as $k \to +\infty$. Therfore there is a sequence $h_k \to 0$ as $k\to +\infty$, such that, almost everywhere in $x$,
$$\frac{1}{h_k}(\psi_{t+h_k}(x)-\psi_t(x)) \to \frac{d \psi_t(x)}{dt}\:.\tag{4}$$
On the other hand we know that, just because $\frac{\partial \psi(t,x)}{\partial t}$ exists, for every $x$ we also have
$$\frac{1}{h}(\psi_{t+h}(x)-\psi_t(x)) \to \frac{\partial \psi(t,x)}{\partial t}\quad \mbox{if $h\to 0$}.$$
Therefore, in particular, again for every $x$,
$$\frac{1}{h_k}(\psi_{t+h_k}(x)-\psi_t(x)) \to \frac{\partial \psi(t,x)}{\partial t}\quad \mbox{if $k\to \infty$}\:.\tag{5}$$
Comparing (4) and (5), we conclude that (A) holds:
$$\left(\frac{d}{dt} \psi_t\right)(x) = \frac{\partial}{\partial t} \psi(t,x)$$
almost everywhere in $x$. So that (A) is true.
Regarding (B), what has to be proved is that:
$$\lim_{h\to 0} \int \left| \frac{1}{h}(\psi(t+h,x)-\psi(t,x))  - \frac{\partial \psi(t,x)}{\partial t}\right|^2dx =0\:.\tag{6}$$
Lagrange's theorem allows us to re-write the integral as:
$$\int \left| \frac{\partial \psi(\tau,x)}{\partial \tau}|_{\tau= t_{x,h}}  - \frac{\partial \psi(\tau,x)}{\partial \tau}|_{\tau=t}\right|^2 dx$$
where $t_{x,h} \in [t-h,t+h]$. In our hypotheses we also have that:
$$\left| \frac{\partial \psi(\tau,x)}{\partial \tau}|_{\tau= t_{x,h}}  - \frac{\partial \psi(\tau,x)}{\partial \tau}|_{\tau=t}\right|^2 \leq 2|g_t(x)|^2$$
almost everywhere in $x$ and for all sufficiently small $h$.
Lebesgue's dominated convergence theorem implies that the symbol of integral and that of limit can be swapped in the RHS of (6), obtaining
$$\lim_{h\to 0} \int \left| \frac{1}{h}(\psi(t+h,x)-\psi(t,x))  - \frac{\partial \psi(t,x)}{\partial t}\right|^2 dx$$
$$ =
 \int \lim_{h\to 0}\left| \frac{1}{h}(\psi(t+h,x)-\psi(t,x))  - \frac{\partial \psi(t,x)}{\partial t}\right|^2 dx =0\:,$$
as wanted.


text:
Q: junit assert in thread throws exception What am I doing wrong that an exception is thrown instead of showing a failure, or should I not have assertions inside threads?
 @Test
 public void testComplex() throws InterruptedException {
  int loops = 10;
  for (int i = 0; i < loops; i++) {
   final int j = i;
   new Thread() {
    @Override
    public void run() {
     ApiProxy.setEnvironmentForCurrentThread(env);//ignore this
     new CounterFactory().getCounter("test").increment();//ignore this too
     int count2 = new CounterFactory().getCounter("test").getCount();//ignore
     assertEquals(j, count2);//here be exceptions thrown. this is line 75
    }
   }.start();
  }
  Thread.sleep(5 * 1000);
  assertEquals(loops, new CounterFactory().getCounter("test").getCount());
}

StackTrace
Exception in thread "Thread-26" junit.framework.AssertionFailedError: expected:<5> but was:<6>
    at junit.framework.Assert.fail(Assert.java:47)
    at junit.framework.Assert.failNotEquals(Assert.java:277)
    at junit.framework.Assert.assertEquals(Assert.java:64)
    at junit.framework.Assert.assertEquals(Assert.java:195)
    at junit.framework.Assert.assertEquals(Assert.java:201)
    at com.bitdual.server.dao.ShardedCounterTest$3.run(ShardedCounterTest.java:77)

A: Where multiple worker threads are concerned, such as in the original question, simply joining one of them is not sufficient. Ideally, you'll want to wait for all worker threads to complete while still reporting assertion failures back to the main thread, such as in Eyal's answer.
Here's a simple example of how to do this using my ConcurrentUnit:
public class MyTest extends ConcurrentTestCase {
    @Test
    public void testComplex() throws Throwable {
        int loops = 10;
        for (int i = 0; i < loops; i++) {
            new Thread(new Runnable() {
                public void run() {
                    threadAssertEquals(1, 1);
                    resume();
                }
            }).start();
        }

        threadWait(100, loops); // Wait for 10 resume calls
    }
}

A: The JUnit framework captures only assertion errors in the main thread running the test. It is not aware of exceptions from within new spawn threads.
In order to do it right, you should communicate the thread's termination state to the main thread. You should synchronize the threads correctly, and use some kind of shared variable to indicate the nested thread's outcome.
EDIT:
Here is a generic solution that can help:
class AsynchTester{
    private Thread thread;
    private AssertionError exc;

    public AsynchTester(final Runnable runnable){
        thread = new Thread(() ->
            {
                try{
                    runnable.run();
                }catch(AssertionError e) {
                    exc = e;
                }
            }
        );
    }

    public void start(){
        thread.start();
    }

    public void test() throws InterruptedException {
        thread.join();
        if (exc != null)
            throw exc;
    }
}

You should pass it the runnable in the constructor, and then you simply call start() to activate, and test() to validate. The test method will wait if necessary, and will throw the assertion error in the main thread's context.

A: A small improvement to Eyal Schneider's answer:
The ExecutorService allows to submit a Callable and any thrown Exceptions or Errors are rethrown by the returned Future.
Consequently, the test can be written as:
@Test
public void test() throws Exception {
  ExecutorService es = Executors.newSingleThreadExecutor();
  Future<?> future = es.submit(() -> {
    testSomethingThatMightThrowAssertionErrors();
    return null;
  });

  future.get(); // This will rethrow Exceptions and Errors as ExecutionException
}

A: JUnit throws AssertionError that extends of Throwable, it has the same parent of Exception. You can catch the  fail assert of the thread, then save in a static field and finally check in the main thread if the other thread has failed some assert.
First, create the static field
private volatile static Throwable excepcionTE = null;

Second, wrap the asserts in a try/catch and catch AssertionError
        try
    {
      assertTrue("", mensaje.contains("1234"));
    }
    catch (AssertionError e)
    {
      excepcionTE = e;
      throw e;
    }

And finally, check in the main thread that field
 if (excepcionTE != null)
{
  excepcionTE.printStackTrace();
  fail("Se ha producido una excepcion en el servidor TE: "
      + excepcionTE.getMessage());
}

A: I ended up using this pattern it work with both Runnables and Threads. It is largely inspired from the answer of @Eyal Schneider:
private final class ThreadUnderTestWrapper extends ThreadUnderTest {
    private Exception ex;

    @Override
    public void run() {
        try {
            super.run();
        } catch ( Exception ex ) {
            this.ex = ex;
        }
    }

    public Exception getException() throws InterruptedException {
        super.join(); // use runner.join here if you use a runnable.
        return ex;
    }
}

A: I was looking for a simple and readable solution. Inspired by Eyal Schneider and Riki Gomez's answer, I've come up with this:
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ThreadExceptionTest {
    private static Throwable failedThreadException;

    @BeforeEach
    public void setup() {
        failedThreadException = null;
    }

    @Test
    public void threadTest() {
        final Thread thread = new Thread(() -> codeThatMayFail(...));

        thread.start();

        // We have to join before we check for exceptions,
        //   otherwise we might check before the Thread even finished.
        thread.join();

        if (failedThreadException != null) {
            fail("The thread failed with an exception", failedThreadException);
        }
    }

    private void codeThatMayFail(...) {
        try {
            // Code that may throw the exception
            // ...
        } catch (Exception e) {
            failedThreadException = e;
        }
    }
}

So, you can achieve the desired result with the help of a static variable. The thread runs as usual, and all you have to do is store the exception you are interested in on the static variable. Just don't forget to reset its value to null before every test, or you may run into trouble on subsequent tests on the same Class.
Final note: If you are planning on running multiple Threads on the same test, and it is expected for them to run the same blocks of code simultaneously, I would advice to make the static variable volatile so that updates to the variable propagate predictably to other threads:
private volatile static Throwable failedThreadException;


text:
Q: How to get the name of the select element from another html field in Angular I have these two elements (select and a text field) I want to disable the text box if the name the user selects from the drop down is "Other".
ex. clModal.idustryName !== 'Other'
Currently I only know how to get the ceModal.industryId because that is what I'm saving. How can I reference the name?
Here are my two elements

  Industry
  <select class="form-control" [(ngModel)]="ceModal.industryId" (ngModelChange)="markDirty()" name="ceIndustry" #ceIndustry="ngModel" required>
    <option [ngValue]=null>None selected</option>
    <option *ngFor="let industry of industryList" [value]="industry.code">{{industry.name}}</option>
  </select>

Industry is required

  Industry Other
  <input type="text" class="form-control" placeholder="ex. Other industry info" [(ngModel)]="ceModal.industryOther" (ngModelChange)="markDirty()" name="ceIndustryOther" [disabled]="(clModal.idustryName !== 'Other')">


text:
Q: All the Gear and No Idea: Suggestions for re-designing my home/office/entertainment network Help/ Advice/ Suggestions please:
I have a load of kit that I love but which currently operate in disconnected, sometimes counter-productive way.
Because I never really had a masterplan I just added these things one after another and connected them up in ad hoc ways. Since I bought my Macbook I've found I spend much less time on the MacPro that was until then my main machine. Perversely, as my  job involves writing .Net software, I spend a lot of Mac time actually inside a Windows 7 VM.
I stream media from the HP box to the PS3 and thus to the TV, but its not without its limitations/annoyances. We listen to each other's iTunes libraries but the music files are all over the place and it would be good to know they were all safely in one location (and fully backed up).
I need to come up with a strategy that will allow me to use all the kit for work, play (recording live music, making tunes, iMovie work), pushing/streaming media to the TV and sharing files with my other half (she uses a Windows laptop and her iPod touch). Ideally I'd like to be able to work on any of the machines and have a shared homedrive that was visible to all machines so all my current files were synced up wherever i was. It would be great if I could access everything securely and quickly over the web. I'd also like to be able to set up a background backup process.
The kit list thus far:

*

*Apple MacPro 8GB/3x250GB RAID0 + 1TB

*Apple MacBook Pro 13" 8GB/250GB - I spend a lot of my work time on a Windows 7 VM on this.

*Crappy Acer laptop (for children's use - iPlayer, watching movies/tv files)

*HP Proliant Server 4GB/80GB+160GB+300GB

*Sun Ultra 10 2 x 80GB (old, but in top-notch condition)

*PS3

*160GB iPod Classic

*2 x 8GB iPod Touch

Observations:

*

*Part of the problem is our dual use of Windows and OS X - we can't go for a pure NT style roaming profile.

*Because the server is also used for hosting test/beta applications and a SQL Server db, it can't be dedicated to file serving.

*The two Macs really could do with sharing a roaming profile or similar.

*I'd love to be able to do something useful with the Ultra 10. My other half has been trying to throw it away for over five years now and regularly ask what function it serves in my study :-(

*I've got no shortage of 500GB external USB hard drives

*iMovie files are very large and ideally would be processed on a RAID system.

*Apple's TimeMachine isn't so great.

If anyone could suggest all or part of a setup that would fulfil some of my requirements I'd be very grateful. I am willing to consider purchasing one or two more bits of kit (an Apple TV and a Squeezebox have been moted by friends) if they will help make efficiencies rather than add to the chaos and confusion.
Thanks for looking.

A: A Windows Home server is what you need.  It's super easy to use and uses a WebUI to configure everything.  In fact, when you first get it, you just plug a network cord into it and insert a dvd into your client computer to configure it.  Probably the best investment I've ever made.
http://www.microsoft.com/windows/products/winfamily/windowshomeserver/default.mspx


text:
Q: How can I create a regex pattern than spans multiple lines I have a long regex pattern that I want to split over multiple lines.
Is there a way to take
$s !~ m"((\d)|(\d))";

and split it so you get something like
$s !~ m"((\d)|"+
"(\d))";

The above guess is incorrect and results in
Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE (\d)|/ at perl5.pl line 20.

What can I use?

A: You can't split a pattern into two like that. You can however have a single pattern spread neatly over multiple lines by using the /x modifier to tell the regex parser to ignore whitespace. For example:
$s !~ m{
         ((\d)
         |
        (\d))
    }x;


text:
Q: Make "outer" variables "visible" in setInterval function in this code:
  update: function(e,d) {
var element = $(this);
var data    = element.data();
var actor   = element.find('.actor');
var value = basicdesign.defaultUpdate( e, d, element, true );
var on = templateEngine.map( element.data( 'threshold_value' ), element.data('mapping') );
// value >= threshold
if (value >= on){
    var maxcount = data.count;
    var interval = data.interval;
    var audioWidget = document.getElementById(element.data('id'));
    if (audioWidget.paused == true){
        if (maxcount && interval) {
            var numOfCalls = 0;
            audioWidget.play();
            var intervalID = setInterval(function () {
            audioWidget.play();
            numOfCalls = numOfCalls + 1 ;
            if (numOfCalls == maxcount-1) clearInterval(intervalID);
            if **(value < on)** clearInterval(intervalID);
            }, interval);
        }
        else audioWidget.play();
    }
};
// value < then threshold
if (value < on){
var audioWidget = document.getElementById(element.data('id'));
audioWidget.pause();
};

}
I can't use value and on in the setInterval-function. I now, that maybe the solution is an closure - but how ???
(this is an code-fragment from cometvisu (audio.js), an open source visu)
THX

A: Looks like it's because value is a variable inside update, and you're trying to use it inside another function (that it hasn't been declared in, so that function doesn't know it exists).
You'd be better off, if you can, declaring the value of "value" outside of the update function.
Alternatively, you can pass "value" as a parameter into the function that is called on setInterval.


text:
Q: How to store and use data from accelerometer for 3 seconds of time? First of all sorry for the silly question.
What i'm trying to do is capture the accelerometer data for each second for three seconds and do addition of that data, but due to lack of experience i'm finding it hard time to do it.
What I've accomplished till now is:
Get acceleration data of X,Y,X axes in real time and calculated resultant acceleration as resultant_acceleration = Math.sqrt(X^2+y^2+z^2) that is real time as well and keeps changing with time.
What i want to do is:
Find resultant_acceleration at end of first, second and third second,i.e a1,a2,a3 and return (a1+a2+a3) I'm going through hard times to write a method in java that does the task.
        public void onSensorChanged(SensorEvent event) {

   final ArrayList<Double> accln = new ArrayList<>();

    //enter your code here
    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
    if (!mInitialized) {
        mLastX = x;
        mLastY = y;
        mLastZ = z;

        mInitialized = true;
    } else {
        float deltaX = Math.abs(mLastX - x);
        float deltaY = Math.abs(mLastY - y);
        float deltaZ = Math.abs(mLastZ - z);
        if (deltaX < NOISE) deltaX = (float) 0.0;
        if (deltaY < NOISE) deltaY = (float) 0.0;
        if (deltaZ < NOISE) deltaZ = (float) 0.0;
        mLastX = x;
        mLastY = y;
        mLastZ = z;

       final double a =Math.sqrt((deltaX*deltaX)+(deltaY*deltaY)+(deltaZ*deltaZ));
        accln.add(a); //what i am trying to do here is collect the sample data of acceleration in an array list for 3 seconds,// so later i can calculate average acceleration

    }
    }

A: I suggest starting a timer, then when it hits 1000 milliseconds take a measurement, then at 2000 and 3000. This might help:
Android timer? How-to?

A: Solved the Problem
Just use Timer class method do this every 1s
new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                                     // Just calculate your accleration here

                              }
                                                 }, 0, 1000);

A: You never mentioned at what rate you were trying to get accel data, so I just figured it would be at ~5hz (SENSOR_DELAY_NORMAL). Keep in mind this is just a hint. You could potentially get events at a faster rate if another app registers for accel sensor data at a faster rate. As for the code:
// SOMEWHERE IN YOUR APP

final ArrayList<Double> accln = new ArrayList<>(); //THIS SHOULD BE OUTSIDE YOUR CALLBACK!

final SensorEventListener eventListener = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    //enter your code here
                    float x = event.values[0];
                    float y = event.values[1];
                    float z = event.values[2];
                    if (!mInitialized) {
                        mLastX = x;
                        mLastY = y;
                        mLastZ = z;

                        mInitialized = true;
                    } else {
                        float deltaX = Math.abs(mLastX - x);
                        float deltaY = Math.abs(mLastY - y);
                        float deltaZ = Math.abs(mLastZ - z);
                        if (deltaX < NOISE) deltaX = (float) 0.0;
                        if (deltaY < NOISE) deltaY = (float) 0.0;
                        if (deltaZ < NOISE) deltaZ = (float) 0.0;
                        mLastX = x;
                        mLastY = y;
                        mLastZ = z;

                        final double a = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY) + (deltaZ * deltaZ));
                        accln.add(a); //what i am trying to do here is collect the sample data of acceleration in an array list for 3 seconds,// so later i can calculate average acceleration

                    }
                }

                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {
                }
            };

SensorManager sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
Handler handler = new Handler();
Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(eventListener, accel, SensorManager.SENSOR_DELAY_NORMAL);  //~5hz of data
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        sensorManager.unregisterListener(eventListener);
    }
}, 5000);

This would register your listener and unregister 5 seconds later from the handler runnable.


text:
Q: SPI_IOC_MESSAGE return EINVAL We are updating from an ARM embedded Ubuntu 14.04 to ARM embedded Ubuntu 16.04. On the first platform we are accessing a chip using SPIDEV without a problem. On the Ubuntu platform I am getting an EINVAL error following a ioctl SPI_IOC_MESSAGE.
I have seen the message SPI_IOC_MESSAGE(N) macro giving me fits and it does not solve the issue.
My code is as follows:
 SpiComm_t::Transfer(int i4Length) {
   int ret = -1;

   m_tr.len = i4Length;

   ret = ioctl(m_fd, SPI_IOC_MESSAGE(1), &m_tr);
   if (ret )   {
     printf("SPI IOCTL error %s\n", strerror(errno));   }

  return ret;
}

The calling code looks like:
  // Reset memory (Optional...  Helps diagnose failures to read.)
  memset(m_c1BufTx, 0xFF, sizeof(m_c1BufTx));

  // Put address
  m_c1BufTx[0] =  address;

  // Reset memory (optional...)
  memset(m_c1BufRx, 0xFF, sizeof(m_c1BufRx));

  // Invoke ioctl transaction
  int result = Transfer(size+1);

We are using Kernel 4.9.59 from TI SDK 4.0. I have traced the EINVAL to the spidev.c driver but cannot make sense of why I am getting the error.
spidev.c code is:
tmp = _IOC_SIZE(cmd);
if ((tmp % sizeof(struct spi_ioc_transfer)) != 0)
    return ERR_PTR(-EINVAL);
*n_ioc = tmp / sizeof(struct spi_ioc_transfer);
if (*n_ioc == 0)
    return NULL;

/* copy into scratch area */

Any help would be greatly appreciated.

A: The problem appears to have been that the spi_ioc_transfer had some garbage in it. Zeroing out the structure solved the issue. Either cs_change or pad was the cause of the error.
Also, the return code from ioctl(fd, SPI_IOC_MESSAGE(1), ...) does not indicate failure or success. Instead in this instance it returns a size of the message returned. To test for error had to check errno directly.
The updated code for the transfer function is now:
errno = 0;
ret = ioctl(m_fd, SPI_IOC_MESSAGE(1), &m_tr);
// NOTE this ioctl returns the lenght of the answer not an indication of  setting errno
// Check errno instead
if (errno != 0)
{
    printf("SPI IOCTL ret(%d)error(%d) %s\n", ret, errno, strerror(errno));
}


text:
Q: lowess fit curve in R This code gives me the mean, but I don't know how to get the +1sd and -1 sd lines.
y<-lowess(x[,1],x[,2],f=0.01)

Thanks for your help.

A: Hmm, perhabs msir:::loess.sd() does what you want:
require(graphics)
plot(cars, main = "lowess(cars)")

require(msir)
low <- loess.sd(cars[ ,1], cars[ ,2])
lines(low$x, low$y)
lines(low$x, low$upper)
lines(low$x, low$lower)


text:
Q: Loop through array I have records in list.txt (INPUT) as
List of animals SET 1=Dog 2=Crow 3=Snake Pet,bird,reptile
List of Countries SET 1=France 2=Singapore 3=Columbia Europe,Asia,SouthAmerica
List of Parts SET 1=KeyBoard 2=Speaker 3=LEDpanel Computer,AudioPlayer,Television
List of Cities SET 1=Amsterdam 2=KualLumpur 3=Paris Netherlands,Malaysia,France

Want the last column of each line to be used as array for replacing the numbers 1,2,3
For eg. Use Pet,bird,reptile of first line to make Pet=Dog bird=Crow and reptile=Snake.
So, the OUTPUT file would be
List of animals SET Pet=Dog bird=Crow reptile=Snake
List of Countries SET Europe=France Asia=Singapore SouthAmerica=Columbia
List of Parts SET Computer=KeyBoard AudioPlayer=Speaker Television=LEDpanel
List of Cities SET Netherlands=Amsterdam Malaysia=KualLumpur France=Paris

Using awk, I could split the last column as string of array.
But unable to use the same to replace the numbers 1,2,3.

A: You can loop over items in an awk array a using the syntax for (i in a). So for example you could do something like
awk '{split($NF,a,","); $NF=""; for (i in a) sub(i"=",a[i]"=",$0); print}' list.txt

A: If there are always 3 items (x=y) and no space in the lines, this awk statement should work:
awk -F',| |=' '{printf "%s %s %s %s %s=%s %s=%s %s=%s\n", \
$1, $2, $3, $4, $11, $6, $12, $8, $13, $10}' list.txt

Explanation:

*

*-F',| |=': set the field separator to ,, space and =

*'{printf ... print the values in the desired format

*list.txt the input file

A: This script should work for any number of items in a row.

while read line
  do
      valType=($(echo $line | awk '{ print $NF }' | tr ',' ' '))
      vals=($(echo $line | awk '{ $NF="";$1="";$2="";$3="";$4="";  print $0 }' | tr [1234567890] ' ' | tr '=' ' ' ))
      echo $line | awk '{print $1" "$2" "$3" "$4 }' | tr -d '\n'
      numVals=${#vals[@]}
      for i in $(seq 0 $((numVals-1)))
      do
          echo -n " "${valType[$i]}"="${vals[$i]}
      done
      echo " "
  done < list.txt

Explanation:
valType contains an array of the comma seperated elements.
vals contains the associated values between the 4th and last positions in the row, with numbers and equals signs removed.
Looping through the number of values in the arrays, the matching values in both arrays can be referenced.

A: set '.\(=.[^ ]*\) ' '\([^,]*\),'
sed "s/\$/,/;s/$1$1$1$2$2$2/\4\1 \5\2 \6\3/
" <<\DATA
List of animals SET 1=Dog 2=Crow 3=Snake Pet,bird,reptile
List of Countries SET 1=France 2=Singapore 3=Columbia Europe,Asia,SouthAmerica
List of Parts SET 1=KeyBoard 2=Speaker 3=LEDpanel Computer,AudioPlayer,Television
List of Cities SET 1=Amsterdam 2=KualLumpur 3=Paris Netherlands,Malaysia,France
DATA

That uses the shell array to set your array.
OUTPUT
List of animals SET Pet=Dog bird=Crow reptile=Snake
List of Countries SET Europe=France Asia=Singapore SouthAmerica=Columbia
List of Parts SET Computer=KeyBoard AudioPlayer=Speaker Television=LEDpanel
List of Cities SET Netherlands=Amsterdam Malaysia=KualLumpur France=Paris


text:
Q: Speed of pinewood derby car If I drop a pinewood derby car from 4 feet I know it hits the ground in half a second at about 10.6 mph.
If it rolls down the track (starting at 4 feet) it takes longer, but is it possible for it to travel faster than 10.6 mph at any point?
I believe it will not travel faster but I can't prove it to myself.

A: You have to approach this from an energy standpoint.  You start with a certain amount of energy, in this case gravitational potential energy, which is dependent on the initial height ($h=4\ \text{ft}$).  At the end, you have a final energy, in the form of kinetic energy, which is given by $\frac{1}{2}mv^2$.  With no other energy terms involved (meaning you don't push it, or there is no drag or friction to drain energy), the final velocity will be the same no matter how the car gets down to the final height of 0.  Other drag terms will only reduce the energy that the car has, which will reduces the final speed.  The maximum velocity for the car can be solved for by using conservation of energy:
$$mgh = \frac{1}{2}mv_{max}^2$$
$$v_{max} = \sqrt{2gh}$$
which you can see is only dependent on the initial height, $h$.


text:
Q: What Angular 2 Tour-of-Heroes files do I need to deploy to a web server not running node I have the Angular 2 Tour-of-Heroes tutorial running on my local machine, but I would like to deploy it to a server not running node. I've tried to upload the node_modules folder, but it is huge and the environment won't doesn't allow .json files. Needless to say, it doesn't work.
I'm sure that I don't need to the .ts files in the app folder since those are generated when tsc command is run. I also think I don't need the systemjs.js, tsconfig.json, and tslint.json files.
File Structure is:
app
  app.component.js
  app.component.ts
  app.module.js
  app.module.ts
  main.ts
  main.js
  hero.js
  hero.ts
  hero-detail.component.js
  hero-detail.component.ts
  app.component.spec.js.map
  app.component.js.map
  app.component.spec.ts
  app.module.js.map
node_modules
index.html
package.json
styles.css
systemjs.config.extras.js
systemjs.config.js
tsconfig.json
tslint.json

package.json file:
If I don't want to upload all the node modules files, I have a feeling I have to change this package.json file, but I'm not sure how.
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
  "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
  "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
  "lint": "tslint ./app/**/*.ts -t verbose",
  "lite": "lite-server",
  "pree2e": "webdriver-manager update",
  "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
  "test-once": "tsc && karma start karma.conf.js --single-run",
  "tsc": "tsc",
  "tsc:w": "tsc -w"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
  "@angular/common": "~2.4.0",
  "@angular/compiler": "~2.4.0",
  "@angular/core": "~2.4.0",
  "@angular/forms": "~2.4.0",
  "@angular/http": "~2.4.0",
  "@angular/platform-browser": "~2.4.0",
  "@angular/platform-browser-dynamic": "~2.4.0",
  "@angular/router": "~3.4.0",

  "angular-in-memory-web-api": "~0.2.4",
  "systemjs": "0.19.40",
  "core-js": "^2.4.1",
  "rxjs": "5.0.1",
  "zone.js": "^0.7.4"
},
"devDependencies": {
  "concurrently": "^3.1.0",
  "lite-server": "^2.2.2",
  "typescript": "~2.0.10",

  "canonical-path": "0.0.2",
  "http-server": "^0.9.0",
  "tslint": "^3.15.1",
  "lodash": "^4.16.4",
  "jasmine-core": "~2.4.1",
  "karma": "^1.3.0",
  "karma-chrome-launcher": "^2.0.0",
  "karma-cli": "^1.0.1",
  "karma-jasmine": "^1.0.2",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~4.0.14",
  "rimraf": "^2.5.4",

  "@types/node": "^6.0.46",
  "@types/jasmine": "^2.5.36"
},
"repository": {}
}

Index.html:
I noticed that I don't have a reference to angular.js file, but the tutorial didn't use it.
<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
</html>

I am not including all the file details as I don't think that they have an impact, but I'm not sure so if you need more details, I will be happy to provide them.

A: Use Angular CLI to create, manage and build the project. Once you build the project using ng build, copy the output files from dist folder and paste these files into a server and point the index.html file.


text:
Q: UICollectionView only show last cell I'm doing a collectionView programmatically for a menu. So basic I press a button and the menu appears from the bottom of my screen. That's is working, the problem is, that I'm trying to set label on my collectionview. I set everything, but when I run the app, just my last cell show up.
So here is my CollectionView:
class SettingsLauncher: NSObject, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {

    private var blackView = UIView()

    let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        return cv
    }()
   override init() {
        super.init()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(MenuCell.self, forCellWithReuseIdentifier: K.CollectioViewCell.cell_identifier_menu)
    }

    //MARK: - Collection View DataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        3
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CollectioViewCell.cell_identifier_menu, for: indexPath)
        return cell
    }    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 60)
    }
}

And here is my cell configuration:
class BaseCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    func setupView() {

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = "Test"
    label.backgroundColor = .red
    return label
}()

let labelArray = ["nameLabel" : nameLabel]

class MenuCell: BaseCell {

    override func setupView() {
        super.setupView()
        backgroundColor = .blue
        addSubview(nameLabel)
        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[nameLabel]-|", options: [], metrics: nil, views: labelArray)
        let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|[nameLabel]|", options: [], metrics: nil, views: labelArray)

        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(horizontalConstraint)
        NSLayoutConstraint.activate(verticalConstraint)

    }
}

A: Views can only have one superview. Your nameLabel is created once, then added to each MenuCell, which means your label is removed from the previous cells. Create a UILabel for each cell and your code should work fine, like so:
class MenuCell: BaseCell {

   let nameLabel: UILabel = {
       let label = UILabel()
       label.text = "Test"
       label.backgroundColor = .red
       return label
   }()

    override func setupView() {
        super.setupView()
        backgroundColor = .blue
        addSubview(nameLabel)
        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[nameLabel]-|", options: [], metrics: nil, views: labelArray)
        let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|[nameLabel]|", options: [], metrics: nil, views: labelArray)

        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(horizontalConstraint)
        NSLayoutConstraint.activate(verticalConstraint)

    }
}


text:
Q: Safety of Class.forName in java Suppose I have the following:
public class ForNameTest {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException {
        final String s = "java.lang.Integer";
        Object test = Class.forName(s).getConstructors()[0].newInstance(222);
        System.err.println(test);
    }
}

In this code I make an object from the String s whose value is known at compile time, so I believe this code is guaranteed to be free from exploits.  Is there any value that "s" could take that would execute arbitrary code?  "s" can contain the code that is desired, if desired.

A: One can probably modify the .class file to replace string "java.lang.Integer" in string pool with "com.something.MaliciousClass". This class will be loaded and its static initializer will be executed. Even if the constructor parameters do not match.
But if one can modify .class file, then any kind of malicious code can be put in there, there is no point in replacing just one String.
If your string is assigned at compile time, you're probably safe, if you read it from somewhere, make sure it contains what you expect, i.e. whitelist names of classes that can be instantiated.


text:
Q: Python request with authentication (access_token) I am trying to use an API query in Python. From the command line I can use curl like so:
curl --header "Authorization:access_token myToken" https://website.example/id

This gives some JSON output. myToken is a hexadecimal variable that remains constant throughout.
I would like to make this call from python so that I can loop through different ids and analyze the output. Before authentication was needed I had done that with urllib2. I have also taken a look at the requests module but couldn't figure out how to authenticate with it.

A: Have you tried the uncurl package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl. Your curl request returns:
>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"

requests.get("https://website.com/id",
    headers={
        "Authorization": "access_token myToken"
    },
    cookies={},
)

A: I had the same problem when trying to use a token with Github.
The only syntax that has worked for me with Python 3 is:
import requests

myToken = '<token>'
myUrl = '<website>'
head = {'Authorization': 'token {}'.format(myToken)}
response = requests.get(myUrl, headers=head)

A: >>> import requests
>>> response = requests.get('https://website.com/id', headers={'Authorization': 'access_token myToken'})

If the above doesnt work , try this:
>>> import requests
>>> response = requests.get('https://api.buildkite.com/v2/organizations/orgName/pipelines/pipelineName/builds/1230', headers={ 'Authorization': 'Bearer <your_token>' })
>>> print response.json()

A: I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN
header = {'PRIVATE-TOKEN': 'my_token'}
response = requests.get(myUrl, headers=header)

A: The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):
>>> import requests
>>> response = requests.get(
... 'https://website.example/id', headers={'Authorization': 'access_token myToken'})

If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this (source: the missing manual):
>>> import urllib2
>>> response = urllib2.urlopen(
... urllib2.Request('https://website.example/id', headers={'Authorization': 'access_token myToken'})

A: import requests

BASE_URL = 'http://localhost:8080/v3/getPlan'
token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImR"

headers = {'Authorization': "Bearer {}".format(token)}
auth_response = requests.get(BASE_URL, headers=headers)

print(auth_response.json())

Output :

{
"plans": [
    {
        "field": false,
        "description": "plan 12",
        "enabled": true
    }
  ]
}

A: A lot of good answers already, but I didn't see this option yet:
If you're using requests, you could also specify a custom authentication class, similar to HTTPBasicAuth. For example:
from requests.auth import AuthBase

class TokenAuth(AuthBase):
    def __init__(self, token, auth_scheme='Bearer'):
        self.token = token
        self.auth_scheme = auth_scheme

    def __call__(self, request):
        request.headers['Authorization'] = f'{self.auth_scheme} {self.token}'
        return request

This could be used as follows (using the custom auth_scheme from the example):
response = requests.get(
    url='https://example.com',
    auth=TokenAuth(token='abcde', auth_scheme='access_token'),
)

This may look like a more complicated way to set the Request.headers attribute, but it can be advantageous if you want to support multiple types of authentication. Note this allows us to use the auth argument instead of the headers argument.

A: One of the option used in python to retrieve below:
import requests

token="abcd" < retrieved based>
headers = {'Authorization': "Bearer {}".format(token)}
response = requests.get(
    'https://<url api>',
    headers=headers,
    verify="root ca certificate"
)

print(response.content)

If you get hostname mismatch error then additional SANs need to be configured in the server with the hostnames.
Hope this helps.


text:
Q: Custom title in PDF files when using ps2pdf I convert .txt files to .ps files with enscript, OK!
After that I use "ps2pdf" to convert the .ps files to .pdf files. OK!
And I can see:

Question: What parameter do I have to use (with enscript or ps2pdf) to give the PDF's custom "$subject" name (I don't want "Enscript Output" title on the top of my PDF reader).
So this is not about the filenames, this is about the "$subject" that a PDF file has.

A: Angus is correct about the %%Title: comment controlling the title that the PDF will have.  But the easiest way to set the title with enscript is to use its --title option:
enscript --title 'My PDF title' foo.txt -o foo.ps

A: At the beginning of each PS file, there are especially formatted comments with some important metadata. Among them, the title (take a look to the output of head your-ps-file.ps).
You need to change the %%Title: comment. One way could be to do it right when you convert it to PDF.
< psfile.ps sed '1,/^%%EndComments/ s/^%%Title:.*/%%Title: New Title/' | \
ps2pdf - pdffile.pdf


text:
Q: How to efficiently select several value ranges in Pandas? I was revising some old code and stumbled upon this snippet.
df = pd.DataFrame({
'x': ['a', 'b', 'c', 'd', 'e', 'dc', 'ca', 'cd', 'cf', 'cv', 'cs', 'ca', 'ac', 'fc'],
'a': [34, 28, 51,5,120,12,45,56,67,54,34,32,1213,2]})

five = df[df['a'] < 5]
ten = df[(df['a'] > 5)  &  (df['a'] < 10)]
twenty = df[(df['a'] > 10)  &  (df['a'] < 20 )]
thirty = df[(df['a'] > 20)  &  (df['a'] < 30 )]
forty = df[(df['a'] > 30)  &  (df['a'] < 40 )]
fifty = df[(df['a'] > 40)  &  (df['a'] < 50 )]
sixty =  df[(df['a'] > 50)  &  (df['a'] < 60)]
over =  df[(df['a'] > 60)]

Basically there is a DataFrame and I need to group values that are within a certain range. There are multiple ranges. The grouped values are later used in a box plot.
The code above gets the job done but I am pretty sure there is a better way to do this!
Question:
What if I need to create 1000 groups? I want to change the edge values and add new groups more dynamically. How can this be done?

A: You can use pd.cut() to create bins and then df.groupby() to create a grouper object with list of dataframes split by bin. Then you can store that in a list.
(Note: I have not named each of the dfs because as you say if you have 1000 dfs, it doesn't make sense to name each. You can just store them in a list.)
import pandas as pd

cuts = [5,10,20,30,40,50,60]   #pd.cut take 2 elements from this for grouping (5,10); (30,40) etc
cols = ['x','a']             #columns to keep in final list of dataframes

df1['bin'] = pd.cut(df1['a'], cuts, right=False)   #create bins
group = df1.groupby('bin')   #groupby bins (grouper object)
dfs = [j[cols] for i,j in group]   #Iterate over grouper object to get dfs

#Printing block (ignore this)
k = list(zip(cuts,cuts[1:]))
for i,j in enumerate(dfs):
    print('Group in range',k[i],':')
    print(j)
    print('\n')

Group in range (5, 10) :
   x  a
3  d  5

Group in range (10, 20) :
    x   a
5  dc  12

Group in range (20, 30) :
   x   a
1  b  28

Group in range (30, 40) :
     x   a
0    a  34
10  cs  34
11  ca  32

Group in range (40, 50) :
    x   a
6  ca  45

Group in range (50, 60) :
    x   a
2   c  51
7  cd  56
9  cv  54

You can check the documentation for cut and groupby for more details

A: METHOD#1
You can use pd.cut and the create dynamic groups and save them in a dictionary, ,the refer each keys for the individual dataframe:
bins = [0,5,10,20,30,40,50,60,np.inf]
labels = ['five','ten','twenty','thirty','forty','fifty','sixty','over']

u = df1.assign(grp=pd.cut(df1['a'],bins,labels=labels))
d = dict(iter(u.groupby("grp")))

test runs:
print(f"""Group five is \n\n {d['five']}\n\n
         Group forty is \n\n{d['forty']} \n\n Group over is \n\n{d['over']}""")

Group five is

      x  a   grp
3    d  5  five
13  fc  2  five

Group forty is

     x   a    grp
0    a  34  forty
10  cs  34  forty
11  ca  32  forty

 Group forty is

     x     a   grp
4    e   120  over
8   cf    67  over
12  ac  1213  over

METHOD#2
you can also use locals for saving dictionary keys a local variables but the dict method is better:
bins = [0,5,10,20,30,40,50,60,np.inf]
labels = ['five','ten','twenty','thirty','forty','fifty','sixty','over']

u = df1.assign(grp=pd.cut(df1['a'],bins,labels=labels))
d = dict(iter(u.groupby("grp")))
for k,v in d.items():
    locals().update({k:v})

print(over,'\n\n',five,'\n\n',sixty)

     x     a   grp
4    e   120  over
8   cf    67  over
12  ac  1213  over

      x  a   grp
3    d  5  five
13  fc  2  five

     x   a    grp
2   c  51  sixty
7  cd  56  sixty
9  cv  54  sixty

A: You could use pandas.cut() to assign certain bins to your values. For example: you can add an extra column category in your dataframe as such:
df['category'] = pd.cut(df['a'], bins=np.arange(5, 65, 5))
This will give you the following dataframe:
     x     a      category
0    a    34  (30.0, 35.0]
1    b    28  (25.0, 30.0]
2    c    51  (50.0, 55.0]
3    d     5           NaN
4    e   120           NaN
5   dc    12  (10.0, 15.0]
6   ca    45  (40.0, 45.0]
7   cd    56  (55.0, 60.0]
8   cf    67           NaN
9   cv    54  (50.0, 55.0]
10  cs    34  (30.0, 35.0]
11  ca    32  (30.0, 35.0]
12  ac  1213           NaN
13  fc     2           NaN

and then use those values in a groupby() method using the new column after that. The bins that you supply as argument can be created quite flexibly (as shown above).
The documentation for the cut() function is here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html