text:
Q: Using Perl to conditionally add tag to XML file I am not a developer in any way, but a network security guy. I need to insert a tag and value for an element if it does not already exist.
Here's a snippet of my XML file
<NessusClientData_V2>
    <Policy>
    ...
    <Report>
    ...
        <ReportHost name="1.2.3.4">
        ...
            <HostProperties>
            ...
                <tag name="HOST_END">Thu Sep 17 17:23:19 2015</tag>
                <tag name="system-type">general-purpose</tag>
                <tag name="operating-system">MS WIN</tag>
                <tag name="ssh-auth-meth">password</tag>
                <tag name="ssh-login-used">backup</tag>
                <tag name="local-checks-proto">ssh</tag>
                <tag name="host-ip">1.2.3.4</tag>
                <tag name="HOST_START">Thu Sep 17 17:00:14 2015</tag>
            </HostProperties>
            ...

I need to check each ReportHost element and create a
<tag name="mac-address">

if it doesn't already have one.
My output needs to contain all of the original information, but only needs to be added to.

A: You can use XML::Twig to do this. The following code iterates all HostProperties nodes and checks them for the existance of a tag with name mac-address, and if it's not there, inserts one.
use strict;
use warnings;
use XML::Twig;

# at most one div will be loaded in memory
my $twig = XML::Twig->new(
    twig_handlers => {
        '//ReportHost/HostProperties' => sub {
            my $seen = 0;
            foreach my $elem ( $_->children('tag') ) {
                if ( $elem->atts->{name} eq 'mac-address' ) {
                    $seen++;
                    last;
                }
            }
            $_->insert_new_elt(
              'last_child',
              'tag' => { name => 'mac-address' },
              'barfoo'
            ) unless $seen;
        }
    },
    pretty_print => 'indented',
);

$twig->parse( \*DATA );
$twig->flush;

__DATA__
<NessusClientData_V2>
    <Policy>
    <Report>
        <ReportHost name="1.2.3.4">
            <HostProperties>
                <tag name="HOST_END">Thu Sep 17 17:23:19 2015</tag>
                <tag name="system-type">general-purpose</tag>
                <tag name="operating-system">MS WIN</tag>
                <tag name="ssh-auth-meth">password</tag>
                <tag name="ssh-login-used">backup</tag>
                <tag name="local-checks-proto">ssh</tag>
                <tag name="host-ip">1.2.3.4</tag>
                <tag name="HOST_START">Thu Sep 17 17:00:14 2015</tag>
            </HostProperties>
        </ReportHost>
        <ReportHost name="127.0.0.1">
            <HostProperties>
                <tag name="HOST_END">Thu Sep 17 17:23:19 2015</tag>
                <tag name="system-type">general-purpose</tag>
                <tag name="operating-system">MS WIN</tag>
                <tag name="ssh-auth-meth">password</tag>
                <tag name="ssh-login-used">backup</tag>
                <tag name="local-checks-proto">ssh</tag>
                <tag name="host-ip">127.0.0.1</tag>
                <tag name="HOST_START">Thu Sep 17 17:00:14 2015</tag>
                <tag name="mac-address">foobar</tag>
            </HostProperties>
        </ReportHost>
    </Report>
</Policy>
</NessusClientData_V2>

You will have to replace the ->parse(\*DATA) with a ->parse_file and maybe add some random mac address.

A: Well, I answered on perlmonks, and with a bit more of an XML sample, I'll recycle the answer. For this trick, I'd use xpath to query your XML, rather than walking the tree. The reasoning behind this is because xpath lets you query element, attribute and attribute content in a single statement.
#!/usr/bin/env perl
use strict;
use warnings;
use XML::Twig;

my $twig = XML::Twig->parsefile( 'your_file.xml' );

#search for "HostProperties" nodes within the tree. You can
#be more specific about this if you need to.
foreach my $HP ( $twig->get_xpath('//HostProperties') ) {
    #check if it has a "tag" element with a "mac-address" "name" attribute.
    if ( not $HP->get_xpath('./tag[@name="mac-address"]') ) {
        #insert a new element at the end of the entry.
        $HP->insert_new_elt( 'last_child',
                     'tag', { 'name' => 'mac-address' },
                     "DE:AD:BE:EF:F0:FF" );
    }
}

#note - pretty printing helps reading, but might
#cause some problems with certain XML constructs. Shouldn't in your specific example though.
$twig->set_pretty_print("indented_a");
$twig->print;

#to save it to a file:
open ( my $output, '>', 'processed.xml' ) or die $!;
print {$output} $twig -> sprint;
close ( $output );


text:
Q: Error in allocating space to an integer pointer So, I want to create a function that lets the user "declare" an array, something like int_array(a,3); and that's my code for the function:
int int_array(int *p, int n)
{
   *p = (int*)malloc(n*sizeof(int));
   return *p;
}

The thing is, I receive the following error:

invalid conversion from 'int*' to 'int'.

and I don't know why. What does actually cause this error? Is it because 'n' is a simple integer and not a pointer?

A: The problem is your function is dereferencing an int* pointer that doesn't point to a valid int, and then you are trying to assign a newly allocated int array to the dereferenced int. Even if the int were allocated, you can't assign a pointer to a non-pointer variable, which is the error you are getting.
Try this instead:
int* int_array(int n)
{
    return (int*) malloc(n * sizeof(int));
}

int *a = int_array(3);
...
free(a);

But, you shouldn't be using malloc() in C++, use new[] instead:
int* int_array(int n)
{
    return new int[n];
}

int *a = int_array(3);
...
delete[] a;

A better option is to use std::unique_ptr instead:
std::unique_ptr<int[]> int_array(int n)
{
    return std::make_unique<int[]>(n);
}

std::unique_ptr<int[]> a = int_array(3);
...

Or, just get rid of this function and use std::vector instead:
std::vector<int> a(3);
...

A: The problem: *p = (int*)malloc(n*sizeof(int));,
*p is an int and you try to assign int * to it. That doesn't work (atleast not the way you are attempting to do it).
Here is the fix:
int int_array(int *p, int n)
{
   p = (int*)malloc(n * sizeof(int));
   return *p;
}

However, I'm afraid this leaves you with a memory leak because the pointer you allocated inside the array will never be freed.
The solution would be to return a pointer instead, or better yet (since this is supposed to be C++), return a smart pointer.
std::unique_ptr<int[]> int_array(std::unique_ptr<int[]> &p, int n)
{
   p = std::unique_ptr<int[]>(new int[n]);
   return p
}

Why even bother passing in the pointer? Just do:
std::unique_ptr<int[]> int_array(int n)
{
   return std::unique_ptr<int[]>(new int[n]);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Saving user data from Chrome Extension to global variable, then shared for all users Wondering if this is at all possible. I'm working on a Chrome extension where, as users browse a particular site, certain elements on the page are saved to chrome.storage.local (or chrome.storage.sync). Those elements are then called again later on a different page. However, it would be useful to allow all users to save this data to 1 global variable/source, and all users be able to read from that variable/source. Do Chrome extensions have any method of accomplishing this?
The data in question isn't anything sensitive, it's not authentication info or anything. The reason I'm hoping to do this and not just save static variables or JSON objects within a content script is that the website I'm building this for changes fairly frequently, and I would rather that data not be completely static.
Thank you!

A: Not possible natively but there are lots of ways to do it for free (given you have few users and load and assuming you dont surpass their free quotas or rate limits) like a google appengine backend or a public google spreadsheet as sync. For the spreadsheet case, you can store as rows or put everything on a single cell. For appengine, the datastore has free quotas for read/write and free store quota (with limits and rate limits of course).


text:
Q: Increase in Mass with Velocity I just had a confusion. Does the mass of the body actually increase when it is moving with a certain velocity? Or does it only look like the mass has increase to another observer. How can the actual mass of the body increase. Please correct me if I am wrong but I feel that it only seems to the observer that the mass has increased but it does not increase in real.
The increase of actual mass would imply that that its velocity will decrease to comply with conservation of momentum. But how can the velocity decrease if no external force is applied?

A: There isn't a simple answer to your problem because it depends on what you mean by mass.
You've probably heard of Einstein's equation $E = mc^2$, and if you rearrange this equation you can use it as a definition of the mass:
$$ m = \frac{E}{c^2} $$
For a stationary object the mass we get is the rest mass or invariant mass, which is what we normally mean by mass. However if the object is moving then it has some kinetic energy so:
$$ E_{total} = mc^2 + \text{kinetic energy} $$
and we can define a relativistic mass using:
$$ m_r = \frac{E_{total}}{c^2} $$
and for a moving particle this relativistic mass is obviously greater than the invariant mass. This is mathematically a possible definition for the mass, but in the 109 years since special relativity was formulated it has caused generations of students much confusion, just as it is confusing you now in 2014. To avoid this we now rarely refer to relativistic mass, and modify Einstein's equation to be:
$$ E^2 = p^2c^2 + m^2c^4 $$
where $m$ is the invariant mass and $p$ is the momentum. Though I won't duplicate it here, the Wikipedia article on Mass in special relativity gives a proof that the two equations are the same.
You ask if the mass increase is real, but that can't be answered because you have to define what you mean by real. The difference between relativistic and invariant mass comes from accounting for the energy in different ways. One is no more real than the other, though the concept of invariant mass is much less confusing.

A: The inertia (resistance to acceleration) increases, and the object's tendency to curve space around it increases as it's velocity approaches the speed of light. But physicists have found it cumbersome to treat mass as a variable, or to keep saying "rest mass" all the time, so we say that the mass-proper stays the same.
Edit:
Some clarification in response to John Rennie's comment is in order. The gravitational field surrounding a small, massive particle, like a ball bearing, is given by the Schwarzschild metric, thus we are no longer considering purely special relativistic effects. If a test mass is moving with respect to the particle (as measured from a great distance), one would consider a boosted Schwarzschild metric.
If one is considering a distribution of mass in motion, the relevant object is the stress-energy tensor, which is the source term for the metric. The $T^{00}$ term is what you would normally call the energy of the particle, and is $\gamma m v^2 \delta(\mathbf{x}-\mathbf{x}_p(t))$ for a single moving particle. Things get a bit murky when you specify exactly what you mean by $\mathbf{x}(t)$, here, and you're best off taking $m$ to be much smaller than the other length scales in your spacetime.


text:
Q: How to disable paralalleism while db2 backup Currently when I do a db2 backup I can see Autonomic backup/restore - using parallelism = 2. in the logs. How can we disable parallelism so that its at the lowest? I am on DB2 version 11.1.9.0.

A: Try the PARALLELISM 1 clause
db2 backup database test to /dev/null PARALLELISM 1

Backup successful. The timestamp for this backup image is : 20181105183709

db2diag -H 1m | grep "Autonomic backup"
Autonomic backup/restore - using parallelism = 1.

but as you are using Db2 Warehouse, you should use db_backup to backup the database https://www.ibm.com/support/knowledgecenter/en/SS6NHC/com.ibm.swg.im.dashdb.doc/admin/app_backup.html


text:
Q: PHP - Check if data is in a table if so pass it to $_SESSIONS array Hi guys this is my first post here, there have been similar questions on this forum but I couldn't find one which accurately answered my question or at least it wasn't relevant enough for me to workout an answer - this is my 3rd day using PHP so I am still getting used to it..
I am making a small game for my site where by users can pay a small amount of money to win a prize, the prize is a code which will be emailed to them.
Currently I have my database and script setup so that the same code cannot be issued twice using the boolean Available which is set to 1 if the code has not been issued and 0 if it has
I have my code table setup like so
CodeID | ItemID | CodeType | Available | Code             |

1      | 1      | xxxxxxx  | 1         | QLLxbttKQcHv4e4k |
2      | 1      | xxxxxxx  | 1         | 6JKMumiH35Dke4SS |
3      | 3      | xxxxxxx  | 0         | mQ2WyUjqNy5fJiEr |

What I want to do is check each code to see if it is available, if it is I want to take the ItemID and put it in a $_SESSIONS array which I can use in another page to only return results for codes that I have stocked
I am having some trouble checking if the code is available and if it is putting the ItemID in the $_SESSIONS array
Currently I have this to query the database
$stock = $conn -> query('SELECT * FROM codes WHERE Available = 1');

This checks the database and out puts all codes which are currently available, including duplicate ItemIDs
Can anyone help me so that I only take 1 of each ItemID and put that into the $_SESSIONS array which I can use on the next page to only show results with available codes?

A: This query
SELECT DISTINCT ItemID FROM codes WHERE Available = 1

will return you only unique ItemIDs that are available
PS: prefer to select only particular columns you need, not everything with *


text:
Q: How to create coupon using chargify API - PHP/Laravel This is my ChargifyCoupon.php
public function create($product_family_id = null, $details = []) {
        $details = array_replace_recursive([
            "name" => "15% off",
            "code" => "15OFF",
            "description" => "15% off for life",
            "percentage" => "15",
            "allow_negative_balance" => "false",
            "recurring" => "false",
            "end_date" => "2016-12-31T23:59:59-04:00",
            "product_family_id" => $product_family_id
        ], $details);
        $returnData = $this->connector->createCoupon($details, 'JSON');
        var_dump($returnData);
        die;

    }

This is my ChargifyConnector.php
function createCoupon($product_family_id, $coupon_details = [], $format = 'XML') {
        $extension = strtoupper($format) == 'XML' ? '.xml' : '.json';
        $base_url = "/product_families/{$product_family_id}/coupons" . $extension;
        $data = json_encode([
            "coupon" => $coupon_details
        ]);
        $coupon = $this->sendRequest($base_url, $format, 'POST', $data);
        if ($coupon->code == 200) {
            return $coupon->response;
        } elseif ($coupon->code == 404 || $coupon->code == 500) {
            var_dump($coupon);
            die;
            throw new \Exception($coupon->code, "Coupon was not created.");
        }

    }

When i'm trying to see result i'm getting "array to string conversion"

A: Sorry for late reply..
After so much research on chargify coupon,
simply remove /product_families/{$product_family_id}.
no need to send coupon data with product_families/{$product_family_id}.
For more details see HERE.
Updated Code :
function createCoupon($product_family_id, $coupon_details = [], $format = 'XML') {
    $extension = strtoupper($format) == 'XML' ? '.xml' : '.json';
    // $base_url = "/product_families/{$product_family_id}/coupons" . $extension;
    $base_url = "/coupons" . $extension;
    $data = json_encode([
        "coupon" => $coupon_details
    ]);
    $coupon = $this->sendRequest($base_url, $format, 'POST', $data);
    if ($coupon->code == 200) {
        return $coupon->response;
    } elseif ($coupon->code == 404 || $coupon->code == 500) {
        // var_dump($coupon);
        // die;
        throw new \Exception($coupon->code, "Coupon was not created.");
    }
}


text:
Q: MySQL checking if string exist and updating or creating i am trying to make an simple if exist check for MySQL via php and then i will create an String if not exist; or if an string exist, i will update and add to the value counter = counter + 1
But now i dont now why nothing happend :s
What i am doing wrong --- i had search for the problem but i didnt has find anything..
thanks ahead
heres the code
$rankset = '';
$steamid64 = "76561198070477917";
$localmap = "de_dolls";

mysql_connect("localhost", "######", "###############") or die(mysql_error());
mysql_select_db("server") or die(mysql_error());

$check1 = mysql_query("SELECT * FROM `darkrp_missingmap` WHERE map = '$localmap'") or die(mysql_error());

while($info1 = mysql_fetch_array( $check1 ))
{
  if(mysql_num_rows($info1) == 0) {
    print "existiert nicht wird erstellt...";
    mysql_query("SELECT server INSERT INTO darkrp_missingmap (map, count) VALUES ('$localmap', '1')");
  }
  else {
    print "existiert wird aufgestuft...";
    mysql_query("SELECT server UPDATE darkrp_missingmap SET count = count + 1 WHERE map = '$localmap'");
  }
}

A: mysql_num_rows() takes a resource object as a parameter which is your $check1 while you are passing an array $info1 to it.
You should be doing:
$check1 = mysql_query("SELECT * FROM `darkrp_missingmap` WHERE map = '$localmap'") or die(mysql_error());

if (mysql_num_rows($check1) === 0) {
    #no records found
    print "existiert nicht wird erstellt...";
    #rest of your code
} else if (mysql_num_rows($check1) === FALSE) {
    #query failed
} else {
    #records found
    print "existiert wird aufgestuft...";
    #rest of your code
}

You should be careful about using ==0 because mysql_num_rows() returns FALSE on failure which can also be loosely compared to 0.
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

A: You can try this, you can ref [this]
$check1 = mysql_query("SELECT * FROM `darkrp_missingmap` WHERE map = '$localmap'") or die(mysql_error());
$nums = mysql_num_rows($check1);

if($nums == 0) {
 // do something
}

Or you can use this sql.
SELECT COUNT(*) AS count FROM `darkrp_missingmap` WHERE map = '$localmap'

And get this query's result count.
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$nums = $row[0]['count'];

A: i dont think you select and insert at one time and you dont need that either
try this
if(mysql_num_rows($info1) >0) {

print "existiert nicht wird erstellt...";
mysql_query("INSERT INTO darkrp_missingmap (map, count) VALUES ('$localmap', '1')");

} else {

print "existiert wird aufgestuft...";
mysql_query("UPDATE darkrp_missingmap SET count = count + 1 WHERE map = '$localmap'");
}

try this and tell

A: Ok i have found my trouble i have already select the db "server" and then i tried to make this
INSERT INTO darkrp_missingmap(map, count) VALUES ('zu_kotze', '100')
Here the working example:
    $steamid64 = "76561198070477917";
    $localmap = "de_dollsw";
mysql_connect("localhost", "####", "##########") or die(mysql_error());
mysql_select_db("server") or die(mysql_error());
//maplog

$check1 = mysql_query("SELECT * FROM `darkrp_missingmap` WHERE map = '$localmap'") or die(mysql_error());
$nums = mysql_num_rows($check1);

if($nums == 0) {
print "existiert nicht wird erstellt...";
mysql_query("INSERT INTO darkrp_missingmap (map, count) VALUES ('$localmap', '1')");
} else {
print "existiert wird aufgestuft...";
mysql_query("UPDATE darkrp_missingmap SET count = count + 1 WHERE map = '$localmap'");
}


text:
Q: Performing setRGB on BufferedImage changes pixel to black instead of color ** Important update, see below! **
I am creating a program that changes the pixels of a BufferedImage to a certain color when that pixel fulfills a set of conditions in Java. However, when I write the image to disk, the pixels that should be colored are instead black.
First I define the color, using RGB codes:
Color purple = new Color(82, 0, 99);
int PURPLE = purple.getRGB();

Then I read the image I want to alter from a File into a BufferedImage called "blank":
BufferedImage blank = ImageIO.read(new File("some path"));

Now, loop through the pixels, and when a pixel at location (x, y) matches a criteria, change its color to purple:
blank.setRGB(x, y, PURPLE);

Now, write "blank" to the disk.
File output = new File("some other path");
ImageIO.write(blankIn, "png", output); // try-catch blocks intentionally left out

The resulting file should be "blank" with some purple pixels, but the pixels in question are instead black. I know for a fact that the issue is with setRGB and NOT any import or export functions, because "blank" itself is a color image, and gets written to file as such. I read around and saw a lot of posts recommending that I use Graphics2D and to avoid setRGB, but with no discussion of pixel-by-pixel color changing.
I also tried direct bit manipulation, like this:
blank.setRGB(x, y, ((82 << 16) + (0 << 8) + 99));

I'm probably doing that wrong, but if I put it in correctly it wouldn't matter, because the pixels are getting set to transparent when I do this (regardless of what the numbers say, which is very strange, to say the least).
** When I try this:
blank.setRGB(x, y, Color.RED.getRGB());

My output file is grayscale, so that means setRGB is, in fact, modifying my picture in grayscale. I think this is actually a rather simple issue, but the solution eludes me.

A: Based on the insights in https://stackoverflow.com/a/21981173 that you found yourself ... (a few minutes after posting the question) ... it seems that it should be sufficient to simply convert the image into ARGB directly after it was loaded:
public static BufferedImage convertToARGB(BufferedImage image)
{
    BufferedImage newImage = new BufferedImage(
        image.getWidth(), image.getHeight(),
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return newImage;
}

A: The original image that was imported into Java was actually grayscale, so when Java read it into the BufferedImage, it simply imported it as a grayscale BufferedImage. By adding a very small but imperceptible colored dot in the corner of my image, I was able to get Java to output a correctly colored image.
Unfortunately, this is only a half solution, because I do not know how to fix this programmatically.
SOLUTION:
Convert the BufferedImage from grayscale to ARGB with this snippet:
BufferedImage blank2 = blank;
    // Create temporary copy of blank
blank = new BufferedImage(blank.getWidth(), blank.getHeight(), BufferedImage.TYPE_INT_ARGB);
    // Recreate blank as an ARGB BufferedImage
ColorConvertOp convert = new ColorConvertOp(null);
    // Now create a ColorConvertOp object
convert.filter(blank2, blank);
    // Convert blank2 to the blank color scheme and hold it in blank

You want to add this right after blank = ImageIO.read(new File("some path")).


text:
Q: Difference between "if + negative" and "if + positive" in this context Any semantic difference between the two following sentences?

See if there isn't any room for improvement.
See if there is any room for improvement.

A: Native speaker - I think these are basically equivalent. In both cases, the imperative is to check whether room for improvement exists, so the activity is the same.
There's a slight difference of tone. I would normally use "see if there isn't" in cases where I think there is room for improvement but I'm speaking to someone who disagrees; the implication is that I want them to conduct a more thorough search. But "see if there is" is also correct in that case.
I think you're good either way.


text:
Q: Response Error: 500 after using CSV config data set in request My flow is:
Thread Group
   Login page
   welcome page
Login page has post method (send parameter with request - I placed variable ${user} and ${pass} )
welcome page has get method (there is nothing in send parameter with request)
actual welcome webpage showing user name, password

I am passing the value (user id and password) using CSV data set config to Login Page. This login page request running successfully but after this page Welcome page showing response code 500 error. I have set cookies manager to both request.
So what need to do to display welcome page with userid and password? Why this request showing me error even if previous page running successfully.

A: My expectation is that you need to pass not only the credentials, but also there could be a couple of dynamic mandatory parameters which needs to be passed along with username and password. Given .net tag I'm pretty much sure that server expects at least VIEWSTATE, maybe something else. So your test plan should look  like:

*

*Thread Group

*

*Login Page - GET

*

*PostProcessor

*Login Page - POST (username, password, viewstate, etc.)

*Welcome Page

Where PostProcessor could be one of the following:

*

*Regular Expression Extractor

*CSS/JQuery Extractor

*XPath Extractor
See ASP.NET Login Testing with JMeter for detailed explanation, example configuration and end-to-end demo of loggin into .NET web application.


text:
Q: vb.net Error after Adding typed text item from datagridViewComboboxColumn into database Basically, I wan't the user to be able to type into datagridViewComboboxColumn
and if there is no match it will automatically save the text into the database, update the BindingSource and select the item.
Heres what I have so far.
The bindingsource:
With acctTitleCombo6
    .AutoComplete = True
    Try
        .DataSource = ds4
        .DisplayMember = "desc_description"
        .ValueMember = "desc_id"
        .DataPropertyName = "desc_id"
        .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End With

Changing combobox style to dropdown in EditingControlShowing:
Dim comboBoxColumn As DataGridViewComboBoxColumn = DataGridView2.Columns(0)
If (DataGridView2.CurrentCellAddress.X = comboBoxColumn.DisplayIndex) Then
    Dim cb As ComboBox = TryCast(e.Control, ComboBox)
    If (cb IsNot Nothing) Then
        cb.DropDownStyle = ComboBoxStyle.DropDown
    End If
End If

Checking if typed text is already in the source item (CellValidating event).
Dim comboBoxColumn As DataGridViewComboBoxColumn = DataGridView2.Columns(0)
cs2.Open()
Dim comm, comm2, comm3 As New MySqlCommand
comm.Connection = cs2
Dim msgAddDesc As String = "Your description is currently not in the list." & vbNewLine & _
    "Would you like to add '"

If (e.ColumnIndex = comboBoxColumn.DisplayIndex) And Not String.IsNullOrWhiteSpace(e.FormattedValue) Then
    Dim itemIE As IEnumerator = comboBoxColumn.Items.GetEnumerator
    itemIE.Reset()
    Dim thisItem As DataRowView
    Dim exist As Boolean = False
    While itemIE.MoveNext()
        thisItem = CType(itemIE.Current(), DataRowView)
        Dim valueMember As Object = thisItem.Row.ItemArray(0)
        Dim displayMember As Object = thisItem.Row.ItemArray(1)
        If displayMember.ToString = e.FormattedValue Then
            exist = True
        End If
    End While

    If exist = False Then
        If MessageBox.Show(msgAddDesc & e.FormattedValue & "' to the list?", "Does not exist", _
        MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
           comm.CommandText = "INSERT INTO ref_description(desc_description) " & _
               "VALUES(@description)"
            With comm.Parameters
                .Add("@description", MySqlDbType.VarChar).Value = e.FormattedValue
            End With
            comm.ExecuteNonQuery()
            comm.Parameters.Clear()
        End If
    End If
End If
cs2.Close()

Now, whenever I add a new item into the database, this error comes up but sometimes it doesn't:
The following exception occurred in the DataGridView:
System.FormatException: Value '' cannot be converted to type 'System.String'.

at System.Windows.Forms.DataGridViewComboBoxCell.ParseFormattedValue(Object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
at System.Windows.Forms.DataGridView.PushFormattedValue(DataGridViewCell& dataGridViewCurrentCell, Object formattedValue, Exception& exception)

Another question is, how can I update the combobox after I add the new item into the database, then I also want to automatically select the new item when the user press enter or tab (only when there's a new item added into the database).

A: how can I update the combobox: I don't see the code, how you load the ComboBox in the first place.
Usually, you just update related dataset and re-assign it to ComboBox.DataSource, or you can use databinding (no need to update then, but one usually uses it if in need of more binding features).
Private Sub LoadUpdateSubListCombo()
        Dim cmdText as String
        cmdText = "SELECT ID,SubName FROM SubmarinesTable "
        Dim ds as DataSet
        ds = MyDataAccessLayer.GetQueryResults(cmdText)
        Dim SubDT As DataTable = ds.Tables(0).DefaultView
        cb3.DataSource = SubDT
        cb3.ValueMember = "ID"
        cb3.DisplayMember = "SubName"
End Sub

...where cb3 is a ComboBox...

A: I'm not sure, if I can help. However, the error comes from DataGridView, not combo. I suspect, that you update the datagridview at the same time (as you try to update the combo), which will not work. I think you need to finish cell editing first (incl. validation), then you can update the datagridview. I'd try to move it to CellEndEdit() event.


text:
Q: Zener diode question in simple LED circuit with anti-flicker for model railroad I am a total novice when it comes to electronics.  I had a simple circuits class 30 years ago as a software undergrad.  I've designed a simple LED lighting circuit for N-scale model railroad, to be used to light passenger cars.  The circuit includes "anti-flicker" capacitors so that minor interruptions of input voltage due to dirty track, etc. do not cause the lights to flicker (which is terribly annoying).
I used example circuits from various websites plus input from forum members on an N-scale forum I am on to come up with this circuit.  I've mocked it up on a breadboard and it works, but I wanted to make sure it makes sense to people who know more than me.  The exact values in the circuit are just an example and I am not sure the resistor leading into the zener makes sense.  I've watched a few zener diode YouTube videos and looked at online tutorials.
The goal of the circuit is to have a board made that the user can then populate with their desired components (amount of anti-flicker capacitance, "dimming resistor", number of LEDs in parallel, size of LED, 3.3V or 5V regulator feeding the LEDs etc).
The input is meant to be either DCC track voltage (n-scale levels) which is a digital square wave signal (and represented by the "VAC" inputs and on the output of the rectifier shows as around 13.5--14.5V), or for those using DC analog trains, a positive or negative voltage (usually 0-12V but can be higher than 12V).
So the input is fed through a bridge rectifier, and the output is then fed into the circuit.  The main circuit is composed of anti-flicker capacitors that feed a voltage regulator (listed as L7805 but I am using AMS1117 in 5V or 3.3V versions).  The output of the voltage regulator is fed into the LED circuit, which has a "dimming" resistor (shown here as 2.2k ohms, and which can probably vary from 750 ohms to around 3k ohms depending on how bright the user wants the LEDs to be, what sort of LED (0805 or 1206 -- the difference being the amount of light they produce so relative brightness of an individual LED to get the desired overall passenger car internal brightness), whether 5v or 3,3v from the regulator, etc.
The capacitors are meant to be SMD ceramic capacitors.  While up to 47uF are available in 25V versions, 100uF (in 1206 or smaller or 1210 size) are hard to find in 25V versions (at least economically), but readily available in 12V, so to be able to use 16V versions of the capacitors, I added a zener diode between the rectifier and the capacitors in order to "hard limit" the voltage into the capacitors at about 12V.
(There is also a resistor of 100 ohms or 75 ohms to limit a hard surge of current into the capacitors [as I gathered from other circuits, and a similar low value resistor into the voltage regulator).
It appears from my testing that this is about correct but I am not sure I am computing the resistor leading into the zener correctly.
The zener I have is a ZMM12V (from Chanzon -- inexpensive Chinese stuff as this is meant to be a low cost board) -- https://www.aliexpress.com/store/product/100-500-2500-Pcs-SMD-Zener-Diode-0-5W-12V-ZMM12V-ZMM12-LL-34-SOD/313665_32854074530.html?spm=2114.12010612.8148356.14.711e4cf5y0vwxT
I had computed around 35 ohms based on a 13.5V input and a 12V zener voltage.  But this gives me around 12.5-12.7V.  If I make this resistor 150 ohms the voltage showing between the zener and the capacitor circuit is about 12V.
Because the LEDs are not lit very brightly, the overall load from the LEDs is not that high.  If I am measuring it correctly, usually in the low single digit "ma" .
Does this circuit look reasonable and how do I really compute the resistor for the zener?  I need to be able to handle a variety of input voltages from 12V up to probably around 15V/16V from the rectifier.
Thanks for a newbie.

A: There are more efficient ways to do this. or there are simpler ways to get a long time constant.

The shared load current is 0.6Vbe/Re=470 = 1.2mA on the emitter.
Adjust to suit your requirement.
P.S.
There is a risk after ? hundreds hours of use that the LED's go dark using only 100 uA. This is common effect and some MFG's warn against using below ~ 1~2mA currents. It just means the threshold for photoemission has risen above what was used due to an effect caused by such low currents.  Pulsing to 10mA may or may not restore this dim light suitable for N scale realism.
The other approach is a 0.5% duty cycle pulse @ 200mA (shared) with 20kHz a Schmitt Inverter clock after this current limiter set for same 200mA or R3= approx. 3 Ohms could prevent this with the same low pass filter on supply and same average current.
To cut number of LED's Current must also be reduced with higher Re.
Rev B 12:10 PM


text:
Q: File fixture getting deleted after running RSpec tests I have tests written in RSpec that have been passing up until an upgrade to Ruby 2.5.1.
The test in question has several let statements in a before(:each) block. The file that keeps getting deleted is in there like so:
    let(:fake_s3_file) { File.open(File.join(File.dirname(__FILE__), '../fixtures/Alexa.pdf')) }

Later in before(:each) stanza, I have this:
  allow(s3_client).to receive(:get_object).and_return(fake_s3_file)
  allow(Tempfile).to receive(:new).and_return(fake_s3_file)

It appears that in Ruby 2.5.1, my source files are getting deleted, either because of the File.open or the Tempfile reference. Has anyone run into this, and what is a good way around this? I haven't found any docs that say any changes have happened to Tempfile or to File.open. Should I copy my fixture file into a /tmp directory before every spec run? It seems wrong to do that, and slow.


text:
Q: quickest way to implement .net authentication in Web Forms with Entity Framework 6 I have been checking resources to implement authentication in my web forms application built with entity framework. All examples I found are MVC-related. I have used regular Asp.Net Membership framework a long time before I began to use EF. However, I could not find Membership implementation with Entity Framework code-first. I did implement the Claims-Based Identity (EF created the tables for me in DB) but I do not know how to utilize it in the application (like login), and it looks more complicated to me. Can anyone guide me ?

A: There are a couple of good tutorials on the asp.net web site:
http://www.asp.net/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project
http://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/membership-and-administration


text:
Q: How to select data from mysql with condition of two tables I have two tables: users and sub_list.
Table users contain username and table sub_list contains username, subscribed_user.
**table users**
*username:* john,harris,samantha,peter,joe,max

**table sub_list**
*username:* harris, harris, peter
*subscribed_user:* samantha, john, joe

Let's say my name is harris...
Now I want query to select a random user from table users limited by 1, where harris is not subscribed to that user in table subscribed_user.
So I don't want to get results like: samantha and john because I've already subscribed to them.
This code below doesn't work.
SELECT *
FROM users
WHERE users.username='harris' NOT IN (
   SELECT username
   FROM sub_list)
ORDER BY RAND() DESC
LIMIT 1


text:
Q: Exchange Partition giving -Table or index is not partitioned. Invalid syntax I have 2 schemas TBCAM and AR_TBCAM. There is a table called BKP_COST_EVENT in TBCAM which I have partitioned and I have moved the partition data into another simple table in AR_TBCAM schema called BKP_COST_EVENT_P2016. Now the data has moved to AR_TBCAM schema via this query
ALTER TABLE BKP_COST_EVENT EXCHANGE PARTITION P2016 WITH TABLE AR_TBCAM.BKP_COST_EVENT_P2016 INCLUDING INDEXES WITHOUT VALIDATION;

Now I want to bring the partition data back into the original table BKP_COST_EVENT.
But when I run this query standing on AR_TBCAM
ALTER TABLE BKP_COST_EVENT_P2016 EXCHANGE PARTITION P2016 WITH TABLE TBCAM.BKP_COST_EVENT INCLUDING INDEXES WITHOUT VALIDATION;

It is giving this error:
Error starting at line : 1 in command -
ALTER TABLE BKP_COST_EVENT_P2016 EXCHANGE PARTITION P2016 WITH TABLE TBCAM.BKP_COST_EVENT INCLUDING INDEXES WITHOUT VALIDATION
Error report -
ORA-14501: object is not partitioned
14501. 00000 -  "object is not partitioned"
*Cause:    Table or index is not partitioned.  Invalid syntax.
*Action:   Retry the command with correct syntax.

Can anyone suggest what am I doing wrong? Or how to bring/restore the data back to my TBCAM schema table BKP_COST_EVENT.
I have not dropped the partition p2016 in the original BKP_COST_EVENT

A: In exchange partition syntax first table should be the one which is partitioned, second should be unpartitioned one.
So, your first command was correct but 2nd command is wrong.
If you are bringing back data to same table's partition run the same command again.
ALTER TABLE BKP_COST_EVENT EXCHANGE PARTITION P2016 WITH TABLE AR_TBCAM.BKP_COST_EVENT_P2016 INCLUDING INDEXES WITHOUT VALIDATION;
Also, if there are no indexes to be moved, its better not to use including indexes clause.


text:
Q: In javascript, is it possible for me to return the element of any DOM element I'm hovering over? For example, if I have an HTML snippet like so:

        I'm a title!

I'm the first element!

I'm the first element!

Obviously, if I wanted to get a specific element, say the div with id of 1, I could do something like
document.getElementById("1").addEventListener("mouseover", () => console.log("in div 1!"), false);

and that would output in div 1! whenever I hovered over it. But is there some javascript I can have that apply to every single element in body? To basically write some function like, getElementUserIsHoveringOver()?
I don't think addEventListener works on HTMLCollections, which was my only idea.

A: mouseover bubbles, so if you attach a listener to the , you can watch for events and log the event.target:

document.body.addEventListener('mouseover', (e) => {
  console.log(e.target);
});

    I'm a title!

I'm the first element!

I'm the second element!


text:
Q: error: type mismatch found : Array[Byte] [error] required: Byte So I don't know Scala that much I used ScalaToJava converter to convert some code into Scala But now I have this error.type mismatch;
[error]  found   : Array[Byte]
[error]  required: Byte
def generateAuthTkt(username: String,
                  tokens: Array[String],
                  userData: Array[String],
                  encode: Boolean,
                  ignoreIP: Boolean,
                  ip: String,
                  secretKey: String,
                  timestampInSeconds: Long): String = {
val username: String =
  (if (StringUtils.isBlank(username)) StringUtils.EMPTY else
username)
val tokens: Array[String] = (if (tokens == null) Array() else
tokens)
val userData: Array[String] = (if (userData == null) Array() else
userData)
var ipAddress: String = ip
if (ignoreIP || StringUtils.isBlank(ipAddress)) {
  ipAddress = "0.0.0.0"
}
val ipLong: Long = convertIPToLong(ipAddress).longValue()
val ipBytes: Array[Byte] = longToBytes(ipLong)
val tsBytes: Array[Byte] = longToBytes(timestampInSeconds)
val ipts: Array[Byte] = ArrayUtils.addAll(
  ArrayUtils.subarray(ipBytes, 4, 8),
  ArrayUtils.subarray(tsBytes, 4, 8))
//I am getting the error in the upper line
var dataBytes: Array[Byte] = ArrayUtils.addAll(ipts,
secretKey.getBytes)


text:
Q: Set state twice in onChange ReactJS I have the following snippet of React that I can't get to work right.  Essentially I'm displaying a spinner based on the state of this onChange call (due to the update sometimes taking 3-5 seconds).  However, the first call to set state seems to go unnoticed (or as I'm researching being batched up) and therefore the state of loading is never updated.  This is part of a toggle/switch a user can select infinite times on a page (if they desired obviously).
  const [state, setState] = useState({ loading: false });
  const onToggleChange = () => {
    setState(prevState => {
      return {
        ...prevState,
        loading: true,
      };
    });
    console.log("loading1: " + JSON.stringify(state));

    // this takes a long time depending on the users actions
    setFilterMode(!filterChecked);

    setState(prevState => {
      return {
        ...prevState,
        loading: false,
      };
    });
    console.log("loading2: " + JSON.stringify(state));
  };

I've reviewed the current questions/answer (which is how I got as far as the above), but it still doesn't load correctly.


text:
Q: objective c resizing mask i have a view within 3 Buttons. My problem is, how can i set the resizing mask or autolayout programmatically that i get this solution:
Small view and a larger view..

Objective-c code:
_button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[_button1 setFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)]; // set a height?!
[_button1 setBackgroundColor:[UIColor colorWithRed:235/255.0f green:235/255.0f blue:235/255.0f alpha:1.0f]];
_button1.autoresizingMask = UIViewAutoresizingFlexibleHeight;

_button2 and_button3 are the same..

How can i set the button height flexible in dependence of the view height?
Thanks for helping..

A: An example of how you might achieve this using AutoLayout might look like this:
// Build the view hierarchy
_button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[_button1 setBackgroundColor:[UIColor colorWithRed:235/255.0f green:235/255.0f blue:235/255.0f alpha:1.0f]];
_button1.translatesAutoresizingMaskIntoConstraints = NO;
_button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[_button2 setBackgroundColor:[UIColor colorWithRed:235/255.0f green:235/255.0f blue:235/255.0f alpha:1.0f]];
_button2.translatesAutoresizingMaskIntoConstraints = NO;
_button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[_button3 setBackgroundColor:[UIColor colorWithRed:235/255.0f green:235/255.0f blue:235/255.0f alpha:1.0f]];
_button3.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addSubview: _button1];
[self.view addSubview: _button2];
[self.view addSubview: _button3];

NSMutableArray* constraints = [NSMutableArray array];

// Arrange them vertically
[constraints addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: @"V:|-[_button1]-[_button2]-[_button3]-|" options:0 metrics:nil views: NSDictionaryOfVariableBindings(_button1, _button2, _button3)]];

// Make their heights equal
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem: _button2 attribute: NSLayoutAttributeHeight multiplier:1.0 constant:0.0]];
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem: _button3 attribute: NSLayoutAttributeHeight multiplier:1.0 constant:0.0]];

// Set their widths equal to superview
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem: self.view attribute: NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem: self.view attribute: NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button3 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem: self.view attribute: NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];

// Center them horizontally in the superview
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem: self.view attribute: NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button2 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem: self.view attribute: NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
[constraints addObject: [NSLayoutConstraint constraintWithItem:_button3 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem: self.view attribute: NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];

// Add the constraints
[self.view addConstraints: constraints];


text:
Q: Solving 12! but for addition I'm trying to solve the equivalent of 12! but rather than have 12 * 11 * 10 * n...I'm trying to figure out how to write this equation in terms of addition, so 12 + 11 + 10..etc.  Any ideas on how to write that?

A: For every $n \in \mathbb{N},$ $$n+ (n-1) + \ldots 2 + 1 \;= \;1+2+\ldots+ (n-1) +n=\frac{n(n+1)}2$$
So for $n = 12,\;$ just compute $\;\dfrac{12(12+1)}2$
Challenge: See if you can prove this by induction on $n$.

A: Add:
$$\begin{array}{c}
1&+&2&+&3&+&\ldots&+&(n-1)&+&n&=&S\\
n&+&(n-1)&+&(n-2)&+&\ldots&+&2&+&1&=&S\\ \hline
(n+1)&+&(n+1)&+&(n+1)&+&\ldots&+&(n+1)&+&(n+1)&=&2S
\end{array}$$
There are $n$ columns, so the bottom line is $n(n+1)=2S$, and therefore $S=\dfrac{n(n+1)}2$.

A: $\large \frac{n(n+1)}{2}$ is the equation that solves this


text:
Q: how to make header title with buttons there is a ionic framework in which it is too easy to make header title  with two left and right buttons and it is responsive.In other words header title always in middle of page .
here is code how they implement ..here is my plunker
http://plnkr.co/edit/BqtvCYYfhhbokzbbOXU4?p=preview

<ion-header-bar align-title="center" class="bar-positive">

    <button class="button" ng-click="doSomething()">Left Button</button>

Title!

    <button class="button">Right Button</button>

</ion-header-bar>

But same thing I need to implement using only HTML5 and css3 or css I tried but I am not able to set my button position  left and right .how to set button position left and right .
here is my code
http://plnkr.co/edit/OGr7px9jueIfDTsHhePA?p=preview

     <button style="position:absolute;left:5px">left</button>

Title !

   <button style="position:absolute;right:5px">right</button>

css
.header{
  background:blue;
  height:44px;
  text-align:center;
  position:relative;
}

A: Move the 2nd button above the H2 and add top: 2px (or something you need) to both buttons' style. They need a top-rule, otherwise the 2nd gets displayed after the H2 like now.

A: The h2 is forcing the button to move down because it forces a line break, just rearrange the order like this:

   <button style="position:absolute;left:5px">left</button>
   <button style="position:absolute;right:5px">right</button>

Title !


text:
Q: To get distinct month name and count the values of duplicates, among multiple tables in mysql I have three tables likely tbdata,tbdatahw,tbdatamr. In that all tables the fields called status and c42 are same. for example tbdatahw table
like this same fields in tbdata and tbdatamr table. Field status 1 specifies green color and 2 for yellow and c42 for date details. what i try achieve is in January month how many green yellow status in among all 3 tables. I tried this query in workbench
    SELECT  MONTHNAME(c42) MONTH, SUM( case when status = 0 THEN 1 else 0 end) AS red
,SUM( case when status = 1 THEN 1 else 0 end) AS green
,SUM( case when status = 2 THEN 1 else 0 end) AS yellow
FROM  tbdata where  month(c42) is not null group by month(c42)
union all
SELECT  MONTHNAME(c42) MONTH, SUM(distinct case when status = 0 THEN 1 else 0 end) AS red
,SUM(distinct case when status = 1 THEN 1 else 0 end) AS green
,SUM(distinct case when status = 2 THEN 1 else 0 end) AS yellow
FROM  tbdatamr where  month(c42) is not null group by month(c42)
union all
SELECT  MONTHNAME(c42) MONTH, SUM(distinct case when status = 0 THEN 1 else 0 end) AS red
,SUM(distinct case when status = 1 THEN 1 else 0 end) AS green
,SUM(distinct case when status = 2 THEN 1 else 0 end) AS yellow
FROM  tbdatahw where  month(c42) is not null group by month(c42);

It is giving the output with redundancy like
i don't want the February month coming two times but  i want to add the green status value from two feb into one.  I tried distinct and union as well but not working. I want the output like this

A:     select month,
SUM(t.red) as red,
SUM(t.green) as green,
SUM(t.yellow) as yellow
from ( {put your whole query here} ) as t GROUP BY month ORDER BY FIELD(month, 'JANUARY', 'FEBRUARY',{please continue to DECEMBER})


text:
Q: Sails js socket broadcast from server I have done my first app with SailsJs. At the moment I'm using ajax to retrieve data for page, but I'd like to change it to use sockets. I have a cron job running on server and my purpose is to send message to all connected clients after every cron job done. I can see echo example from github: https://github.com/balderdashy/sails-docs/blob/0.9/sockets.md, but it's not quite what I need. I rather see server sending messages, no need for clients send anything but listen.
Server side CronController.js
// including my cron script
var cron = require('../../assets/js/cron');

module.exports = {
   index: function (req, res) {
        // including cron job module
        var cronJob = require('cron').CronJob;
        var job = new cronJob('0,10,20,30,40,50 * * * * *',
            function() {
                cron.run();
            }, function () {
                console.log('cron done');
            },
            true,
            null
        );
        return res.json({
            message: 'running cron...'
        });
    },
    _config: {}
};

Server side cron.js
var io = require('socket.io').listen(8887);
io.sockets.on("connection", function (s) {
    s.emit('welcomemessage', { hello: "world" });
});

// Later on code
io.sockets.emit('Cron done', {msg:"msg"});

Client side script.js
socket.on('welcomemessage', function (json) {
    console.log(json);
});

socket.on('Cron done', function (json) {
    console.log(json);
});

I also changed socket.io.js port: 8887
console says: info  - socket.io started and webpage localhost:8887 gives indication socket is working, but I get no welcome message or other messages to client side...
Other threads dealing with same question:
node.js + socket.io broadcast from server, rather than from a specific client?
emit socket.io and sailsjs (Twitter API)
Node.js client for a socket.io server
SOLUTION
I found socket variable on client side is able to get messages thru controller actions:
socket.get("/mycontroller", function (response) { console.log(response); });

So what I had to do was:
var s = io.connect("http://localhost:8887");

s.on('welcomemessage', function (json) {
    console.log(json);
});


text:
Q: Select unique combinations (unique on both sides) EDIT: added a link to Fiddle for a more comprehensive sample (actual dataset)

I wonder if the below is possible in SQL, in BigQuery in particular, and in one SELECT statement.
Consider following input:
  Key | Value
 -----|-------
  a   |     2
  a   |     3
  b   |     2
  b   |     3
  b   |     5
  c   |     2
  c   |     5
  c   |     7

Logic: select the lowest value "available" for each key. Available meaning not yet assigned/used. See below.
  Key | Value |                    Rule
 -----|-------|--------------------------------------------
  a   |     2 | keep
  a   |     3 | ignore because key "a" has a value already
  b   |     2 | ignore because value "2" was already used
  b   |     3 | keep
  b   |     5 | ignore because key "b" has a value already
  c   |     2 | ignore because value "2" was already used
  c   |     5 | keep
  c   |     7 | ignore because key "c" has a value already

Hence expected outcome:
  Key | Value
 -----|-------
  a   |     2
  b   |     3
  c   |     5

Here the SQL to create the dummy table:
with t as ( select
'a' key, 2 value UNION ALL select 'a', 3
UNION ALL select 'b', 2 UNION ALL select 'b', 3 UNION ALL select 'b', 5
UNION ALL select 'c', 2 UNION ALL select 'c', 5 UNION ALL select 'c', 7
)
select * from t

EDIT: here another dataset
Not sure what combination of FULL JOIN, DISTINCT, ARRAY or WINDOW functions I can use.
Any guidance is appreciated.

A: EDIT: This is an incorrect answer that worked with the original example dataset, but has issues (as seen with comprehensive sample). I'm leaving it here for now to maintain comment history.

I don't have a specific BigQuery answer, but here is one SQL solution using a Common Table Expression and recursion.
WITH MyCTE AS
(
  /* ANCHOR SUBQUERY */
  SELECT MyKey, MyValue
  FROM MyTable t
  WHERE t.MyKey = (SELECT MIN(MyKey) FROM MyTable)

  UNION ALL

  /* RECURSIVE SUBQUERY */
  SELECT t.MyKey, t.MyValue
  FROM MyTable t
  INNER JOIN MyCTE c
     ON c.MyKey < t.MyKey
    AND c.MyValue < t.MyValue
)

SELECT MyKey, MIN(MyValue)
FROM MyCTE
GROUP BY MyKey
;

Results:
  Key | Value
 -----|-------
  a   |     2
  b   |     3
  c   |     5

SQL Fiddle


text:
Q: How can a PHP CLI script detect if running in the background? I am developing a CLI PHP script that can either be executed in the foreground or the background. If running in the foreground I want to be able to interact with the user getting input information. Obviously if the script is launched in the background using the '&' parameter any user interaction should be skipped...
So is there a way for a PHP script to detect that it has been launched in the background?

A: Its not possible to detect if its running in background. I still didn't find any way to do.
One way could be to traverse process list and check the status of /usr/bin/php
The best ways is to use a parameter (say --daemon). When this parameter is passed it'll be running in background otherwise it'll print useful information on front-end.
You can create daemon using System_Daemon pear package.

A: There's a Unix frequently asked question (which I found via this Stack Overflow post) that basically claims it cannot reliably be done. One suggestion the article gives is to check whether or not stdin is a terminal:
sh: if [ -t 0 ]; then ... fi
C: if(isatty(0)) { ... }

I agree with Pekka's comment that you should simply provide a parameter to the script. The -i (for interactive) option is sometimes used for this express purpose. If that parameter isn't passed, you can assume you're in "automated" mode.


text:
Q: Concatenate two files in loop i try to concatenate two .txt in loops, here is the file
mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ ls
Alnus1.txt  Alnus2.txt  Alnus3.txt  Alnus4.txt  Bobi1.txt  Bobi2.txt  Bobi3.txt  Bobi4.txt`

I try to combine Alnus1 and Bobi1 into a new file named combination1.txt
I am new in bash and need guidance
I here is my failed trial, please take a look.
mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ ls
Alnus1.txt  Alnus2.txt  Alnus3.txt  Alnus4.txt  Bobi1.txt  Bobi2.txt  Bobi3.txt  Bobi4.txt
mn@LeNOVO-220414-A:/mnt/c/Users/LeNOVO/Alnus$ for name in *1.txt
> do
> other = "${name/1/1}"
> cat "$name" "%other" > "$combination1"
> done
other: command not found
-bash: : No such file or directory
other: command not found
-bash: : No such file or directory

I try to combine Alnus1 and Bobi1 into a new file named combination1.txt

A: This is probably what you're looking for:
for file in Alnus*.txt; do
    suffix=${file#Alnus}
    cat "$file" "Bobi$suffix" > "combination$suffix"
done

The value of ${file#Alnus} is the value of the variable file with the string Alnus removed from the beginning.

A: edit: updated snippets according to the tips in the comments
If you know exactly how many files there are, you can do this:
for i in {1..4}; do
        cat "Alnus${i}.txt" "Bobi${i}.txt" > "combination${i}.txt"
done

If you don't, you can use find . -name "Alus*.txt" | wc -l to make it work for any number of files (assuming you are always starting the count from 1), like this:
for i in $(seq 1 "$(find . -name "Alnus*.txt" | wc -l)"); do
        cat "Alnus${i}.txt" "Bobi${i}.txt" > "combination${i}.txt"
done


text:
Q: Merging multiple rows based on criteria into 1 in power query could you please assist solving the following tasks:

*

*F.e. I have data set:

What i need - to create a task with description, which discounts need to be check. It should be in following format though:
SKU within same brand with same discount depth should be merged into 1 row - Check Discount 10% for brand 1 for SKU's: cream & oil.
While others should remain as same rows as they have different discounts within brand:
Check Discount 20% for brand 2 for SKU detergent
Check Discount 15% for brand 2 for SKU tabs.
There is more levels of data, f.e. the task should be within same outlet (if there is x > 1 outlets, task will be multiplied by x according to amount of outlets). But I guess it should be easy further on if I get the method how to do the mentioned above task.

*Should be pretty similar to the previous one, but I might be wrong

Monitor & Catalogue columns basically describe which rows can be merged. So the output out of this table should be 2 rows:

*

*Check positioning of 1-oil and 2-tabs on the monitor

*Check positioning of 1-cream and 2-detergent on the catalogue

There can be multiple levels of aggregation, i.e. on top of rows with 1's, there can be rows with 2's - meaning they should be merged in separate task as well. 0 in all cases means - don't take.
I understand it might be a little bit overcomplicated, but i'm looking to speed up this process in Power Query as it's currently being done with VBA analyzing each row and finding match positions.
Here's the desired result with input data:

Everything further is simple. I just eliminate brand-sku and group by task.

Thank you!

A: Here's the first one - note that the format you requested in the first one (data entered into separate rows within the same cell using alt+enter) isn't supported in powerquery, so I separated the data with commas instead.
Instructions

*

*Add column>add index column

*Highlight index columns>transform>pivot>sku as values>advanced options>don't aggregate

*Highlight all of the columns to the right>transform>merge columns (choose a separator if you want one, I chose commas)

*Transform>Replace ,, with , (may have to do a few times)

*Change Brand to text, Discount to %

*Add column>custom column formula = "Check discount " & Number.ToText([Discount]*100) & "% for brand " & [Brand] & " for SKU " & Text.Trim([Merged],",")

Before/After

M Code
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Brand", Int64.Type}, {"SKU", type text}, {"Discount", type number}}),
    #"Added Index" = Table.AddIndexColumn(#"Changed Type", "Index", 1, 1),
    #"Pivoted Column" = Table.Pivot(Table.TransformColumnTypes(#"Added Index", {{"Index", type text}}, "en-US"), List.Distinct(Table.TransformColumnTypes(#"Added Index", {{"Index", type text}}, "en-US")[Index]), "Index", "SKU"),
    #"Merged Columns" = Table.CombineColumns(#"Pivoted Column",{"1", "2", "3", "4", "5"},Combiner.CombineTextByDelimiter(",", QuoteStyle.None),"Merged"),
    #"Changed Type1" = Table.TransformColumnTypes(#"Merged Columns",{{"Brand", type text}, {"Discount", Percentage.Type}}),
    #"Added Custom" = Table.AddColumn(#"Changed Type1", "Custom", each "Check discount " & Number.ToText([Discount]*100) & "% for brand " & [Brand] & " for SKU " & Text.Trim([Merged],","))
in
    #"Added Custom"

2nd Example Instructions
Note: For this one it is easies to do Monitor and Separator separately. Just filter for a different one each time.

*

*Add column>add index column

*Highlight index columns>transform>pivot>sku as values>advanced options>don't aggregate

*Filter for Monitor =1

*Delete Monitor & Catalogue columns

*Merge remaining columns, use - as separator

*Transpose

*Merge columns using , as separator

*Find and replace -- with - (may have to do a couple times)

*Custom column> Use the formula ="Check place ment of " & Text.Trim([Merged]) & " on Monitor"

2nd Example Before/After

2nd Example M-Code
let
    Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Brand", Int64.Type}, {"SKU", type text}, {"Monitor", Int64.Type}, {"Catalogue", Int64.Type}}),
    #"Added Index" = Table.AddIndexColumn(#"Changed Type", "Index", 0, 1),
    #"Pivoted Column" = Table.Pivot(Table.TransformColumnTypes(#"Added Index", {{"Index", type text}}, "en-US"), List.Distinct(Table.TransformColumnTypes(#"Added Index", {{"Index", type text}}, "en-US")[Index]), "Index", "SKU"),
    #"Filtered Rows" = Table.SelectRows(#"Pivoted Column", each ([Monitor] = 1)),
    #"Removed Columns" = Table.RemoveColumns(#"Filtered Rows",{"Monitor", "Catalogue"}),
    #"Merged Columns" = Table.CombineColumns(Table.TransformColumnTypes(#"Removed Columns", {{"Brand", type text}}, "en-US"),{"Brand", "0", "1", "2", "3"},Combiner.CombineTextByDelimiter("-", QuoteStyle.None),"Merged"),
    #"Transposed Table" = Table.Transpose(#"Merged Columns"),
    #"Merged Columns1" = Table.CombineColumns(#"Transposed Table",{"Column1", "Column2"},Combiner.CombineTextByDelimiter(", ", QuoteStyle.None),"Merged"),
    #"Replaced Value" = Table.ReplaceValue(#"Merged Columns1","--","-",Replacer.ReplaceText,{"Merged"}),
    #"Replaced Value1" = Table.ReplaceValue(#"Replaced Value","--","-",Replacer.ReplaceText,{"Merged"}),
    #"Added Custom" = Table.AddColumn(#"Replaced Value1", "Custom", each "Check place ment of " & Text.Trim([Merged]) & " on Monitor")
in
    #"Added Custom"

Hopefully that gets you started on how to apply PQ to your data! You may have to adjust slightly if your data sets vary.

A: Thanks for your advices, Hooded 0ne. Gave me the right direction.
I've done only 1st part though, here are some adjustments I made:

*

*Added $ to SKU to find position later to be replaced with "," - now I can clear the delimiters from merge in 1st step via replace ";" with blank, replace "$" with "," and Text.End or Trim the first "," in the row

*Added Select Columns to the step after "Pivot columns". There's dynamic list of columns, so I can't hardcode "1,2,3,4,5" like you did

Here's my final code for p1:
    #"Add $" = Table.AddColumn(#"Filtered Rows", "SKU_SYMBOL", each "$"&[ROI_LKA_BASE.SKU]),
    #"Add Index" = Table.AddIndexColumn(#"Add $", "Index", 0, 1, Int64.Type),
    #"Added Custom" = Table.AddColumn(#"Add Index", "TextIndex", each "TASK_"&Number.ToText([Index])),
    #"Removed Columns2" = Table.RemoveColumns(#"Added Custom",{"Index", "Shelf start", "Shelf End", "KAM", "Вид Инф. АУ", "Место размещ. АУ", "Адрес", "Attribute", "Value", "ROI_LKA_BASE.Мониторы", "ROI_LKA_BASE.Каталог", "ROI_LKA_BASE.Confirmed with customer", "ROI_LKA_BASE.Confirmed plan", "ROI_LKA_BASE.SKU"}),
    #"Pivoted Column" = Table.Pivot(#"Removed Columns2", List.Distinct(#"Removed Columns2"[TextIndex]), "TextIndex", "SKU_SYMBOL"),
    ColumnsToSelect = List.Select(Table.ColumnNames(#"Pivoted Column"),each Text.Contains(_,"TASK")),
    #"Select Pivoted Columns" = Table.SelectColumns(#"Pivoted Column",ColumnsToSelect),
    #"Merged Columns" = Table.CombineColumns(#"Pivoted Column",Table.ColumnNames(#"Select Pivoted Columns"),Combiner.CombineTextByDelimiter(";", QuoteStyle.None),"PIVOT_MERGED"),
    #"Replaced Value" = Table.ReplaceValue(#"Merged Columns",";","",Replacer.ReplaceText,{"PIVOT_MERGED"}),
    #"Replaced Value1" = Table.ReplaceValue(#"Replaced Value","$",",",Replacer.ReplaceText,{"PIVOT_MERGED"}),
    #"Added Custom1" = Table.AddColumn(#"Replaced Value1", "TASK", each "Проверить скидку на " & [ROI_LKA_BASE.Бренд] & ": "
& Text.End([PIVOT_MERGED],Text.Length([PIVOT_MERGED])-1)),
    #"Grouped Rows" = Table.Group(#"Added Custom1", {"Promo ID", "promotool_code", "ROI_LKA_BASE.Начало акции", "ROI_LKA_BASE.Конец акции", "ROI_LKA_BASE.Chain code", "ROI_LKA_BASE.Описание промо", "ROI_LKA_BASE.Сеть", "TASK"}, {{"Count", each Table.RowCount(_), Int64.Type}}

Will return later with my solution on 2nd part.
Thanks again Hooded 0ne, big help.

A: You guys are making it more complicated than it needs to be. The key here is that you can aggregate text columns when using Group By.
Here's how I'd do the first one:
let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUUouSk3MBdKGBqpKsToQsfzMHCQRIyA7JbUktSg9Na8EyDZCEi9JTCoGKTUFCsUCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Brand = _t, SKU = _t, Discount = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Brand", Int64.Type}, {"SKU", type text}, {"Discount", Percentage.Type}}),
    #"Grouped Rows" = Table.Group(#"Changed Type", {"Brand", "Discount"}, {{"SKU", each Text.Combine([SKU],", "), type nullable text}}),
    #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Result task", each "Check discount " & Number.ToText([Discount], "P0") & " for brand " & Number.ToText([Brand]) & " for SKU: " & [SKU], type text)
in
    #"Added Custom"

Result:

Note that I've grouped on Brand and Discount and aggregated the SKU column but combining each row into a list separated by ", " using Text.Combine([SKU],", ") as the aggregating function instead of any of the default options you can choose. I usually pick Max as the aggregation and then replace that function, i.e. List.Max([SKU]), in the formula for that step.
Once you've done that grouping, you just need to string the pieces together in a custom column.

The second one can be done similarly with the added step of concatenating Brand and SKU into one column before grouping.
let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUUouSk3MBdIGQGyoFKsDEc3PzAHzQeIgMSMgKyW1JLUoPTWvBEU1SKYkMakYoTwWAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Brand = _t, SKU = _t, Monitor = _t, Catalogue = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Brand", Int64.Type}, {"SKU", type text}, {"Monitor", Int64.Type}, {"Catalogue", Int64.Type}}),
    #"Added Custom" = Table.AddColumn(#"Changed Type", "BrandSKU", each Number.ToText([Brand]) & "-" & [SKU], type text),
    #"Grouped Rows" = Table.Group(#"Added Custom", {"Monitor", "Catalogue"}, {{"BrandSKU", each Text.Combine([BrandSKU], ", "), type text}}),
    #"Added Custom1" = Table.AddColumn(#"Grouped Rows", "Result task", each "Check placement of " & [BrandSKU] & " on " & (if  [Catalogue] = 1 then "Catalogue" else "Monitor"), type text)
in
    #"Added Custom1"


text:
Q: Which root paths (e.g., /lib) can never be symlinks? VBox suggests an extremely inadequate default size for its root partition, so I had to create and mount a more realistic /dev/sdb1 to do anything useful.  Despite that, / (/dev/sda1) is 96% full, and /usr appears to be by far the largest consumer, causing me to ^C out of du -s /usr.
My first mistake was to sudo mv /lib /home/jerry/sdb1/root_lib with the intention of following this with ln -s /home/jerry/sdb1/root_lib /lib, only to find that nothing in /bin works without /lib!
I am in the process of repairing this by mounting both virtual disks on a different device and copying the path back to its original location (even if not necessarily to the original clusters, as boot code might require).  Obviously, even if I did create a symlink while it's not bootably mounted, it's unlikely the system could process a symlink without /lib as an absolute path!
Before I waste my time and patience on another misguided experiment, is either /usr itself or any of its more bloated subdirectories, safe to move to another partition and instantiate as a symlink?  :D

A: In archlinux, /bin, /lib, lib64, /sbin are all symlinks and this works fine.
I don't see why it's not working with you. You should have made the symlinks while the system was not running, ie by mounting the filesystem in a live session or similar
Also, if you use partitions and mount them, then I don't see why you need to use symlinks at all? For example, you could copy only the content of /lib/* into your new partition and mount it under /lib with /lib directory still on your root partition. That way, there is no need for symlinks.


text:
Q: Push Windows Updates? Is there a method or software that will allow the ability to push windows updates to clients in an non-active directory environment?
WSUS is not an option for the situation as it doesn't have the ability to push the updates to the clients, only for the clients to pull updates.

A: http://wpkg.org/Category:Silent_installers_for_Windows_Hotfixes
wpkg "pulls" hotfixes as well, but you can let windows run wpkg  whenever you want.

A: Also pull, but this is a script that will search for, download and immediately install updates when run - which I sometimes use for Core servers. Executing this remotely is pretty close to a "push".

A: You could force the scan of new updates using wuauclt /detectnow.
I don't think it is possible to push the updates, since they are retrieved via http protocol by a service running with Administrator privileges; a system to "push" something into that service from an external source would be a good entry point for malware.

A: A logon batch file inside your startup folder pointing to an offline version of wsus setup to run invisible from the current user.
I run a similar setup to some PC's which for security reasons aren't connected directly to the network.
http://download.wsusoffline.net/
I update it every Wednesday and by Thursday the few computers have all the newest patches.


text:
Q: __setitem__() implementation in Python for Point(x,y) class I'm trying to make a Point class in python. I already have some of the functions, like __ str__ , or __ getitem__ implemented, and it works great.
The only problem I'm facing is that my implementation of the __ setitem__ does not work, the others are doing fine.
Here is my Point class, and the last function is my __ setitem__():
class point(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "point(%s,%s)" % (self.x, self.y)

    def __getitem__(self, item):
        return (self.x, self.y)[item]

    def __setitem__(self, x, y):
        [self.x, self.y][x] = y

It should work like this:
p = point(2, 3)
p[0] = 1  # sets the x coordinate to 1
p[1] = 10  # sets the y coordinate to 10

Am I even right, should the `setitem()  work like this?
Thanks!

A: This is pretty old post, but the solution for your problem is very simple:
class point(object):
    def __init__(self,x=0,y=0):
        self.x=x
        self.y=y

    def __str__(self):
        return "point(%s,%s)"%(self.x,self.y)

    def __getitem__(self,item):
        return self.__dict__[item]

    def __setitem__(self,item,value):
        self.__dict__[item] = value

Each class has his own dictionary with all properties and methods created inside the class. So with this you can call:
In [26]: p=point(1,1)
In [27]: print p
point(1,1)
In [28]: p['x']=2
In [29]: print p
point(2,1)
In [30]: p['y']=5
In [31]: print p
point(2,5)

It is more readable then your "index" like reference.

A: Let's strip this down to the bare minimum:
x, y = 2, 3
[x, y][0] = 1
print(x)

This will print out 2.
Why?
Well, [x, y] is a brand-new list containing two elements. When you do reassign its first member to 1, that just changes the brand-new list, so its first element is now 1 instead of 2. It doesn't turn the number 2 into the number 1.
Since your code is essentially identical to this, it has the same problem. As long as your variables have immutable values, you can't mutate the variables.

You could fix it by doing something like this:
x, y = [2], [3]
[x, y][0][0] = 1
print(x[0])

Now you'll get 1.
Why? Well, [x, y] is a new list with two elements, each of which is a list. You're not replacing its first element with something else, you're replacing the first element of its first element with something else. But its first element is the same list as x, so you're also replacing x's first element with something else.

If this is a bit hard to keep straight in your head… well, that's usually a sign that you're doing something you probably shouldn't be. (Also, the fact that you're using x for a parameter that means "select x or y" and y for a parameter that means "new value" makes it a whole lot more confusing…)
There are many simpler ways to do the same thing:

*

*Use an if/else statement instead of trying to get fancy.

*Use a single list instead of two integer values: self.values[x] = y. (That's unutbu's answer.)

*Use a dict instead of two integer values: self.values['xy'[x]] = y.

*Use setattr(self, 'xy'[x], y).

*Use a namedtuple instead of trying to build the same thing yourself.

A: This works in python 2.6 i guess it works for 2.7 as well
The __setitem__ method accept 3 arguments (self, index, value)
in this case we want to use index as int for retrive the name of the coordinate from __slots__ tuple (check the documentation of __slots__ is really usefull for performance)
remember with __slots__ only x and y attributes are allowed! so:
p = Point()
p.x = 2
print(p.x)  # 2.0

p.z = 4  # AttributeError
print(p.z)  # AttributeError

This way is faster respect using @property decorator (when you start to have 10000+ instances)
class Point(object):
    @property
    def x(self):
        return self._data[0]  # where self._data = [x, y]
...

so this is my tip for you :)
class Point(object):

    __slots__ = ('x', 'y')  # Coordinates

    def __init__(self, x=0, y=0):
        '''
        You can use the constructor in many ways:
        Point() - void arguments
        Point(0, 1) - passing two arguments
        Point(x=0, y=1) - passing keywords arguments
        Point(**{'x': 0, 'y': 1}) - unpacking a dictionary
        Point(*[0, 1]) - unpacking a list or a tuple (or a generic iterable)
        Point(*Point(0, 1)) - copy constructor (unpack the point itself)
        '''
        self.x = x
        self.y = y

    def __setattr__(self, attr, value):
        object.__setattr__(self, attr, float(value))

    def __getitem__(self, index):
            '''
            p = Point()
            p[0]  # is the same as self.x
            p[1]  # is the same as self.y
            '''
        return self.__getattribute__(self.__slots__[index])

    def __setitem__(self, index, value):
            '''
            p = Point()
            p[0] = 1
            p[1] = -1
            print(repr(p))  # <Point (1.000000, -1.000000)>
            '''
        self.__setattr__(self.__slots__[index], value)  # converted to float automatically by __setattr__

    def __len__(self):
        '''
        p = Point()
        print(len(p))  # 2
        '''
        return 2

    def __iter__(self):
        '''
        allow you to iterate
        p = Point()
        for coord in p:
            print(coord)

        for i in range(len(p)):
            print(p[i])
        '''
        return iter([self.x, self.y])

    def __str__(self):
        return "(%f, %f)" % (self.x, self.y)

    def __repr__(self):
        return "<Point %s>" % self

A: Let self.data and only self.data hold the coordinate values.
If self.x and self.y were to also store these values there is a chance self.data and self.x or self.y will not get updated consistently.
Instead, make x and y properties that look up their values from self.data.
class Point(object):
    def __init__(self,x=0,y=0):
        self.data=[x, y]

    def __str__(self):
        return "point(%s,%s)"%(self.x,self.y)

    def __getitem__(self,item):
        return self.data[item]

    def __setitem__(self, idx, value):
        self.data[idx] = value

    @property
    def x(self):
        return self.data[0]

    @property
    def y(self):
        return self.data[1]

The statement
[self.x, self.y][x]=y

is interesting but problematic. Let pick it apart:
[self.x, self.y] causes Python to build a new list, with values self.x and self.y.
somelist[x]=y causes Python to assign value y to the xth index of somelist. So this new list somelist gets updated. But this has no effect on self.data, self.x or self.y. That is why your original code was not working.

A: Your may find it a lot easier to use namedtuple for this:
 from collections import namedtuple
 Point= namedtuple('Point', ['x','y'])

 fred = Point (1.0, -1.0)
 #Result: Point(x=1.0, y=-1.0)

The main drawback is that you can't poke values into a namedtuple - it's immutable. In most applications that's a feature, not a bug

A: What's happening in setitem is it builds a temporary list, sets the value, then throws away this list without changing self.x or self.y. Try this for __setitem__:
def __setitem__(self,coord,val):
    if coord == 0:
        self.x = val
    else:
        self.y = val

This is quite an abuse of __setitem__, however... I'd advise figuring out a different way of setting the x/y coordinates if possible. Using p.x and p.y is going to be much faster than p[0] and p[1] pretty much no matter how you implement it.

A: Here's an example:
from collections import namedtuple

Deck = namedtuple('cards',['suits','values'])

class FrenchDeck(object):

    deck = [str(i) for i in range(2,11)]+list('JQKA')
    suits = "heart clubs spades diamond".split()

    def __init__(self):
        self.totaldecks = [Deck(each,every) for each in self.suits for every in self.deck]
    def __len__(self):
        return len(self.totaldecks)
    def __getitem__(self,index):
        return self.totaldecks[index]
    def __setitem__(self,key,value):
        self.totaldecks[key] = value

CardDeck = FrenchDeck()
CardDeck[0] = "asdd"       # needs`__setitem__()`
print CardDeck[0]

If you don't use the __setitem__(),  you will get an error
TypeError: 'FrenchDeck' object does not support item assignment


text:
Q: Point in Polygon Algorithm in Programming Contests What is the best algorithm to solve point in polygon in programming contests?

A: Shoot a ray(in arbitrary direction) from the point and check the number of times it has crossed the edges of polygon if it is even then the point is outside the polygon otherwise the point is inside the polygon.
If you need to do it for lots of query points, you can triangulate the polygon (actually triangulate both inside and the region between the polygon the convex containing it) so that you could do ray shooting in O(log n)

A: if you have a convex polygon you can use this :
http://e-maxx.ru/algo/pt_in_polygon


text:
Q: Android: Text in TextView not aligned well I have a TextView in RelativeLayout in which I am setting the text from a string and that string contains the text more than 2 lines. But I want to set the Text into two lines. All is working but the problem is the Text in two lines is not aligned well.
Here is how it looks:
This is the text of first line
which contains a dummy text
As you can see I have set left margin of 5 then it only applied on first line but not on the second one. So what is the problem and how can I solve it?
<TextView
    android:id="@+id/message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/image"
    android:maxLines="2"
    android:layout_marginLeft="10dp"
    android:textSize="20sp"
    android:textColor="#000000"
    android:textAppearance="?android:attr/textAppearanceMedium">
</TextView>


text:
Q: MemoryError Precedes BrokenPipeError While Training CNN Generally for running pip with no cache we use --no-cache-dir, like
pip install pytorch --no-cache-dir.
I downloaded a CNN model I want to use from github.
The first two lines of execution
 python generate_dataset.py --is_train=True --use_phase=True --chip_size=100 --patch_size=94 --use_phase=True --dataset=soc
 python generate_dataset.py --is_train=False --use_phase=True --chip_size=128 --patch_size=128  --use_phase=True --dataset=soc

executed succesfully. But while running
python train.py --config_name=config/AConvNet-SOC.json

It is giving MemoryError.
The publisher of above repository is using 32GB RAM and 11 GB GPU. But I have 8 GB RAM and 8GB GPU.
Here is what I have done:
I thought of running it without cache. like,
python train.py --config_name=config/AConvNet-SOC.json --no-cache-dir

But it is throwing below error
FATAL Flags parsing error: Unknown command line flag 'no-cache-dir' Pass --helpshort or --helpfull to see help on flags.
I think it is because no-cache-dir argument is not defined in it by using absl.flags. Does python supports using no chache directory implementation
I am able to solve it by decreasing the number of epochs and batch_size. But I want to run it for full epochs.
Using zeo_grad() of Pytorch makes the gradients zero for every minibatch, so that GPU won't run out of memory. But it is already used in the code I am running in _base.py. Is there anyway I can leverage more of this.
How to resolve this.


text:
Q: Cursor Pointer doesn't work in Web-Kit Browsers I have file-uploader control.
When i hover on button in Web-Kit browsers, cursor is default, while must be pointer.
I red this post The cursor:pointer property doesn't apply to file upload buttons in Webkit browsers but in my case i don't use property height. Also try solution that @Mohammed Ibrahim suggest, but it also doesn't work for me.
Here is my example : http://jsfiddle.net/q686cc7s/4/ I try to add cursor:pointer for every possible selector, but no success.
Any suggestions? Thanks.

If set display:none for input then cursor works correctly but uploader - not :)

A: Adding this always did it for me
input[type="file"]::-webkit-file-upload-button {
    cursor: pointer;
}


text:
Q: Does it ever make sense to have two concurrent sessions in the same browser? I was wondering if it ever would make sense to have two concurrent sessions in the same browser? There could be two types of cases with this:
1) A user opens a browser window and logs in as user A, starting session 1. Then he opens another browser window (in the same browser) where he logs in as user A, but starts a different session, session 2.
I know that this is often not possible in many browsers, as one session cookie is set for the entire browser. However, in some browsers, it is possible to have multiple sessions in that manner.
2) This is similar to 1, except that the second time the user logs in, he logs in as user B, starting session 2. So now you have a person logged in as two users in the same browser.
Finally, allowing these things doesn't seem like the best security practice and neither does it seem to be practical. What do others think?

A: First thing First as the your Assumption is wrong. First of all you have to understand that when Single website is accessed from browser have single session and its not possible to simultaneously run different session of same web Browser.
It seems you have wrongly understand the working of Private Browser. Private Session are not made not to share information cookies and data with other public session and vise versa also. As soon as you close the Private Session all the Cache, Cookie and other things are deleted for forever.
I have not seen any web browser supporting the Multiple session of browser.
But an alternative approach is available i.e you have to create different Web Browser Profiles which can help you as each Profile data is maintained separately and have no conflict with other sessions.

A: One possible scenario currently I am facing requires allowing multiple user sessions from the same browser and I have not been able to find a proper solution for it yet.
We are using Yii framework. Currently we have two kinds of users i.e customers and admins. Both login from the same login form and use same session name and variables to store session information. Only based on type column in user table(customer or admin), the user is taken to appropriate views. In one of admin views(pages), there is an option for admin to log in as any of the users and propagate through the user's view in an iframe. The problem is that when the admin open two tabs and logs in as two different users, the session information of one overwrites the other and we start getting session related issues.
Can anyone suggest me a proper way to handle these kind of issues. I have searched a lot on trying to handle this with multiple sessions, but have not been able to find a proper solution yet.

A: There's nothing to "provide support for" here. One browser cannot hold more than one session, since it only holds one unique cookie per site, regardless of window. If a browser actually has a mode in which it supports holding two separate identical cookies per site, then it's the same as if the user logged on from another browser or another machine. That certainly should work; i.e. you should not try to subvert that behavior. A double session inside the same browser is then just a specific instance of this multi-session behavior, nothing special.


text:
Q: Posting Custom Fields to HTML from Wordpress I'm using a free shopping cart template called Roman Cart (https://romancart.com).
Per their documentation, they have the ability to post customer details to the cart (https://www.romancart.com/shopping-cart/how-it-works-examples/#aa).
But unfortunately, me being a newbie, am trying to figure out how and where I should use this? Should I be sending the customer details along with the  tag I use to add items to the shopping cart?
    <form action="https://www.romancart.com/cart.asp" method="post"><input type="submit" value="Add to Order">

<input type="hidden" name="price" value="670.8">
<input type="hidden" name="storeid" value="10000">
<input type="hidden" name="quantity" value="1">
<input type="hidden" name="itemname" value="Pirinho">
Include Sample
<select name="itemname2"required oninvalid="this.setCustomValidity('Select Sample Preference')" oninput="this.setCustomValidity('')" >
Include sample
<option value="">-Select-</option>
<option value="Sample Preference: Green {15.00}">Green (+$)</option>
<option value="Sample Preference: Roasted {15.00}">Roasted (+$)</option>
</select>
</form>

So to send customer details, should I start using it like this?
<input type="hidden" name="CompanyName" value="ACME">

Also, I use Wordpress for people to register. How can I get the current_user information and send it alon with the  tag?
<input type="hidden" name="CompanyName" value="wp_get_current_user();echo 'Company Name'">

I'm pretty sure the above is incorrect and there is a better way to execute this. Can somebody please help me? I will be forever so grateful
Thanks a million!


text:
Q: MailServer forwarding policy issue Description:
We have a mailbox to which emails are forwarded from external system. Based on the mails events are generated.
Whenever a email is sent it is getting forwarded to another mail id.
But we are unable to understand what script is behind. The script reads the emails and forwards to one of the mails from the list. In /etc/aliases I see the below. But I want to know is how mails are first coming to either of the policies mentioned below.

port-policy: "| /etc/smrsh/script.pl -u uei.opennms.org/xxx/OCI/SMTP/portViolationAlert"
  storage-policy: "| /etc/smrsh/script.pl -u uei.opennms.org/xxx/OCI/SMTP/storageViolationAlert"
  volume-policy: "| /etc/smrsh/script.pl -u uei.opennms.org/xxx/OCI/SMTP/volumeViolationAlert"


text:
Q: If $\varphi$ is a positive linear functional then the following are equivalent. $\begin{align} &\text{(1) } \varphi(x^*x)=\varphi(xx^*)\text{ for all }x\in A.\\&\text{(2) } \varphi(u^*au)=\varphi(a)\text{ for all }a\in A \text{ and unitary } u\in \tilde A.\end{align}$
$\tilde A$ is the unitalization of $A$ by adding a $1$ ($A$ may have its own $1_A$).
my trying:
Extend $\varphi$ by defining $\varphi(a+k)=\varphi(a)+k\|\varphi\|$. Then $(1)\Leftrightarrow\varphi((a+k)^*(a+k))=\varphi((a+k)(a+k)^*)$ and $(2)\Leftrightarrow\varphi(u^*(a+k)u)=\varphi(a+k)$ .
Thus we may assume that $A$ is unital and prove that
$\begin{align} &\text{(1) } \varphi(x^*x)=\varphi(xx^*)\text{ for all }x\in A.\\&\text{(2) } \varphi(u^*au)=\varphi(a)\text{ for all }a\in A \text{ and unitary } u\in A.\end{align}$
are equivalent.
Since every $a$ can be decomposed in to $a=\text{Re}(a)^+-\text{Re}(a)^-+i\text{ Im}(a)^+-i\text{ Im}(a)^-$, and $\varphi(u^*xu)=\varphi(\sqrt x u^*u\sqrt x)=\varphi(x)$ for positive $x$, that (1) implies (2) is trivial.
However, I have no idea on how to show (2) implies (1). If $|x|$ is invertible, that there is a unitary $u$ such that $x=u|x|$ follows from polar decomposition.  Then $ux^*xu^*=xx^*$ follows. Similarly, if $x$ can be approximated by invertible elements, $\varphi(x^*x)=\varphi(xx^*)$ still holds. But this is true only for certain kinds of C*-algebras. Do I need to use Gelfand-Naimark representation on this?

A: Use the following statement:

If $A$ is a unital $C^*$-algebra and $x\in A$ there are unitaries $u_1,...,u_4$ and complex numbers $a_1,...,a_4$ with $x=\sum_i a_i u_i$.

So:
$$\varphi(x^*x)=\varphi\left(\sum_i(a_iu_i)^*\sum_j(a_ju_j)\right)= \sum_{ij} \overline{a_i}a_j\varphi(u_i^*u_j)$$
now note that $\varphi(u_i^*u_j)= \varphi\left(u_i(u_i^*u_j)u_i^*\right) = \varphi(u_ju_i^*)$ by (2). Hence:
$$\varphi(x^*x)=\sum_{ij}\overline{a_i}a_j\varphi(u_ju_i^*) =\varphi\left(\sum_j(a_ju_j)\sum_i(a_iu_i)^*\right)=\varphi(xx^*)$$


text:
Q: Core Java Threading and Volatile keyword Usage I have recently started studying multithreading in core Java. I am studying a Volatile keyword. As per my understanding threads are allowed to keep the values of the variables locally. If the variables are driving any logic (e.g. loop) then the changes to the variables will not be visible to the threads and they will keep using the outdated cached values unless the variable declared as 'volatile'.
I created a small code to demonstrate this, however, my observation is different. The changes made by one thread (main thread) are very well visible to the other thread even if the shared variable 'done' is not volatile. Could anyone please help me understand this behavior
package com.test;

public class App implements Runnable {
    private boolean done= true;
    private static App a = new App();

    public static void main( String[] args ) throws InterruptedException {
        Thread t = new Thread(a);
        t.start();
        System.out.println("Main Thread:"+ Thread.currentThread().getName());
        Thread.sleep(1);
        a.done=false;
        System.out.println("Value of done in main method is:"+ a.done);
    }

    public void run() {
        while(done) {
             System.out.println("Second Thread:"+ Thread.currentThread().getName());
            System.out.println("Still running");
        }
    }
}

Output of the above code is as follows
Main Thread:main
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Second Thread:Thread-0
Still running
Value of done in main method is:false

A: The keyword volatile guarantees the behavior you described. The value of a volatile field is visible to all readers after a write operation. This means that no cached values are used.
If you are not using the volatile keyword this does not automatically mean though that you are always using old, cached variables. It's just the possibility that this could happen.

Takeaway:
You use the volatile keyword to guarantee memory visibility. It does not mean that not using it will break your code as soon as you use multithreading.

Also note that volatile does not guarantee atomic interaction with your variable. This means that a volatile field is not automatically thread safe regarding race conditions and other potential trouble.


text:
Q: Using Netty as a HTML server like Play Want to wrap my Spring services with RestEasy and hook the RestEasy dispatcher into Netty (there is a nice helper class called NettyJaxrsServer, just adds the RestEasy encodes/decoders into the pipeline).  That gets me going for client Ajax calls.  But what about serving up HTML content like is normally done through Apache or Tomcat.  Seen that people front Netty with Apache/Tomcat to get all the goodies of cookie management and so forth.  Took a brief look at the Play module for Netty which looks like it does so cookie management, caching, file chunking etc.  How comprehensive is Play's module?
Just browsing around for what others are doing.  In the end I want to push out a set of static HTML, JS, CSS content part of the Extjs or Foundation frameworks while Netty handling the "service" calls.


text:
Q: Problem with path when trying to write a file with a defined name given before by the code in Python I'm having issues when I try to write a file in Python giving it a certain name and not only pathing it. Here is what I'm trying to do:
page_title=page.find('title')

raw_data_path ='output/'+page_title+'_raw.txt'
print (page_title)

with open(raw_data_path, 'w') as file:
   file.write ()

When running this code, I receive the error [Errno 22] Invalid argument: 'output/myfile_raw.txt'
If instead of raw_data_path ='output/'+page_title+'_raw.txt' I put, for example, raw_data_path ='output/'+'_raw.txt' the code works well, so for some reason I can't combine the path with the name I'm trying to give the file.
I've searched that error and I see that it is a routing error, so it might be happening because when I want to add the page_title something happens with the path, but I can't see which is the mistake because it should be working.
Can someone give me some help with this issue?


text:
Q: Deploying AppFuse app on cloudbees I have searched a lot for this but have not found any documentation or blog post on how to deploy Appfuse app on cloudbees. I am kind of new to all this. Does anyone have any documentation or blog describing step by step about how to deploy Appfuse app on cloudbees?
Please help.
Thanks in advance.

A: If you can find a tutorial on deploying a WAR that was developed with Maven, that should work for AppFuse.


text:
Q: How to render form field inside list item in sencha touch 2 I have a List with elements. How can I render formfield inside list item, so that when user clicks on list item, this field gets focus, and user can enter a value.

A: I suppose in the itemTpl config on your list you can add html input / text fields
        xtype:'list',
        disableSelection:true,
        store: 'Store',
        itemTpl:'
INFO	<INPUT TYPE="TEXT" NAME="name" SIZE="20">
' ,


text:
Q: Handle destination per route in nodejs with multer package I use multer package and make it dynamic and its work. Now it try to make it dynamic per route and stuck with this.
This is my fileupload service:
const path = require("path");
const multer = require("multer");
const crypto = require("crypto");
const fs = require("fs-extra");

const today = new Date();
const date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();

const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    const { companyID, flowID } = req.body;
    let path = `./uploads/${companyID}/${flowID}`;
    fs.mkdirsSync(path);
    callback(null, path);
  },
  filename: (req, file, cb) => {
    crypto.pseudoRandomBytes(8, (err, raw) => {
      if (err) return cb(err);
      cb(
        null,
        date + "_" + raw.toString("hex") + "_" + path.extname(file.originalname)
      );
    });
  }
});

//Must be under storage
const upload = multer({ storage: storage }).single("upload");

const deleteFileFromServer = (companyID, flowID, filePath) => {
  return new Promise((resolve,reject)=>{
    fs.unlink(`./uploads/${companyID}/${flowID}/${filePath}`).then(()=>{
      resolve("File Deleted");
    }).catch((err)=> {
      reject(err);
    })
  })
};

module.exports = {
  upload: upload,
  deleteFileFromServer: deleteFileFromServer
};

my route: Here i want handle destination in every route set diffrent destination
router.post("/uploadfile", upload, (req, res, next) => {
  const file = req.file;
  const flowID = req.body.flowID;
  if (!file) {
    const error = new Error("Please upload a file");
    error.httpStatusCode = 400;
    return next(error);
  } else {
    createFileInDB(file.originalname, flowID, file.filename)
      .then(() => {
        console.log("File Created");
        res.json(file);
      })
      .catch(err => {
        res.status(500).send(err);
      });
  }
});

What i want it to be? i want that every route i can choose different destination.
router.post("/uploadfile", upload, (req, res, next) => {
  upload.destination = "my path/"
});

Thanks!!