text:
Q: Using typedef in a program Yesterday I had my exam's and there was a question like this:
Write a program using typedef to find out the larger of two numbers.
So the solution to this problem is obvious right? But we have to use typedef thats the condition, So this is what i did.
#include <stdio.h>

typedef struct {
    int a;
}LARGE;

void main()
{
    LARGE a,b;
    int c;
    scanf("%d%d", &a.a,&b.a);
    c = large(a.a,b.a);
    printf("%d", c);
}

This is the main program and I have written a function named large() that returns largest of two numbers.
This is how I added the keyword typedef in my program, but the department teachers says we should use typedef to create new names and not use it in structures i,e:
typedef int large a,b;

now large is a new name for int.
But the question does not explicitly specify to use typedef to create new name for the data types being used, so i wrote the program using structures using typedef, so please let me know what is the right way.
Thanks in advance.

A: But the right use of typedef is to create aliases for existing data types. If you use it to name an anonymous struct (it is a perfectly valid use) then it seems to miss the point of the lesson.
Your answer is valid indeed, the problem is that your teacher probably wanted to give another name to int.


text:
Q: How to restore USB drive after using Startup Disk Creator on Ubuntu 17.04? I recently used Startup Disk Creator on Ubuntu 17.04 to create a bootable Ubuntu 17.10 on a 16 GB USB drive. The USB does boot and live disk works.
But when I plug in the USB to use it on Windows 10 or my installed Ubuntu 17.04, it shows the size of USB to be only 2.22 MB out of which 18 KB is free.
How to restore the USB drive to the previous state of 16 GB storage?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop in two lists I have these lists:
list1 = [3, 5, 2, 1, 9]
list2 = [6, 9, 1, 2, 4]
list3 = []
list4 = []

and I want to pass these formula:
x = a/b
y = 1/b

in which a is every value in list1 and b is every value in list2 and append the result of calculations into two empty lists - list3 and list4.
This is what I have but it's a disaster haha :(
u = 0
while u<len(list1):
    for a in list1:
        for b in list2:
            x = a/b
            y = 1/b
            u+=1
            list3.append(x,)
            list4.append(y,)

Anyone can help me with this?

A: Here is a oneliner:
>>> list3,list4 = zip(*[(a/b,1/b) for a,b in zip(list1,list2)])
>>> list3
(0, 0, 2, 0, 2)
>>> list4
(0, 0, 1, 0, 0)

The output are tuples. But they can be easily converted to list.
Oh. It may be made even more memory efficient by using generator expression instead of list comprehension:
>>> zip(*((a/b,1/b) for a,b in zip(list1,list2)))

A: for a, b in zip(list1, list2):
    x = a/b
    y = 1/b
    list3.append(x)
    list4.append(y)

This is assuming you meant you wanted to use the lists pair-wise.  If instead you meant you wanted every possible pairing of the lists, then:
for a in list1:
    for b in list2:
        x = a/b
        y = 1/b
        list3.append(x)
        list4.append(y)

A: for a,b in zip(list1,list2):
  x = a/b
  y = 1/b

?? something like this

A: Just use the zip function in Python:
for a, b in zip(list1, list2):
    list3.append(a/b)
    list4.append(1/b)

A: list3 = map((lambda x, y: x/y), list1, list2)
list4 = map(lambda x: 1/x), list2)

OR:
list3, list4 = zip(*map((lambda x, y: (x/y, 1/y)), list1, list2)


text:
Q: How to tokenize text by sentences with XSLT I've reached the limit of my knowledge of XSLT with the following problem.
I have an XML file that looks like this, simplified:
<?xml version="1.0" encoding="UTF-8"?>
<root>

    <w>This</w>
    <w>is</w>
    <w>a</w>
    <w>sentence</w>
    <w>with</w>
    <w>a</w>
    <entity type="name">Name</entity>
    <w>and</w>
    <w>a</w>
    <entity type="place">Place</entity>
    <w>etc</w>. <w>This</w>
    <w>is</w>
    <w>another</w>
    <w>sentence</w>
    <w>with</w>
    <w>an</w>
    <w>abbrev</w>. <w>before</w>
    <w>its</w>
    <w>end</w>. <w>Is</w>
    <w>this</w>
    <w>a</w>
    <w>question</w>? <w>Sure</w>
    <w>it</w>
    <w>is</w>!

</root>

The text is already tokenized by word. I need to automatically mark up sentences. To do that, I have a variable that contains possible characters which end a sentence:
<xsl:variable name="SEnd">.!?</xsl:variable>

So, I need an XSLT 2.0 stylesheet which will:

*

*loop over each paragraph

*group words (<w>) together starting with the first <w> in a paragraph and ending with a <w> element whose immediate sibling text() node starts with one of the members of the variable set "SEnd", but if and only if the following-sibling::w starts with a capital letter (this has to be a REGEX \p{Lu} and not just [A-Z] because I have multiple scripts;

*wrap each of the above-mentioned groups in <s></s>.

This way <w>abbrev</w>. will not be recognized as the last word of a sentence, because it's followed by a lower-case word.
The result should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<root>

    <s><w>This</w>
        <w>is</w>
        <w>a</w>
        <w>sentence</w>
        <w>with</w>
        <w>a</w>
        <entity type="name">Name</entity>
        <w>and</w>
        <w>a</w>
        <entity type="place">Place</entity>
        <w>etc</w>.</s>
    <s><w>This</w>
        <w>is</w>
        <w>another</w>
        <w>sentence</w>
        <w>with</w>
        <w>an</w>
        <w>abbrev</w>. <w>before</w>
        <w>its</w>
        <w>end</w>.</s>
    <s><w>Is</w>
        <w>this</w>
        <w>a</w>
        <w>question</w>?</s>
    <s><w>Sure</w>,
        <w>it</w>
        <w>is</w>!</s>

</root>

I know that this is not bullet-proof, and that there will be exceptions, but that is not important for this particular task. I understand the problem conceptually, and I think one should use <xsl:for-each-group> but I am at a loss how to actually put it all together.
I would very much appreciate your help.
All best,
Tench

A: How about:
<xsl:template match="p">
    <xsl:copy>
        <xsl:for-each-group select="node()" group-ending-with="text()[matches(., $SEnd)][matches(following-sibling::w[1], '^\p{Lu}')]">
            <s>
                <xsl:apply-templates select="current-group()" />
            </s>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>


text:
Q: Why is this true? $\sum_{k=1}^\infty \frac{s^{k-1}}{k!} = \sum_{k=0}^\infty \frac{s^k}{(k+1)k!} $ In my notes I have:
$$\sum_{k=1}^\infty \cfrac{s^{k-1}}{k!} = \sum_{k=0}^\infty \cfrac{s^k}{(k+1)k!} $$
And maybe I am brain-dead, but I can't see how this was done?

A: By $m=k-1$ we have
$$\sum_{k=1}^\infty \cfrac{s^{k-1}}{k!}=\sum_{m=0}^\infty \cfrac{s^{m}}{(m+1)!}=\sum_{m=0}^\infty \cfrac{s^{m}}{(m+1)m!}$$

A: $$\sum_{k=0}^\infty \cfrac{s^k}{(k+1)k!}=\sum_{k=0}^\infty \cfrac{s^k}{(k+1)!}=\sum_{k=1}^\infty \cfrac{s^{k-1}}{k!}$$


text:
Q: Using JAXB to pass subclass instances as superclass What I have is a set of Java classes (close to 25) representing message types.  They all inherit from a Message class which I'd like to be abstract.  Each message type adds a few additional fields to the set provided by the Message superclass.
I'm implementing some RESTful web services using RESTeasy and would like to have methods like this:
public Response persist(Message msg) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        em.persist(msg);
    } catch (Exception e) {
        e.printStackTrace();
    }
    tx.commit();
    em.close();
    return Response.created(URI.create("/message/" + msg.getId())).build();
}

instead of having 25 separate persist methods, each tailored to a particular message type.
Currently, I've annotated my Message class like this:
@MappedSuperclass
@XmlRootElement(name = "message")
public abstract class Message implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Integer id;
    @Embedded
    Header header;
    @Embedded
    SubHeader subHeader;

My subclass then looks like this:
@Entity
@XmlRootElement(name="regmessage")
@XmlAccessorType(XmlAccessType.FIELD)
public class REGMessage extends Message {

    @XmlElement(required = true)
    int statusUpdateRate;
    @XmlElement(required = true)
    int networkRegistrationFlag;

This creates a schema which looks like it should work, but all that's seen on the server side during a persist operation is a Message object (the subtype is completely lost, or at least it isn't marshalled back into its proper subtype).  On the client side, to invoke the method I do this:
REGMessage msg = new REGMessage();
// populate its fields
Response r = client.createMessage(msg);

Is what I'm attempting possible?  What JAXB magic do I need to use to make the translations happen the way they should -- ie, to treat everything in Java as if it's a Message to keep the number of methods down yet still preserve all the subtype-specific information?

Thanks to Blaise's blog pointers, this now looks like it's on the road to working fully.  Here's what I've got, and it does work:
//JAXB annotations
@XmlRootElement(name="message")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso(REGMessage.class)
//JPA annotations
@MappedSuperclass
public class Message {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @XmlAttribute
    private Integer id;

    private JICDHeader header;
    private int subheader;

    @XmlAnyElement
    @Transient
    private Object body;

One of the problems I encountered this morning was a cryptic error from Hibernate about the number of columns being mismatched.  Once I realized that "body" was being mapped into the table, I marked it transient and voila!
@XmlRootElement(name="regmessage")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
public class REGMessage extends Message {

    private int field1;
    private int field2;

The only table generated from this code now is the regmessage table.  On the RESTeasy side:
@Path("/messages")
public class MessageResource implements IMessageResource {

    private EntityManagerFactory emf;
    private EntityManager em;

    Logger logger = LoggerFactory.getLogger(MessageResource.class);

    public MessageResource() {
        try {
            emf = Persistence.createEntityManagerFactory("shepherd");
            em = emf.createEntityManager();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @POST
    @Consumes("application/xml")
    public Response saveMessage(Message msg) {

        System.out.println(msg.toString());

        logger.info("starting saveMessage");
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        try {
            em.persist(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        tx.commit();
        em.close();
        logger.info("ending saveMessage");

        return Response.created(URI.create("/message/" + msg.getId())).build();
    }
}

This implements an interface:
@Path("/messages")
public interface IMessageResource {

    @GET
    @Produces("application/xml")
    @Path("{id}")
    public Message getMessage(@PathParam("id") int id);

    @POST
    @Consumes("application/xml")
    public Response saveMessage(Message msg) throws URISyntaxException;

}

Marshalling & unmarshalling work as expected, and persistence is to the subclass's table (and there is no superclass table at all).
I did see Blaise's note about JTA, which I may attempt to bring into this mix after I finish fleshing the Message & REGMessage classes back out fully.

A: Have you tried adding the following to your message class?  The @XmlSeeAlso annotation will let the JAXBContext know about the subclasses.
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

@XmlRootElement
@XmlSeeAlso(RegMessage.class)
public abstract class Message {

    Integer id;

}

Alternate Strategy:
Here is a link to a strategy I have helped people use:

*

*http://bdoughan.blogspot.com/2010/08/using-xmlanyelement-to-build-generic.html
Essentially you have one message object, and multiple individual message payloads.  The relationship between the message and payload is handled through a @XmlAnyElement annotation.
Note on Transaction Handling
I noticed that you are handling your own transactions.  Have you considered implementing your JAX-RS service as a session bean and leverage JTA for your transaction handling?  For an example see:

*

*http://bdoughan.blogspot.com/2010/08/creating-restful-web-service-part-45.html


text:
Q: Remove duplicated products from catalog I mass import products into my site on a nightly basis (affiliate products). Occasionally the products are duplicated so I want to write a quick SQL Statement to remove the duplicated products.
What I will then do is put the SQL into a PHP script and call it each night after the import so it will remove the duplicated products before I reindex.
I've done some research and found come up with the following script to get all of the product names from the database:
SELECT `value` AS product_nameFROM catalog_product_entity_varchar WHERE entity_type_id = (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_product') AND attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_product'))

I have also found this example script to identify duplicates in SQL:
`SELECT name, email, COUNT(*) FROM users GROUP BY name, email HAVING COUNT(*) >` 1

I wondered if someone could help me put this together?
Thanks in advance!
Chris

A: I have tested this and it works but since it involves the deletion of products, I strongly recommend that you backup your database first.

include 'app/Mage.php';
Mage::app();

Mage::register('isSecureArea', 1);

$limit    = 100;
$model    = Mage::getModel('catalog/product');
$resource = $model->getResource();
$adapter  = $resource->getReadConnection();
$name     = $resource->getAttribute('name');

// retrieve a list of all products that have more than 1 occurrence of the same name
$select = $adapter->select()->from($name->getBackendTable(),array($resource->getIdFieldName(),'value','count' => 'COUNT(*)','entity_ids' => new Zend_Db_Expr("GROUP_CONCAT({$resource->getIdFieldName()})")));
$select->where('attribute_id = ?',$name->getAttributeId());
$select->where('entity_type_id = ?',$name->getEntityTypeId());
$select->group('value');
$select->having('count > 1');
$select->limit($limit);
$result = $adapter->fetchAll($select);

// here, we remove the lowest product id from each set of duplicate-named products.
// the theory is that the product which was created first, hence the lowest
// product id, is the one you want to keep
$result = array_map(function($row){
    $entityIds = explode(',',$row['entity_ids']);
    $min = min($entityIds);
    $key = array_search($min, $entityIds);
    unset($entityIds[$key]);
    $row['entity_ids'] = $entityIds;
    return $row;
},$result);

// now that we have narrowed down to the ids of the products we want to delete,
// lets get all product ids to delete into a single array
$entityIds = array();
foreach($result as $row){
    $entityIds = array_merge($entityIds,$row['entity_ids']);
}

// lets delete each one individually
$collection = $model->getCollection();
$collection->addFieldToFilter($resource->getIdFieldName(),array('in' => $entityIds));
foreach($collection as $product){
    $product->delete();
}


text:
Q: MySQL: SELECT row which meets criteria I have a Table myTable with the Columns

id, foreignID, isDefault, textValue

Values could be something like

1, 1, 1, NULL
2, 1, 0, NULL
3, 1, 0, 'ABC'
4, 2, 1, 'DE'
5, 2, 0, 'AB'
6, 3, 1, NULL
6, 3, 0, 'DE'

I want to get ONE textValue for every foreignID where the textValue is not NULL.
If there are more then one textValues which are not NULL for the foreignID and one of those has "isDefault = 1) I want to select this one.
Any ideas? :)
(So I would like to get the rows number 3, 4 and 6)

A: You can use row_number() to get the entire row:
select t.*
from (select t.*, row_number() over (partition by foreignId) as seqnum
      from myTable t
      where textValue is not null
     ) t
where seqnum = 1;

Or if you just want textValue, use aggregation:
select foreignId, max(textValue)
from mytable
where textValue is not null
group by foreignId;

A: You can try below way - by adding an order by clause in row_number()
select *
from (select *, row_number() over (partition by foreignId order by  isDefault desc) as rn
      from tablename
      where textValue is not null
     ) A
where rn= 1


text:
Q: Change . to , decimal number userform entry on vba I have a create a Userform VBA EXCEL asking an Exchange Rare value, the entry comes (for example) 1.25, but Excel don't recognized as number. So as soon as I tried a calculation on new cell, the error comes as #VALUE!"
How can I change this "Text" into Value. My code below.
Private Sub Exchange_Rate_Exit(ByVal KeyAscii As MSForms.ReturnBoolean)

    If Not IsNumeric(Exchange_Rate.Value) Then
        MsgBox "Only DECIMAL NUMBER VALUES allowed"
        Cancel = True
    End If

    Sheets("Menu").Range("EXC_RAT") = Exchange_Rate

End Sub


text:
Q: Shell script to delete files smaller than x kb I'm trying to find out how to write a little script to delete text files that are smaller than 50 Kilobytes but I have had no success.
My attempt looks like this:
#!/bin/bash
for i in *.txt
do
   if [ stat -c %s < 5 ]
   then
     rm $i
   fi
done

I would appriciate some guidance, thank you!

A: You should use fedorqui's version, but for reference:
#!/bin/bash
for i in ./*.txt   # ./ avoids some edge cases when files start with dashes
do
  # $(..) can be used to get the output of a command
  # use -le, not <, for comparing numbers
  # 5 != 50k
  if [ "$(stat -c %s "$i")" -le 50000 ]
  then
    rm "$i"  # specify the file to delete
  fi # end the if statement
done

It's usually easier to write a program piece by piece and verifying that each part works, rather than writing the entire program and then trying to debug it.

A: You can directly use find with the size option for this:
find /your/path -name "*.txt" -size -50k -delete
                              ^^^^^^^^^^
                              if you wanted bigger than 50k, you'd say +50

You may want to stick to the files in the current directory, without going down in the directory structure. If so, you can say:
find /your/path -maxdepth 1 -name "*.txt" -size -50k -delete

From man find:

-size n[cwbkMG]
File uses n units of space. The following suffixes can be used:
'b' for 512-byte blocks (this is the default if no suffix is used)
'c' for bytes
'w' for two-byte words
'k' for Kilobytes (units of 1024 bytes)
'M' for Megabytes (units of 1048576 bytes)
'G' for Gigabytes (units of 1073741824 bytes)


text:
Q: css animation how to use "reverse" for a hover and out event? Given this code (http://jsfiddle.net/bzf1mkx5/)

.intern {
    -webkit-animation: in 1s 1 reverse forwards;
}

.intern:hover {
    -webkit-animation: in 1s 1 normal forwards;
}

@-webkit-keyframes in {
    from   { -webkit-transform: scale(1); }
    to { -webkit-transform: scale(1.2);}
}

Why are animations absent? Where is the mistake?
EDIT:
By using two separated animations it does work, but then what's the point of having a reverse property?

.intern {
    -webkit-animation: in2 1s 1 reverse forwards;
}

.intern:hover {
    -webkit-animation: in 1s 1 normal forwards;
}

@-webkit-keyframes in {
    from   { -webkit-transform: scale(1); }
    to { -webkit-transform: scale(1.2);}
}
@-webkit-keyframes in2 {
    from   { -webkit-transform: scale(1); }
    to { -webkit-transform: scale(1.2);}
}

EDIT2:
If I use higher times, I should see the animations even though I will see the unwanted effect of jumping from one state to the another

.intern {
    -webkit-animation: in 20s 1 reverse forwards;
}

.intern:hover {
    -webkit-animation: in 20s 1 normal forwards;
}

@-webkit-keyframes in {
    from   { -webkit-transform: scale(1); }
    to { -webkit-transform: scale(4);}
}

A: Let's first understand what reverse mean

The animation plays backwards each cycle. In other words, each time the animation cycles, the animation will reset to the end state and start over again. Animation steps are performed backwards, and timing functions are also reversed. For example, an ease-in timing function becomes ease-out. ref

Let's take a basic example to understand:

.box {
  width:50px;
  height:50px;
  margin:5px;
  background:red;
  position:relative;
}
.normal {
  animation: move normal  2s linear forwards;
}
.reverse {
  animation: move reverse 2s linear forwards;
}

@keyframes move{
  from {
    left:0;
  }
  to {
    left:300px;
  }
}

We have one animation and the first element is runnig it forwards while the second element is running it backwards. Technically, it's like we invert the from and to. reverse is useful in order to avoid defining a new animation in the opposite direction. We define a left-to-right animation and with reverse we have the right-to-left one. Until now, it's trivial.
Now, if you run any kind of animation defined by its name and in the road you modify a property of this animation you will change the behavior of the whole animation and we calculate again the value of the current state based on the new animation.
Example:

.box {
  width:50px;
  height:30px;
  margin:5px;
  background:red;
  position:relative;
}
.normal,
.special{
  animation: move normal  20s linear forwards;
  background:blue;
}
.reverse,
div:hover .special{
  animation: move reverse 20s linear forwards;
  background:green;
}

@keyframes move{
  from {
    left:0;
  }
  to {
    left:300px;
  }
}

p {
 margin:0;
}

Reference

Hover the element

We have 3 elements animating using the same animation at the same time so they will all be at the same progress. The third one is the same as the first animation and on hover it become the same as the second one. The trick is here! on hover you will not consider the actual position of the element and simply move in the other direction but you will consider the new animation defined by reverse and calculate the value of left considering the actual progress of the animation.
If the element is at 5s of the animation in the normal state we will have left:100px and in the reverse state we will have left:200px so if you hover at 5s you will toggle between 100px and 200px. You will not consider left:100px and move back to the 0px
Now it clear that if the animation is over, you will simply toggle between the first and the last state. You will not trigger a new animation again since we are dealing with the same animation and we simply changed one setting (the direction)

.box {
  width:50px;
  height:30px;
  margin:5px;
  background:red;
  position:relative;
}
.normal,
.special{
  animation: move normal  1s linear forwards;
  background:blue;
}
.reverse,
div:hover .special{
  animation: move reverse 1s linear forwards;
  background:green;
}

@keyframes move{
  from {
    left:0;
  }
  to {
    left:300px;
  }
}

p {
 margin:0;
}

Reference

Hover the element

Same logic happen if you change any other property. You will not see an intuitive result because you need to imagine how the new animation will be in order to identify how the current state will become.
Example if we change the timing-function

.box {
  width:50px;
  height:30px;
  margin:5px;
  background:red;
  position:relative;
}
.normal,
.special{
  animation: move  20s linear forwards;
  background:blue;
}
.reverse,
div:hover .special{
  animation: move 20s ease forwards;
  background:green;
}

@keyframes move{
  from {
    left:0;
  }
  to {
    left:300px;
  }
}

p {
 margin:0;
}

Reference

Hover the element

Example if we change the duration:

.box {
  width:50px;
  height:30px;
  margin:5px;
  background:red;
  position:relative;
}
.normal,
.special{
  animation: move  20s linear forwards;
  background:blue;
}
.reverse,
div:hover .special{
  animation: move 30s linear forwards;
  background:green;
}

@keyframes move{
  from {
    left:0;
  }
  to {
    left:300px;
  }
}

p {
 margin:0;
}

Reference

Hover the element

What you are looking for can be achieved with transition because transition will only care about the current value and will transition to a new one when you want (on hover for example)

.intern {
  width: 100px;
  height: 100px;
  margin:50px;
  background-color: red;
  transition:10s all;

}

.intern:hover {
  transform:scale(4);
}

When you hover you will start a scale animation that will last 10s BUT if you unhover before you will get back to the initial state. You cannot do this with animation. An animation need to either run fully or you abruptly cancel it in the middle and you get back to initial state
Even if you define two animation you will not always have the needed result in you hover when the running one is not yet over. You will cancel it and run the new one.

.intern {
  width: 100px;
  height: 100px;
  margin:50px;
  background-color: red;
  animation:in 5s linear forwards;
}

.intern:hover {
  animation:out 5s linear forwards;
}

@keyframes in {
  from {
    transform:scale(1);
  }
  to {
    transform:scale(4);
  }
}
@keyframes out {
  from {
    transform:scale(4);
  }
  to {
    transform:scale(1);
  }
}

Try to hover/unhover rapidly and you will see the bad effect. You will only have a perfect result if you hover at the end of each animation.

A: You have to set the transform as a property as well:

.intern {
  -webkit-transform: scale(1);
  -webkit-animation: in 1s infinite reverse forwards;
}

.intern:hover {
  -webkit-animation: in 1s infinite normal forwards;
}

@-webkit-keyframes in {
  from {
    -webkit-transform: scale(1);
  }
  to {
    -webkit-transform: scale(1.2);
  }
}

Edit: To have a simple effect, you can use transitions instead of keyframes.

.intern {
  width: 100px;
  height: 100px;
  background-color: red;
  transform: scale(1);
  transition: transform 1s;
}

.intern:hover {
  transform: scale(1.2);
}


text:
Q: Precondition Check Failed while using Gmail API service account I am using Google Gmail API for sending emails using delegate account but it showing me precondition check failed error.
Error is : <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Precondition check failed.". Details: "Precondition check failed.">.
Can Someone help me in this ?


text:
Q: Why is probability of infinite sequence of independent Gaussian r.v. in a sphere equals zero for any radius? Suppose we have a sequence of independent standard normal r.v. $(X_i)_{i=1}^n$. Also, let $S_r$ be an  $n$-dimensional ball of radius $r$ centered at zero.
Then why does
\begin{align}
 \lim_{n \to \infty} P[ (X_i)_{i=1}^n \in  S_r]=0
\end{align}
for any $r \ge 0$ ?
Here is an argument for the limit.  Let's calculate  $P[ (X_i)_{i=1}^n \in  S_r]$ for any finite $n$. Using result from this question we have that
\begin{align}
P[ (X_i)_{i=1}^n \in  S_r]= \frac{ \Gamma( \frac{n}{2})- \Gamma( \frac{n}{2},r^2) }{\Gamma( \frac{n}{2})}
\end{align}
where  $\Gamma( \frac{n}{2},r^2) $ is an incomple Gamma function. It is not difficult to check that the above expression goes to one as $n \to \infty$.
My questions:
1) From finite dimensional cases, in particular for $n=1$, we know that Gaussian is well centered around the origin. Why is thin not the case for $n \to \infty$?
2) I would like to see more intuition behind this conclusion. Is it saying that the probability that at least one coordinate would be outside of a sphere of any radius is 1.

A: It may become easier if we enlarge the sphere to a cube $Q_r$of side length $2r$. Then each $X_i$ individually has a positive probability $p$ of not falling into $[-r,r]$, from which
$$P[(X_i)_{i=1}^n\in S_r]\le P[(X_i)_{i=1}^n\in Q_r]=p^n $$
and this clearly $\to 0$ as $n\to\infty$.


text:
Q: Windows 7 installation of new software in other drive partition I just bought a Dell Vostro 3450 notebook whose drive was already partitioned when I got it. It has a 500GB hard drive: 100GB used for the Dell programs and Windows while the other 400GB is not used by anything. I thought of using the 400GB partition for data - however since I am using Windows 7 I cannot move the Users folder (i.e. My Documents, My Pictures, etc) to the 400GB partition, so I'm thinking how I could use the 400GB partition.
I'm considering using the 400GB partition for installing my software but I'm unsure if it will be healthy for my computer to have my new software installed in the other partition.
Should I instead shrink the 400GB partition and increase the C: drive (100GB) which is currently the system drive? If so, how can I do this?

A: There's no reason you can't install software in the other partition, if you want - just select Custom installation if necessary and direct the installer to place the program in a folder on D:.
In your case though, I would recommend just removing the D partition and expanding C since you don't have any real use for a drive partitioned in that manner. OEMs sometimes provide drives that way with the idea that it will make it easier to recover the machine, but understanding how most users actually use their systems that benefit is rarely achieved.


text:
Q: Attempted to call function "apc_fetch" from namespace "Doctrine\Common\Cache" I've APC installed on my server, wondering if I'm missing something else.  I want to be able to cache a 3rd party API request.
     code -
      $cache = new \Doctrine\Common\Cache\ApcCache();

      $data =  $cache->fetch('namesaved');

      if($data === false) {
      $cache->save('namesaved','keyword');
      }

      returns -
     Attempted to call function "apc_fetch" from namespace
     "Doctrine\Common\Cache" in      vendor/doctrine/cache/lib/Doctrine/Common/Cache/ApcCache.php line 40.

A: You are getting this error because the function apc_fetch could not be found. This means that either APC is not (correctly) installed, or that the module is not loaded in the PHP config.


text:
Q: discrete valuation ring and ring of witt vectors Given a perfect field $F$ of prime characteristic the ring of Witt Vectors $W(F)$ is a discrete valuation ring. For example, $W(\mathbb{F}_p)$ is the ring of $p$-adic integers. Is it possible to embed an arbitrary unramified discrete valuation ring of mixed characteristic into  a Witt Vector ring of a perfect field?

A: I think this is possible, if I understand your question correctly. If $R$ is a discrete valuation ring of mixed characteristic $(0,p)$ with residue field $k$ and maximal ideal $pR$, then $R$ is a Cohen ring for $k$. Cohen rings are unique up to (generally non-unique) isomorphism, and there is a construction of the Cohen ring for any field $k$ of characteristic $p$ which realizes the ring as a subring of $W(k)$. Now $W(k)$ is a subring of $W(k^{p^{-\infty}})$, where $k^{p^{-\infty}}$ is the perfect closure of $k$.


text:
Q: Remove a property of a multidimensional array tree - using lodash or underscore or js Example tree:
[
    { id: 32, name: 'unique name', children: [] },
    { id: 43, name: 'unique name', children: [] },
    { id: 55, name: 'unique name', children: [
        { id: 31, name: 'unique name', children: [] },
        { id: 63, name: 'unique name', children: [] },
        { id: 84, name: 'unique name', children: [
            { id: 47, name: 'unique name', children: [] },
            { id: 56, name: 'unique name', children: [] }
        ] }
    ] }
    { id: 67, name: 'unique name', children: [
        { id: 78, name: 'unique name', children: [] },
        { id: 89, name: 'unique name', children: [] },
    ] },
    { id: 30, name: 'unique name', children: [] }
]

Someone, please let me know how to remove just name property for the tree using lodash or pure js?
the output should be:
{ id: 32,  children: [] },
{ id: 43,  children: [] },
{ id: 55,  children: [
{ id: 31,  children: [] },
{ id: 63,  children: [] },
{ id: 84,  children: [
{ id: 47,  children: [] },
{ id: 56,  children: [] }] }
] }
{ id: 67,  children: [
{ id: 78,  children: [] },
{ id: 89,  children: [] },
] },
{ id: 30,  children: [] }

A: Just pick properties which you want. You can use map function:
let originArray = [
    { id: 32, name: 'unique name', children: [] },
    { id: 43, name: 'unique name', children: [] },
    {
        id: 55, name: 'unique name', children: [
            { id: 31, name: 'unique name', children: [] },
            { id: 63, name: 'unique name', children: [] },
            {
                id: 84, name: 'unique name', children: [
                    { id: 47, name: 'unique name', children: [] },
                    { id: 56, name: 'unique name', children: [] }
                ]
            }
        ]
    },
    {
        id: 67, name: 'unique name', children: [
            { id: 78, name: 'unique name', children: [] },
            { id: 89, name: 'unique name', children: [] },
        ]
    },
    { id: 30, name: 'unique name', children: [] }
]

let flattenArray = originArray.map(item => {
    return {
        id: item.id,
        children: item.children
    };
});

console.log(flattenArray);

A: You can do this with simple recursion and forEach:
function removeName(node) {
  delete node['name'];
  node.children.forEach(removeName);
}

The idea is to start with deleting name at the top level, and then recursively doing it again for each node in the children array:

var tree = [{
    id: 32,
    name: 'unique name',
    children: []
  },
  {
    id: 43,
    name: 'unique name',
    children: []
  },
  {
    id: 55,
    name: 'unique name',
    children: [{
        id: 31,
        name: 'unique name',
        children: []
      },
      {
        id: 63,
        name: 'unique name',
        children: []
      },
      {
        id: 84,
        name: 'unique name',
        children: [{
            id: 47,
            name: 'unique name',
            children: []
          },
          {
            id: 56,
            name: 'unique name',
            children: []
          }
        ]
      }
    ]
  },
  {
    id: 67,
    name: 'unique name',
    children: [{
        id: 78,
        name: 'unique name',
        children: []
      },
      {
        id: 89,
        name: 'unique name',
        children: []
      },
    ]
  },
  {
    id: 30,
    name: 'unique name',
    children: []
  }
];

function removeName(node) {
  delete node['name'];
  node.children.forEach(removeName);
}

tree.forEach(removeName);
console.log(tree);


text:
Q: MinGW64 Is Incapable of 32 Byte Stack Alignment (Required for AVX on Windows x64), Easy Work Around or Switch Compilers? I'm trying to work with AVX instructions and windows 64bit. I'm comfortable with g++ compiler so I've been using that, however, there is a big bug described reported here and very rough solutions were presented here.
Basically, m256 variable can't be aligned on the stack to work properly with avx instructions, it needs 32 byte alignment.
The solutions presented at the other stack question I linked are really terrible, especially if you have performance in mind. A python program that you would have to run every time you want to debug that replaces instructions with their sub-optimal unaligned instructions, or over-allocating and doing a bunch of costly hacky pointer math in code to get proper alignment. If you do the pointer math solution, I think there is still even a chance for a seg fault because you can't control the allocation or r-values / temporaries.
I'm looking for an easier and cheaper solution. I don't mind switching compilers, would prefer not to, but if it's the best solution I will. However, my very poor understanding of the bug is that it is intrinsic to windows 64 bit, so would switching compilers help or do other compilers also have the same issue?

A: You can solve this problem by switching to Microsoft's 64-bit C/C++ compiler. The problem is not intrinsic to 64-bit Windows. Despite what Kai Tietz said in the bug report you linked, Microsoft's x64 ABI does allow a compiler to give variables a greater than 16-byte alignment on the stack.
Also Cygwin's 64-bit version of GCC 4.9.2 can give variables 32-byte alignment on the stack.
Clang for Windows also makes working executables with AVX, and is a good choice in terms of optimizing well.


text:
Q: Command for formatting a special term How can write a new command which formats a certain 2-word-term always in a special font, all uppercase, with the line-height of the uppercase characters being the same as the line-height of down-case characters in normal text??

A: This sounds like a job for small caps. It prints all lower case letters as small upper case letters. You can use \MakeLowercase to ensure all letters are lower case.
\documentclass{article}

%\newcommand{\term}[1]{\textsc{#1}}
\newcommand{\term}[1]{\MakeLowercase{\textsc{#1}}}

\begin{document}

Text \term{Two Words} text

\end{document}


text:
Q: History or Histories? For a website I am going to show a list of changes to various fields shown for various components on the screen.
There is some question as to whether this is a 'Fields History', 'Field Histories', or something else entirely.
What is grammatically correct here?

A: As Edwin Ashworth's comment from 20 months ago observes, the issue you raise isn't fundamentally one of grammar, since various combinations of "field[s]" and "histor[y/ies]" do not offend against grammatical correctness, depending on how you frame them.
Idiomatically, however, "Field History" and "Field Histories" seem the least awkward and most intuitively reasonable choices. The choice between History and Histories depends on whether you understand your presentation of changes to the various fields to be "a history of the changes to the various fields [or to each field] shown" or whether you prefer to conceive of it as "a collection of histories—one for each field." There is no logical reason to prefer one interpretation over the other.
As for Field versus Fields, there is again no ironclad rule requiring you to choose one over the other. A similar situation might arise if you were trying to describe a cookbook (or multiple cookbooks) dedicated to recipes for desserts: "dessert cookbook," "desserts cookbook," dessert cookbooks," and "desserts cookbooks" are defensible, depending on the situation and your own stylistic preference.
Having said that, I note that many English phrases take the choice out of the speakers (or writer's) hands by endorsing—through popular usage—the singular form of the first word in such pairs. For example, a person who watches birds, is by general agreement a "birdwatcher," not a "birds watcher"; a game of cards is a "card game," not a "cards game"; and a house built of bricks is a "brick house" not a "bricks house." It seems to me that the cumulative effect of this preference for the singular first word in English is to push the needle of intuitive naturalness toward "Field History" and "Field Histories" and away from "Fields History" and "Fields Histories."

A: However, in more specific contexts, the plural form can also be histories e.g. in reference to various types of histories or a collection of histories.


text:
Q: Counting from first item, ignore counting within next 30 days I have a set of subscriptions which last 30 days each from the purchase of the first item during the period
PID    |     Date Purchased     |   User ID      | Owner ID
=======+========================+================+==============
1      |  1/1/2011              | 1              |  1
2      |  2/1/2011              | 1              |  1
3      |  19/1/2011             | 1              |  1
4      |  3/2/2011              | 1              |  1
5      |  5/1/2011              | 2              |  1
6      |  9/2/2011              | 2              |  1

I have a table containing a billing cycle
Owner ID | DATEBEGIN        | DATEEND
=========+==================+============
1        | 1/2/2011         | 2/3/2011

So for each owner id I would need to categorize periods into 30 day intervals before the dateend value. I need to count the purchases by unique user id's from the first purchase, and 'book' the next 30 days (don't count during this period), and count the first after that.
So for instance PID (PurchaseID) 1 on 1/1/2011, 'books' the next 30 days so they are ignored.
But this falls into a previous billing period, and the remainder is carried into the next
so 3/30 in the first, and 27/30 in the next, (sales on 2/1/2011, 19/1/2011 are ignored, but on 3/2/2011 isn't booked so it is counted)
Owner ID   | User ID   | PeriodBegin     | PeriodEnd    | Usage    | Comment
===========+===========+=====+===========+===============+=========+================
1          | 1         | 3/12/2010       | 1/1/2011     | 3/30     |
1          | 1         | 2/1/2011        | 1/2/2011     | 27/30    |
1          | 1         | 2/2/2011        | 4/3/2011     | 29/30    |
1          | 1         | 5/3/2011        | 4/4/2011     | 1/30     |
1          | 2         | 2/2/2011        | 4/3/2011     | 25/30    |
1          | 2         | 5/3/2011        | 4/4/2011     | 5/30     |

Eventually I aggregate these into the next
Owner ID  | PeriodBegin     | PeriodEnd    | Usage    |
==========+=================+==============+==========+
1         | 3/12/2010       | 1/1/2011     | 3/30     |
1         | 2/1/2011        | 1/2/2011     | 27/30    |
1         | 2/2/2011        | 4/3/2011     | 54/30    |
1         | 5/3/2011        | 4/4/2011     | 6/30     |

So I'm stuck trying to figure out how to tell MySQL to ignore the values within 30 days of the first purchase and then to count the ones after this 'booked' period ends.
To make it easier to understand I've made an analogy to mp3 subscriptions. The first table can be purchases from record company to distributors (which each have their own owner ids and multiple accounts for each end user (user id).
So within their first purchase of an mp3, they have a 30 days subscription service to download unlimited mp3s. The second last table is their billing schedule. So its unfair to charge a full days worth of mp3s if they buy a song 1 day before the billing period ends so it has to be split up into pieces, and the balance charged the following month.


text:
Q: If cell value changes, copy value to another worksheet I created a project management template where I update the project's status on a regular basis.
I want as soon as the cell value of one cell changes, the exact value will be copied to a cell on another worksheet.
If the cell value of the original cell is changed again (due to further project updates), I want the value to be copied again but below the previous copy, and so on.
As I would like to solve the problem on my own, I would be happy if you could give me some hints on how to proceed or where to look.

A: You can use the Worksheet_Change() event. For example, if the cell you're changing is A1, test to see if the Target cell matches. If so, determine the last used row on your destination sheet (Sheet2, below) and then assign the value.
Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = Range("A1").Address Then

        ' Get the last row on our destination sheet (using Sheet2, col A here)...
        Dim intLastRow As Long
        intLastRow = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row

        ' Add our value to the next row...
        Sheet2.Cells(intLastRow + 1, "A") = Target.Value

    End If

End Sub


text:
Q: nvd3 line chart issue
Here, I have used line chart from nvd3. I am trying to fix a few issues with this chart
1. This is an interactive chart, but even if i hover over a point where there are no points from the data, it still shows up the x and y-points.
2. x-axis and y-axis lines do NOT show up. Also the interactive guide doesn't come up in a rectangular box outlined.
3. The x-axis gets cut off at the end (see 14:29:19 being cut off at the end) no matter how much i increase the width to.
4. I am trying to remove the fill that we see above the line graph but styling changes made by me resulted in no success.
code that i use to fetch the line chart
var redraw = function(testData) {
    var dataT = [{
        key : 'Character Count',
        values : testData,
        color : '#00AEEF',
        area : false
    }];

    var margin = {
        top : 80,
        right : 20,
        bottom : 80,
        left : 50
    }, width = 1000 - (margin.left + margin.right), height = 600 - (margin.top + margin.bottom), x = d3.time.scale().range([0, width]), y = d3.scale.linear().range([height, 0]);

    x.domain(d3.extent(dataT[0].values, function(d) {
        return d3.time.format('%X')(new Date(d.TimeStamp));
    }));
    y.domain([0, d3.max(dataT[0].values, function(d) {
        return d.CharCount;
    })]);

    nv.addGraph(function() {
        chart = nv.models.lineChart().transitionDuration(350).useInteractiveGuideline(true)
            .showLegend(true).showYAxis(true).showXAxis(true).x(function(d) {
                return new Date(d.TimeStamp);
            }).y(function(d) {
                return d.CharCount;
            });

        chart.xAxis.axisLabel('Time').tickFormat(function(d) {
            return d3.time.format('%X')(new Date(d));
        }).scale(x).orient("bottom");

        chart.yAxis.axisLabel('Character Count').tickFormat(d3.format(',')).scale(y);

        chart.lines.forceY([0]);

        d3.select('#chart2 svg')//.append("g")
        .datum(dataT).attr('height', height).attr('width', width).call(chart);

        nv.utils.windowResize(chart.update);

        return chart;
    });
};

redraw(data)--data fetched froma  service ith dateTimeStamp in x-axis and integer in y-axis points.
Please help!

A:

*

*This is an interactive chart, but even if i hover over a point where there are no points from the data, it still shows up the x and
  y-points. 2. x-axis and y-axis lines do NOT show up. Also the
  interactive guide doesn't come up in a rectangular box outlined.

Adding corresponding javascript file in nvd3 zip file should solve the problem(line.js, linechart.js and corresponding css file)

3.The x-axis gets cut off at the end (see 14:29:19 being cut off at the end) no matter how much i increase the width to.

This is because you have not set the width and height of the chart in your codes to generate the chart
you should do
chart.width(width).height(height)

4.I am trying to remove the fill that we see above the line graph but styling changes made by me resulted in no success

This I am not sure how to solve as I do not have your dataset, so I not able to reproduce the problem
Here is my test code


text:
Q: Delivery Status Notification (Delay) emails from my server? I am using a Debian Jessie server and have setup exim4 to send me emails instead of postfix or sendmail.
Thats when I started getting loads of emails as follows:
First:

Title: * SECURITY information for vultr.guest *
Body: vultr.guest: Dec  7 12:13:29 : root : unable to resolve host vultr.guest

Second:

Title: Cron  test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp
Body:
This is an automatically generated Delivery Status Notification

THIS IS A WARNING MESSAGE ONLY.

YOU DO NOT NEED TO RESEND YOUR MESSAGE.

Delivery to the following recipient has been delayed:

     root@example.com

Message will be retried for 2 more day(s)

Technical details of temporary failure:
The recipient server did not accept our requests to connect. Learn more at https://support.google.com/mail/answer/7720
[(10) example.com. [xxx.xxx.xxx.90]:25: socket error]

----- Original message -----

DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=gmail.com; s=20120113;
        h=from:to:subject:mime-version:content-type:content-transfer-encoding
         :message-id:date;
        bh=k/8GlT8DBvBIJzBOOfw8qR0kGPzj7m9ZR/aj+JOKBhg=;
        b=eA6kpVtS0eNBO0CFBfLzlnaYwZ9/GubMaWTGUkG4MaxbNy55YxY2jZAuh3RHI2mo8Q
         qp5OmKihchYTgCxcAx0xvJaXuuxDhoT9dCJ6YEIzqjmypWjpUEqoXkNu7uKU4Cd1vTfS
         5/dSvE7zVE6TYe4L18vrOiYBEUNrJQ3lTdv//RrlHZs/f62GorIyMHgVL4XvkVNLWF/K
         lK9SSybf9ee3KTKUxurBm1Tyah62Gk4/869Hynr1QEAjSAzM8sSKDyKH/KOZ06sDWtPQ
         jE0Agxffk8RkhsFkEtIbpZBfS/zagGZ8+CXsGqR9541ylMAHGOGeYtRp4oiB8tVP2Sbv
         h4Rw==
X-Received: by 10.129.114.10 with SMTP id n10mr3081975ywc.0.1449600002717;
        Tue, 08 Dec 2015 10:40:02 -0800 (PST)
Return-Path: <myEmailAddress@gmail.com>
Received: from vultr.guest ([104.156.246.90])
        by smtp.gmail.com with ESMTPSA id f203sm2998216ywf.45.2015.12.08.10.40.02
        for <root@example.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 08 Dec 2015 10:40:02 -0800 (PST)
From: Cron Daemon <myEmailAddress@gmail.com>
X-Google-Original-From: root@example.com (Cron Daemon)
Received: from smmsp by vultr.guest with local (Exim 4.84)
        (envelope-from <smmsp@example.com>)
        id 1a6NBB-0007Vu-Os
        for root@example.com; Tue, 08 Dec 2015 13:40:01 -0500
To: root@example.com
Subject: Cron <smmsp@vultr> test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <MAILTO=root>
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/var/lib/sendmail>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=smmsp>
Message-Id: <E1a6NBB-0007Vu-Os@vultr.guest>
Date: Tue, 08 Dec 2015 13:40:01 -0500

I edited /etc/cron.d/sendmail and first tried to change the MAILTO= line from root to my gmail address. That did not help. So I commented that line out, and the
*/20 *    *    *    *       smmsp   test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp

That made it stop from sending me emails every 20 minutes with junk. But I still get many and often emails with the
Subject: * SECURITY information for vultr.guest *
Body:
This is an automatically generated Delivery Status Notification

THIS IS A WARNING MESSAGE ONLY.

YOU DO NOT NEED TO RESEND YOUR MESSAGE.

Delivery to the following recipient has been delayed:

     root@example.com

Message will be retried for 1 more day(s)

Technical details of temporary failure:
The recipient server did not accept our requests to connect. Learn more at https://support.google.com/mail/answer/7720
[(10) example.com. [xxx.xxx.xxx.90]:25: socket error]

I did modify /etc/hostname and removed vultr.guest and replaced it with example.com. And in /etc/hosts I only have:
127.0.0.1   localhost
127.0.1.1   install.install install

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

What did I configure wrong? And how can I fix it?
UPDATE: The /etc/exim4/update-exim4.conf.conf contents are:
dc_eximconfig_configtype='satellite'
dc_other_hostnames=''
dc_local_interfaces='127.0.0.1 ; ::1'
dc_readhost=''
dc_relay_domains=''
dc_minimaldns='false'
dc_relay_nets=''
dc_smarthost='smtp.gmail.com::587'
CFILEMODE='644'
dc_use_split_config='false'
dc_hide_mailname='true'
dc_mailname_in_oh='true'
dc_localdelivery='mail_spool'

A: It seems to me that VULTR's tutorial is not correct. When you configure exim4 by dpkg-reconfigure exim4-config, they tell you to choose mail sent by smarthost; no local mail, and configure it as follows:
System mail name: YOUR_HOSTNAME
IP-addresses to listen on for incoming SMTP connections: 127.0.0.1 ; ::1
Other destinations for which mail is accepted: <BLANK>
Visible domain name for local users: <BLANK>
IP address or host name of the outgoing smarthost: smtp.gmail.com::587
Keep number of DNS-queries minimal (Dial-on-Demand)? No
Split configuration into small files? No
Root and postmaster mail recipient: <BLANK>

But I doubt that the Other destinations for which mail is accepted: should be BLANK. If you configure it, add your email address, or your example.com domain/email.
Otherwise, try to edit the following locations:
/etc/aliases:
root: address@example.com
mailer-daemon: address@example.com
postmaster: address@example.com
nobody: address@example.com
hostmaster: address@example.com
usenet: address@example.com
news: address@example.com
webmaster: address@example.com
www: address@example.com
www-data: address@example.com
ftp: address@example.com
abuse: address@example.com
noc: address@example.com
security: address@example.com
*: address@example.com

and edit /etc/email-addresses to include the user:email combo:
root: address@example.com
mail: address2@example2.com
*: address@example.com

Then restart
service sendmail restart and service exim4 restart


text:
Q: Perl text file grep I would like to create an array in Perl of strings that I need to search/grep from a tab-deliminated text file. For example, I create the array:
#!/usr/bin/perl -w

use strict;
use warnings;

# array of search terms
my @searchArray = ('10060\t', '10841\t', '11164\t');

I want to have a foreach loop to grep a text file with a format like this:
c18                 10706      463029             K
c2                  10841      91075              G
c36                 11164      .                  B
c19                 11257      41553              C

for each of the elements of the above array. In the end, I want to have a NEW text file that would look like this (continuing this example):
c2                  10841      91075              G
c36                 11164      .                  B

How do I go about doing this? Also, this needs to be able to work on a text file with ~5 million lines, so memory cannot be wasted (I do have 32GB of memory though).
Thanks for any help/advice in advanced! Cheers.

A: Using a perl one-liner.  Just translate your list of numbers into a regex.
perl -ne 'print if /\b(?:10060|10841|11164)\b/' file.txt > newfile.txt

A: You can search for alternatives by using a regexp like /(10060\t|100841\t|11164\t)/. Since your array could be large, you could create this regexp, by something like
$searchRegex = '(' + join('|',@searchArray) + ')';

this is just a simple string, and so it would be better (faster) to compile it to a regexp by
$searchRegex = qr/$searchRegex/;

With only 5 million lines, you could actually pull the entire file into memory (less than a gigabyte if 100 chars/line), but otherwise, line by line you could search with this pattern as in
while (<>) {
    print if $_ =~ $searchRegex
}

A: So I'm not the best coder but this should work.
#!/usr/bin/perl -w

use strict;
use warnings;

# array of search terms
my $searchfile = 'file.txt';
my $outfile = 'outfile.txt';
my @searchArray = ('10060', '10841', '11164');
my @findArray;

open(READ,'<',$searchfile) || die $!;
while (<READ>)
{
    foreach my $searchArray (@searchArray) {
        if (/$searchArray/) {
            chomp ($_);
            push (@findArray, $_) ;
        }
    }
}
close(READ);

### For Console Print
#foreach (@findArray){
#   print $_."\n";
#}

open(WRITE,'>',$outfile) || die $!;
foreach (@findArray){
    print WRITE $_."\n";
}
close(WRITE);


text:
Q: How to calculate input resistance of a multiplxer I am trying to measure the input resistance of the following multiplexer:
Multiplexer
The reason I am measuring the input resistance of this multiplexer is that I have a signal coming out of my source and upon the signal reaching the input of my multiplexer the signal is distorted. My guess is that the output resistance of the source is high compared to the  input resistance of the multiplexer. I want to be able to measure the input resistance of my multiplexer but I am not sure how. I have the following ideas but not sure which is correct:
I am using a push-pull circuit to model my input of my multiplexer:
Here VDD is 3.3V and VSS is 0V. To measure the input impedance of the entire multiplexer I tried the following:

Where the signal from my function generator was 1.8 Vpp, square wave, and I tried at frequencies from 1KHz to 8 MHz. This resulted in an decrease in impedance as the frequency is increased due to MOS gate capacitance. I measured V2 with respect to ground and V1 with respect to ground (V2 and V1 were measured peak to peak). Then Iin = (v2-V1)/R (in this case R = 4.7K). Then Rin = V1/Iin. Now i am not sure if this is the input impedance of my multiplexer or not? The reason I am not sure of this is I also wanted to add in a pull-down resistor to pull down my signal to ground. So I wanted to calculate the input resistance between the ground and input. Therefore I could add in a pull-down resistor to the input of the circuit.
That way this could help bring down my signal to ground (two resistors in parallel of about the same size would decrease the resistance in half) so i wanted to measure the resistance between the input and ground and then wanted to see what the resistance would be between the input and Vss(+) if I were to use a pull-up resistor as well (for another test). For input resistance between the input and VDD(+) I used a similar set-up as mentioned above expect instead of connecting my reference to ground I connected it to VDD(+) (3.3V). I am not sure if this is correct? Then for the resistance between the input and ground I realized that this would be the exact same as what I did for the input resistance of the entire multiplexer (first scenario). Therefore, I am confused as to how to measure the total input resistance of my multiplexer, the input resistance seen between my input and ground, and my input resistance seen between my input and VDD.

A: An issue probably causing the signal distortion you describe is that the logic inputs must always be positive relative to ground but not more than the logic supply voltage, nominally +5V. 74LS TTL and 74HCT CMOS logic families should not have their outputs driven negative relative to ground nor more positive than the logic supply voltage.  In fact, voltages above supply voltage or below ground may damage the input pins of the logic devices if the driving source impedance is low impedance.
Your signal generator output is probably bipolar, both positive and negative relative to ground.  Most signal generators provide 50 Ohm output impedance which is possibly low enough impedance to damage the inputs of either LS TTL or HCT CMOS logic devices.  If your signal generator provides output voltage offset capability, setting offset to +1.6V and amplitude around 3.3V peak to peak will make the output signal compatible with LS TTL or HCTL CMOS inputs and likely solve the signal distortion problem.
74HCT CMOS logic family is CMOS logic compatible as drop-in replacement for LS TTL logic.  Input is capacitive around a few picofarads.  The H means high speed comparable to or faster than LS TTL,  The T in HCT CMOS logic means that the input switching thresholds and output drives are compatible with TTL logic.  HCT CMOS logic device inputs include protection diodes from ground to the input pin and from the input pin to the logic supply voltage.  This clamps the input signal to a voltage range of about -0.6V to logic supply voltage plus 0.6v.  These diodes conduct to protect the device inputs in case of static discharge and are actually more important when the devices are not installed in circuit assemblies.  Modern 74HCTL logic can operate with 3.3V supply voltage and inputs and outputs are still compatible with 74LS TTL running from 5V supply voltage.  CMOS outputs drive both high and low levels very close to the supply rails.
CMOS logic which is not TTL compatible switches at half the supply voltage.  These inputs might not switch or might respond erratically when driven from LSTTL logic device outputs.
A common ad hoc scheme for driving inputs from an external signal is to use capacitive coupling to the input with 220 Ohm pull up and 330 Ohm pull down resistors on the input pin.  This biases the input to a 3.0V, a logic high level and provides impedance around 130 Ohms, which is close to the characteristic impedance of twisted pair cables or printed circuit traces.  If you want a more symmetrical response to input signals or more sensitivity to small signals at the expense of greater noise sensitivity you may reverse the configuration of the pull up and pull down to bias the input pin to about 2.0V.  Either way, this imposes a maximum dwell time at a low logic level input from the RC time constant of the blocking capacitor and the biasing resistors
The correct way to condition an input signal to TTL levels is a high speed comparator with output pulled up to the logic supply voltage.
The pull up resistor for the comparator or biasing pull up plus pull down resistors should be placed near the logic device input pins to prevent signal reflections, which can also distort the input signal.  Comparator inputs should likewise use a termination resistor to absorb reflections at the signal inputs coming from the signal generator.  These resistors should match the characteristic impedance of the cable connecting the signal generator to the comparators.  The reflection occurs at signal level transitions and can make the transition as much as twice the transition voltage.  The Schottky diodes added to the inputs of LS TTL, low power Schottky logic devices, are put there to damp the over voltage and under voltage spikes at the device inputs caused by the impedance mis match from the characteristic impedance of the circuit wires or circuit board traces to the input impedance of the driven logic devices.

A: I'm not going to tell you how to calculate it because the data sheet gives better ideas. There's usually something in the data sheet that gives a clue such as this graph: -

This graph tells you how much feed thru there is on a switch that is "open". The measured/predicted value is across a 50 ohm terminator on the "far side" of the input. As expected, as frequency rises feed-thru rises.
At 10 MHz there is about -55dB feed thru or in voltage terms, if the input were a 1Vp-p sinewave, the output is 1.78 mV. This implies a 50 ohm current of 35.6 uA RMS and an input impedance of 28.1 kohm.
So, input impedance can be calculated but it depends on several factors such as what is connected to the output and input capacitance. Given also that there are input leakage currents to consider (circa 1 uA), it's a complex picture.
If you take the 1 MHz scenario, attenuation is ~ 75 dB and this is equivalent to 178 uV across the 50 ohms and a current of 3.56 uA RMS. If you take this figure and the previous figure you can see that in one decade the feed-thru has dropped to one tenth. This tells me that the dominant force behind the transfer of leaking signals is capacitive.
So, you have an impedance of 28.1 kohm at 10 MHz and this translates to a capacitance of 0.57 pF.
So now you have a fairly reasonable model of the input pin - there's about 0.57pF to the output common pin and there's typically 5pF down to ground. Leakage currents are also present.


text:
Q: Two image channels, one quantitative, one "relative". Best architecture/preprocessing? I'm performing semantic segmentation on a multi-channel image with a residual U-NET. I'm getting DICE scores that are ok for this task but I want to do even better.
The problem is that the first channel has no intrinsic scale. It's like a photograph, where the intensity level might depend on (random) illumination when the picture was taken, it might have a slowly-varying bias etc...etc... So I want my network to learn to look only at contrasts. So I normalize this channel according to the median intensity of each acquisition.
My second channel instead is quantitative. I know that a specific grey-level value has the same meaning in every single subject and  acquisition. Therefore I normalize the intensity according to the maximum possible value I can get.
The I build a CNN where I pass in input the two channels as they were two color channels. Is this the best thing to do?  Or does this confuse the network? To help the network I augment my image by randomly scaling and changing the illumination of the first channel but not the second.
Are there different architectures that might be better? Like keeping the two images separate in the decoding path? Any other idea?


text:
Q: how to joining muiltiple select query without common column? I want to combine multiple columns of different select queries(all return 2 column and 1 row). How can I do it?
for example
select p.* from(
   (select a.id, a.global from table1 as a)
   (select j.gogl, j.popl from table2 as j)
) as p

It have multiple select but they all return 2 column and only 1 row
Expected output

id
global
gogl
popl

First
row
First
row

A: If you want all combinations of rows from the two tables, then use:
select a.id, a.global, j.gogl, j.popl
from table1 a cross join
     table2 j

Note:  If all the tables have 1 row, then the result set will have one row.  However, the number of rows can grow or shrink dramatically, depending on the size of the tables.  If any table has no rows, for instance, the result set has no rows.

A: If a single row is guaranteed, just combining the output of each select into 4 columns you can use a full join with an always true condition - that way you'll always get the value from one if the other happens to return null.
select * from
    (select id, global from table1) as a
full join
    (select gogl, popl from table2) as j
on 1=1


text:
Q: How the Filter function is working? I have these few lines of code in an example. The Tutorial explains that filter function matches and returns matched country record. Where & how the entry.name was set.
myApp.controller('detailcontroller', function($scope, $routeParams, $http) {
  $scope.name=$routeParams.countryname;
  $http.get('countries.json').success(function(data) {
     var country =data.filter(function(entry) {
        return entry.name === $scope.name;
     }) [0];

  console.log(country);
});

});

A: It wasn't "set". You specify an iterator (callback) function to the filter function.
The docs says : Function to test each element of the array. Return true to keep the element, false otherwise.
So basically, entry represents an element of the array. For each of the elements in the array, your function will be called with the element as parameter (if you have an array of countries, entry will be the first country, then the second one, etc.).
Maybe this is easier to understand for you :
var testIfCountryMatches = function(country){
    console.log("is "+country+" France ? : "+(country.name === "France"));
    return country.name === "France";
}

var matchingCountries = data.filter(testIfCountryMatches);
var fr = matchingCountries[0];


text:
Q: How to pass data between two viewcontrollers in iwatch? I am working on a app which sends notification to iwatch.I want to show notification msg on next viewcontroller, how to pass data from notification viewcontroller to next viewcontroller in page based navigation?

A: From the Official Documentation:

When pushing a new interface controller, it is recommended that you
  pass a context object to the pushControllerWithName:context: method. A
  context object is your only way to communicate information to the new
  interface controller about what it should display. A context object
  can be an existing data object, or it can be a dictionary that you
  create dynamically and fill with relevant information.
If you prefer to use segues to initiate hierarchical navigation
  between interface controllers, WatchKit calls the
  contextForSegueWithIdentifier:inTable:rowIndex: or
  contextForSegueWithIdentifier: method based on whether the source of
  the segue was a table row or a button. Use those methods to provide
  the context object needed to initialize the new interface controller.

A: If you want to pass data than simply use this ...
NSString *a = @"a";
NSString *b = @"b";

[self pushControllerWithName:@"DetailViewController" context:[NSDictionary dictionaryWithObjectsAndKeys:a, @"name",b,@"id", nil]];

and goto the push view and log it's context..
- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    NSLog(@"context %@",context);
}

in context see the dictionary formate where you can set before pushing the view.

A: I found the answer here
Basically you need to reload the controller (or page) you want to pass the context to.
// Inside Init or awakeFromContext of "Page1"
// Reload the next controller and pass the context or data you want
[WKInterfaceController reloadRootControllersWithNames:@[@"Page2"] contexts:@[someData]];


text:
Q: DML not allowed in page action when nothing happens in constructor This question may similar to DML not allowed in page action but I can't resolve it.
This is my page:
<apex:page Controller="MyController"
           action="/{!MyAction}">
Page loading...
</apex:page>

and this is my controller
public with sharing class MyController {
    public PageReference MyAction() {
        // ...
        // update something in DB
        // ...
        PageReference page = new PageReference('/' + this.opportunityId);
        return page;
    }
}

I get DML not allowed in page action but my constructor is empty.
Any tips?

A: I think this is because you have the page action attribute as:
action="/{!MyAction}"

the slash that precedes the {!MyAction} merge field means that the {!MyAction} will be treated as a getter.  The method you have posted is named getUpdateAndRedirectToPage, so it satisfies the getter requirements (assuming that MyAction is just an example?).
DML isn't allowed in getters, so I'd expect an error of 'DML not currently allowed' or similar.  If you remove the '/', the method will be executed as a page action and DML will be allowed (although not necessarily recommended, due to the lack of order of execution guarantees).


text:
Q: Blazor: binding collection of elements to a List In my Blazor server-side application, I dynamically created multiple InputNumber controls based on the NumberOfOutlets provided by the user:

    Number of Outlets

        <InputNumber id="numberOfOutlets" @bind-Value="QuoteModel.NumberOfOutlets" ParsingErrorMessage="Number of Outlets must be a valid number" class="form-control mx-2" />

@for (short outlet = 1; outlet <= QuoteModel.NumberOfOutlets; outlet++)
{

        Number of Outlets

            <InputNumber id="@($"outlet{outlet}offTheRight")" ParsingErrorMessage="Outlet location must be a valid number" class="form-control mx-2" />

}

How can I bind the InputNumbers to the following property?
public List<short> OutletLocations { get; set; } = new List<short>(50);

I don't need to populate the controls from the List, rather, I want to populate the List based on the values entered by the user.


text:
Q: Pivot Table from VBA macro displaying incorrect data Somehow my Pivot Table created from my VBA script displays different data than when i create the pivot table manually.
My macro does the following:

*

*Database is in sheet 2. Pivot is in sheet 1.

*Macro deletes all rows in sheet 2 and adds new data.

*M deletes rows containing the current pivot.

*M deletes the data-connection for the pivot.

*M creates new data-connection for the new data in sheet 2 and creates a new
pivot in sheet 1.

Everything works without errors, but somehow the data is not the same as to when i create the pivot manually.
My guess is that it uses some old data-connection, but im not sure how or how to fix this.
VBA - Code for pivot table creation:
'Delete old pivot
Sheets("Sheet1").Select
Range("A1:C5").Select
Selection.ClearContents

'Create new Connection
ActiveWorkbook.Connections("PivotConnection").Delete
Workbooks("File.xlsm").Connections.Add2 _
    "PivotConnection", "", _
    "WORKSHEET;*ABSOLUTE PATH*[File.xlsm]Sheet2" _
    , "Sheet2!$A:$Q", 7, True, False

'Create new pivot
ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _
    ActiveWorkbook.Connections("PivotConnection"), Version:=6).CreatePivotTable _
        TableDestination:=Worksheets("Sheet1").Cells(1, 1), TableName:="PivotTable3", DefaultVersion:=6

With ActiveSheet.PivotTables("PivotTable3")
    .ColumnGrand = True
    .HasAutoFormat = True
    .DisplayErrorString = False
    .DisplayNullString = True
    .EnableDrilldown = True
    .ErrorString = ""
    .MergeLabels = False
    .NullString = ""
    .PageFieldOrder = 2
    .PageFieldWrapCount = 0
    .PreserveFormatting = True
    .RowGrand = True
    .PrintTitles = False
    .RepeatItemsOnEachPrintedPage = True
    .TotalsAnnotation = True
    .CompactRowIndent = 1
    .VisualTotals = False
    .InGridDropZones = False
    .DisplayFieldCaptions = True
    .DisplayMemberPropertyTooltips = True
    .DisplayContextTooltips = True
    .ShowDrillIndicators = True
    .PrintDrillIndicators = False
    .DisplayEmptyRow = False
    .DisplayEmptyColumn = False
    .AllowMultipleFilters = False
    .SortUsingCustomLists = True
    .DisplayImmediateItems = True
    .ViewCalculatedMembers = True
    .FieldListSortAscending = False
    .ShowValuesRow = False
    .CalculatedMembersInFilters = True
    .RowAxisLayout xlCompactRow
End With
ActiveSheet.PivotTables("PivotTable3").PivotCache.RefreshOnFileOpen = False
ActiveSheet.PivotTables("PivotTable3").RepeatAllLabels xlRepeatLabels

Thanks in advance
EDIT:
Just to clarify how the data is incorrect:

*

*The distinct count of a row gives me e.g. 1000

*I run the macro and new pivot with modified data is created

*Distinct count still shows 1000

*Manually created pivot shows e.g. 980 for distinct count


text:
Q: How do binary files run on different machines? I always wondered about how executable binary files actually work. Compilation is always stated as

taking the source code and translating it to machine language

But what does that really mean?
Namely:

*

*Can I move a binary file from computer A to computer B and expect it
to work? (assuming that I also move the appropriate libraries)

*Is every executable binary file made to work with a specific
processor?

*What sort of information is inside an executable binary file?

*How come executable files on windows can be launched on any windows version? (It's an other story if they work)

*Why can't I run a Linux executable on Windows? Does it have to do
with the kernel(so not the processor)?

Mind that I have limited knowledge on processors and compilers and none on assembly.

A: *

*Not necessarily. If it's build for portability and the platforms are compatible, then yes (e.g. 64 bit editions of Windows are able to execute 32 bit and 64 bit Windows executables, but not 16 bit ones anymore).

*Not necessarily. They're made for a specific instruction set. Since those are typically extensions and there's backward compatibility, you might run older files on newer processors, but not necessarily the other way around. For example, a program compiled for Windows 95 will probably still run on today's hardware, but you can't run a program compiled for today's hardware on an old Windows 95 machine. However, if two machines run completely different instructions, the executables won't be compatible (e.g. Intel vs. ARM).

*This is platform dependent, there are multiple formats with different headers and stuff, but basically there's always some kind of header working as an index, telling the operating system where to find specific things (such as the main entry point).

*They actually can't (see #2 above).

*First of all, Windows and Linux use different formats for their executable files. But even then there are differences, for example the whole environment and provided platform API/libraries. For example, a Linux executable would typically try to talk to a window manager such as X11, while a Windows program would try to call the Windows API. However, there are ways to get such things working. Older versions of Windows (NT?) actually had POSIX extensions so you could run a limited set of Linux programs as far as I'm aware, although I've never really tried that or had a closer look. On the other side, for Linux there are tools such as Wine, which will try to emulate the Windows environment, providing the API files, path conversions, etc. It's no complete emulation (like in using a virtual machine).

A: *

*Only under very controlled circumstances: Both computers must have a compatible processor and operating system.

*Not a specific processor, but a set of compatible processors. E.g. a file compiled for compatibility with x86 and no extensions will work on every Intel or AMD x86 or x64 processor, assuming the OS is compatible.

*First and foremost the machine code from the compilation step. In addition to that, a few other socalled "sections" will have e.g. resources (ever wondered, why an executable has a dedicated Icon on Windows, even if it is not running, but just shown in explorer), the description of binary compatibility and more.

*This is a side effect of 1.: Whenever the OS provides compatibility with the executable format, it can be launched. Modern Windows versions provide a range of compatibility: DOS, Win16, Win32, Win64, dotnet are the most important ones.

*The OS provides the executable with an environment, that is indispensable for execution. Those environments differ wildly between Linux and Windows. This means, you can't directly run executables from one on the other. There are projects underway to bridge this gap: The WINE project aims to allow launching of Windows executables on Linux (and other OSes), while the Cygwin project aims to make it possible to run Linux software on Windows. Cygwin doesn't aim for binary compatibility, but to allow for recompilation of unmodified source.
It is importand to understand, that the executable (e.g. the .exe) is not the result of the compilation process - it is the result of the linking process, which combines the output of compilation with the other ingredients needed to create what I described in 3.


text:
Q: How to get the tag Names from the HTML in selenium webdriver I wanted to get the names of all the Travels name, present in the tags, ( They are dynamic so wanted to take in array to have count)
in http://www.redbus.in/Booking/SelectBus.aspx?fromCityId=124&fromCityName=Hyderabad&toCityId=462&toCityName=Mumbai&doj=30-May-2013&busType=Any&opId=0
here's the some part of html file

 Akbar Travels

 Omer Travels

 Sangita Travel Agency

I have tried with
        List<WebElement> linkElements = driver.findElements(By.tagName("//table[@cellspacing=\"0\"]"));

        String[] linkTexts = new String[linkElements.size()];

when i debug got as linkElements   ArrayList<E>  (id=82)
                      linkTexts         String[0]  (id=95)
Not working.
tried this also
List<WebElement> linkElements = driver.findElements(By.tagName("t1-results"));

        String[] linkTexts = new String[linkElements.size()];

Can anyone please suggest me how to take the names.

A: Try using a CSS selector, like this:
List<WebElement> linkElements = driver.findElements(By.cssSelector("table tr.r1 > td.i1"));

I just made a quick test and this code finds all the 63 matches (as of this writing):
driver.get("http://www.redbus.in/Booking/SelectBus.aspx?fromCityId=124&fromCityName=Hyderabad&toCityId=462&toCityName=Mumbai&doj=30-May-2013&busType=Any&opId=0");

//Find's the elements using a CSS selector: all td's (with class "i1"), directly inside a tr (with class r1) which are inside a table.
List<WebElement> linkElements = driver.findElements(By.cssSelector("table tr.r1 > td.i1"));
String[] linksText = new String[linkElements.size()];
int index = 0;
for(WebElement element : linkElements){
    linksText[index++] = element.getText();
}

A: Xpath is also good option, use this hope help you.
List<WebElement> linkElements = driver.findElements(By.Xpath("Your Xpath"));
String[] linksText = new String[linkElements.size()];
int index = 0;
for(WebElement element : linkElements){
linksText[index++] = element.getText();
}

A: Try with the CSS Count Concept given below
int size=driver.findElements(By.cssSelector("#t1-results > #t1-list5 > tbody > tr.r1")).size();
for(int i=1;i<=size();i++)
{
    String travelname = driver.findElement(By.cssSelector("#t1-results > #t1-list5 > tbody > tr.r1 > td.i1"))
}

Let me know is the above script works for you.

A: Both CSS and XPath entries can be used for problems such as these, but some clarification needs to be made:

*

*some CSS entries are relevant to frequently-changed style features and should not be used as locators,

*characterizing XPath locators en-masse as "fragile" hearkens back to the olde days when the term implied the full DOM path between the parent /html and the end widget being sought.

There are algorithms for constructing XPath locators that are designed first and foremost to be robust in light of frequent/massive DOM retooling -- such locators are anything but fragile.
The last concern noted earlier (that some browsers [notably IE] have non-standard XPath implementations) is unfortunately true, irrespective of your take on the value of XPaths in general.
That isn't grounds for abandoning XPath as a tool for one's toolbag -- but it might lend credence to abandoning a browser with so many proprietary features.


text:
Q: How to pass an object with encapsulation (private properties) to another tab through localStorage? If I try to pass an instance of it to another tab through localStorage where I need to use JSON.stringify, the object logically becomes empty. Is there any way to pass it without saving the private properties in a different way by using getters? Can I somehow stringify the instance in a different way and pass it without losing it original character?
I have the following class definition:
class User {
  constructor(username, password, email) {
    let _username = '';
    let _password = '';
    let _email = '';

    this.setUsername = username => {
      if (!username) {
        throw new Error("Benutzername darf nicht leer sein!");
      }
      _username = username;
    };
    this.getUsername = () => _username;

    this.setPassword = password => {
      if (!password) {
        throw new Error("Passwort darf nicht leer sein!");
      }
      _password = password;
    };
    this.getPassword = () => _password;

    this.setEmail = email => {
      if (!email) {
        throw new Error("E-Mail-Adresse darf nicht leer sein!");
      }
      _email = email;;
    }
    this.getEmail = () => _email;

    this.setUsername(username || '');
    this.setPassword(password || '');
    this.setEmail(email || '');
  }
}

A: You can create a method to save it to localStorage, something like this:
saveToLocal() {
  localStorage.setItem(this._email, JSON.stringify(
    { this._email, this._username, this._password }
  ));
}

And then you can retrieve it from localStorage by using:
localStorage.getItem(<email>) || {};


text:
Q: RDLC Subreport Parameters Not Working as Expected I have an RDLC report, which displays basic information about financial transactions, and within that report I have a subreport to display the details for these transactions.
I'm having some trouble getting parameters to pass between the main and subreport.  The subreport accepts one parameter: TransactionID.  When I set the main report to send the actual value of TransactionID for each row, the SubreportProcessing event handler never fires, and when I try to expand the subreport, a message about a null reference exception appears in the debug output, but I cannot catch this exception to find out exactly what is null.  Along with the null reference exception, the subreport displays:

Error: Subreport could not be shown

As a test, I tried to hard-code the value 0 for TransactionID, and then the SubreportProcessing event fired for every row, but with obviously incorrect results.  This leads me to suspect that the TransactionID value in the rows of the main report is somehow coming up null when it tries to use it as a parameter, but I don't understand how that could be happening, or how to fix it.
Edit:
Since the literal value 0 worked, I dedcided to try one of the TransactionID values from the actual report (2652791667), and found that it failed under those conditions as well.  Noting that the given value exceeds the range of an Int32, I tried a smaller number, which worked.

A: The Int32 issue was the answer.  I tried changing the subreport's TransactionID parameter to Text, but it apparently couldn't automatically convert the numeric value of TransactionID from the main report data to a string.
In the end, I added a field to my dataset, called TransactionIDStr, and populated it with TransactionID.ToString(), and it now functions flawlessly.


text:
Q: How to find out double word count in hadoop using mapreduce with java I need mapreduce code in java to find out double word count solution in hadoop
input :
"what is your name ? what you want from me ?
 You know best way to earn money is Hardwork
 what is your aim ?"
Double W.C. Output :
what is 2
is your 2
your name 1
what you 1
a quicker response is very much appreciable.
thanks in advance.

A: The below code works for me.
package hadoop;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class doubleWc {
public static class doubMapper extends   Mapper<LongWritable,Text,Text,IntWritable>
{
    Text outkey=new Text();
    IntWritable outvalue=new IntWritable();
    public void map(LongWritable key,Text values,Context context) throws IOException, InterruptedException
    {
        String []cols=values.toString().split(",");
        for(int i=0;i<(cols.length) - 1 ;i++)
        {
            outkey.set(cols[i]+","+cols[i+1]);
            outvalue.set(1);
            context.write(outkey, outvalue);
        }
    }
}
public static class douReducer extends Reducer<Text,IntWritable,Text,IntWritable>
{
    IntWritable outvalue=new IntWritable();
    public void reduce(Text key,Iterable<IntWritable> values,Context context) throws IOException, InterruptedException
    {
        int sum=0;
        for(IntWritable t:values)
        {
            sum=sum+t.get();
        }
        outvalue.set(sum);
        context.write(key, outvalue);
    }
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
    Configuration conf=new Configuration();
    @SuppressWarnings("deprecation")
    Job job=new Job(conf,"double program");

    job.setJarByClass(doubleWc.class);
    job.setMapperClass(doubMapper.class);
    job.setReducerClass(douReducer.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));

    System.exit(job.waitForCompletion(true)?1:0);

}

}

PLEASE LET ME KNOW IF IT HELP!!!!


text:
Q: How do I match code to Git commit, and create branch? I have a git repository on my "DEV" machine. A while ago, I copied some code to my PROD machine. Since then, there have been many commits in my DEV machine. However there may have been a couple of ad-hock code changes on my PROD machine that was never committed or "Brached" out.
Question: How can I find the commit on DEV that is closest to code on PROD?
I then will create a branch and merge. The objective is to merge all into 1 branch. There are many files on PROD that have never been modified so maybe that will be easier, just search all commits for an exact match.
I use git-extensions.
ty.

A: One option would be to use git bisect to search over your old commits, at each step using a directory diff tool to compare the git working directory with PROD. If the working directory has new changes since PROD you want to keep, mark it good. If the working directory has old versions of files and you want the PROD version instead, mark it bad. Eventually you should find the commit that's closest to where PROD started - create a branch from there, copy over from PROD and you're good to go.

A: With no other information (and assuming your PROD machine's install isn't a git repository itself, which would make this quite simple), I'd probably just compare file creation timestamps with your DEV repo's commit history. Presumably your PROD machine's code was copied in a narrow window. It's also likely that you weren't committing while you were doing this copy. Simply use git log to find the commit timestamp right before the copy timestamp, then something like:
git checkout -B new_branch <hash_of_that_commit>    # Checks out 'new_branch' at that commit

Next, diff DEV and PROD, copying PROD changes back onto DEV either incrementally or as a batch. Commit with each increment or batch.
At that point you have a viable topic branch. You can merge or rebase it back into your master branch at your leisure.


text:
Q: Conditional dropdown for loop is not working in the expected way I had posted in Stack Exchange earlier; however, did not get much response from that yet; hence, posting it here.
I am trying to scrape some data using the following code. When I run the code line by line, it works fine. However, when I want to run all code at one go, the dropdown options go blank and as a result, the last line returns error. Your help would be much appreciated. The code is below.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
import os

path = os.path.join(r"D:\ScrapedData\TN\SocialAudit")
path_to_chromedriver = 'D:\ScrapedData/chromedriver'
options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : path}
options.add_experimental_option('prefs', prefs)
browser = webdriver.Chrome(chrome_options=options ,executable_path=path_to_chromedriver)

url = "http://mnregaweb4.nic.in/netnrega/SocialAudit/StateList.aspx"
browser.get(url)
browser.set_page_load_timeout(45)
browser.maximize_window()

browser.find_element_by_link_text("BIHAR").click()
browser.implicitly_wait(5)

year=['2016-2017', '2017-2018', '2018-2019', '2019-2020']
elem2 = browser.find_element_by_name("ctl00$ContentPlaceHolder1$ddlFin")
elem2.send_keys(year[0])
browser.implicitly_wait(5)

select_dist = browser.find_element_by_name("ctl00$ContentPlaceHolder1$ddldist")
options = [x for x in select_dist.find_elements_by_tag_name("option")]
dist=[]
for e in range(len(options)):
    select_dist = Select(browser.find_element_by_name("ctl00$ContentPlaceHolder1$ddldist"))
    select_dist.select_by_index(e)

    select_block = Select(browser.find_element_by_name("ctl00$ContentPlaceHolder1$ddlblock"))
    options1 = select_block.options
    for f in range(len(options1)):
        select_block = Select(browser.find_element_by_name("ctl00$ContentPlaceHolder1$ddlblock"))
        select_block.select_by_index(f)

        select_gp = Select(browser.find_element_by_name("ctl00$ContentPlaceHolder1$ddlpanchayat"))
        options2 = select_gp.options
        for g in range(len(options2)):
            select_gp =  Select(browser.find_element_by_name("ctl00$ContentPlaceHolder1$ddlpanchayat"))
            select_gp.select_by_index(g)

            browser.find_element_by_css_selector("#ctl00_ContentPlaceHolder1_rbLoginLevel_1").click()
            browser.implicitly_wait(10)

            elem6 = browser.find_element_by_name("ctl00$ContentPlaceHolder1$txtperiodFrom")
            elem6.send_keys('01/04/2016')
            browser.implicitly_wait(10)

            elem7 = browser.find_element_by_name("ctl00$ContentPlaceHolder1$txtperiodTo")
            elem7.send_keys('31/03/2017')
            browser.implicitly_wait(10)

            browser.find_element_by_css_selector("#ctl00_ContentPlaceHolder1_login").click()
            browser.implicitly_wait(10)

            browser.find_element_by_link_text("Download All Reports").click()

A: Besides that the target page is slower than an aged snail, and those 10 second waits are barely enough for anything, there are two things you missed an those caused your troubles:

*

*you did not take account that the first element of the select options are "select an option" types. So if you try to cycle trough all of them, you must ignore the option at the first index, else it will look like "nothing is selected"

*wait for that spinner. After the spinner is gone, page will be refreshed. Do not grab the elements before page refresh is complete, wait until the spinner is gone.

With these two helper functions it is possible to press the "Get Reports" button without issues:
def is_spinner_gone(arg):
    loaded_spinner = browser.find_element_by_xpath('//div[//div[@class="loader"]]')
    if loaded_spinner:
        return loaded_spinner.get_attribute('style') == 'display: none;'
    return True

def wait_for_element(xpath):
    # this is necessary because the spinner does not pop up instantly
    time.sleep(1)
    no_spinner =  WebDriverWait(browser, 500).until(is_spinner_gone)

    element = WebDriverWait(browser, 500).until(
        EC.element_to_be_clickable((By.XPATH, xpath)))
    return element

If you get your elements via the wait_for_element call then you'll be able to interact with them without error. I guess you know that pressing that button is not the end of the road yet, you'll have to choose the report format and who knows what later on.
Adjusted code:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
import os
import time

path = os.path.join(r"D:\ScrapedData\TN\SocialAudit")
path_to_chromedriver = 'D:\ScrapedData/chromedriver'
options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : path}
options.add_experimental_option('prefs', prefs)
browser = webdriver.Chrome(chrome_options=options ,executable_path=path_to_chromedriver)

start = time.time()
url = "http://mnregaweb4.nic.in/netnrega/SocialAudit/StateList.aspx"
browser.get(url)
browser.set_page_load_timeout(45)
browser.maximize_window()

loaded = time.time()
print(f'PAGE LOADED IN {loaded-start} seconds')

browser.find_element_by_link_text("BIHAR").click()

def is_spinner_gone(arg):
    loaded_spinner = browser.find_element_by_xpath('//div[//div[@class="loader"]]')
    if loaded_spinner:
        return loaded_spinner.get_attribute('style') == 'display: none;'
    return True

def wait_for_element(xpath):
    # this is necessary because the spinner does not pop up instantly
    time.sleep(1)
    no_spinner =  WebDriverWait(browser, 500).until(is_spinner_gone)

    element = WebDriverWait(browser, 500).until(
        EC.element_to_be_clickable((By.XPATH, xpath)))
    return element

year=['2016-2017', '2017-2018', '2018-2019', '2019-2020']
elem2 = wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$ddlFin"]')
selector_page_loaded = time.time()
print(f'WORK AREA LOADED IN {selector_page_loaded-loaded} seconds')

elem2.send_keys(year[0])

select_dist = wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$ddldist"]')
options = [x for x in select_dist.find_elements_by_tag_name("option")]
dist=[]
# ISSUE: default fields are included in the options!
for e in range(1,len(options)):
    select_dist = Select(wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$ddldist"]'))
    select_dist.select_by_index(e)

    select_block = Select(wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$ddlblock"]'))
    options1 = select_block.options
    for f in range(1, len(options1)):
        select_block = Select(wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$ddlblock"]'))
        select_block.select_by_index(f)

        select_gp = Select(wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$ddlpanchayat"]'))
        options2 = select_gp.options
        for g in range(1, len(options2)):
            select_gp = Select(wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$ddlpanchayat"]'))
            select_gp.select_by_index(g)

            wait_for_element('//*[@id="ctl00_ContentPlaceHolder1_rbLoginLevel_1"]').click()

            elem6 = wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$txtperiodFrom"]')
            elem6.send_keys('01/04/2016')

            elem7 = wait_for_element('//*[@name="ctl00$ContentPlaceHolder1$txtperiodTo"]')
            elem7.send_keys('31/03/2017')

            wait_for_element('//*[@value="Get Reports"]').click()
            print(f'FIRST RUN IN {time.time()-selector_page_loaded}')


text:
Q: Cordova Plugin Geolocation Timeout on IOS 11 I visited all links about this problem and none helped me.
I get the error code 3 (timeout) in response always when execute the method "getCurrentLocation" from "cordova-plugin-geolocation" on IOS .
follow my code:
getCurrentPosition() {
 return new Promise(function (resolve, reject) {
  document.addEventListener("deviceready", function(){
    navigator.geolocation.getCurrentPosition((position) => {
      resolve(position);
    }, (error) => {
      reject(error);
    }, {
      timeout: 10000
    });
  }, false);
 });
}

I upgraded all plugins and engines and the error persisted.
Follow my current versions:

*

*cordova 8.0.0;

*cordova-ios 4.5.4;

*cordova-android 7.0.0;

*cordova-plugin-geolocation 4.0.0.

A: After the hardwork, I found the fix. I added the follow keys in "/platform/ios/{project_name}/{project_name}-Info.plist":
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>My app requires constant access to your location, even when the screen is off.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>My app requires constant access to your location, even when the screen is off.</string>


text:
Q: How to perform pattern recognition across parameters and interpolate it using Python? Let's say there is a simple sinusoidal data according to a parameter.
For a parameter a = [1, 2, 3, ..., 18, 19, 20],
2-D temporal data exists where,
y(a, t) = a*sin(a*t + a)           (t=time)
So, amplitude, frequency, and phase of the 2-D data, y(a,t) changes according to a parameter a.
I want to build a network that is capable of recognizing the pattern and interpolate data y(a,t) according to the parameter a.
For instance, I would like to get y(a=10.5, t).
I've tried LSTMs (seq2seq, autoencoder, etc) but had no luck. From my research so far, it looks like Python/TensorFlow does not have modules that can handle both interpolation of a parameter and pattern recognition.