Q:

Semi-regular network failure (Dropped RX Packets)

Networking is not my specialty, and I have done my best to try and isolate this problem, I would like some pointers as to how to further narrow down what the issue may be.
Server: File Sever running Limetech Unraid 5.0.6 (Slackware based OS with kernel 3.9.11p)
This server has been running reliably for about 2 years with the only recent hardware change being a RAM upgrade (I have already used a memory tool to verify that the RAM is working perfectly)
Initial Symtoms:
Other computers on the network accessing network shares suffered intermittent disconnection for 10-20 seconds every 3-5 minutes.
Investigations
Using repetitive ping tests, I was able to determine that all other devices on the network maintained their connections, it was only the file server that was dropping of for brief periods of time.
Pinging to or from the file server would fail for up to 8 seconds at semi-random intervals from just 30 seconds apart to greater than 15 minutes apart, with an average of around 3-5 minutes.
Rebooting the server seemed to make the problem go away for a few hours.
ifconfig shows small numbers (3-7) of RX packets being dropped at about the same time the connection appears to fail
syslog doesn't report anything unusual either on boot, or during the failure.
ethtool shows that the Link is maintained 100% of the time
I'm not a network engineer, but it seems that the issue is specific to this device (Other devices connected to the same infrastructure have no issues).
Is this likely to be a hardware issue with the NIC itself? or is it something to do with the OS or Network config? Could it be caused by user Software?
Any suggestions on how to identify the root cause would be greatly appreciated.
Log/Troubleshooting output:
Ping from Windows laptop to Unraid Server:
Reply from x.x.x.100: bytes=32 time=3ms TTL=64
Reply from x.x.x.100: bytes=32 time=7ms TTL=64
Reply from x.x.x.100: bytes=32 time=3ms TTL=64
Reply from x.x.x.100: bytes=32 time=3ms TTL=64
Reply from x.x.x.100: bytes=32 time=4ms TTL=64
Reply from x.x.x.100: bytes=32 time=3ms TTL=64
Request timed out.
Request timed out.
Request timed out.
Reply from x.x.x.200: Destination host unreachable.
Request timed out.
Reply from x.x.x.100: bytes=32 time=2ms TTL=64
Reply from x.x.x.100: bytes=32 time=1ms TTL=64
Reply from x.x.x.100: bytes=32 time=4ms TTL=64
Reply from x.x.x.100: bytes=32 time=2ms TTL=64
Reply from x.x.x.100: bytes=32 time=2ms TTL=64

ifconfig -a
eth0      Link encap:Ethernet  HWaddr 94:de:80:03:2e:3c
          inet addr:x.x.x.100  Bcast:x.x.x.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:35866080 errors:0 dropped:2107 overruns:0 frame:0
          TX packets:35139719 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1597778360 (1.4 GiB)  TX bytes:1548836243 (1.4 GiB)
          Interrupt:49

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:1583 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1583 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:158298 (154.5 KiB)  TX bytes:158298 (154.5 KiB)

netstat -i
Kernel Interface table
Iface   MTU Met   RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0       1500 0  35866360      0   2107 0      35139884      0      0      0 BMRU
lo        65536 0      1583      0      0 0          1583      0      0      0 LRU

dmesg | grep r8168
r8168 Gigabit Ethernet driver 8.037.00-NAPI loaded
r8168 0000:02:00.0: irq 49 for MSI/MSI-X
r8168: This product is covered by one or more of the following patents: US6,570,884, US6,115,776, and US6,327,625.
r8168  Copyright (C) 2013  Realtek NIC software team <nicfae@realtek.com>

cat /var/log/syslog | grep eth
Jan 10 03:04:03 ServerName logger: /etc/rc.d/rc.inet1:  List of interfaces: 'eth0'
Jan 10 03:04:03 ServerName kernel: eth%%d: 0xf8560000, 94:de:80:03:2e:3c, IRQ 49
Jan 10 03:04:03 ServerName logger: /etc/rc.d/rc.inet1:  Polling for DHCP server on interface eth0:
Jan 10 03:04:03 ServerName logger: /etc/rc.d/rc.inet1:  /sbin/dhcpcd -t 10 -h ServerName -L eth0
Jan 10 03:04:03 ServerName dhcpcd[1203]: eth0: waiting for carrier
Jan 10 03:04:08 ServerName kernel: r8168: eth0: link up
Jan 10 03:04:08 ServerName dhcpcd[1203]: eth0: carrier acquired
Jan 10 03:04:08 ServerName dhcpcd[1203]: eth0: broadcasting for a lease
Jan 10 03:04:11 ServerName dhcpcd[1203]: eth0: offered x.x.x.100 from x.x.x.1
Jan 10 03:04:11 ServerName dhcpcd[1203]: eth0: acknowledged x.x.x.100 from x.x.x.1
Jan 10 03:04:12 ServerName dhcpcd[1203]: eth0: checking for x.x.x.100
Jan 10 03:04:16 ServerName dhcpcd[1203]: eth0: leased x.x.x.100 for 86400 seconds
Jan 10 03:04:31 ServerName logger: #  * SSL.Connection objects, wrapping the methods of Python's portable
Jan 10 03:04:36 ServerName avahi-daemon[7491]: Joining mDNS multicast group on interface eth0.IPv4 with address x.x.x.100.
Jan 10 03:04:36 ServerName avahi-daemon[7491]: New relevant interface eth0.IPv4 for mDNS.
Jan 10 03:04:36 ServerName avahi-daemon[7491]: Registering new address record for x.x.x.100 on eth0.IPv4.
Jan 10 03:05:08 ServerName ntpd[1258]: Listen normally on 2 eth0 x.x.x.100 UDP 123
Jan 10 15:04:17 ServerName dhcpcd[1203]: eth0: renewing lease of x.x.x.100
Jan 10 15:04:17 ServerName dhcpcd[1203]: eth0: acknowledged x.x.x.100 from x.x.x.1
Jan 10 15:04:17 ServerName dhcpcd[1203]: eth0: leased x.x.x.100 for 86400 seconds
Jan 11 03:04:18 ServerName dhcpcd[1203]: eth0: renewing lease of x.x.x.100
Jan 11 03:04:18 ServerName dhcpcd[1203]: eth0: acknowledged x.x.x.100 from x.x.x.1
Jan 11 03:04:18 ServerName dhcpcd[1203]: eth0: leased x.x.x.100 for 86400 seconds
Jan 11 15:04:18 ServerName dhcpcd[1203]: eth0: renewing lease of x.x.x.100
Jan 11 15:04:18 ServerName dhcpcd[1203]: eth0: acknowledged x.x.x.100 from x.x.x.1
Jan 11 15:04:18 ServerName dhcpcd[1203]: eth0: leased x.x.x.100 for 86400 seconds

Yes this is selected output - I have viewed the syslog and dmesg in detail and can provide more if required, however I am confident that there is nothing in there of value. The reason for holding back? I am paranoid about providing to much info about my network set up on the public internet, and cleaning out put is time consuming.

A:

Problem solved - it was not the Unraid server, but rather unexpectedly, a surge protector.
In my network setup I have a high end surge protector that isolates the internal network from the outside world so in the event of a lightning strike/power surge my expensive equipment is protected.
It's a bit of a long story as to why everything indicated it was the File Server, but the short answer is:

The file server and internet gateway sat on one side of the protector while everything else was on the other
Only traffic passing through the protector was affected (So 2 devices pinging each other on the same side of the S.P didn't appear to show any problems)
Losing connectivity for a few seconds every few minutes is almost completely undetectable for most network applications - it was only the high data throughput required when using the File Server that made the issue noticeable.

When I was isolating network hardware to ensure it was the file server that was the problem, I never thought to isolate this particular component (I barely consider it to be network hardware).
I have no idea why it was causing the problem, but it is clear that it was. I have simply removed it from the network for now, it's hardly vital to the system in any case.


Q:

SQL Server 2005 - How to take a record from one table and loop through another table looking for match

I have 2 tables. for this example I will use only one users records.
The first table has the user name and an evaluation date as such:
USER  EVALDATE
--------------
bobr  6/7/2010
bobr  9/20/2010
bobr  9/21/2010

The above table needs to be joined against this user history table, which has the history of the ID's and the dates they were valid, to look for a match (the NULL date means current):
USER   STARTDATE   ENDDATE
----------------------------
bobr   2/20/2006   4/18/2010
bobr2  4/19/2010   9/7/2010
bobr   9/8/2010    null

What I'm trying to do in SQL Server 2005 is take the first record from the first table, loop it through the second table and when(if) the EVALDATE is within one of these date ranges and the IDs match, then flag that record from the first table as valid.
The current code takes the record from the first table and runs against all rows of the second table and kicks out a record for each invalid evaldate, so it kicks out a record when joined against the second table because the evaldate is not between the dates of the first record on the history table, even though the record is fine because the evaldate is between the start and end dates of the third record in the history table.
I hope this makes sense! In something like SAS I can create an array and loop through checking against each record in the history table. How do I do this in SQL? What I was trying to do was just update the first table with a flag if the records dates are invalid. Any ideas? Thanks!!!

A:

Try this:
SELECT  [USER]
       ,[EVALDATE]
       ,CASE WHEN ( SELECT  COUNT(*)
                    FROM    [UserStartEndDates] b
                    WHERE   [a].[USER] = [b].[User]
                            AND [EVALDATE] BETWEEN [STARTDATE]
                                               AND COALESE([ENDDATE],[EVALDATE])
                  ) > 0 THEN 1
             ELSE 0
        END AS [IsValid]
FROM    [Evaluations] a


Q:

How do I programmatically generate something like /proc/pid/maps?

How do I programmatically generate something like /proc/pid/maps ?
Is there an API which can get me the same data as in /proc/pid/maps ?
Parsing text can be a bit flaky.

A:

/proc/$pid/maps is the API. If you're using C, you can reliably parse lines in this file using the scanf format:
"%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu %n"

(source)


Q:

Loading Vector Layer using python console in qgis

I am using qgis2.6 version and new to pyQGIS. I tried to load a vector file using python console in qgis. I don't know where I am wrong. The layer was not loaded and does not show any error too. Help would be appreciated.The code which i tried is below.
wb = QgsVectorLayer('C:\Users\new\Desktop\PyQGIS\pyqgis_data\world_borders.shp', 'world_borders', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(wb)

A:

I don't have a Windows OS to test it, but I'm pretty sure the problem is in the path to your ShapeFile. Make sure the path is correct and try with slashes (/) or double back slashes (\\).


Q:

Looking for idiom meaning "to make many serious or stupid mistakes"

I'm working on a translation with the guidelines to make it as accurate as possible, so dynamic equivalence is important. My provisional translation is "to screw up royally," but it feels a bit too extreme compared to the original phrase.
EDIT: I belatedly realized I should've explained the context better.
The (Ukrainian) idiom literally translates as "to break firewood." It's meant to evoke the image of chopping logs incorrectly or incompetently, thus ruining them for their intended use. The translated sentence reads as follows:
"Yes, on one hand it may be correct to catch a bunch of smugglers, but on the other, it is possible to break firewood."
The context of the sentence is that simply capturing criminals while disregarding the underlying cause for their existence -- the local population's mentality and socioeconomic status -- is (as the used idiom indicates) a mistake that will carry a repeated or cumulative negative effect.
I hope this explains things better and my apologies for doing such a poor job of it the first time around.

A:

I'd suggest "make a hash of", which is defined by oxforddictionaries.com as "make a mess of; bungle".
This phrase seems especially apt as a translation of the original Ukranian idiom because the origin of the verb "to hash" is given by the Online Etymology Dictionary as "from French hacher 'chop up' (14c.), from Old French hache 'ax' (see hatchet)".


Q:

Variable value not getting resolved in argument and echo statement failed to print

I have child script which will source the main script and will pass the argument to the Function available in Main script and execute the function definition. Function call is working fine for me, but i'm facing the below issues

First echo statement is not getting printed

Variable now is not getting resolved in child script argument
Please find my findings below.

Main Script
Function_1 ()
{
cd /home/test/

File_name="$1".txt

if [[ "$File_name" =~ ^[[:alnum:]][[$_."#&']] ]]; then
echo " For your Info, File name can be alpha numeric and can contain special characters like $_."&'#" please proceed "
fi

 if [[ -f "$File_name" ]];
then
echo "File Name - $File_name"
else
echo "File Name - $File_name doesn't exists"
 fi

}

Child Script
export now=$( date '+%Y%m%d' )
Function_1 'abc_${now}'

Expected result
For your Info, File name can be alpha numeric and can contain special characters like $_."&'#" please proceed
File Name - abc_20200204.txt

Actual result
File Name - abc_$now.txt doesn't exists

A:

I think the problems you experienced can in general be attributed to the handling of special characters and quoting in your shell script.
As a leading remark: you didn't mention how your child script gets access to the functions in the main script, but I assume you do something like
~$ source main_script.sh
~$ export now=$( date '+%Y%m%d' )
~$ Function_1 'abc_${now}'

If I do so, my shell complains about several syntax errors, and the script wouldn't work. I assume you also use the bash since you used that tag, and I admit that I am surprised you did not encounter these errors. You may still want to consider using a tool like shellcheck, available online or as software package in many Linux distributions, to verify your shell-scripts - it certainly helps me finding typos and the like.
Now to the issues you encountered.
You state that the first echo output never occurs. I think this is related to the construction of your regular expression, and the use of special characters:

In the test statement [[ "$File_name" =~ ^[[:alnum:]][[$_."#&']] ]], you use a character list [$_."#&'] with characters that are special to the shell: The $_ for example, will likely be interpreted as the last shell argument, and the double-quotes " will be interpreted by the shell as the beginning of a literal string, which ends in the next line with the first " of your echo command. This should throw a syntax error, beacuse the shell tries to interpret your output message as shell commends; it definitely does so when I try it. You should make sure to escape such characters to inhibit unwanted interpretation by the shell, as in \$_\"\#\&\'.
Also, you use double square brackets [[ ... ]] for a character list. However, this is syntactically undefined. What is defined is a character list [ ... ] consisting of only one character class, e.g. [:alnum:]. This kind of construct would indeed be written as [[:alnum:]], as you already did in the first part of your regular expression. You should therefore omit the "outer" pair of square brackets.
You have started your regular expression with the "start anchor" ^. I assume therefore that you want to allow filenames that start with a regular letter or number, but then may contain all special characters you mentioned. However, your regular expression allows only for filenames starting with one alphanumeric character and then requiring one of the special characters as second character. If you want to ensure that any number of these are allowed in addition to alphanumeric characters, you would instead write something like ^[[:alnum:]][[:alnum:]\$_.\"\#\&\']*$. The second part is then a character list [ ... ] containing the character class [:alnum:] and in addition the special characters $, _, ., ", #, & and ', zero or more times (*) until the end of the string ($). This last anchor character ensures that the entire filename consists only of the characters you allowed.

Your next point concerns that the ${now} variable is not resolved (i.e. "expanded" in the shell terminology).

As was already noted in several comments, parameter expansion does not happen inside single quotes ' ... '. If you use double quotes " ... " instead, the variable expansion will work.
You seem to be certain that you need single quotes at this point. It that is really so, there is little you can do; in that case, you may need to further explain why you need the single quotes (i.e. what you want to achieve, or whether further processing of the expression 'abc_${now}' including the quotes is desired later in the process).


Q:

Setting the ConnectionStrings.config transformation in Habitat

We are using habitat in our project for a multisite implementation.
Can we setup the ConnectionStrings.config transformation in the Project/common layer of the habitat framework. Is this doable?

A:

You can do this. You would just need to add the config file to the project and it will get published with the rest of the files and it will overwrite the file in the webroot.
I would question if you should do this tho. The connection strings get set when you install the Sitecore instance. So each developer should already have that set. If you put this file in the project and thus source control, you either need to make sure all devs have the exact same machine setup or they will have to make changes and not commit those.
Also you end up potentially having SQL Server logins stored in plain text. Not something I would be comfortable with. So while you can do it, I would recommend not doing it.
Edit
Environment Transforms
As an update to the previous answer, I agree totally with @jammykam. If you need to update connection strings per environment, that is where you need to tokenize your values in the source file and then use your release management tool, whether that be Octopus Deploy, TFS Release Manager etc... to substitute those tokens with the real values.
For local development, you can then use a .debug.config transform and a tool like SlowCheetah to make sure your development values are added. That is how I work with all configs not just the connection strings.


Q:

MySQL link to return results

I have an image that is displayed from a table and I want the user to be able to click the image which directs them to a page that returns the rest of the data for that row. Do I need a php loop for this? I can't quite figure it out.
This returns the Last Name, First Name, and an Image:
    <?php
    if (isset($_GET['LastName'])) {
    $ln = $_GET['LastName'];
    }
        include 'connection.php';
        $query = "SELECT * FROM residents WHERE LastName like '$ln%' ";
        $result = mysql_query($query);

    while($person = mysql_fetch_array($result)) { ?>

         <a class="pull-left" href="redirectionpage.php?<?php echo $person['ID'];?>.php">
    <img class="media-object" src="upload/<?php echo $person['Picture'];?>"   width="100" height="100"/>

<?php echo $person['LastName'] . ", " . $person['FirstName']; ?>

    <?php }>?

Is the best way to accomplish this by redirecting the user to a new page and using a mysql statement to display the new data?
This is the code for the other page:
    <?php
    //Gets data from the database
        include ('header.php');
        include ('footer.php');
        include ('connection.php');

        $query = "SELECT * FROM residents WHERE ID = LastName LIMIT 1";
        $result = mysql_query($query);

       while($row = mysql_fetch_array($result)){
       $outputpicture.='

';
       $outputname.= $row['LastName'] . ", " . $row['FirstName']. '
';
       $outputspouse.= $row['Spouse']. '
';
       $outputrelatives.= $row['Relatives']. '
';
       $outputaddress.= $row['Address']. '
';
       $outputbirthday.= $row['Birthday']. '
';
       $outputbegan.= $row['BeganResidence']. '
';
       $outputended.= $row['EndedResidence']. '
';
       $outputformer.= $row['FormerResidence']. '
';
       $outputcareer.= $row['Career']. '
';
       $outputeducation.= $row['Education']. '
';
       $outputmaritalstatus.= $row['MaritalStatus']. '
';
       $outputsiblings.= $row['Siblings']. '
';
       $outputspecialinterests.= $row['SpecialInterests'].'
';
       }

      ?>

A:

The link needs to be changed to
<a class="pull-left" href="redirectionpage.php?id=<?php echo $person['ID'];?>">

Adding this id= will allow you to access the id parameter in redirectionpage.php via the $_GET superglobal.
$id = $_GET['id'];

You can use the $id variable to select the specified row from your database. You will see a lot of examples that do it like this:
$query = "SELECT * FROM residents WHERE ID = $id";

This works but you should not do it, because it creates an SQL injection vulnerability. Read about prepared statements and create your SQL so that you can pass the ID as a paramater.
$stmt = $pdo->prepare("SELECT * FROM residents WHERE ID = :id");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();

This should also be applied to the code you use to select the list of images.
Assuming ID is the key for your residents table, this should select only one record, so you will not need the while loop. You can just use one fetch.


Q:

Numpy print a 1d array as a column

I have an array that is 1d, and I would like to print it as a column.
r1 = np.array([54,14,-11,2])
print r1

gives me this:
 [ 54  14 -11   2]

and
 print r1.shape

gives me this:
(4L,)

Is there something I can plug into np.reshape() so that
print r1.shape

gives me this?
(,4L)

And the printed output looks something like
 54
 14
-11
 2

A:

This will work:
import numpy as np

r1 = np.array([54,14,-11,2])

r1[:, None]

# array([[ 54],
#        [ 14],
#        [-11],
#        [  2]])


Q:

Loading Window on Page Load asp:UpdateProgress

I have a really large page that takes some time to pull the data and load.  When first navigating to the .aspx page I would like it to have a nice loading .png image to come up so people don't close the window before it displays.  I've tried putting an asp:UpdateProgress but this never shows up until after the page loads and I do something on the page.  How do I get the loading screen first before the rest of the page loads?  Below is what I tried that doesn't work.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="10">
        <ProgressTemplate>

            <asp:Label ID="Label12" runat="server" Text="Loading...">
            </asp:Label>
            <asp:Image ID="Image1"
            runat="server" ImageUrl="~/images/1status.png" />

        </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <%-- My page loading stuff -->
        </ContentTemplate>
</asp:UpdatePanel>

I've also tried with a timer.  Here it gets interesting.  Labels inside the ContentTemplate show up fine on tick.  The GridView I place inside Content Template does not.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:Image ID="Image1" runat="server" ImageUrl="~/images/1status.png" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" Visible="false">
        <ContentTemplate>

        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Timer ID="Timer1" runat="server" Interval="600" OnTick="Timer1_Tick"></asp:Timer>

protected void Timer1_Tick(object sender, EventArgs e)
{
 UpdatePanel1.Visible = true;
 Timer1.Enabled = false;
 Image1.Visible = false;
}

I've even tried taking out the updatepanel completely and just changing the gridview visible state on timer and that still doesn't work.  The gridview never appears.
What's interesting is that if I put a button on the page that does the following,
protected void ButtonHide_Click(object sender, EventArgs e)
{
        if (GridView1.Visible)
        {
            GridView1.Visible = false;
        }
        else
        {
            GridView1.Visible = true;
        }

}

I can click it and hide and show the GridView as many times as I want with no problem.  Why is the timer any different?

A:

In the .aspx code I set up a timer, TimerRefresh but leave it turned off.  Then when the page begins loading if this is not a PostBack (the first time) I turn on TimerRefresh.  It immediately ticks. This causes a page reload which will be a PostBack.  This causes UpdateProgress1 to show.  PageLoad() will do nothing because this is a PostBack.  TimerRefresh_Tick(object sender, Eventargs e) fires because this was triggered from the timer ticking.  This causes it to turn off the timer from running again and loads the page with data.  As soon as it is complete UpdateProgress1 goes away.
In Page_Load()
if (!IsPostBack)
{
 TimerRefresh.Enabled = true;
}

In TimerRefresh_Tick(object sender, EventArgs e)
TimerRefresh.Enabled = false;
codeToLoadDate();

The .aspx
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="10">
    <ProgressTemplate>

        <asp:Label ID="Label12" runat="server" Text="Loading...">
        </asp:Label>
        <asp:Image ID="Image1"
        runat="server" ImageUrl="~/images/1status.png" />

    </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Timer ID="TimerRefresh" runat="server" Interval="100"
         ontick="TimerRefresh_Tick" Enabled="False">
    <%-- My page loading stuff - controls that would hold data -->
    </ContentTemplate>
</asp:UpdatePanel>


Q:

From within a function, how to view the result that so far will be returned to the pipeline

Recently I had to add an intermediate variable to a PowerShell script, otherwise the New-Item result would be part of the function result:
      # Put in local varible, otherwise we will return it as part of the function result
      $Local:logDirectory = New-Item -ItemType directory -Path $Local:logDir
      Write-Host "Created directory '$Local:logDir'"
  }
  return "$Local:logDir\$LogFileName"

While debugging this, I would have loved to be able to dump (Write-Host or something) the current bits that the function already has queued up to end in the pipeline upon function return.
So:
From within a PowerShell function, how to view the result that so far will be returned to the pipeline

A:

Use PowerGUI (a powershell IDE), you will be able to insert breakpoints and inspect the runtime variables.
http://en.community.dell.com/techcenter/powergui/m/
You can also use piping to Out-Null, i.e:
New-Item -ItemType directory -Path $Local:logDir | Out-Null
to get rid of spurious output. Unfortunately you might have to go through your code line by line.


Q:

Xcode 9 doesn't have any simulator device

I just downloaded xcode 9 beta, but there is no simulator within it. Try to add new simulator but the create button doesn't work. Please help
By "no simulator within it" I mean there is option to build with simulator.
See
.
Also, the create button doesn't work

A:

Go to Xcode Preferences -> Locations and go to the Derived Data location in Finder:

Just remove all contents from it, then right click on Xcode icon and quit it, and reopen it:

A:

It is a simulator but you need to close Xcode 8 if you have it open and restart Xcode 9 beta.


Q:

Convert a String[] in C# to a Char *[] in C++

I am currently using Visual Studio 2010.  This is my first time writing a wrapper for a C++ class.  The class in C++ looks like this:
bool exampleCode(char* arrayOfStrings[], int number, char* regularString)

I created the header file which looks like:
bool exampleCode(array<String^>^ arrayOfStrings, int number, String^ regularString)

and the .cpp file class looks like:
bool exampleCode(array<String^>^ arrayOfStrings, int number, System::String^ regularString)

I figured out how to marshal the regularString data but I'm not sure how to convert the String array into a char*[].  Any help would be appreciated.

A:

Here's an easily reusable version (complete with demonstration) that improves on @ildjarn's answer by reducing the number of allocations and improving locality.  It also uses your choice of encoding such as UTF-8.
#include <iostream>
#include <vector>

#include <windows.h>
#include <vcclr.h>

using namespace System;

template <typename T>
struct advanced_marshal;

template <>
struct advanced_marshal<char*[]>
{
    char** get() { return &m_strings[0]; }

    advanced_marshal( array<System::String^>^ strings, UINT code_page = CP_ACP ) : m_strings(strings->Length)
    {
        if (int count = strings->Length) {
            int i;
            size_t total_length_estimate = count; // one NUL byte per string
            for( i = 0; i < count; ++i ) {
                total_length_estimate += strings[i]->Length * 4;
            }

            m_buffer.resize(total_length_estimate);
            auto tail = m_buffer.begin(), end = m_buffer.end();
            i = 0;
            do {
                m_strings[i] = &*tail;
                pin_ptr<const WCHAR> pwsz = PtrToStringChars(strings[i]);
                tail += 1 + WideCharToMultiByte(code_page, 0, pwsz, strings[i]->Length, &*tail , end - tail, nullptr, nullptr);

                ++i;
            } while (i < count);
        }
    }

    advanced_marshal(advanced_marshal<char*[]>&& other) { m_buffer.swap(other.m_buffer); m_strings.swap(other.m_strings); }

private:
    advanced_marshal(const advanced_marshal<char*[]>&); // = delete
    void operator=(const advanced_marshal<char*[]>&); // = delete

    std::vector<char> m_buffer;
    std::vector<char*> m_strings;
};

void print_some_strings( char* strings[], int num )
{
    for( int i = 0; i < num; ++i )
        std::cout << strings[i] << "\n";

    std::cin.get();
}

int main(array<System::String ^> ^args)
{
    print_some_strings(advanced_marshal<char*[]>(args).get(), args->Length);
    return 0;
}


Q:

Get data from API and iterate over in Angular2

I am new in Angular2 and trying to do a simple task but it doesn't seem to work.
This is my TS file
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
products;

constructor(private api: ApiService) {}

ngOnInit() {
    this.getProducts();
}

getProducts() {
    this.products = this.api.get('http:/api/products').map((res:Response) => res.json());
    console.log(this.products);
}
}

But when I try to iterate in html file like this.

Products

{{ products.title }}

There is no output shown. What is strong with my code?

A:

You forgot to subscribe to the observable.
Please change this.products = this.api.get('http:/api/products').map((res:Response) => res.json());
to
this.subscription = this.api.get('http:/api/products').map((res:Response) => res.json()).subscribe(data => this.products = data);
Also, consider changing #product of products ; #i = index to let product of products" most examples, guides use let. If you don't use the i from #i = index later in the code please consider deleting it to keep the code more simple.
Edit: Also add a new property in the component private subscription: Subscription and import Subscription from RxJS. Later don't forget to unsubscribe on ngOnDestroy or after this.products = data;.
Assuming that private api: ApiService calls internally the http Angular service.
Or change to the template let product of products | async and keep the typescript code as you have it originally without changes. | async will subscribe to the products observable and unsubscribe automatically. Also {{ product.title } is the correct syntax and not products.


Q:

awk maximum value of sequence of directories

I'm trying to find the maximum value in a directory suffix using awk.  The directories are named: dir.{1,2,3,4,5,6,7,8,9,10,11,12,13,etc}.  My best attempts keep returning "9" as the highest value, probably due to it listing after the 'teens.
The best I could do was to output the directory listing to a temporary file and run awk against that.  Is there a better way to find the greatest value in the suffix of dir.* with awk? I'd like to avoid creating a temporary file and just use 'ls -1' or similar input.
My directories of interest:
$ ls -1
dir.1
dir.10
dir.11
dir.12
dir.13
dir.14
dir.15
dir.2
dir.3
dir.4
dir.5
dir.6
dir.7
dir.8
dir.9

My awk command and output:
$ awk 'BEGIN {max = 0} {if ($1>max) max=$1} END {print max}' DATA
dir.9

I'd like that result to be "dir.15".

A:

When you compare two strings which are not numbers in awk, it compares them alphabetically. So you need to compare the actual numbers.
awk -F. '$NF+0>max{max=$NF;maxline=$0}END{print maxline}'

-F. sets the field separator to ., so that $NF, which is the value of the last field, will be the number following the last (or only) dot. We add 0 in case it is not a number. That will force it to be a number, converting any string which doesn't start with a digit into a 0.
There is no need to initialize max because as an uninitialized variable, it is numerically equivalent to 0.
Also, as @triplee notes in a comment, there is no need for a temporary file, since you can just pipe ls -d directly into the above awk line, assuming that no directory has a newline in its name:
ls -d | awk -F. '$NF+0>max{max=$NF;maxline=$0}END{print maxline}'


Q:

Distinct ball weights but balance on the scale

You are given eight identical-looking balls and a two-sided scale. All of the ball weights are distinct, but if you put 4 specific ones on the one side, and the rest on the other side of the scale, they balance themselves.
If you are only allowed to put exactly 4 balls on both sides at a time,

What is the minimum number of weighings required to find the balance in the worst case scenario?

A:

Not a proper solution to the question asked, but per @Oray's request, perhaps a reasonably elegant benchmark?
Label the balls A-H, and start ABCD in the left pan, EFGH in the right.  Add a dot to each ball in the heavier pan.  For each subsequent weighing, the left pan should contain the lexicographically first combination of four balls among those which distribute the dots as evenly as possible between the two pans, excluding those which have already been tried.  For example, the second weighing will be ABEF<>CDGH, since each pan will have two dots regardless of which initial set was heavier.
To take this for a test drive, I took two sets of balls which summed to one, and partitioned each into distinct fractions with coprime denominators.  To start,  (1,2,3,4)/10  and (1,2,3,5)/11.  This does give two 2-subsets that add to 5/10, but as I mentioned above, I don't think this is actually relevant, and you can always add/subtract an epsilon if it bothers you without affecting the results.  Then I assigned all 40320 permutations of A-H and counted weighings up to the one that balanced, with the following results.
1 1152
2 1152
3 1264
4 1388
5 1296
6 1396
7 1404
8 1517
9 1530
10 1532
11 1674
12 1782
13 1871
14 1777
15 1645
16 1832
17 1945
18 2028
19 2109
20 2199
21 2146
22 2183
23 1722
24 1033
25 504
26 171
27 38
28 29
29 1

for an average-case of ~13.68...an improvement over brute-force case-checking (17.5), but not as much as I might have hoped.  There is something obscenely inefficient going on in my code, as it only checks about 20 cases/second, otherwise would have many more cases checked.   That lone straggler, by the way, is:
[A,B,C,D,E,F,G,H]=[44, 10, 50, 11, 30, 20, 22, 33]
and the resulting sequence of marks and weightings:
1 [0, 0, 0, 0, 0, 0, 0, 0] ABCD 0 0 115 105
2 [1, 1, 1, 1, 0, 0, 0, 0] ABEF 2 2 104 116
3 [1, 1, 2, 2, 0, 0, 1, 1] ABCE 4 4 134 86
4 [2, 2, 3, 2, 1, 0, 1, 1] ABDF 6 6 85 135
5 [2, 2, 4, 2, 2, 0, 2, 2] ABCF 8 8 124 96
6 [3, 3, 5, 2, 2, 1, 2, 2] ABDE 10 10 95 125
7 [3, 3, 6, 2, 2, 2, 3, 3] ABGH 12 12 109 111
8 [3, 3, 7, 3, 3, 3, 3, 3] ABCG 16 12 126 94
9 [4, 4, 8, 3, 3, 3, 4, 3] ABDG 15 17 87 133
10 [4, 4, 9, 3, 4, 4, 4, 4] ABEG 16 20 106 114
11 [4, 4, 10, 4, 4, 5, 4, 5] ABFH 18 22 107 113
12 [4, 4, 11, 5, 5, 5, 5, 5] ABCH 24 20 137 83
13 [5, 5, 12, 5, 5, 5, 5, 6] ABDH 21 27 98 122
14 [5, 5, 13, 5, 6, 6, 6, 6] ACDE 29 23 135 85
15 [6, 5, 14, 6, 7, 6, 6, 6] ADEF 25 31 105 115
16 [6, 6, 15, 6, 7, 6, 7, 7] ACDF 33 27 125 95
17 [7, 6, 16, 7, 7, 7, 7, 7] ADEG 28 36 107 113
18 [7, 7, 17, 7, 7, 8, 7, 8] ACDG 38 30 127 93
19 [8, 7, 18, 8, 7, 8, 8, 8] ADFG 32 40 97 123
20 [8, 8, 19, 8, 8, 8, 8, 9] ABEH 33 43 117 103
21 [9, 9, 19, 8, 9, 8, 8, 10] ACFG 44 36 136 84
22 [10, 9, 20, 8, 9, 9, 9, 10] AEFH 38 46 127 93
23 [11, 9, 20, 8, 10, 10, 9, 11] AEGH 41 47 129 91
24 [12, 9, 20, 8, 11, 10, 10, 12] AFGH 44 48 119 101
25 [13, 9, 20, 8, 11, 11, 11, 13] AEFG 46 50 116 104
26 [14, 9, 20, 8, 12, 12, 12, 13] ABFG 47 53 96 124
27 [14, 9, 21, 9, 13, 12, 12, 14] ADEH 50 54 118 102
28 [15, 9, 21, 10, 14, 12, 12, 15] ADFH 52 56 108 112
29 [15, 10, 22, 10, 15, 12, 13, 15] ADGH 53 59 110 110

A long way from the lower bound of 6, but still better than exhaustively testing all 35.  The other angle I was considering was to start with 7 weighings such that every triplet of balls shares a pan exactly once, but I suspect pathological cases will stop that from being sufficient, and this would be easier to execute from memory/by hand in a pinch.
UPDATE:  Some combinations of 13ths and 14ths got up to a worst-case of 32, suggesting that additional heuristics like @Ben J's  are needed to avoid particularly unfortunate orderings (with the same inputs his worst-case is 30, so they do help).  I have a couple of refinements in mind myself, but perhaps a more binary-tree oriented approach would be better, if we could map out the feasible sum-orderings (which look to be a MUCH smaller set than I'd imagined, but tricky to make sure I've caught them all...)
...or maybe, per Dave B's suggestion,  [1,2,3,25,26,27,28,100] renders the whole exercise moot.  Well, at least it behaves interestingly for more uniform distributions. ^_^b

A:

Since the question asks about

[T]he minimum number of weighings required to find the balance in the worst case scenario?

The answer is either

 1 (We got lucky, despite having the worst-scenario setup - a lucky guess would always be the minimum, right?)

or

 35 (Using an nCr of 8C4, then dividing by two because we count everythig twice - an A-B-C-D / E-F-G-H split is identical to E-F-G-H / A-B-C-D)

But why?

 The worst-case scenario is a Jovian setup.  If we let the letters A-H represent the weights of the orbs such that A > B > C > ... > H, a Jovian scenario is one where the balance is A (Jupiter) plus the three smallest weights (F + G + H)

 This is the worst case scenario because no matter how you mix the spheres, the side that contains Jupiter will always outweigh the other side, with the single exception of when Jupiter is partnered with the three lightest ones, which is our solution

Thus

 There is no way, within the confines of this puzzle, to extract any additional information about any of the other orbs to take any short cuts.  We can identify which orb is Jupiter after only a few moves, but once we have done so we are no closer to finding the correct combination - the only combinations we have ruled out are the exact combinations that we have already tried along the path to discovering that we have a Jupiter orb and a Jovian system.

Assuming 'Worst-Case-Scenario' means that, no matter what our strategy/setup is, we will guess wrong every time until we have 100% certainty:

 35 operations is the worst-worst-case scenario, since we cannot gain any additional information about the identities of orbs B through H in a Jovian situation.

Another way to phrase this would be:

 Given that there are 35 possible combinations, each attempt will rule out at least one of those 35 possibilities.  If we can manipulate the scales in some way to learn more about the identities of the balls and their relative weights, we can potentially rule out more than one.

 However, when Jupiter is in the mix, we can never learn anything about the relative weights of orbs B-H. We can only figure out that A plus any three is heavier than the remaining four. This knowledge doesn't help us get to the solution any faster.  Once we've identified Jupiter, every non-solution trial looks identical to every other non-solution trial, so there is no additional information to be gleaned by doing clever comparisons. Even if we fix Jupiter and only shuffle the remaining orbs, our choices total 7C3, which is exactly equal to (8C4)/2.

Note: Jason Kim has a good point in their partial answer:

 If we don't need to actually verify that the last combination works, we can subtract 1 from the total number of weighings. Thus, once we have ruled out 34 of the possible combinations we know what the correct combination is.

 However, if we're in a dastardly dungeon where the sealed door won't unlock until the correct distribution of mystic orbs are placed on the correct receptacles, the unlucky adventurers won't get through until their 35th try

A:

Assuming only one combination will balance the scale:

 You can fix one ball on one side of the scale. You are then left with 7 balls.

Then:

 Divide the 7 balls into two groups of 3 and 4. This can be done in $^7C_4 = 35$ ways.


Q:

Events, double dispatching and abstract event handling

Imaging a simple double-dispatch event handling scheme:

It's cool. Moreover it works. However I see several issues here:

EventHandlerInterface must explicitly know all the events.
As a result of (1) handlers may have large space overhead because of subscribing for unused events.

What I want this structure to be, looks more like this:

As you can see, I want separate event types produced by different modules and I want for each module to implement only necessary event handling interfaces. I am not sure how to tie this all together. Ideally I would like to have a list of EventServices ready to accept any event.
One thing, I can think of here, is to have an inherited EventService for each EventHandlerInterface type and downcast event handlers to the certain type inside notify method. However it is not type safe and looks like an ugly idea.
Second approach, I can see, is to make EventService a template and statically check template argument to be a child of EventHandlerInterface. That would be type safe and will almost do what I want. However this way I can not store all EventServices into one list/vector as I would like to. Therefore this approach is not preferable.
Actually it feels like I am looking the wrong way but how to find the right one I don't know.
Thanks!

A:

I am not sure the visitor pattern is the right approach for this problem. Sure it gives you a mechanism to achieve double dispatch but that's about it, and as you said it has drawbacks, e.g. the visitor (EventHandlerInterface) has to provide an overload for every different type of host (EventInterface). This creates a tight coupling and only makes sense if you add classes to the host hierarchy very infrequently.
Why not go for a solution according to the publish-subscribe pattern? It allows loose coupling and avoids the need of redundant interfaces. In brief, the publisher offers some events, to which subscribers can subscribe. When an event is triggerd, subscribers are notified and handle it. Subscribers only subscribe to events they find relevant. Different subscribers can provide different handling for the same type of event, which seems to be the purpose of double dispatch in your case.
In many languages (e.g. C#) there is special syntax for supporting this pattern easily. In C++ you need to use a library such as boost signals although there are others too. See also here for an example.


Q:

Add legend to multiple time-series plot using ggplot

I have two time series data that I want to show on the same graph.
Both series have three columns: Date, County and Value.
Here is my code:
#Data
Series1 <- data.frame(Date = c(2000,2001,2000,2001), County = c("a", "a", "b", "b"),Total = c(100,150,190,130))
Series2 <- data.frame(Date = c(2000,2001,2000,2001), County = c("a", "a", "b", "b"),Total = c(180,120,140,120))

#Plot data
ggplot() +
    geom_line(data = Series1, aes(x = Date, y = Total, color = County), linetype="solid") +
    geom_line(data = Series2, aes(x = Date, y = Total, color = County), linetype="dashed")

The plot looks like this:

Now I just need to add one legend showing that solid line represents Series1 and dashed line represents Series2. How can I do this?

A:

Legends are created automatically when you use aes() to map a data column to an aesthetic. You don't have a data column that you're mapping to the linetype aesthetic, so we need to create one.
Series1$series = 1
Series2$series = 2
all_series = rbind(Series1, Series2)

Now we've all the data together and plotting is easy:
ggplot(all_series,
       aes(x = Date, y = Total, color = County, linetype = factor(series))) +
    geom_line()

Automatic legend, only one geom_line call, using ggplot as it's meant to be used: with tidy data.


Q:

Fermion propagator as derivative of scalar propagator

I've seen this expression in two spacetime dimensions,
$$ \langle \bar{\psi}(x) \psi(0) \rangle = \gamma^\mu{\partial_\mu} \langle \phi(x) \phi(0) \rangle $$
The LHS is the fermion propagator, and the expectation on RHS is the scalar propagator. For 2 dimensional case, the scalar propagator is (assuming all massless)
$$ \langle \phi(x) \phi(0) \rangle = \int \frac{d^2p}{4\pi^2} \frac{1}{p^2} e^{-ipx} $$
Two questions:

Why the fermion propagator is derivative of scalar propagator?
How are the gamma matrices defined in two dimensions?

A:

The free scalar and fermion propagator is
$$
G_\psi(x,y) = \int \frac{d^dp}{(2\pi)^d} \frac{-i(\gamma^\mu p_\mu + m)}{ p^2 + m^2 - i \epsilon} e^{- i p \cdot ( x - y ) }
$$
The scalar propagator is
$$
G_\phi(x,y) = \int \frac{d^dp}{(2\pi)^d} \frac{-i}{ p^2 + m^2 - i \epsilon} e^{- i p \cdot ( x - y ) }
$$
Clearly,
$$
G_\psi(x,y) = (  i \gamma^\mu \partial_\mu -m)G_\phi(x,y)~.
$$
PS - In any dimension, the gamma matrices are defined to satisfy $\{ \gamma^\mu , \gamma^\nu \} = - 2 \eta^{\mu\nu}$.
PPS - I am using metric signature $(-,+,+,+,\cdots)$ in this answer.


Q:

Can I use my familiar to cast Warding Bond on myself?

Find Familiar lets you cast touch spells through your familiar. Warding Bond is a Touch spell, that creates a connection between "you and the target". I can't find anything against it, but would it be possible to have my Wizard make his familiar cast Warding Bond on the Wizard himself, so that the Wizard gets the +1 to AC and saving throws and resistance to damage?
I realized after I wrote this much that Wizards don't get Warding Bond, but I think the question is still valid for multiclassers.

A:

So to start with, it's worth pointing out that you can cast Warding Bond on yourself. Touch range spells are described as:

Some spells can target only a creature (including you) that you touch.

Further, under the Targeting Yourself section, it says:

If a spell targets a creature of your choice, you can choose yourself, unless the creature must be hostile or specifically a creature other than you.

You can cast touch spells on yourself unless they specifically say you can't, and Warding Bond doesn't specify that. This is actually not a bad idea - you'll get the +1 to AC and saving throws, and the double damage you'll take will be canceled out by the resistance to damage.
Find Familiar says that:

when you cast a spell with a range of touch, your familiar can deliver the spell as if it had cast the spell.

Your familiar can deliver the spell as if it had cast the spell. This is the only way in which the familiar acts as the caster of the spell. It can certainly deliver Warding Bond for you, but you will still be the caster of the spell, and the "you" in Warding Bond will still be you, not your familiar. This is effectively equivalent to casting it on yourself directly, except that it took your familiar's reaction.

A:

Short Answer

If you can cast Warding Bond on yourself, via touch, then Yes, your familiar can do it.
If you can't cast Warding Bond on yourself, via touch, then No, your familiar cannot do it.

The embedded question required to answer the question posed is:
"Can you cast Warding Bond on yourself?"

Miniman's answer suggests that you can.
The following RAW-based analysis suggests "No, You Can't" based on the specifics in the spell description rather than the general rules cited in the "Yes" answer.  The spell relies on there being two creatures (plural) for this magical bond to form and protect one of them.  From the spell description:

The spell ends if you drop to 0 hit points or if you and the target become separated by more than 60 feet.  It also ends if the spell is cast again on either of the connected creatures.

A tweet by Jeremy Crawford suggests that you can't:

Sean @Lord_Sicarious · 6 Oct 2016
  @JeremyECrawford can you cast Warding Bond on yourself? Its rules seem to assume two people, but no explicit limitation.
Jeremy Crawford @JeremyECrawford · 6 Oct 2016
  Warding bond—you can't target yourself with it. #DnD

"Specific over General" supports No over Yes.
Each DM will rule on what makes most sense to that DM.  Since the impact isn't game breaking, it probably doesn't matter.  A "Yes" ruling provides a one-hour period where a cleric gets +1 AC and +1 to saves for the price of a level 2 spell after touching him /  her self while wearing two platinum rings.  A "No" ruling means the cleric uses the 2d level slot on something else.

Analysis of the Spell to Support the No Answer (Specific over General)

Casting Time: 1 action
  Range: Touch
  Components: V, S, M (a pairof platinum rings worth at least 50 gp each, which you and the target must wear for the duration)

The italicized text implies two creatures -- a caster and a target -- each wearing a platinum ring, but it does not state that explicitly in this part of the spell description.

This spell wards a willing creature you touch and creates a mystic connection between you and the target until the spell ends.

"A willing creature" isn't necessarily only "another willing creature," so one can argue that the caster is "a willing creature" who can touch his/her self.   That said, the second half of the sentence implies two parties being involved: the caster and a target.  this spell

... creates a mystic connection between you and the target until the spell ends.

"You create a mystic connection with yourself"

is not the same statement as

"you create a mystic connection between you and (any other different creature than you.)"

The "general rule" arguments about spell targets, self spells, and touch spells seems to have raised its head again. (See a previous discussion on Paladin Smite spells).
Two parties being involved is the common sense / common usage reading of this spell description.

While the target is within 60 feet of you, it gains a +1 bonus to AC and saving throws, and it has resistance to all damage.

We see a second and a third person usage, implying the presence of another creature other than the caster.

Also, each time it takes damage, you take the same amount of damage.

"You take damage" and "it" takes damage: second person and third person references.  Two different persons, to different creatures are damaged.

The spell ends if you drop to 0 hit points or if you and the target become separated by more than 60 feet.

The caster reaching a zero-hit-point condition ending a spell is common result. Neither a pro nor con element for this question.  Outside edge case magical effects, you can't be separated from yourself so this makes no sense in a case other than two creatures being involved.

It also ends if the spell is cast again on either of the connected creatures.  You can also dismiss the spell as an action.

Creatures, plural.  Two creatures, a caster and a target who needs to be touched while wearing the appropriate platinum ring.
What was implied in previous language is specified at the end of the spell description.  "Either" obviously refers to more than one party/creature.
Conclusion:
By reading the specifics of the spell description, the spell requires two creatures, each wearing the appropriate platinum ring, one touching the other, and both staying within 60' of each other for up to an hour for the spell to provide the damage reduction to recipient of this spell, as well as the AC and Saving throw bonuses.
No, you can't cast this spell on yourself because it requires two creatures, each wearing that platinum ring, to create the spell effect.


Q:

How does group by statement in SQL affect the results ?

Does including an extra column in group by change the number of rows in the results ?
I was doing a select query on a table A(col1,col2....col9) and I first included
select col1,col2,col3
from A where col1 = (condition)
group by col1, col2, col3

which yielded me certain number of results.
now I changed the query to this
`select col1,col2,col3, col8,col9
from A where col1=(condition)
group by col1,col2,col3, col8,col9'

and I got a different number of rows in the results. What could be the possible explanation ?

A:

If the combination of col1, col2 and col3 is not unique, you can have more than one row with the same combination of those three.
If that happens, and those duplicates have different values for col8 and/or col9, then grouping by those extra columns will result in more rows.
Note that you can use select distinct to get the same results. group by is especially used if you want to aggregate over other columns, for instance, calculate a sum or a count, like so:
select
  col1, col2, col3,
  sum(col8) as total8
from A
group by col1, col2, col3

The query above will give you each unique combination of col1, col2 and col3 plus the sum over all col8's for each combination.


Q:

Insert JTextArea into a JPanel with a JLabel

I am trying to display the drawing that I have posted. When my code runs and the user clicks Account, the panel only displays the buttons "OK" and "Cancel" (see screenshot). I have added three JTextAreas with a JLabel for each to the panel accountPanel but they don't display. My code is below.

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Component;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

public class TestApplication implements ActionListener {

    public static void main(String[] args) {
    JLabel input = new JLabel();
    final JFrame frame = new JFrame();
    frame.setSize(1000, 1000);
    frame.setTitle("RBA Test Application");
    frame.add(input);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    JRadioButton apprve = new JRadioButton("Approve");
    JRadioButton decline = new JRadioButton("Decline");

    JRadioButton ethernet = new JRadioButton("Ethernet");
    ethernet.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JDialog esettings = new JDialog(frame);
            esettings.setTitle("Ethernet Settings");
            esettings.setSize(400, 400);
            esettings.pack();
            esettings.setVisible(true);

        }
    });

    JRadioButton rs = new JRadioButton("RS232");
    rs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JDialog rsettings = new JDialog(frame);
            rsettings.setTitle("RS232 Settings");
            rsettings.setSize(400, 400);
            rsettings.pack();
            rsettings.setVisible(true);

        }
    });

    JRadioButton usbcdc = new JRadioButton("USB_CDC");
    usbcdc.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JDialog usbc = new JDialog(frame);
            usbc.setTitle("USB_CDC Settings");
            usbc.setSize(400, 400);
            usbc.pack();
            usbc.setVisible(true);

        }
    });

    JRadioButton usbhid = new JRadioButton("USB_HID");
    usbhid.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JDialog usbh = new JDialog(frame);
            usbh.setTitle("USB_HID Settings");
            usbh.setSize(400, 400);
            usbh.pack();
            usbh.setVisible(true);

        }
    });

    JButton next = new JButton("Next");
    JButton aok = new JButton("OK");
    JButton bok = new JButton("OK");
    JButton cok = new JButton("OK");
    JButton acancel = new JButton("Cancel");
    JButton bcancel = new JButton("Cancel");
    JButton ccancel = new JButton("Cancel");
    JButton dcancel = new JButton("Cancel");

    JLabel cardLabel = new JLabel("Card Number: ");
    JLabel expLabel = new JLabel("Exp. Date: ");
    JLabel cvvLabel = new JLabel("CVV: ");

    JTextArea card = new JTextArea();
    card.add(cardLabel);

    JTextArea expDate = new JTextArea();
    expDate.add(expLabel);

    JTextArea cvv = new JTextArea();
    cvv.add(cvvLabel);

    final JPanel PortSettings = new JPanel();
    PortSettings.add(ethernet);
    PortSettings.add(rs);
    PortSettings.add(usbcdc);
    PortSettings.add(usbhid);
    PortSettings.add(next);
    PortSettings.add(bcancel);

    final JPanel accountPanel = new JPanel();
    accountPanel.add(bok);
    accountPanel.add(ccancel);
    accountPanel.add(card);
    accountPanel.add(expDate);
    accountPanel.add(cvv);

    final JPanel apprvordecl = new JPanel();
    apprvordecl.add(apprve);
    apprvordecl.add(decline);
    apprvordecl.add(aok);
    apprvordecl.add(acancel);

    final JPanel amountPanel = new JPanel();
    amountPanel.add(cok);
    amountPanel.add(dcancel);

    input.setFont(new java.awt.Font("Tahoma", 3, 18));
    input.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    input.setText("Input / Output Log");

    JButton initialize = new JButton("Initialize");

    JButton connect = new JButton("Connect");

    JButton disconnect = new JButton("Disconnect");

    JButton shutdown = new JButton("Shut Down");

    JButton portsettings = new JButton("Port Settings");
     portsettings.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog port = new JDialog(frame);
                port.setTitle("Port Settings");
                port.setSize(400, 400);
                port.add(PortSettings);
                port.pack();
                port.setVisible(true);

            }
        });

    JButton online = new JButton("Go Online");

    JButton offline = new JButton("Go Offline");

    JButton status = new JButton("Status");

    JButton reboot = new JButton("Reboot");

    JButton account = new JButton("Account");
     account.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog accountDialog = new JDialog(frame);
                accountDialog.setTitle("Account");
                accountDialog.setSize(400, 400);
                accountDialog.add(accountPanel);
                accountDialog.pack();
                accountDialog.setVisible(true);

            }
        });

    JButton amount = new JButton("Amount");
     amount.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog amount2 = new JDialog(frame);
                amount2.setTitle("Amount");
                amount2.setSize(400, 400);
                amount2.add(amountPanel);
                amount2.pack();
                amount2.setVisible(true);

            }
        });

    JButton reset = new JButton("Reset");

    JButton approvordecl = new JButton("Approve / Decline");
     approvordecl.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JDialog apprv = new JDialog(frame);
                apprv.setTitle("Approve / Decline");
                apprv.setSize(400, 400);
                apprv.add(apprvordecl);
                apprv.pack();
                apprv.setVisible(true);

            }
        });
    JButton test = new JButton("Test Button #1");

    JButton testing = new JButton("Test Button #2");

    JRadioButton button = new JRadioButton("Radio Button");

    JRadioButton button2 = new JRadioButton("Radio Button");

    JCheckBox checkbox = new JCheckBox("Check Box");

    JCheckBox checkbox2 = new JCheckBox("Check Box");

    ButtonGroup group = new ButtonGroup();
    group.add(usbhid);
    group.add(usbcdc);
    group.add(ethernet);
    group.add(rs);

    ButtonGroup approvegroup = new ButtonGroup();
    approvegroup.add(apprve);
    approvegroup.add(decline);

    JPanel testPanel = new JPanel();
    testPanel.add(button);
    testPanel.add(button2);
    testPanel.add(checkbox2);

    JPanel posPanel = new JPanel();
    posPanel.add(test);
    posPanel.add(testing);
    posPanel.add(checkbox);

    JPanel llpPanel = new JPanel();
    llpPanel.add(online);
    llpPanel.add(offline);
    llpPanel.add(status);
    llpPanel.add(reboot);
    llpPanel.add(account);
    llpPanel.add(amount);
    llpPanel.add(reset);
    llpPanel.add(approvordecl);

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(initialize);
    buttonPanel.add(connect);
    buttonPanel.add(disconnect);
    buttonPanel.add(shutdown);
    buttonPanel.add(portsettings);
    frame.add(buttonPanel);
    frame.add(buttonPanel, BorderLayout.NORTH);

    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
    tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
    tabbedPane.addTab("Test", null, testPanel, "Test");

    JPanel tabsPanel = new JPanel(new BorderLayout());
    tabsPanel.add(tabbedPane);
    frame.add(tabsPanel, BorderLayout.CENTER);

    frame.pack();

}

@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}

}

A:

JPanel uses FlowLayout by default which respects preferred sizes. The default width of  the preferred size for the JTextArea's is 0 x 0. You need to give the JTextComponent's a preferred size for them to appear. Use the constructor that specifys rows & columns:
JTextArea card = new JTextArea(5, 10);

Don't forget to make the JTextArea scrollable by enclosing it in a JScrollPane:
accountPanel.add(new JScrollPane(card));


Q:

asp.net mvc datannotation password validate

how can i validate a password with asp.net mvc dataanotation, the password must be between 6 and 16 characters

A:

Look up the StringLengthAttribute in data annotations.
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute(v=VS.95).aspx


Q:

Finding an ID with the maximum value of an attribute in a group with SQL

If we have a simple table (SQLite syntax):
CREATE TABLE Receptions (
    ID INTEGER PRIMARY KEY AUTOINCREMENT,
    ID_Patients INTEGER NOT NULL,
    ID_Doctors INTEGER NOT NULL,
    StartDateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP);

filled with some ids, what is the best SQL query for getting doctor with latest date for each patient? Is it possible to optimize the following example somehow to make it work faster?
SELECT ID_Patients pid, ID_Doctors did FROM Receptions INNER JOIN
    (SELECT MAX(StartDateTime) maxDate, ID_Patients pid FROM Receptions GROUP BY pid) a
    ON a.pid = pid AND a.maxDate = StartDateTime;

I wonder if anyone can explain how this query is executed and what data structures are created on the server side (assuming there are all required indices).

A:

This might work faster with a correlated subquery:
SELECT r.*
FROM Receptions r
WHERE r.StartDateTime = (SELECT MAX(r2.StartDateTime)
                         FROM FROM Receptions r2
                         WHERE r2.pid = r.pid
                        );

For performance, you want an index on Receptions(pid, StartDateTime).


Q:

Tie multiple values to an event in Google Analytics

I have a search form with several fields - 1 or all of them may be used. I also have an outbound link on the search results that trigger an event. What I am trying to do is determine how many of each search term is used in some way that resulted in a click to each of these outbound link events.
For example, let's say that I have the following searches, both which result in a click event on OutboundLink A
Search 1

FirstName: John
LastName: Smith
ZipCode: 90210

Search 2

LastName: Smith
State: California

I would want something that aggregated the search terms that came before that outbound click event like this:

John: 1
Smith: 2
90210: 1
California: 1

I can try to figure out a way to track this server-side, but I was hoping that I would be able to do this with Google Analytics.

A:

Event parameters are plain text, so you can set whatever you want. Just keep in mind you must follow a convention (defined by yourself) for what you concatenate and how you sort that data, this way your data will be consistent.
The way you want to view your data in Events Report can be accomplished only if you set every single search criteria into one of the parameters of an event and fire an event for each one. As I said before, you can set whatever you want in your parameters, but it's better to stay close to convention, so, maybe the parameter that best fits for this is Label. The simplest thing to do could be something like this:
_trackEvent('whatever-category', 'whatever-action', 'smith');
_trackEvent('whatever-category', 'whatever-action', 'john');
_trackEvent('whatever-category', 'whatever-action', '90210');

Asynchronous version:
_gaq.push(['_trackEvent', 'whatever-category', 'whatever-action', 'smith']);

Universal Analytics version:
ga('send', 'event', 'whatever-category', 'whatever-action', 'smith');

In your current implementation, supposing you are already using Category, Action, Label, maybe you have something like this:
_trackEvent('outboundlink', 'click', 'url-clicked-by-visitor');

Trying to add something else to any of these parameters will result in data split, and I think that's not a good idea.
Abusing a little bit of event parameters you could track every search criteria and relate it to the outbound link clicked:
_trackEvent('outboundlink', 'click', 'url-clicked-by-visitor');
_trackEvent('searchcriteria', 'url-clicked-by-visitor', 'smith');
_trackEvent('searchcriteria', 'url-clicked-by-visitor', 'john');
_trackEvent('searchcriteria', 'url-clicked-by-visitor', '90210');

Because URL's will be too many, I'll prefer to set them as Action, and set just one Category for keeping all of them grouped. Also you could set your search criteria as Action and URL as Label.
Parameter Action should indicate some kind of user interaction, but, I guess it's up to the webmaster set whatever makes sense. Anyway, this is not a best practice, but it'll work.


Q:

Is DockPanel not available in Windows IOT Core

I'm trying to make my first Universal Windows app for Windows IOT Core.  I'm reusing some code that I had previously used on a regular Windows WPF app (I guess they call it "classic desktop").  Trying to use a dockpanel, I get the error:

Unknown type 'DockPanel' in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'

Searching online for "unknown type "dockpanel: in xml namespace +iot" returns zero results.  In general I haven't had much success at finding sample UW/IOT core applications out there to learn from.
Is this not available in Universal Windows?  Or am I missing some prerequisite?
Here's the code:
    <Grid Margin="5" DataContext="{Binding ElementName=me}">
    <Rectangle x:Name="backgroundRect" Fill="LightGray" Stroke="DarkGray" StrokeThickness="2" RadiusX="5" RadiusY="5" />
    <DockPanel LastChildFill="True" Margin="5">

A:

DockPanel is only avaiable in WPF. See this link.
Depends on the layout you want to achieve, but you can use a Grid as a replacement:
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />

      <!-- Fill up remaining space -->
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Grid.Column="0" Text="Stuff" />
    <ContentControl Grid.Column="1" />
  </Grid>


Q:

Is there a way to change the default Booean operation type?

I use the Boolean modifier a lot and almost always use the "Difference" option. It would be great if I could make that the default rather than "Intersection". Is there a way to do this?

A:

This has been asked before in 2015: Where are the modifier scripts in the Blender package contents folder?
They are part of the main app coding, so unless things have changed, not easily modified.
I would like to do this, too, as I use Booleans a lot for 3D print drawing.
Not changing dimensions from millimetres to CM would be good as well.


Q:

Clipped contents of Flex DataGrid are indicated by null" instead of trailing dots

My Flex app uses a DataGrid. Clipped cell contents are indicated by trailing dots. This works fine in English language. When we launch the browser in a different language (say Portugese), the cell contents are indicated by "null" instead. Any clues?

A:

Apparently my SWF was compiled with English version of framework resource property files. As per design, Flex cant load framework property files in runtime.
Workaround this by specifying English as fall back language.
resourceManager.localeChain=[myLocale,"en_US"];


Q:

Finding near-integers in a range

I have a (transcendental) constant $\alpha$ and a fixed parameter $\varepsilon>0.$ I'd like to find all positive integers $n<\ell$ for which $\|n\alpha\|<\varepsilon,$ where $\|x\|$ is the distance between $x$ and the nearest integer. Is there a good way to do this?
The first natural thought is to use continued fractions but at best this would give me a few good examples rather than all of the numbers in the range.
For concreteness let's say $\ell>10^{10}$ and $\varepsilon\approx\ell/\log\ell$. In short I'm searching a big range for integers which are very close to a multiple of $\alpha.$

A:

If you know how to solve problems of the form "find the least integer $n(\eta) \ge 1$ such that $n\alpha \in [- \eta - \varepsilon; - \eta + \varepsilon]  \pmod 1$" where $|\eta| \le \varepsilon$, then you can easily find all those integers one after the other.
Thus, you want to keep a list of the integers $n$ such that $n \alpha$ is closer to $0$ than for any other smaller multiple. You need two lists, one made of the positive records and one of the negative records (those will contain the multiples corresponding to the continued fractions, so they are still relevant to the problem).
Both lists start with $n=1$, corresponding to $+(\alpha-\lfloor \alpha \rfloor)$ and $-(\lceil \alpha \rceil - \alpha)$.
To continue the lists, one can prove by induction that the next record is the sum of the two current records. Add it to the list corresponding to its sign, and repeat.
Once the difference between the two current records gets smaller than $2\varepsilon$, you can stop, and use the few records smaller than $2\varepsilon$ to compute the piecewise constant function $n(\eta)$ for $|\eta| \le \varepsilon$.
Finally, you obtain the sequence you want recursively by $N_0 = n(0)$ and $N_{k+1} = N_k + n(N_k \alpha \mod 1)$.

For example, suppose you want to find the multiples of $\sqrt 2$ that are less than $10^{-2}$ to an integer.
Modulo $1$, you have the following records :
$\begin{matrix}1\sqrt 2 & = + 0.4142 & = -0.5857 \\
2\sqrt 2 && = -0.1715 \\
3\sqrt 2 &= +0.2426& \\
5\sqrt 2 &= +0.0711& \\
7\sqrt 2 &&= -0.1005 \\
12\sqrt 2 &&= -0.0294 \\
17\sqrt 2 &= +0.0416& \\
29\sqrt 2 &= +0.0122& \\
41\sqrt 2 &&= -0.0172 \\
70\sqrt 2 &&= -0.0051\end{matrix} $.
Since $29\sqrt 2 = +0.0122$ and all the previous values are bigger than $0.02$, this shows that $n(\eta) = 29$ for $|\eta + 29\sqrt 2| \le 0.01 \pmod 1$, which means $\eta \in [-0.01 ; -0.0022] = [-0.01 ; -29\sqrt 2 + 41.01]$
Next, we have $n(\eta) = 41$ for the remaining $\eta$ satisfying $|\eta + 41\sqrt 2| \le 0.01 \pmod 1$, which means $\eta \in [+0.0072 ; +0.01] = [-41\sqrt 2 + 57.99 ; +0.01]$.
Finally, we have $n(\eta) = 70$ for the remaining $\eta$ satisfying $|\eta + 70\sqrt 2| \le 0.01 \pmod 1$, which means $\eta \in [-0.0022 ; +0.0072] = [-29\sqrt 2 + 41.01 ; -41\sqrt 2 + 57.99]$.
So if the current multiple falls in $[-0.01 ; -0.0022]$, we add $29\sqrt 2$, if it falls in $[-0.0022 ; +0.0072]$, we add $70\sqrt 2$, if it falls in $[+0.0072 ; +0.01]$, we add $41\sqrt 2$ :
Now we obtain the sequence :
$70\sqrt 2 = -0.0051\\ 99\sqrt 2 = +0.0071 \\ 169\sqrt 2 = +0.0021 \\ 239\sqrt 2 = -0.0030 \\ 268\sqrt 2 = +0.0092 \\ 309\sqrt 2 = -0.0080 \\ \ldots$

If you want to skip ahead and start from $\ell_1$, it's a bit more difficult, because from $\ell_1 \alpha$ you have to to solve a problem of the form "find the smallest $n$ such that $n\alpha$ is in such interval of length $2\varepsilon$", and this interval is unlikely to contain $0$. To find that first integer, you need to enlarge the target interval so that it contains $0$, then use the list of records to solve the problem with the enlarged interval. You will then get a bit closer to the target interval, so the next target interval will be closer to $0$, and repeat.


Q:

Joomla - How to restart SESSION based on session ID from external php

I am trying to integrate SWFUpload into Joomla (customized implementation, and this is why cannot use extensions with swfupload).
I am passing through SWFUpload the ID if SESSION and on server side I need to get all data of $_SESSION for the passed ID.
This is the code I have (direct script access):
based on this tutorial
if (isset($_POST["PHPSESSID"])) {
    session_write_close();             // End the previously-started session
    session_id($_POST["PHPSESSID"]);   // Set the new session ID
    session_start();                   // Start it
}

and here is the error I get in SWFUpload debug window:
Fatal error: session_start(): Failed to initialize storage module: user (path: /var/lib/php5) in /srv/www/htdocs_appsrv/.../incoming.php on line 19

Line 19 is
session_start();

How can I restart a session having session ID and then grab all needed data from $_SESSION?
Please help.
Thank you.

A:

Ok, the code below seems to work
if (isset($_POST["PHPSESSID"])) {
    session_write_close();             // End the previously-started session
    $jd = new JSessionStorageDatabase();
    session_id($_POST["PHPSESSID"]);   // Set the new session ID
    session_start();                   // Start it
}

I found that based on this tutorial


Q:

AWK / SED extract string between HUGE line

I have a huge line that is a response from a ws, I need to get all the strings that are between <asunto> and </asunto>. The file is like this:
Content-Type: application/xop+xml; charset=UTF-8; type="application/soap+xml";
Content-Transfer-Encoding: binary
Content-ID: <root.message@cxf.apache.org>

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Body><ns1:consultarComunicacionesResponse xmlns:ns1="http://ve.tecno.afip.gov.ar/domain/service/ws"><ns2:RespuestaPaginada xmlns:ns2="http://ve.tecno.afip.gov.ar/domain/service/ws" xmlns:ns3="http://core.tecno.afip.gov.ar/model/ws/types" xmlns:ns4="http://ve.tecno.afip.gov.ar/domain/service/ws/types"><pagina>1</pagina><totalPaginas>1</totalPaginas><itemsPorPagina>100</itemsPorPagina><totalItems>2</totalItems><ns4:items><ns4:ComunicacionSimplificada><idComunicacion>sdfgsfdgsfdgsd</idComunicacion><cuitDestinatario>sdfgsdfgsdfgsfdg</cuitDestinatario><fechaPublicacion>sdfgsdfg</fechaPublicacion><fechaVencimiento>sdfgsdfgsdfg</fechaVencimiento><sistemaPublicador>sdfgsdfgsfg</sistemaPublicador><sistemaPublicadorDesc>sdfgsdfggf</sistemaPublicadorDesc><estado>2</estado><estadoDesc>sdfgsdfgsgf</estadoDesc><asunto>EXAMPLEEEEEEEEEEEEEEEE1</asunto><prioridad>3</prioridad><tieneAdjunto>sdfgfdg</tieneAdjunto></ns4:ComunicacionSimplificada><ns4:ComunicacionSimplificada><idComunicacion>sdfgsdfgdfg</idComunicacion><cuitDestinatario>sdfgdfsg</cuitDestinatario><fechaPublicacion>sdfgsdfg</fechaPublicacion><fechaVencimiento>sdfgdsfg</fechaVencimiento><sistemaPublicador>sdfgsdfg</sistemaPublicador><sistemaPublicadorDesc>sdfgsdfgdsfggsdf</sistemaPublicadorDesc><estado>1</estado><estadoDesc>dsfgsdfgsgd</estadoDesc><asunto>EXAMPLEEEEEEEEEEEEEEEE2</asunto><prioridad>asdfdsf</prioridad><tieneAdjunto>asdfasdf</tieneAdjunto></ns4:ComunicacionSimplificada></ns4:items></ns2:RespuestaPaginada></ns1:consultarComunicacionesResponse></soap:Body></soap:Envelope>

I shuold get something like this:
EXAMPLEEEEEEEEEEEEEEEE1
EXAMPLEEEEEEEEEEEEEEEE2

There may be a lot of repetition, between 0 and hundreds.
Thank you!!

A:

awk to the rescue!
$ awk -v RS='[<>]' '/\/asunto/{f=0;next} f; /asunto/{f=1}' file

EXAMPLEEEEEEEEEEEEEEEE1
EXAMPLEEEEEEEEEEEEEEEE2

UPDATE: based on the comments if there is a chance that the tag exist in elsewhere you can anchor on the left and right of the open/close tags
$ awk -v RS='[<>]' '/^\/asunto$/{f=0;next} f; /^asunto$/{f=1}' file
EXAMPLEEEEEEEEEEEEEEEE1
EXAMPLEEEEEEEEEEEEEEEE2

or equivalently, check for an exact string match
$ awk -v RS='[<>]' '$0=="/asunto"{f=0;next} f; $0=="asunto"{f=1}' file
EXAMPLEEEEEEEEEEEEEEEE1
EXAMPLEEEEEEEEEEEEEEEE2

also note that not all awk variants support multi char RS.


Q:

Tomcat write permission apache server user uploads

When a user uploads an image, the file is created in "/var/www/example.com/uploads" by the tomcat webapp so that apache can serve the image. However, the tomcat group/user creates the file so it is not accessible through example.com/uploads/image.jpg unless I manually change the read permissions, then the file is no longer forbidden. But, every file is created without read permissions. I am not fluent with ubuntu and I do not know if I need to change something within the java servlet or to the folder/group/user. Any help would be greatly appreciated.
-rw-r----- 1 tomcat tomcat 120264 Jul 14 19:26 second-image.jpg
-rw-r--r-- 1 tomcat tomcat 172853 Jul 14 19:05 image.png

Edit:
The file is submitted as multipart config form data. After checking the types, size, etc., it is written to the system simply as:
Path imageDir = Path.of("/var/www/example.com/uploads");
Path imageFile = Files.createFile(imageDir.resolve(fileName).toAbsolutePath());
part.write(imageFile.toString());

A:

Your application code is already calling a method that is able to set permissions, but isn't providing a parameter to do so. You can read this tutorial on File Attributes to see an example of setting file permissions. I'm guessing you'd want to create the permissions from a string, since you're already working with the format:
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-------");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(file, attr);


Q:

Text message "reverser"

I decided to step out of my comfort zone (Java) and try out Python. I wrote a very simple reverser.py and want it to be reviewed.
"""
This python script basically takes a string and reverses it.

This python script can be used as a command line script as well as a separate
module.
"""
import sys

def reverse(message):
    """
    This function takes a string and reverses it, so as to somewhat obfuscate
     it.

    :param message: The unencrypted text message to be reversed.
    """
    text = ''
    for character in message:
        text = character + text
    return text

if __name__ == '__main__':
    numberOfArgs = len(sys.argv)

    message = ''
    if numberOfArgs == 1:  # i.e. the program name only
        message = input('Please enter the text to be encrypted : ')
    elif numberOfArgs == 2:
        message = sys.argv[1]
    else:
        print('Incorrect number of arguments : %d\n' % numberOfArgs)
        print('Usage: python3 reverseCipher [unencrypted string]')
        exit(2)  # '2' stands for command-line syntax errors in unix

    print(reverse(message))

Examples in the terminal:
$ python3 reverser.py

Please enter the text to be encrypted : I understand that text manipulation in python is quite easy.
.ysae etiuq si nohtyp ni noitalupinam txet taht dnatsrednu I

$ python3 reverser.py "I am just starting out with python"

nohtyp htiw tuo gnitrats tsuj ma I

It would be great if I would be advised about:

Code style and idioms
The required mindset (for I have one for Java)
Anything that can help me learn the language

A:

This is going to be a short answer, but did you know Python has such a feature in-built?
text = "I'm a stringy!"
print(text[::-1])

Above would replace your reverse method and is the most Pythonic way to solve this.
This is called extended slicing and has been added since Python 2.3. Slicing is a very easy to use method when handling array-like data.
The following illustrates how slicing and extended slicing can be used, executed in the interactive Python IDE:
In [1]: text = "I'm a stringy!"

In [2]: print(text)
I'm a stringy!

In [3]: print(text[:-1])
I'm a stringy

In [4]: print(text[::-1])
!ygnirts a m'I

In [5]: print(text[:4:-1])

In [6]: print((text:4:-1] + text[:3:5])[::-1])
I stringy!

In [7]: print(text[::-1][::-1][::-1])
!ygnirts a m'I

As picture.

A:

I guess you might have heard of PEP8, which is the style guideline for Python. Contrary to a lot of other programming languages, this style guideline is actually used a lot, and is the main standard for coding in Python.
Your code looks clean, and I like that you've commented using docstrings moth the module/file and the function. Mast does have a point that you can accomplish the same using message[::-1], but part of going into a new language is learning what the language can offer in standard libraries.
Do look into using slice'ing, which is extremely powerful and useful.  A challenge for you is to resolve Project Euler #13: Large sum using Python and sliceing. I think you'll get some pleasant surprises related to string vs number handling, and handling of large numbers as well.
Two other comments related to style issues:

Use snake_case for variable and function naming – That is use number_of_arguments instead of numberOfArgs
Look into using format for string formatting – The % is scheduled for depreceation, and you should rather use print('Incorrect number of arguments: {}'.format(number_of_arguments)). For more on this see Format specification mini language, on that page there is also useful examples and syntax for how to pretty print using format.


Q:

tensorflow merge and zip two tensors

I have two tensors as below:
x1 = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
x2 = tf.constant([[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]])

How should I merge and transform x1 and x2, so that I can have a tensor like below:
[[[1.0, 7.0]
  [2.0, 8.0]
  [3.0, 9.0]]

 [[4.0, 10.0]
  [5.0, 11.0]
  [6.0, 12.0]]
]

A:

Use tf.stack on the last axis:
tf.InteractiveSession()

tf.stack([x1, x2], axis=-1).eval()

#array([[[  1.,   7.],
#        [  2.,   8.],
#        [  3.,   9.]],

#       [[  4.,  10.],
#        [  5.,  11.],
#        [  6.,  12.]]], dtype=float32)


Q:

Find the library that a specific function is defined in

Somebody sent me a piece of C++ code, and it includes some headers and functions that I'm unfamiliar with. I want to find which header file defined a particular function. For example, I have these headers:
#include <iostream>
#include <ncurses.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>

and I want to know witch of them defined this function:
tcgetattr

or which of them defined this struct:
termios

Can anyone help me?

A:

The tcgetattr is a "get attribute" function from termios.h. The termios structure is also from that header as I would have thought was self-evident by virtue of the fact it shares the name.
See, for example, the Linux man page here.
If you're looking as to which headers contain arbitrary functions, I usually (in UNIX-like operating systems) just grep in known locations, something like:
grep tcgetattr /usr/include/*.h /usr/include/*/*.h

(or using the recursive option of grep, or find to search everywhere).


Q:

Can't access Alamofire Request body

I'm facing a problem while requesting from server, everything was fine
suddenly the Alamofire.request can't access responseJSON and can't access the body of the function and it returns , what I have to do?
I'm using multi Alamofire request in the navigationController but after two or three requests this happens!
I'm really in trouble please help me!
this code can't execute
    let group = DispatchGroup()
    group.enter()
    Alamofire.request(url, method: .get, parameters: nil,
      encoding:
        JSONEncoding.default, headers: header as? HTTPHeaders)
        .responseJSON { (response) in
            if response.result.isSuccess{
                if let response = response.result.value {

                    let json = JSON(response)
                    self.updateAnswers(json: json)
                    print(json.arrayValue)
                    group.leave()
                }
            }
    }

A:

If it’s not successful, you should dive in and take a look at the error that was returned. You might even want to look at the body of the response (if its a development server, it might provide some useful error messages in the body of the response).
let group = DispatchGroup()
group.enter()
Alamofire.request(...)
    .responseJSON { response in
        defer { group.leave() }

        switch response.result {
        case .failure(let error):
            print(error)
            print(response.response ?? "no HTTPURLResponse")
            if let data = response.data {
                if let string = String(data: data, encoding: .utf8) {
                    print(string)
                } else {
                    print(data as NSData)
                }
            } else {
                print("no data")
            }

        case .success(let json):
            print(json)
        }
}

By the way, I’d suggest moving the leave call outside of any if/switch statement because you want to make sure your dispatch group is satisfied regardless of whether it was successful or not.
But, bottom line, you won’t be able to diagnose the problem until you start to look at precisely what error was returned.


Q:

javascript sdk is opening multiple login dialogs

Im having an issue where the Javascript SDK opens multiple dialogs to log in.
if i log in and then out it works fine, but the next time i log in it will open 2 popups. next time it will open 3 and so on.
The Page is using PHP, Javascript/Jquery
The code is a tweaked version of this tutorial
http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/
Here is my Code:

A:

if i log in and then out it works fine, but the next time i log in it will open 2 popups. next time it will open 3 and so on.

Are you staying on the same page – without reloading it in between?
That would explain what you’re describing, because then every time your function updateButton is called and goes into the else branch, it will add a new additional click event handler to #loged, so they would start “accumulating”, and therefor FB.login will be called multiple times – because each single click will trigger multiple handlers (that all do the same stuff).


Q:

Can Google Sheets be opened/edited in Ubuntu?

I have a number of Google Sheets (spreadsheets) saved on Google Drive normally accessed from an android phone collaboratively but would like to edit them from within Ubuntu.
I can save the file as either an .ods (LibreCalc) or .xlsx (MS Excel) file from android and whilst either formats can be edited in LibreCalc I cannot find a way of successfully re-saving the file in the Sheets format back to Google Drive for continued collaboration.
Any ideas?

A:

Use Google Drive files offline
This answer requires Google Chrome web browser to be installed and regularly updated.

If you aren't connected to a Wi-Fi or mobile network, you can still
view and edit files, including:

Google Docs
Google Sheets
Google Slides

Open files offline
To turn on offline access:

You must be connected to the Internet.
Use  the Google Chrome browser.
Don't use incognito mode.
Install and enable Google Docs offline Chrome extension. The Google Docs extension makes it possible to edit your documents, spreadsheets and presentations when you aren’t connected to the internet. Plus, you can copy and paste between Docs, Sheets and Slides.
Make sure you have enough free space on your device to save your files.

Open your Google Drive files offline

Open Chrome. Make sure you're signed in to Chrome.

Go to drive.google.com/drive/settings.

Check the box in the Offline category next to "Sync Google Docs, Sheets, Slides & Drawings files to this computer so that you can edit offline."

Source: Use Google Drive files offline – Google Drive Help


Q:

Does the order of columns in a covering index matter?

I have the following covering indices:
INDEX (col1, col3); -- index 1
INDEX (col1, col2, col3); -- index 2

because I would like to support the following type of queries:
1)
  SELECT col3
    FROM my_table
   WHERE col1 = ... AND
         col2 = ...
ORDER BY col3

2)
  SELECT col3
    FROM my_table
   WHERE col1 = ...
ORDER BY col3

I am unfamiliar with how a covering index works.  Is index 1 redundant? Or does a covering index requires that the columns be side by side?

A:

"Covering" is the wrong term to start with.  I'll get back to that in a minute.
The optimal index for your queries can be summarized:

The first columns in the index must be all the = columns in the WHERE, in -any_ order.
The last columns in the index must be the ORDER BY columns in the same order, and either be all ASC or all DESC.  (MySQL 8.0 has an exception here.)

Your index 1 is necessary and sufficient for query 2.
Your index 2 is necessary and sufficient for query 1.
Anything different would be sub-optimal.
Note that they would also be "covering" in that all the columns anywhere in the SELECT are found in the respective indexes.
Index 2 "covers" both queries, but it is not very good for Query 2.

Devise the optimal index for each important query.
Eliminate redundancy.  Example: Given INDEX(a), INDEX(a,b), toss the former.
Then think about adding some columns on the end to make an index "covering".

For those tips, plus more, see http://mysql.rjweb.org/doc.php/index_cookbook_mysql
This is "covering", but not efficient because col99 in first in the index, but not used for filtering or sorting:
INDEX(col99, col1, col2, col3)

It might be used, but only because it is covering.  It can't be used for filtering or sorting.
This is "covering" and might be used to avoid sorting because the ORDER BY column(s) are first:
INDEX(col3, col2, col1)

Query 1 would be just as happy with this regardless of the cardinality of the individual columns:
INDEX(col2, col1, col3)

Back to the title question:

Does the order of columns in a covering index matter?

Answer:

For the sake of "covering":  No.
For speeding up the query:  It depends.  And that is why I recommend starting with other 'rules' for building a good index.

An analogy

A table is an unordered set of things.  Analog:  a textbook.
An index is an ordered list, referencing those things.  Analog:  the index in the back of the textbook.
When everything you need to answer a question is sitting in the index (and you don't need to leaf back into the body of the textbook), then the index is "covering".

A B+Tree has two important properties:

It is quick to jump into the middle at any specific word.
It is fast to scan forward from that word.