text:
Q: How to map a MainValue property using Fluent or LinqToNHibernate? I have a one to many relationship between my product and image entities. What I'm trying to achieve is to map a main image in the product entity, using Fluent mapping or LinqToNHibernate.
My classes:
public class Product {
    public virtual int Id { get; set; }
    public virtual IList<Image> images { get; set; }
}

public class Image {
    public virtual int Id { get; set; }
    public virtual Product Product { get; set; }
    public virtual bool IsMain { get; set; }
}

My mappings:
public class ProductMap : ClassMap<Product> {
    public ProductMap() {
        Id(x => x.Id);
        HasMany(x => x.images).KeyColumn("id_product");
    }
}

public class ImageClassMap : ClassMap<Image> {
    public ImageClassMap() {
        Table("product_image");
        Id(x => x.Id);
        References(x => x.Product, "id_product");
        Map(x => x.IsMain).Column("is_main");
    }
}

I was able to achieve this with QueryOver as follows:
Image imageAlias = null;
var product = session.QueryOver<Product>()
    .Where(x => x.Id == 2)
    .Left.JoinQueryOver(x => x.images, () => imageAlias, x => x.IsMain)
    .SingleOrDefault();

Is it possible to have a MainImage property in the Product class, where IsMain property is true, using Fluent mapping or LinqToNHibernate?

A: Yes, you can try,
public class Product {
    ...
    public Image MainImage { get; set; }
}

and then the mapping,
public ProductMap() {
    ...
    HasOne(product => product.MainImage).KeyColumn("main_image_id");
}


text:
Q: "1º Noun + 2º Noun " or "2º Noun + of the + 1º Noun"? I know this must be a simple question, but I really can't find (probably I don't know how express this question to search in google) the explanation for this.
In the phrase:
    Full Coverage of the Industry
Could we say:
    Industry Full Coverage
Is there a correct way or any rules that can help us this and in other similar cases?? Usually I use what sounds right for me, but I'm never sure of what is the correct one

Same thing for
Car Manufacters of Passenger vehicles or Passenger vehicles car manufacters
Thank you all

A: "Full Industry Coverage" would be ok. In such a case, all of the nouns other than the first one are being used as adjectives. A list showing the order in which a string of adjectives normally appear can be found here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parsing XML Data in a loop to create multiple objects in Python 3 I have the following XML structure:
<celestialBodies>
<stars>
    <star>
        <item name="Name">Sun</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </star>
</stars>
<planets>
    <planet>
        <item name="Name">Mercury</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Venus</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Earth</item>
        <item name="Distance from the Earth">0</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Mars</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Jupiter</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Saturn</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Uranus</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Neptune</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Pluto</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
</planets>
</celestialBodies>

and I would like to read each of these into a created object in Python 3.
I have the following loop:
# Create the solar system
celestialBodies = list()
for i in range(10):
    planet = Planet("Mercury", 1000000, 0.5, 0.1, ['Moon A', 'Moon B'], ['Hydrogen, Nitrogen'], 8, 0.15)
    celestialBodies.append(planet)

but as you can see, instead of hardcoding the planets myself, I would like to get the data from the XML file in a nice way. So instead of me saying "Mercury", it should traverse through the tree and get the values of each celestial body into the variables and create the object.
What I can't get it through is the XML reading part. No matter what I tried I could not loop through the levels to read the values into the variables. I've already tried BeautifulSoup, lxml, ET but no luck.
Some trials:
   root = lxml.etree.fromstring('planet_info.xml')
   results = root.findall('planets')
   textnumbers = [r.find('planet/name').text for r in results]
   print(textnumbers)

or
solarSystem = ET.parse('planet_info.xml')
celestialBodies = solarSystem.getroot()
for bodies in celestialBodies:
    for star in bodies[0]:
        print(star.tag, star.attrib, star.nodeValue)

with each resulting with errors. There should be a straightforward way of doing this.
Any suggestions?
EDIT: So with the following I am able to reach the two children but no more:
   # Get the data from the XML
   solarSystem = ET.parse('planet_info.xml')
   celestialBodies = solarSystem.getroot()
   for bodies in celestialBodies:
       print(bodies.tag, bodies.attrib)

output:
stars {}
planets {}

How to loop inside these and retrieve the values though?

A: This code using etree works. You are missing one line that returns only the item elements which have name set to some value.
import xml.etree.ElementTree as ET

root = ET.parse(PATH_TO_YOUR_FILE)
planets = root.findall('./planets/planet')

planets_list = []
for planet in planets:
        name = planet.find("./item[@name='Name']").text
        d = planet.find("./item[@name='Distance from the Earth']").text
        //...
        planets_list.append(Planet(name, d, ...)

From here you should be able to solve the rest yourself. Hope it helps.

A: Firstly you can find planets and stars elements, add them to list and choose first values from it.
import xml.etree.ElementTree as ET
dump = ET.parse('planet_info.xml')
root = dump.getroot()
planet_name = star_name = planet_list = []
for content in root:
    planet_name = content.findall("planet")
    star_name = content.findall("star")
    if planet_name:
        for planet in planet_name:
             planet_list.append(Planet(planet[0].text, planet[1].text, etc)
    elif star_name:
        for star in star_name:
            planet_list.append(Planet(star[0].text, star[1].text, etc)
    else:
        print("Nothing")

A: Here''s a simple way to iterate over that data structure. To keep the code self-contained, I read the XML directly from a string, rather than from a file.
import xml.etree.ElementTree as ET

data = '''\
<?xml version="1.0"?>
<celestialBodies>
<stars>
    <star>
        <item name="Name">Sun</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </star>
</stars>
<planets>
    <planet>
        <item name="Name">Mercury</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Venus</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Earth</item>
        <item name="Distance from the Earth">0</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Mars</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Jupiter</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Saturn</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Uranus</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Neptune</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
    <planet>
        <item name="Name">Pluto</item>
        <item name="Distance from the Earth">100000</item>
        <item name="Size">9</item>
        <item name="Moons">A,B,C</item>
        <item name="Gravity">0.4</item>
        <item name="Elements Found">H, HE, C</item>
        <item name="Orbiting Time">15</item>
        <item name="Day Time">12</item>
    </planet>
</planets>
</celestialBodies>
'''

root = ET.fromstring(data)

for kind in root:
    print(kind.tag)
    for child in kind:
        print(' '*2, child.tag)
        for item in child:
            print(' '*4, '{!r}: {!r}'.format(item.attrib['name'], item.text))
        print()

output
stars
   star
     'Name': 'Sun'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE'
     'Orbiting Time': '15'
     'Day Time': '12'

planets
   planet
     'Name': 'Mercury'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Venus'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Earth'
     'Distance from the Earth': '0'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Mars'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Jupiter'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Saturn'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Uranus'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Neptune'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

   planet
     'Name': 'Pluto'
     'Distance from the Earth': '100000'
     'Size': '9'
     'Moons': 'A,B,C'
     'Gravity': '0.4'
     'Elements Found': 'H, HE, C'
     'Orbiting Time': '15'
     'Day Time': '12'

This variation loads the data into a dictionary containing two lists, one for stars & one for planets. Each of those lists contains a dictionary for each body found in that category. We can use the json module to print the data nicely.
import xml.etree.ElementTree as ET
import json

root = ET.fromstring(data)

bodies = {}
for kind in root:
    bodies[kind.tag] = bodylist = []
    for child in kind:
        bodylist.append({item.attrib['name']: item.text for item in child})

print(json.dumps(bodies, indent=4))

output
 {
    "stars": [
        {
            "Name": "Sun",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE",
            "Orbiting Time": "15",
            "Day Time": "12"
        }
    ],
    "planets": [
        {
            "Name": "Mercury",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Venus",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Earth",
            "Distance from the Earth": "0",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Mars",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Jupiter",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Saturn",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Uranus",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Neptune",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        },
        {
            "Name": "Pluto",
            "Distance from the Earth": "100000",
            "Size": "9",
            "Moons": "A,B,C",
            "Gravity": "0.4",
            "Elements Found": "H, HE, C",
            "Orbiting Time": "15",
            "Day Time": "12"
        }
    ]
}


text:
Q: Code not running properly The code I have below is supposed to run the number of words that start with a certain letter, but when I run it, the counts are all 0, instead of what they should be: {'I': 2, 'b': 2, 't': 3, 'f': 1}. I appreciate any help. Thanks!
def initialLets(keyStr):
        '''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper
        and lower case letters should be considered different letters.'''
        inLets = {}
        strList = keyStr.split()
        firstLets = []
        for words in strList:
            if words[0] not in firstLets:
                firstLets.append(words[0])
        for lets in firstLets:
            inLets[lets] = strList.count(lets)
        return inLets

text = "I'm born to trouble I'm born to fate"
print(initialLets(text))

A: You can try this:
text = "I'm born to trouble I'm born to fate"
new_text = text.split()
final_counts = {i[0]:sum(b.startswith(i[0]) for b in new_text) for i in new_text}

Output:
{'I': 2, 'b': 2, 't': 3, 'f': 1}

A: You don't have a counter as you append the letter but not its number of occurrences.
So to simplify:
def initialLets(keyStr):
        '''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper
        and lower case letters should be considered different letters.'''

        strList = keyStr.split()

        # We initiate the variable that gonna take our results
        result = {}

        for words in strList:
            if words[0] not in result:
                # if first letter not in result then we add it to result with counter = 1
                result[words[0]] = 1
            else:
                # We increase the number of occurence
                result[words[0]] += 1

        return result

text = "I'm born to trouble I'm born to fate"
print(initialLets(text))

A: Firstly, you are checking if the first letter of the word is in the list before putting it in. That would just make the list comprise of only 1 of each letter. Secondly, your strList is a list of each word, instead of inLets[lets] = strList.count(lets), it should be inLets[lets] = firstLets.count(lets)... While your current code isn't the cleanest way to do it, this minor modification would have worked.
def initialLets(keyStr):
    '''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper
    and lower case letters should be considered different letters.'''
    inLets = {}
    strList = keyStr.split()
    firstLets = []
    for words in strList:
        firstLets.append(words[0])
    for lets in firstLets:
        inLets[lets] = firstLets.count(lets)
    return inLets

text = "I'm born to trouble I'm born to fate"
print(initialLets(text))


text:
Q: Xml Serialization: Is there a way to control xml declaration using attribute(s) Is there a way to control/tweak xml declaration while serializing an object using attributes in the class.
In other words I am searching for attribute(s) in C# that can be used to decorate my class and will help in tweaking the xml declaration part(attributes in it) while serializing an object of that class. I know that there is a class XmlDeclaration that can be used to achieve it, however I want to achieve the same result using attributes, which I think is cleaner as different processing instruction stays with the POCO classes and which can be varied across different POCO classes.
Kindly let me know if there is any out-of-the-box feature/custom solution for that or this is just another stupid question... :)

A: As your comment notes you are talking about the XML Declaration
<?xml …>

that can start an XML document.
It appears the direct answer is No: there is no XmlDocumentAttribute or something similarly named in the System.Xml.Serialization namespace.
However, there is no need to have the XML serialisation engine write directly to a file. Rather write to an XmlWriter you have correctly configured to write the XML declaration you want (including none). Then pass that writer to the right Serialize method overload.
See this answer for overriding the default encoding in the XML Declaration.
(While this doesn't answer you question—how to do this with attributes in your POCO types—one can argue that the XML Declaration is all about how the XML in the file is encoded so correctly belongs with the file writing/reading code, not the serialisation code.)

A: You would need to override the default XmlWriterSettings and set the OmitXmlDeclaration property to true e.g.
XmlWriterSettings writerSettings = new XmlWriterSettings
{
    OmitXmlDeclaration = true
};
using (StringWriter strWriter = new StringWriter())
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
    XmlSerializer serializer = new XmlSerializer(typeof(myObject));
    serializer.Serialize(xmlWriter, myObject);
}

Turns out StringWriter defaults to UTF-16, if you need control over the encoding you would need to derive your own StringWriter, there is a good example of how to do that already.


text:
Q: The statement has been terminated I have a table for which a update stored procedure has been created.
For this table I created an update trigger. But when I either execute the stored procedure or execute an update query I am getting this error message:

Msg 8152, Level 16, State 14, Procedure OperationHistory, Line 95
  String or binary data would be truncated.
  The statement has been terminated.

Create Trigger OperationHistory on [dbo].[Employee]
For Update
AS
Declare @EmployeeID int;
Declare @Employeename varchar(100);
Declare @SSN bigint;
Declare @Phonenumber bigint;
Declare @JoinDate Date;
Declare @OperationHistory varchar(100);
Declare @Operationtimestamp Datetime;

select @EmployeeID=i.EmployeeId from inserted i;
select @Employeename=i.Employeename from inserted i;
select @SSN=i.SSN from inserted i;
select @Phonenumber=i.Phonenumber from inserted i;
select @JoinDate=i.JoinDate from inserted i;

If Update (EmployeeId)
Set @OperationHistory='updated employee id';
If Update (Phonenumber)
Set @OperationHistory='updated phonenumber';
If Update (SSN)
Set @OperationHistory='updated SSN';
If Update (Employeename)
Set @OperationHistory='updated employeename';
If Update (JoinDate)
Set @OperationHistory='updated JoineDate';

Insert into Employee_History
Values(@EmployeeID,@Employeename,@SSN,@Phonenumber,@JoinDate,@OperationHistory,getdate())

Go

A:
Insert into Employee_History
  Values(@EmployeeID,@Employeename,@SSN,@Phonenumber,@JoinDate,@OperationHistory,getdate())

Make sure the column order of the Employee_History table matches the order of the variables listed.  The best practice is to list column names on INSERT statements.
The other possible cause is that the EmployeeName column in the Employee_History is shorter than 100 characters.
Importantly, as suggested in the comments, triggers fire once per statement instead of once per row so must be coded to handle multi-row inserts.  The history table insert should be refactored as INSERT INTO Employee_History(column-list) SELECT column-list FROM inserted  Not related to this error, though.
Also, there are a number of other errors in the trigger.  An UPDATE statement can update multiple columns yet the trigger code identifies only one the potentially changed columns.  The UPDATED function in an UPDATE trigger does not indicate the value has changed, only that it specified in the SET clause of the UPDATE statement.  This may cause erroneous messages in the history table.


text:
Q: Laravel forms broken after including Vue I am in the process of adding real-time messaging functionality to a Laravel 6.x site. The messaging seems to be working, but as soon as I include
 just after the main menu, some of the existing forms stop working. E.g., this form:

        <form id="form-status{{$task->id}}" action="{{ url('xxx') }}" method="POST" style="display: none;">
          @csrf
          id}}">Status:
          <select class="form-control" id="status{{$task->id}}" name="status">
            <option value="0" selected="selected">Not started</option>
            <option value="10">Started</option>
            <option value="20">Finished</option>
          </select>
        </form>

  id}}').submit();"> Update

The post action is still executed, but I get a 419 "page expired" error, so I assume the csrf value is not sent with the post data anymore.
Does anyone know why this may be happening? For now, I've moved the APP id to a small section of the website with no pre-existing forms, but in future I would like to have more Vue components on the page, so I will have to fix it at some stage.
I am using Bootstrap 3, so I removed Bootstrap 4 in Laravel using npm, and I import it using a script tag. The HTML header includes:
  <link href="http://myurl/css/bootstrap.min.css" rel="stylesheet">
  <link href="http://myurl/css/reset.css" rel="stylesheet">
  <link href="http://myurl/css/dashboard.css" rel="stylesheet">
  <link href="http://myurl/css/sticky-footer-navbar.css" rel="stylesheet">
  <link href="http://myurl/css/bootstrap-datepicker.css" rel="stylesheet">

Thanks,
Hendrik.
EDIT:
The html sent to the client is as follows:

        <form id="form-status94" action="myurl/projects/35/nodes/68/tasks/94/status" method="POST" style="display: none;">
          <input type="hidden" name="_token" value="7ynFCghH2yNGpaO5Pfpd45EMYGIQHdXdNjYooNtJ">
          Status:
          <select class="form-control" id="status94" name="status">
            <option value="0" selected="selected">Not started</option>
            <option value="10">Started</option>
            <option value="20">Finished</option>
          </select>
        </form>

  Update

A: Your curly braces conflict with Vue.js. There's a Blade & JavaScript Frameworks section in Laravel's documentation, saying:

Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

Laravel

Hello, @{{ name }}.

In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.


text:
Q: WPF Combobox box keeps closing when mouse over the non selected item I have an Excel addin that uses some WPF / XAML to render a Combobox in a grid. When I click on the Combo it drops down the other items but when I mouse down to select the second option in the drop down it closes. I can select other items using the keyboard or mouse scroll wheel when the combo is closed.
The issue only happens on my machine or a HyperV machine hosted by that same machine. The exact version of the code works fine on a remote Azure VM. All 3 are Windows 10.


text:
Q: How to pre-calculate, in C++, a template type and use it in different modules I have an compiler optimisation problem.
Let A, B, C three classes and static_update_manager another class yet implemented.
The static_update_manager have to be used as follow:
typedef typename static_update_manager<A>::type manager_t;

The definition of manager_t is placed inside a header file called manager.hpp and
that header is used by lots of modules.
During the compilation process, static_update_manager::type is calculated
and replaced by
static_update_manager_lst< boost::mpl::vector<A, B, C> >

The time to calculate the type of manager_t is very long and take lots of memory.
The problem is that all the modules are performing that calculus.
But, in fact, we need to do that work just one time.
Is there a C++ mechanism to do that ?
One idea could be to use gcc to convert the file manager.hpp to another file
manager_compiled.hpp looking like :
typedef typename static_update_manager_lst< boost::mpl::vector<A, B, C> > manager_t;

and to use manager_compiled.hpp in all the modules instead of manager.hpp.
But I don't know how to do that correctly.
I have an horrible solution :
 the idea is to make a script, compiling a source code with an error containing
 the type of manager_t, and then, axtract the calculated type with grep in
 order to construct the header manager_compiled.hpp.


text:
Q: What is the difference between Advisor and Aspect in AOP? I am new to Spring AOP. Based on my understanding, I noticed that both Advisor (for example DefaultPointcutAdvisor) and Aspect (for example the class annotated with @Aspect) can both help to solve the cross-cutting problem by doing something more when a method is invoked.
What is the different between these two term please?

A: Most aspects are a combination of advice that defines the
aspect's behavior and a pointcut defining where the aspect should be executed.
Spring recognizes this and offers advisors, which combine advice and pointcuts
into one object.
More specifically, the PointcutAdvisor does this.
public interface PointcutAdvisor {
   Pointcut getPointcut();
   Advice getAdvice();
}

Most of Spring's built-in pointcuts also have a corresponding PointcutAdvisor.
This is convenient if you want to define a pointcut and the advice it is managing
in one place.
Read more in Spring in Action, 3rd Edition
Sanpshots

A: Advisors seem to be an old "AOP lite" type of defining cross-cutting concerns from Spring 1.2 when Java 5 usage was still somewhat uncommon and thus @AspectJ syntax (via Java annotations) not used in Spring. The concept has still survived for lovers of schema-based AOP rather than annotation-based AOP or pure AspectJ syntax, see Spring documentation on advisors.

The concept of "advisors" comes from the AOP support defined in Spring and does not have a direct equivalent in AspectJ. An advisor is like a small self-contained aspect that has a single piece of advice. The advice itself is represented by a bean and must implement one of the advice interfaces described in Advice Types in Spring. Advisors can take advantage of AspectJ pointcut expressions.

A: In my understanding, Aspect is just Aspect Oriented Programming jargon and Advisor is Spring Framework jargon.
Maybe this simple example will be helpful:
Foo.java
public interface Foo {
    void foo();
    void baz();
}

FooImpl.java
public class FooImpl implements Foo {
    @Override
    public void foo() {
        System.out.println("Foo!");
    }

    @Override
    public void baz() {
        System.out.println("Baz!");
    }
}

MethodBeforeAdviceBarImpl.java
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class MethodBeforeAdviceBarImpl implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("Bar!");
    }
}

and finally App.java
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;

public class App {

    public static void main(String[] args) {
        final MethodBeforeAdvice advice = new MethodBeforeAdviceBarImpl();

        final NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor = new NameMatchMethodPointcutAdvisor();
        nameMatchMethodPointcutAdvisor.setMappedName("foo");
        nameMatchMethodPointcutAdvisor.setAdvice(advice);

        final ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.addAdvisor(nameMatchMethodPointcutAdvisor);

        final Foo foo = new FooImpl();
        proxyFactory.setTarget(foo);

        final Foo fooProxy = (Foo) proxyFactory.getProxy();
        fooProxy.foo();
        fooProxy.baz();
    }
}

Running the main method in App.java will output:
Bar!
Foo!
Baz!

So as you see here NameMatchMethodPointcutAdvisor is an Advisor and it consists of a mappedName, which is the pointcut and the Advice itself, which in this case is MethodBeforeAdvice.
And in Aspect Oriented Programming Jargon, an Aspect is Advice + Pointcut, so there you go.. An Advisor seems to be an Aspect after all..

A: Advice is the way you take an action on your Pointcut. You can use before, after or even around advice to apply any action you defined. Talking about Spring Aspect, it is only a class which is a high level and merge two concepts : joinpoint and advice. It can be done through XML based blueprint, or programmatically. Also you should specify your point where you want to plug in an aspect, it is done by using Joinpoint.
Also Spring Aspects and Advice aren't substitute for each other, because Aspects is only merger for joinpoint and advice.


text:
Q: why are stdout_lines [1,2] and [3,4] strings instead of arrays? A shell command outputs one array per line on the standard output: [1,2] then [3,4]. I would like to use each element of the array as a parameter to a module and decided to loop over stdout_lines. However, item.0 and item.1 contains the first and second character of the string instead of the first and second element of the array.

*

*Why is item a string instead of an array?

*What would be the most elegant way to get what I need?

Here is a reproducer to help understand the question, using ansible 2.7.5. The following play:
---
- name: test
  hosts: localhost
  become: false
  gather_facts: false

  tasks:
    - name: one array per line
      shell: |
        echo '[1,2]'
        echo '[3,4]'
      register: result

    - name: each item is an array
      debug:
        msg: "{{ item }}"
      loop: "{{ result.stdout_lines }}"

    - name: accessing the first element of an item
      debug:
        msg: "{{ item.0 }} => {{ item.1 }}"
      loop: "{{ result.stdout_lines }}"

The actual output is:
TASK [each item is an array] *****************************************************
ok: [localhost] => (item=[1, 2]) => {
    "msg": [
        1,
        2
    ]
}
ok: [localhost] => (item=[3, 4]) => {
    "msg": [
        3,
        4
    ]
}

TASK [accessing the first element of an item] ************************************
ok: [localhost] => (item=[1, 2]) => {
    "msg": "[ => 1"
}
ok: [localhost] => (item=[3, 4]) => {
    "msg": "[ => 3"
}

but I was expecting:
TASK [each item is an array] *****************************************************
ok: [localhost] => (item=[1, 2]) => {
    "msg": [
        1,
        2
    ]
}
ok: [localhost] => (item=[3, 4]) => {
    "msg": [
        3,
        4
    ]
}

TASK [accessing the first element of an item] ************************************
ok: [localhost] => (item=[1, 2]) => {
    "msg": "1 => 2"
}
ok: [localhost] => (item=[3, 4]) => {
    "msg": "3 => 4"
}

A: An option would be to convert the list of strings to the list of lists.
    - name: convert strings to lists
      set_fact:
        lists: "{{ lists }} + [ {{ item }} ]"
      loop: "{{ result.stdout_lines }}"

    - name: accessing the 1st and 2nd element of a list
      debug:
        msg: "{{ item.0 }} => {{ item.1 }}"
      loop: "{{ lists }}"

A: After discussions with Pilou on #ansible-fr@irc.freenode.net, a simple solution was found.
It is enough to trigger a jinja2 evaluation by assigning another variable with the content of item. It will be converted from string to a structure, if possible. See the test playbook updated with the solution below.
      debug:
        msg: "{{ array.0 }} => {{ array.1 }}"
      vars:
        array: "{{ item }}"
      loop: "{{ result.stdout_lines }}"

There is no rationale explaining why stdout is converted into a structure when possible but not the elements in stdout_lines. It is how the shell module is implemented. It is possible that it will change in the future. If that's the case, the proposed solution will keep working. Only it would not be necessary.
---
- name: test
  hosts: localhost
  become: false
  gather_facts: false

  tasks:
    - name: one array per line
      shell: |
        echo '[1,2]'
        echo '[3,4]'
      register: result

    - name: each item is an array
      debug:
        msg: "{{ item }}"
      loop: "{{ result.stdout_lines }}"

    - name: accessing the first element of an item
      debug:
        msg: "{{ array.0 }} => {{ array.1 }}"
      vars:
        array: "{{ item }}"
      loop: "{{ result.stdout_lines }}"


text:
Q: Pspice simulation problem What is a convergence problem? My circuit code is below and when I simulate it is saying that the NMOS transistors MPDA and MPDB are not converging. See the following screenshot:

Here's the netlist:
V1 1 0 DC 5V
V2 2 0 PULSE(0 5 3ns 3ns 3ns 20ns 40ns)
V3 3 0 PULSE(0 5 6ns 3ns 3ns 20ns 40ns)
CL 4 0 0.15PF
MPUA 4 2 1 1 IRF150
MPUB 4 3 1 1 IRF150
MPDA 4 2 5 0 IRF250
MPDB 5 3 0 0 IRF250
.MODEL IRF250 NMOS (level=3 w=4u l=3u vto=1.0 tox=470e-10 nsub=38e14 cj=160e-6
+cjsw=430e-12 mj=0.5 mjsw=0.33 kp=30e-6)
.MODEL IRF150 PMOS (level=3 w=10u l=3u vto=-1.0 tox=470e-10 nsub=8.7e14 cj=100e-6
+cjsw=180e-12 mj=0.5 mjsw=0.33 kp=12e-6)
.TRAN 1ns 80ns
.PROBE V(2,0) V(3,0) V(CL) ID(MPDA) ID(MPUA)
.END

A: I imported the netlist into LTSpice and it worked ok (I only had to rename V(CL) to V(4) in the .PROBE directive, since LTSpice didn't recognize that syntax to specify the voltage across the cap):

The results of the simulation are shown below:

Therefore there is nothing inherently wrong with your netlist. Probably the simulation engine of PSPICE didn't succeed to find a solution for the equations. Try to fiddle with the simulation accuracy parameters (I don't use PSPICE, so I cannot help with that).


text:
Q: How to Drag a formula in Excel both across the columns and rows? I have an Excel 2007 file with 2 sheets. The first sheet has 2 columns: one of dates, one of numbers like so:
1/1/2017    37
1/2/2017    82
1/3/2017    96
...

The second sheet has is to store the numbers in a "Calendar-like" fashion, like so:
                     SUN   MON   TUE   WED   THR   FRI   SAT
1/1/2017-1/7/2017    37    82    96    23    54    25    97
1/8/2017-1/14/2017   49    76    65    13    12    14    96
...

I am filling the "Calendar" style sheet from the much larger "List" style sheet. These go on for years, so I need a simple way to fill the "Calendar" style sheet from the plain list. I can use the simple formula of =sheet1!D7 to get from one sheet to the other, but I can only drag that formula in one direction... I can start it on Sunday, Jan 1 and drag it the whole way to Saturday, Jan 7, but if I try to drag the formula from that row to the next, it tries to insert starting with Jan 2 instead of Jan 8:
                     SUN   MON   TUE   WED   THR   FRI   SAT
1/1/2017-1/7/2017    37    82    96    23    54    25    97
1/8/2017-1/14/2017   82    96    23    54    25    97    61
...

Can I get these values  from the list-type sheet to the calendar-type sheet without typing the formula in for each and every cell?

A: Not sure how your data is laid out, but if you adjust the range, this index/match should work:
=INDEX($B$1:$B$31,MATCH(DATEVALUE(LEFT($E3,SEARCH("-",$E3)-1))+COLUMN()-6,$A$1:$A$31,FALSE))

Note: I have one magic number in the formula, a 6.  This is because this is where your "Sun" column starts.  If you put your formula in any other column, adjust that number.  Alternatively, you could get fancy and add logic looking for "Sun" in some array, but thought that's a little overkill.
You can drag this formula over and down.


text:
Q: What happens when Trundle uses his ultimate on someone with negative armor? Suppose, due to armor reduction, someone managed to get negative armor. Trundle's ultimate says:
(Active): Trundle immediately steals health (by dealing magic damage) and a percentage of their armor and magic resistance from his target. Over the next 6 seconds the amount of health, armor, and magic resistance stolen is doubled.
Does Trundle just steal 0 armor? Does he receive negative armor as well? Or is it based off of base values?

A: If a champion has less than 0 armor, they receive bonus damage.  The damage formula:

2-(100/(100-armor))

If Trundle uses his ult on a champion, he lowers their armor by a percent.  This prevents him from dropping an enemy's armor below 0 with his ult alone.  With a Black Cleaver or other form of armor reduction, it would be possible to do bonus damage (use the ult THEN get stacks on the cleaver!).
Edit:
Armor penetration is applied in this order (source):

*

*Percent reduction (Bushwhack / Pounce)

*Flat reduction (The Black Cleaver, Puncturing Taunt, etc)

*Flat penetration (The Brutalizer, Sunder Mastery, Runes of Desolation)

*Percent penetration (Last Whisper)

A: I think that this question is more a curiosity than a real need. Trundle is an anti-tank and it would be quite silly using his ultimate on an unarmored squishy hero.
In addition percentage stolen is 15/20/25% and it is usually difficult to cause an enemy champion to have negative armor values lesser than -20. In this case have a 0 armor buff or a -3/-4/-5 armor debuff is quite irrelevant in terms of gameplay.

A: Look here
Accordingly, there is no such thing as negative armor in LoL.

These attacks will deal damage as though your target has less armor than he really does, but will never bring an opponent below 0 armor. For example, if a target has 20 armor and you have 5 armor penetration, you would deal damage as though the target had 15 armor. If you had 50 armor penetration against the same target, you would deal damage as though he had 0 armor.


text:
Q: Ubuntu 12.04 and 3D
Possible Duplicate:
How do I tell if Ubuntu supports hardware-accelerated graphics on my laptop?

In My sony Vaio, the graphic card is 'Advanced Micro Devices [AMD] nee ATI RV710 [Mobility Radeon HD 4500/5100 Series]'. I am not able to use the 3d effects in ubuntu 12.04.

A: This answer should tell you whether your graphics card is capable of running unity in 3D


text:
Q: How to test mat-select components with karma my component:
@Component({
  selector: 'p-dropdown',
  template: `
<mat-form-field *ngIf="settings">
  <mat-select [value]="settings.selected" [compareWith]="compareFn" [placeholder]="placeholder">
      <mat-option *ngFor="let option of settings.options" [value]="option"> {{option.name}} </mat-option>
  </mat-select>
</mat-form-field>

my test:
fdescribe('Drodown Component', () => {
  let component: TestHostComponent;
  let fixture: ComponentFixture<TestHostComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [TestHostComponent, DropdownComponent],
      imports:[materialModule,BrowserAnimationsModule]
    }).compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(TestHostComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  fit('should show placeholder', () => {
    const el: HTMLElement = fixture.nativeElement;
    fixture.detectChanges();
    const p = el.querySelector('.mat-form-field-label');
    expect(p.textContent).toEqual('name2');
  });
});
@Component({
  selector: `host-component`,
  template: `<p-dropdown [settings]="settings"></p-dropdown>`
})
class TestHostComponent {
  settings = {options:[{_id:1,name:'name1'}, {_id:2,name:'name2'}], selected:{_id:2,name:'name2'}}
}

'p-dropdown' work well in serve, but for some reason, not work in my testing.
In debug, i can see the p-dropdown setting as well, so i don't understand what the problem is.


text:
Q: How to display methods in the console that read from a file? I need to be able to display the Average, ColumnTotal, Highest/Lowest in row, RowTotal. I'm not sure whether it depends on something I did in the methods themselves that has to be changed, or if I can simply that call them with the correct arguments to read from a file. The text file that it reads from basically just inputs two integers that are separated by a space on the same line, those are the arguments I would like to be able to input. I'm not entirely sure how to do this. This is just an assignment from a College text book basically amped up by my Instructor called "TwoDimArray" which I've been able to find many examples of online but none of them had the 'read from file' portion that I have to do here, they all just used a normal array input such as "int[][] array = {{22, 37, 48, 68}} for the main method. I'm going to include the entire program in order to show exactly what I need to be displayed via println.  I've been thinking about how to do this for quite a few hours now and decided that I definitely need help. Any help would be greatly appreciated! Thanks ahead of time.
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TwoDimArray {

private int arr[][];

public TwoDimArray() {
    loadArray();
}

public void loadArray(){
    /**
     * loadArray() method loads user defined filename
     * @return text file's contents
     */
    String fileName = "";
    try {
        fileName = JOptionPane.showInputDialog("Enter file name: ");
    }
    catch (Exception e){
        JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
        return;
    }
    try {
        Scanner in = new Scanner(new File(fileName));
        int rows, cols;
        rows = in.nextInt();
        cols = in.nextInt();
        arr = new int[rows][cols];
        for(int i = 0; i < rows; ++i){
            for(int j = 0; j < cols; ++j){
                arr[i][j] = in.nextInt();
            }
        }
        in.close();
    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
    }
}

public int getArrayMaxValue(){
    /**
     * @return the max vale of the array
     */
    int maxVal = Integer.MIN_VALUE;
    for(int i = 0; i < arr.length; ++i){
        for(int j = 0; j < arr.length; ++j){
            if(arr[i][j] > maxVal){
                maxVal = arr[i][j];
            }
        }
    }
    return maxVal;
}

public int getArrayMinValue(){
    /**
     * @return the minimum value of the array
     */
    int minVal = Integer.MAX_VALUE;
    for(int i = 0; i < arr.length; ++i){
        for(int j = 0; j < arr.length; ++j){
            if(arr[i][j] < minVal){
                minVal = arr[i][j];
            }
        }
    }
    return minVal;
}

public static int getTotal(int[][] array) {
    int total = 0;

    for (int row = 0; row < array.length; row++) {
        for (int col = 0; col < array[row].length; col++) {
            total += array[row][col];
        }
    }

    return total;
}

public static int getAverage(int[][] array) {
    return getTotal(array) / getElementCount(array);
}

public static int getRowTotal(int[][] array, int row) {
    int total = 0;

    for (int col = 0; col < array[row].length; col++) {
        total += array[row][col];
    }

    return total;
}

public static int getColumnTotal(int[][] array, int col) {
    int total = 0;

    for (int row = 0; row < array.length; row++) {
        total += array[row][col];
    }

    return total;
}

public static int getHighestInRow(int[][] array, int row) {
    int highest = array[row][0];

    for (int col = 1; col < array[row].length; col++) {
        if (array[row][col] > highest) {
            highest = array[row][col];
        }
    }
    return highest;
}

public static int getLowestInRow(int[][] array, int row) {
    int lowest = array[row][0];

    for (int col = 1; col < array[row].length; col++) {
        if (array[row][col] < lowest) {
            lowest = array[row][col];
        }
    }
    return lowest;
}

public static int getElementCount(int[][] array) {
    int count = 0;

    for (int row = 0; row < array.length; row++) {
        count += array[row].length;
    }
    return count;
}

public static void main(String[] args){
/**
* what to put in int[][] array to allow println of average, getrowtotal,
* etc..
*/
    int[][] array = ???;

    TwoDimArray twoDimArray = new TwoDimArray();
    System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
    System.out.println("Min value: " + twoDimArray.getArrayMinValue());
    System.out.println(getAverage(array));
    }

}

A: 0) Create numbers.txt in the root of your project. This is the file you will load array from. Example content as follows (2 rows, 3 columns):
2 3
1 2 3
4 5 6

1) You don't need your explicitly created int[][] array = ??? because there is already existing private int arr[][] which will be automatically loaded from file after you type it's name as intended in TwoDimArray constructor.

2) Since main method located at the same class as private int arr[][], you can access this private array without public getter/setter, and get average value like this:
// you don't need following line at all
// int[][] array = ???;

TwoDimArray twoDimArray = new TwoDimArray();

System.out.println("Max value: " + twoDimArray.getArrayMaxValue()); // Max value: 5
System.out.println("Min value: " + twoDimArray.getArrayMinValue()); // Min value: 1

// Average value
System.out.println(getAverage(twoDimArray.arr)); // 3, because 21 / 6 = 3

3) You probably got confused because getArrayMaxValue is signed as public int, and got invoked as twoDimArray.getArrayMaxValue(), whereas getAverage is public static int and must be called in different way.
I suggest marking getAverage as public int instead of public static int, and use private int arr[][] instead of int[][] array provided from arguments, so you will be able to call it the same way you do with other methods:
// Somewhere up
public int getAverage() {
    return getTotal(arr) / getElementCount(arr);
}

// In your main method
System.out.println(twoDimArray.getAverage());

A: Basically, what you have there is a jagged array, it is not a bidimensional array. I will explain you the idea, you do the rest. That it is not a bidimensional array. This is an array of array, in each position you are pointing to a new array of int. If you never instantiated a new array on each position, then you have a position with a null value.

So going back with your question, you should read the entire line with the two integers that are on the same line. Be sure that the line in your file has in the first line 2 numbers separated by a space.
Then use the next() method to get the complete string
String line = in.next();
String[] parts = line.split(" ");
int val1 = Integer.parseInt(parts[0]);
int val2 = Integer.parseInt(parts[1]);

For this question:
what to put in int[][] array to allow println of average, getrowtotal,
int[][] array = new int[4];
array[0] = new int[] {10,20,30,40,50};
array[1] = new int[] {60,71,80,90,91};
array[2] = new int[] {1};

Hope this helps
Now, what do you think you have in array[3]? The answer is: NULL

A: you already read the array from file in your method loadArray...
Use it instead of trying to load the same thing again, remove static modifier from all method and use field arr instead of parameter array
private int getTotal() {
    int total = 0;

    for (int row = 0; row < arr.length; row++) {
        for (int col = 0; col < arr[row].length; col++) {
            total += arr[row][col];
        }
    }

    return total;
}

private int getAverage() {
    return getTotal() / getElementCount();
}

private int getElementCount() {
    int count = 0;

    for (int row = 0; row < arr.length; row++) {
        count += arr[row].length;
    }
    return count;
}

public static void main(String[] args) {
    TwoDimArray twoDimArray = new TwoDimArray();
    System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
    System.out.println("Min value: " + twoDimArray.getArrayMinValue());
    System.out.println(twoDimArray.getAverage());
}


text:
Q: Command prompt goes blank Whenever i go to run the program it prompts me to enter the name when i do so it just sends the line where you type to the next line and i cant do anything but when i close it i see whatever i ctrl c the program i see whatever i should have been typing #This program searches for employees by name/prints info
#set a boolean value to False
found = False
#get the search value name
search = input("Enter a name to search for: ")
#open the employe file in read mode
empFile = open('employees.txt','r')
#read the first line/the name field in the 1st rec
name = empFile.readline()
#if field has records, continue processing
while name != '':
    #get id and dept
    id = empFile.readline()
    dept = empFile.readline()
    #strip newline from each string
    name = name.rstrip('\n')
    id = id.rstrip('\n')
    dept = dept.rstrip('\n')
    #determine if name matches search
    if name == search:
        #display record
        print('Name: ', name)
        print('ID: ', id)
        print('Department: ', dept)
        print()
        found = True
        #Read the name in the next record
        name = empFile.readline()
#close the file
empFile.close()
#If search item not found, print message
if found == False:
    print("The name was not found in  the file")

Traceback

Enter a name to search for: as Traceback (most recent call last):
  File "C:\Users\adam\Desktop\CIS201\searchRecords.py", line 13, in

      id = empFile.readline()   File "C:\Users\adam\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py",
  line 22, in decode
      def decode(self, input, final=False): KeyboardInterrupt

as requested the expected result should be it finding the name (or not depending on what you put) and either printing the name id and department or if you put a name that doesnt exist it should display the error message "The name was not found"

A: Your code only works for the first name in the file because you are not re-reading.  The problem is these lines should not be indented inside the if:
    #Read the name in the next record
    name = empFile.readline()

So, indented inside the loop:
if name == search:
    #display record
    print('Name: ', name)
    print('ID: ', id)
    print('Department: ', dept)
    print()
    found = True
#Read the name in the next record
name = empFile.readline()

There are many improvements that could be made, but fix one thing at a time.


text:
Q: How to get the data out of the loop before the screenshot? I have a loop in a loop to affect a lot of variables, after which I need to display the data in text form via SendKeys.Send and take a screenshot. But when the program starts, the loop produces screenshots, but in the text version it is displayed only at the last moment when all the screenshots have already been taken
private void button1_Click(object sender, EventArgs e)
    {

        int ID = Convert.ToInt32(textBox1.Text); //Тип одежды
        int drawable = Convert.ToInt32(textBox2.Text); //Кол-во одежды
        int Z = Convert.ToInt32(textBox3.Text); //Кол-во цветов
        int all = 1;

        Thread.Sleep(2000);
        for(int i = 0; i < drawable + 1; i++)
        {

            int m1 = 0;
            for (int m=m1; m< Z + 1;m++)
            {
                SendKeys.Send("t");
                SendKeys.Send("/setclothes " + ID + " " + i + " " + m);
                m1 = m;

                    int l = 32;
                    string filename = String.Format("D:\\Test\\" + ID + "_" + i + "_" + m + ".png", l);
                    Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
                    Graphics graphics = Graphics.FromImage(printscreen as Image);
                    graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
                    printscreen.Save(filename, System.Drawing.Imaging.ImageFormat.Png);

            }

        }

A: Your thread does not allow the graphics (on another thread) to refresh. So that when the graphics.CopyFromScreen is called the changes are complete but QUEUED and so no actual changes have occured until the main thread has completed (your function ends).
Try using:
Application.DoEvents();

before the graphics.CopyFromScreen line to force the graphics to update before the screen shot is taken.
i.e.
Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(printscreen as Image);
Application.DoEvents();
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
printscreen.Save(filename, System.Drawing.Imaging.ImageFormat.Png);

note: Calling DoEvents will stop work on the current thread and do work on other threads. This could slow down your loop significantly if you are running lots of other applications in the background!
note2: I would create the bitmap outside the loop unless you expect the screen resolution to change. Allocating room for the bitmap hundreds of times is slow.


text:
Q: getElementsByClassName vs querySelctorAll second iteration doesnt work I am wondering why it skips the second iteration when I am using document.getElementsByClassName?

var sameClass = document.querySelectorAll("p.kokos");

for ( var i = 0; i < sameClass.length; i++){
  sameClass[i].className = "cool";
}

var newClass = document.getElementsByClassName("new");

for ( var i = 0 ; i<= newClass.length; i++){
  newClass[i].className = "red";
}
.lw { font-size: 60px; }

.cool {
  color: #00FFFF;
}
.red {
  color: red;
}

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

A: document.getElementsByClassName() returns a live HTMLCollection.  That means that as you modify the objects in the collection so that they no longer match the class name, the actual HTMLCollection object gets modified right out from under you, affecting your iteration.
One popular work-around is to iterate the collection in reverse order from back to front.  That way, if the current element is removed from the collection, the rest of your iteration is not affected.
var newClass = document.getElementsByClassName("new");

for (var i = newClass.length - 1; i >= 0; i--){
    newClass[i].className = "red";
}

Another work-around is to make a copy of the HTMLCollection into a normal array and iterate that array instead.
document.querySelectorAll() returns a fixed collection, not a live collection so it does not have this issue.

A: It's because newClass is not a static array of nodes as you might assume.  It's a live HTMLCollection.  What that means is that if you change the underlying attribute which makes one of the elements a part of that collection, it will no longer be a part of that collection.  Think of it like this:
You're in a crowd of people wearing hats.  You see three people wearing blue hats and you call them the "Blue Hats".  You then go to the first person and give him a red hat and tell him to wear it.  Now if you look at that same crowd, you might expect there to be three "Blue Hats", but there's only two now.  The person who changed his hat is still there, he's just not a "Blue Hat" now and your collection of "Blue Hats" is smaller.
That's what's happening with your list.  After the first loop, you no longer have the first element.  i has incremented, so it goes to the second element in the list, but the list changed (by losing the first element), so you're really going to the third element instead.  Using the analogy, you've now asked for the second person with a blue hat, which is actually the third person from the original three.  He is also the second person in your current list of blue hat wearing people.
In the below example you can see that the number of elements has decremented because you changed the thing that made the first element in the list a part of the list:

var sameClass = document.querySelectorAll("p.kokos");

for ( var i = 0; i < sameClass.length; i++){
  sameClass[i].className = "cool";
}

var newClass = document.getElementsByClassName("new");

newClass[0].className = "red";

console.log(newClass.length)
.lw { font-size: 60px; }

.cool {
  color: #00FFFF;
}
.red {
  color: red;
}

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

And in this final snippet, I've used a trick to force your HTMLCollection to be an array instead which is not a live list.  The result is that your list doesn't change and all three elements are iterated over:

var sameClass = document.querySelectorAll("p.kokos");

for ( var i = 0; i < sameClass.length; i++){
  sameClass[i].className = "cool";
}

var newClass = [].slice.call(document.getElementsByClassName("new"));

for ( var i = 0 ; i< newClass.length; i++){
  newClass[i].className = "red";
}
.lw { font-size: 60px; }

.cool {
  color: #00FFFF;
}
.red {
  color: red;
}

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!

Hello Weaver!


text:
Q: Adding to row in MySQL if it doesn't exist When adding a row to a table, but first checking to see if it exists first Which would be the most efficient way of handling this?
Would it be a case of query to see if it exist, if not then insert.
Or using on duplicate?
Or simply replace (Would this work, if the row did not exist)?
Thanks

A: I think this is the fastest way in MySQL:
REPLACE into table (col1, col2) values(1, 'ABC')

EDIT:
MySQL will delete the row if it does exist and insert a new one.

A: I think you need INSERT IGNORE see this or INSERT ON DUPLICATE KEY UPDATE

A: depends what you mean by 'exists' if there is a unique field you can check against such as 'email' or 'login' then you can just try the insert and mysql raise error if exists, otherwise you'd do the replace as juergen d just suggested.
NB: don't use replace if you wanted your timestamps for any reason (such as if they're used in encrypted passwords or salt


text:
Q: Reading URLs from a HTML webpage and writing them to a file I want to create a simple program that only reads the URLs contained within <a> tags in the source code of a webpage specified by the user. As I am new to Java, any help would be greatly appreciated. Here is what I have so far, but this only adds the entire webpage to the file...
import javax.swing.*;
import java.net.*;
import java.io.*;

public class siteReader {
  public static void main(String[] args) throws Exception {
    URL address = new URL(JOptionPane.showInputDialog("Input a webpage address:"));
    BufferedReader in = new BufferedReader(new InputStreamReader(address.openStream()));
  }
}

A: Jsoup would do what you want with something like:
Document doc = Jsoup.connect(address).get();
Elements links = doc.select("a");


text:
Q: Running functions on the GPU with swift I have a function that can run a long time processing a job (has several inner-loops). I assume that running this on the GPU instead of the CPU will be faster?
Is there a way to run arbitrary functions on the GPU?
Apple has stated that Metal:

Metal 2 provides near-direct access to the graphics processing unit (GPU), enabling you to maximize the... compute potential of your apps

I see examples using Metal for gaming and graphics rendering, but are there any examples or links to help me with just running regular functions?

A: The GPU can be useful for certain kinds of pure computation.
The task must be highly parallelizable.
It must not require any APIs from the system libraries or frameworks. Metal has its own library that only has computation features. No disk access. No data structures beyond arrays/buffers.
There's an upper limit on how long the system will allow a compute shader to run (because it could be an infinite loop with no other way to stop it). So, depending on what you mean by "long time processing", it might not be suitable, or would only be suitable if broken up into chunks of work.
If a task is suitable for the GPU, it has to be explicitly programmed for the GPU. You can't just migrate normal code to the GPU transparently or automatically. It will have to be rewritten.


text:
Q: How to remove only html tags from text with Jsoup? I want to remove ONLY html tags from text with JSOUP. I used solution from here  (my previous question about JSOUP)
But after some checkings I discovered that JSOUP gets JAVA heap exception: OutOfMemoryError for big htmls but not for all. For example, it fails on html 2Mb and 10000 lines. Code throws an exception in the last line (NOT on Jsoup.parse):
public String StripHtml(String html){
  html = html.replace("<", "<").replace(">", ">");
  String[] tags = getAllStandardHtmlTags;
  Document thing = Jsoup.parse(html);
  for (String tag : tags) {
      for (Element elem : thing.getElementsByTag(tag)) {
          elem.parent().insertChildren(elem.siblingIndex(),elem.childNodes());
          elem.remove();
      }
  }
  return thing.html();
}

Is there a way to fix it?

A: Alternatively, you can give a try to Jsoup cleaning capabilities. The code below will remove ALL html tags located in the passed html string.
public String StripHtml(String html) {
    return Jsoup.clean(html, Whitelist.none());
}

The whitelist (Whitelist.none()) tells the Jsoup cleaner which tags are allowed. As you can see, none html tags are allowed here. Any tags not referenced in the whitelist will be removed.
You may be interested by other provided whitelists:

*

*Whitelist.basic()

*Whitelist.basicWithImages()

*Whitelist.none()

*Whitelist.relaxed()

*Whitelist.simpleText()
Those base whitelists can be customized by adding tags (see addTags method) or by removing tags (see removeTags method).
If you want to create your own whitelist (be careful !), here is the way to go:
Whitelist myCustomWhitelist = new Whitelist();
myCustomWhitelist.addTags("b", "em", ...);

See details here: Jsoup Whitelists
Jsoup 1.8.3

A: After many searching in google and after some attempts to implement html stripper by myself, my solution is to use HTMLStripCharFilter class of Solr with replacing escapedTags to blackList with standard html tags.

*

*HTMLStripCharFilter is faster than JSOUP library and regexes for big size files

*HTMLStripCharFilter hasn't memory problem like JSOUP (Out of memory exception) for big size files

*HTMLStripCharFilter isn't entering to "catastrophic backtracking" like regexes

A: I see two solutions:

*

*Increase the Java Heap space. It seems that generating the html as string needs more memory than you allow. Increasing the maximum JAVA heap can be done with the -Xmx command line parameter to the JVM:
java -Xmx512m parsing.java

*You could switch from DOM based JSoup to a SAX based parser like nekohtml Such parsers can deal with any size html documents because they never build the complete DOM in memory.

A: for me was sufficient to use combination of Jsoup methods:
Jsoup.clean(Jsoup.parse(htmlString).text(), Whitelist.simpleText())

whitelist you may choose...

A: Jsoup 1.14.2, just use:
doc.select(cssQuery).text();

Strips all tags and returns a nice text content. In my case I had a ul, li pairs, it nicely stripped them all.


text:
Q: Using variable in SelectByAttribute_management I am new in Python. I was trying to use a variable for selecting a feature instead of giving a direct input. My code sample will explain it better:
import arcpy
from arcpy import env
env.overwriteOutput = True
env.workspace = "H:/shp"

#variables
parcel = "parcel.shp"
parcel_Layer = "parcel_Layer"

Make Feature Layer
arcpy.MakeFeatureLayer_management(parcel, parcel_Layer, "", "", "FID FID VISIBLE NONE;Shape Shape VISIBLE NONE;OBJECTID OBJECTID VISIBLE NONE;ACCOUNTID ACCOUNTID VISIBLE NONE;PropID PropID VISIBLE NONE")

parcel_Layer_selattr = arcpy.SelectLayerByAttribute_management(parcel_Layer, "NEW_SELECTION", "\"PropID\" = 142855")

This code works fine as long as I enter the property ID directly ("\"PropID\" = 142855"). But when I declare the PropID as a variable, it doesnot work. Here is the code sample:
import arcpy
from arcpy import env
env.overwriteOutput = True
env.workspace = "H:/shp"

#variables
parcel = "parcel.shp"
parcel_Layer = "parcel_Layer"
x = 142855
Make Feature Layer
arcpy.MakeFeatureLayer_management(parcel, parcel_Layer, "", "", "FID FID VISIBLE NONE;Shape Shape VISIBLE NONE;OBJECTID OBJECTID VISIBLE NONE;ACCOUNTID ACCOUNTID VISIBLE NONE;PropID PropID VISIBLE NONE")

parcel_Layer_selattr = arcpy.SelectLayerByAttribute_management(parcel_Layer, "NEW_SELECTION", "\"PropID\" = x")

This is not working. it gives me this error msg:
 Runtime error  Traceback (most recent call last):   File "<string>", line 1, in <module>   File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\management.py", line 6435, in SelectLayerByAttribute     raise e ExecuteError: ERROR 000358: Invalid expression Failed to execute (SelectLayerByAttribute).

What I am doing wrong?

A: problem solved. Found Jason's (thanks to him) post in another thread and here is the working code:
parcel_Layer__selattr = arcpy.SelectLayerByAttribute_management(parcel_Layer, "NEW_SELECTION", "\"PropID\" = {}".format(x))


text:
Q: Changing color incrementally

#mainbody :nth-child(1){
    border-color: #FFCC00;
}
#mainbody :nth-child(2) {
    border-color: #FFAA00;
}
#mainbody :nth-child(3) {
    border-color: #FF8800;
}
#mainbody :nth-child(4) {
    border-color: #FF6600;
}

This is awkward, especially if you add another 20 children. Would it be possible to use something like this, feeding calc() the position and using it in rgb()?
Is there another way of doing this? (counter()?)
#mainbody h2 {
    border-color: rgb(255, calc( 255 / ( childposition / 4 ) ) ,0);
}

The following shows promise but I don't think rgb() accepts an internal counter():
body {
    counter-reset: headcolors 255;
}
h2:after {
    counter-increment: headcolors -34;
    content: "rgb(255," counter(headcolors) ",0);";
}
h2 {
    counter-increment: headcolors -34;
    color: rgb(255,counter(headcolors),0);
}

A: Since you haven't said that you want a CSS only solution, I would recommend you to use a SASS/LESS based solution.
http://sassmeister.com/gist/925757ff999824ec0270
$baseColor: #FFCC00;

@for $i from 1 to 5 {
  #mainbody :nth-child(#{$i}) {
      border-color: adjust-color($baseColor, $green: ($i - 1) * 1);
  }
  $i: $i + 1;
}

The above code generates this:
#mainbody :nth-child(1) {
  border-color: #ffcc00;
}

#mainbody :nth-child(2) {
  border-color: #ffcd00;
}

#mainbody :nth-child(3) {
  border-color: #ffce00;
}

#mainbody :nth-child(4) {
  border-color: #ffcf00;
}

A: Either use JS or one of the options suggested by pradeek. As of now, there is no way to use variables in CSS native language, if not by using counter-reset and counter-increment, but then you have to use them along with content, and that will change the content displayed inside the element, they will not treated as variables to use for operations.
Read here or here to understand why variables don't fit with CSS.

A: With jQuery you can do the following when the page is loaded:
$(document).ready(function(){
    var startfrom = 204; // CC in Hex, the starting value for the green color
    var endto = 255 - startfrom; // the ending value for the green color
    var limit = 4;
    for(var i = 1; i <= limit; i++)
    {
        $("#mainbody :nth-child("+i+")").css("border-color", "rgb(255,"+Math.round(startfrom - (startfrom - endto)*(i-1)/(limit-1))+",0)");
    }
});

See the jsfiddle with 4 children and with 20 children

A: Looking at your hex values, you are essentially just changing the hue by 8 each time. ie:
#ffcc00 = HSL: 48° 100% 50%
#ffaa00 = HSL: 40° 100% 50%
#ff8800 = HSL: 32° 100% 50%

etc.
So this is how you would go about doing this in LESS:
@base: #ffcc00;
@numChildren: 5;
.loop(@counter, @color) when (@counter <= @numChildren) {

  h2:nth-child(@{counter}) {
    border: 5px solid @color;
  }
  @newColor: hsl(hue(@color) - 8, 100%, 50%);
  .loop((@counter + 1),@newColor);    // next iteration
}
.loop(1,@base); // launch the loop

CODEPEN
The above codepen would assume markup something like so (5 children):

one

two

three

four

five

and produces the following CSS:
h2:nth-child(1) {
  border: 5px solid #ffcc00;
}
h2:nth-child(2) {
  border: 5px solid #ffaa00;
}
h2:nth-child(3) {
  border: 5px solid #ff8800;
}
h2:nth-child(4) {
  border: 5px solid #ff6600;
}
h2:nth-child(5) {
  border: 5px solid #ff4400;
}

A: Firefox 31+ or 29+(width options) issue(fiddle):
HTML:

CSS:
::root {
    --bg-color: #000000;
}

div :nth-child(1){
    --bg-color: #FFCC00;
}
div :nth-child(2) {
    --bg-color: #FFAA00;
}
div :nth-child(3) {
    --bg-color: #FF8800;
}
div :nth-child(4) {
    --bg-color: #FF6600;
}

p {
    display: inline-block;
    width: 50px;
    height: 50px;
    background: var(--bg-color);
}

As @Jose said, counter function used only for content property. But vars a now enabled in CSS. Chrome and Firefox has different syntax. There are two specs of W3C CSS Variables Module Level 1(Chrome implementation) and CSS Custom Properties for Cascading Variables Module Level 1(Firefox implementation).


text:
Q: How to continue tracking location after the user restarts the phone? My application need to post the location data to my backend. I have set the location permissions to always and set the pausesLocationUpdatesAutomatically to false for CLLocationManager and need to continue tracking the phones location even when the application is in background or after the phone is restarted.
I'm able to make it work when the application is in background mode. But it stops working when the phone is restarted.
How can I do this?
By the way, I know the

A: This is WELL documented by Apple documentations.
Only if Location manager is started with "startMonitoringSignificantLocationChanges" you can get it.
So for example:
1) in App delegate start a singleton GeoLocationManager.shared.locationManager, so if you restart will be running.
2) in call back:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
{

update your position
it will be re-entrant if crashes.
I think You already set il plist:
<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>

note: add code for privacy, as since ios9 is mandatory..
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
...
}

And in plist:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Needed to track on maps even if background</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Needed to track on maps even if background</string>


text:
Q: How do I put values od dataframe column in 2d matrix? I have the pandas dataframe with 3 columns value, row_index, column_index. I would like to create a matrix, where values of dataframe placed at relevant rows and columns and unknown elements are zeros.
I have made a for-cycle like this:
N_rows = df.row_index.max()
N_cols = df.column_index.max()
A = np.zeros((N_rows, N_cols))
for i in df.row_index:
    for j in df.column_index:
        np.put(A, i*N_cols+j, df['value'][(df.row_index==i) &
                                          (df.column_index==j)])

but it works very slow.
How can I do it faster?

A: I think you need pivot with fillna and for missing values of columns and rows add reindex, last for numpy array add values:
df = pd.DataFrame({'value':[2,4,5],
                   'row_index':[2,3,4],
                   'col_index':[0,2,3]})

print (df)
   col_index  row_index  value
0          0          2      2
1          2          3      4
2          3          4      5

rows = np.arange(df.row_index.max()+1)
cols = np.arange(df.col_index.max()+1)

print (df.pivot('row_index', 'col_index', 'value')
         .fillna(0)
         .reindex(index=rows, columns=cols, fill_value=0))
col_index    0    1    2    3
row_index
0          0.0  0.0  0.0  0.0
1          0.0  0.0  0.0  0.0
2          2.0  0.0  0.0  0.0
3          0.0  0.0  4.0  0.0
4          0.0  0.0  0.0  5.0

a = df.pivot('row_index', 'col_index', 'value')
      .fillna(0)
      .reindex(index=rows, columns=cols, fill_value=0)
      .values
print (a)
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 2.  0.  0.  0.]
 [ 0.  0.  4.  0.]
 [ 0.  0.  0.  5.]]

Another solution with set_index and unstack:
print (df.set_index(['row_index', 'col_index'])['value']
         .unstack(fill_value=0)
         .reindex(index=rows, columns=cols, fill_value=0))

col_index  0  1  2  3
row_index
0          0  0  0  0
1          0  0  0  0
2          2  0  0  0
3          0  0  4  0
4          0  0  0  5

a = df.set_index(['row_index', 'col_index'])['value']
      .unstack(fill_value=0)
      .reindex(index=rows, columns=cols, fill_value=0)
      .values
print (a)
 [[0 0 0 0]
 [0 0 0 0]
 [2 0 0 0]
 [0 0 4 0]
 [0 0 0 5]]

A: Just modifying a minor part in @jezrael's solution. You can actually use Pandas as_matrix() functions to get the arrays:
df = pd.DataFrame({'value':[2,4,5],
                   'row_index':[2,3,4],
                   'col_index':[0,2,3]})

df.pivot('row_index', 'col_index', 'value').fillna(0).as_matrix()
# array([[ 2.,  0.,  0.],
#        [ 0.,  4.,  0.],
#        [ 0.,  0.,  5.]])


text:
Q: The name '' does not exist in the current context - Unity 3D i get the errors The name 'AK74' does not exist in the current context and The name 'STG44' does not exist in the current context in both Debug.Log lines
any solution?
     private void Start()
    {
        weapon = GetComponent<Weapon>();

        Weapon AK74 = new Weapon(2, 30, 200);
        Weapon STG44 = new Weapon(1, 35, 200);

        _currentAmmoInClip = clipSize;
        STG44.Setmagsize(_currentAmmoInClip);

        _ammoInReserve = reservedAmmoCapacity;
        STG44.Setfullmag(_ammoInReserve);
        _canShoot = true;

    }

    private void Update()
    {
        Debug.Log(AK74.Getmagsize());
        Debug.Log(STG44.Getmagsize());
    }

A: The AK47 and STG44 variables are local to Start(), and are out of scope for Update. To make them visible, increase their scope by moving their declaration out of Start(). For instance:
Weapon AK74 = new Weapon(2, 30, 200);
Weapon STG44 = new Weapon(1, 35, 200);

private void Start() {
    weapon = GetComponent<Weapon>();

    _currentAmmoInClip = clipSize;
    STG44.Setmagsize(_currentAmmoInClip);

    _ammoInReserve = reservedAmmoCapacity;
    STG44.Setfullmag(_ammoInReserve);
    _canShoot = true;
}

A: Those variables are defined in the scope of Start method, and they will be deleted as soon as this function will finish. You want to store them in the object itself, so you have to declare them outside of function, in the class itself, like so:
Weapon AK74, STG44;

private void Start()
{
    weapon = GetComponent<Weapon>();

    AK74 = new Weapon(2, 30, 200);
    STG44 = new Weapon(1, 35, 200);

    _currentAmmoInClip = clipSize;
    STG44.Setmagsize(_currentAmmoInClip);

    _ammoInReserve = reservedAmmoCapacity;
    STG44.Setfullmag(_ammoInReserve);
    _canShoot = true;
}

private void Update()
{
    Debug.Log(AK74.Getmagsize());
    Debug.Log(STG44.Getmagsize());
}

A: Read up on variable scope and the use of fields.
Put simply the AK47 and STG44 variables you declared within Start exist only within Start, and you have to move them out into the main class for them to remain available for use in other methods. Spending time going through some tutorials on basic C# programming principles will save you a lot of time in the long run though.


text:
Q: Why is a quaternion a + bi + cj + dk not equal to a + (b+c+d)i i² = -1
j² = -1
k² = -1
But
a + bi + cj + dk is not equal to a + (b+c+d)i
why not ?

A: Because $i, j, k$ aren't equal. In the quaternions, $-1$ has even more square roots than it does in the complex numbers.

A: $$\forall a,b,c,d,a',b',c',d' \in \Bbb R: a + bi +cj +dk = a'+ b'i+c'j+d'k \iff a=a', b=b', c=c', d=d'$$ just as if we'd have written a $4$-tuple $(a,b,c,d)$ for the quaternion. The coefficients uniquely determine the number.
In particular $i = 0+1i + 0j + 0k \neq j = 0 + 0i + 1j + 0k$ etc. The roots of $-1$ are $i,-i,j,-j,k,-k$ already showing the quaternions are not a field (already obvious from non-commutativity: $ij=k, ji=-k$ etc.) as in a field a quadratic like $x^2+1$ can have at most $2$ roots, not $6$.


text:
Q: How to limit the resources of process submitted by non-slurm on CentOS We have a cluster with 1 node, 200 CPU cores and 2T RAM. The server are shared by 15+ people and required to submitted job by slurm.(computing node and login node are on same machine). But some people are unwilling to do so!
So, is there a way to limit the resources of user's process submitted by cmd, but no by slurm?
For example, a no-slurm job shouled be restricted with CPU:2, RAM:4G;
$ resource-consuming-program  # job submitted by cmd should be restricted.

$ cat slurmjob.sh
#!/bin/sh
#SBATCH -J TEST
#SBATCH --cpus-per-task=1
#SBATCH --mem=700G

# We recommend using SLURM to run resource-consuming job.
resource-consuming-program
$ sbatch slurmjob.sh  # job submitted by SLURM won't be restricted.

All in all, we just want to limit which tasks that are not submitted by SLURM. Thanks. ☺

A: Here is a ad-hoc solution to your problem: https://unix.stackexchange.com/questions/526994/limit-resources-cpu-mem-only-in-ssh-session. The idea there is to constrain users in a cgroup whenever they are in an SSH session.
Other than that, there is a tool called Arbiter2 that was created for the purpose of controlling usage resources on login nodes.


text:
Q: Read content in HTML div tag with PHP
Possible Duplicate:
How do you parse and process HTML/XML in PHP?

Currently I have a snippet of code that looks like this:
    echo '
';
    echo 'Results:
';
    echo '
Back
';
    $string = explode('
', $string);
    foreach ($string as $row) {
        preg_match('/^(.+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
        if (preg_match("/$query/i", "$matches[1]")) {
            echo "";
            echo $matches[1];
            echo "
";
        }
    }
    echo '
';

As you can see I have the div tags at the top and bottom echo '
'; echo '
';. What I want to do is my PHP code to scan the output that is between the two tags, and if the text Results:

Back
 is between the tags I want my code to output "Test." Any help regarding my problem would be very helpful!

A: Consider the PHP Simple HTML DOM Parser for getting data from HTML.

A: If you feel comfortable with Regex, you can use it when the page remains pretty much static. This site can help you build regex queries. Otherwise, try and use Simple HTML DOM wherever possible as mentioned above. You'll have less chance of getting errors.


text:
Q: Improve SQL Query for Join Table I have a table.contact_group, and table.contact
The contact's group is store in "table.contact" in the field "group_id" varchar
example data: ;11;22;33;44;55;
Where the 11,22,33,44,55 is the table.contact_group.group_id
There is a lot of data in the database, i have no way to modify the data. I have to try to change to JOIN query, the performance does not improve.
My last option is, trying hard to modify the database, and create a "connection" table to handle relationship (M:M) between table.contact_group and table.contact
SELECT cg.group_id, cg.group_title , COUNT(c.contact_id) AS total
 FROM nano_contacts_group cg , nano_contacts c
WHERE cg.organization_id = '1' AND cg.group_active = '1' AND c.group_id LIKE CONCAT('%;',CONCAT( cg.group_id,';%'))
 GROUP BY cg.group_id
 ORDER BY cg.group_title ASC

I hope can have SQL expert share his/her opinion what I suppose to do.


text:
Q: Email log4j errors to different groups Am using log4j for my error reporting. Ive set my log 4j to also append errors to emails. However i need it to send emails to separate groups depending on the level of the message. For example
      info messages go to management- john@management.com, peter@management.com, simon@management.com
       debug messages go to programmers - paul@programmer.com, matt@programmer.com
       warn messages go to administrator - admin@admin.com

In such a fashion,  is it possible? And has anyone implemented said procedure (a sample properties file would be appreciated)

A: Is should be easy to configure something like this using the SMTPAppender from log4j. But be aware, that emailing logs takes quite a bit of load, especially if you consider mailing DEBUG reports to developers.

A: You can use a log4j Filter to do this (http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html)
The example below writes messages to different files according to the log level.
This can be easily adapted to an SMTPAppender instead of a FileAppender.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="management" class="org.apache.log4j.FileAppender">
        <param name="File" value="management.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m"/>
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="INFO" />
            <param name="LevelMax" value="INFO" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <appender name="programmers" class="org.apache.log4j.FileAppender">
        <param name="File" value="programmers.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m"/>
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="DEBUG" />
            <param name="LevelMax" value="DEBUG" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <appender name="admin" class="org.apache.log4j.FileAppender">
        <param name="File" value="admin.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m"/>
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="WARN" />
            <param name="LevelMax" value="WARN" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <category name="a">
        <level value="ALL" />
        <appender-ref ref="management"/>
        <appender-ref ref="programmers"/>
        <appender-ref ref="admin"/>
    </category>

</log4j:configuration>


text:
Q: IndexOf find no element in a List<> while Mock I have a list of object like below
public class Person
{
   public string Name {get; set;}
   public int Age {get; set;}
}
public class SomeClass
{
public int DoSomething ()
{
    int result;
    List<Person> personList = new List<Person>();
    personList.Add(new Person { //with 1 object, just to keep simple
       Name = "Someone",
       Age = 18});
   Person eighteenYearsOld = _checkAge.FindEighteenYearsOld (personList);
   int index = personList.IndexOf (eighteenYearsOld);
   //do something
   return result;
}
}
[TestMethod]
public void DoSomething_Test()
{
    //Given:

    //When: I call SomeClass object
    Person eightnneYears = new Person {
       Name = "Someone",
       Age = 18};
   _mockCheckAge.Setup (x => x.FindEighteenYearsOld(It.IsAny<List<Person>>())).Returns(eightnneYears);
   _someClass = new SomeClass (_mockCheckAge.Object);
   int result = _someClass.DoSomething();
   //Then:
}

As I have mocked the FindEighteenYearsOld method it returns a Person object with same states which is presents in the personList. But when personList.IndexOf() executes it returns index -1, which is suppose to be 0. What should I do.

A: List.IndexOf uses Equals to find equal objects. If your class doesn't override it only references are compared. Since your two instances are not the same List.IndexOf returns -1.
So override Equals (and also always GetHashCode then):
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals (Object obj)
    {
        Person otherPerson = obj as Person;
        return otherPerson != null
            && otherPerson.Name == Name
            && otherPerson.Age == Age;
    }

    // http://stackoverflow.com/a/263416/284240
    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            hash = hash * 23 + (Name?.GetHashCode() ?? 0); // or: hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode());
            hash = hash * 23 + Age; ;
            return hash;
        }
    }
}


text:
Q: Automapper: Ignore exact match and use postfix match instead I am trying to work out how to populate Foo from FooConfig:
class Bar
{
   int A;
   int B;
}

class Foo
{
   Bar BarValues;
   Bar BarErrorValues;
}

class FooConfig
{
   int A;
   int B;
   int AError;
   int BError;
}

FooConfig is essentially a flattened version of Foo.
I can populate the BarValues easily with AutoMapper (by having a map defined for FooConfig to Bar), but I am having trouble getting the BarErrorValues populated - everything I try it ends up with the A and B values in it instead of the AError and BError values.
I suspect I need to use a "transformer" or RecognizePostfixes (although this does not seem to work as I tried it).

A: This should work "out of the box":
Mapper.CreateMap<FooConfig, Foo>()
    .ForMember(d => d.BarValues, o => o.MapFrom(s => new Bar { A = s.A, B = s.B }))
    .ForMember(d => d.BarErrorValues, o => o.MapFrom(s => new Bar {A = s.AError, B = s.BError}));

A: I think I have found the problem. It appears that if AutoMapper finds an exact match then the name transformer is never used. Bugger :( Here is the AutoMapper source code that shows it:
private static MemberInfo FindTypeMember(IEnumerable<MemberInfo> modelProperties, IEnumerable<MethodInfo> getMethods, string nameToSearch, IMappingOptions mappingOptions)
{
    MemberInfo pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, nameToSearch));
    if (pi != null)
        return pi;

  ...

    pi = modelProperties.FirstOrDefault(prop => NameMatches(mappingOptions.SourceMemberNameTransformer(prop.Name), nameToSearch));
    if (pi != null)
        return pi;


text:
Q: Objective-C property access: unrecognized selector sent to instance I am new to objective-c, but coding for many years now. Somehow I don't get warm with Objective-C. I searched google and stackoverflow, but I think my problem is just to simple and stupid that no one has asked this yet.
My Code is based on DateSelectionTitles Example. http://developer.apple.com/library/ios/#samplecode/DateSectionTitles/Introduction/Intro.html
I have an NSManagedObject
@interface Event : NSManagedObject

@property (nonatomic, retain) NSDate * date;
...

// Cache
@property (nonatomic, retain) NSString * primitiveSectionIdentifier;

All prperties are defined in my datamodel, except the primitiveSectionIdentifier (as in the apple example)
But when I call
NSString *tmp = [self primitiveSectionIdentifier];

I get the Exception
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Event primitiveSectionIdentifier]: unrecognized selector sent to instance 0x74850c0'
To put it simple:
Event *foo = [[Event alloc] init];

if (foo.primitiveSectionIdentifier) {
    NSLog(@"YEAH");
}

throws the same exception. So I basically want to check if primitiveSectionIdentifier is nil. But when I access the property, it throws an exception? Do I need to alloc each property  before I can check if it has a value?!
Which of the Objective-C basics am I not getting here?
Thanks a lot for responses!

A: You are using an older example program, which uses a different style of memory management; if you are compiling under the iOS 5 or 6, that may be causing the problem.
Try
NSLog(@"primitiveSectionIdentifier = %@", self.primitiveSectionIdentifier);

If it doesn't give you the string you are looking for then the problem is likely in that the string object was never initialized and is still set to nil.  In that situation, the code would compile, but sending a selector to a nil pointer would throw up an exception.

A: There is only one way how this can happen without compiler warnings - you must have written @dynamic primitiveSectionIdentifier; in your implementation file. This means that you don't want to define the method because you believe it is already defined somewhere else.
You are using a NSManagedObject, do you know how it works? You declare methods without implementation (putting @dynamic in the implementation) and when the method is called, it is not found and a special handler [NSObject doesNotRecognizeSelector:] is called instead. This handler checks the Core Data model whether an attribute for the given selector exists and if it doesn't, it throws the exception you are seeing.
So, the problem might the caused by the fact that primitiveSectionIdentifier is not declared in your model.


text:
Q: Association property in DomainCollectionView and WCF RIA Services I have a association in my poco class, ex:
public class Category() {
    [Key]
    public int id { get; set}
    public string Name { get; set; }
    /* HERE */
    public virtual ICollection<Book> Books {get; set;}
}

public class Book() {
    [Key]
    public int id { get; set}
    public string Name { get; set; }
}

I use MVVM patern, MVVM Light and RIA Services Toolkit. My Domain Service implementation contains a method GetCategories that include their books, ex:
public IQueriable<Category> GetCategories()
{
    return Model.Categories.Include("Books").OrderBy(pCategory => pCategory.Name);
}

In my ViewModel I have a DomainCollectionView that load GetGruposQuery. I also have a property for bind a grid and other controls, like:
public ICollectionView CollectionViewCategories {
    get { return myDomainCollectionViewCategories;}
}

I need get a child property CollectionView.Books for bind my controls and ADD, REMOVE itens in view, but this property is only EntityCollection and isn't a DomainCollectionView that contains methods for ADD, REMOVE, etc.
How I can get the current Books property (of CollectionViewCategories) as DomainCollectionView in my ViewModel?
Thank you!

I solve this question with: (CollectionViewCategories.CurrentItem as Category).Books.Remove(CollectionViewBooks.CurrentItem as Book)
private ICollectionView CreateView(Object source)
{
    CollectionViewSource cvs = new CollectionViewSource();
    cvs.Source = source;
    return cvs.View;
}
//...
//After CollectionViewCategories loaded:
CollectionViewCategories.CurrentChanged += (s, e) =>
{
    if (CollectionViewCategories.CurrentItem != null)
    {
        CollectionViewBooks = CreateView(fContext.Categories.Where(p => p.Id == (CollectionViewCategories.CurrentItem as Category).Id).FirstOrDefault().Books);
    }
    else
    {
        CollectionViewBooks = null;
    }
    RaisePropertyChanged("CollectionViewBooks");
};

A: Why do you need it ? EntityCollection do have these methods (Add,Remove...)
If you obtain an error while invoking them, it could lead to the fact that the Book class is not fully exposed to the client (lack of insert/update/delete methods on the domainservice)
Just to clarify, DomainCollectionView  is inteded to wrap an EntityCollection primarily for better dealing with MVVM and binding in general (see this link)


text:
Q: She "was taught" or "has been taught" Russian? When using (to be taught), should it be (was taught) or (has been taught)?
For example:

He taught her Russian, in other words, she _____ Russian.

*

*has been taught

*has taught

*taught

*was taught

And why?

A: In real life, both (1) and (4) are grammatically correct, as Peter Shor commented. Which one you choose depends on what you want to emphasize the present or the past respectively.
For the purpose of the exercise, since the active voice is a simple past tense, a straightforward conversion to the passive would yield (4), which I believe is meant to be the "correct" answer.