text:
Q: ArcGIS Online Routing service I have a serious confusion understanding the link: http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis
This is the default format to access the routing service, but this isn't complete, we have to tell further on which area we want to work such that
http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route
The above link works only for San Diego but what if I want my network dataset and hence map to be uploaded as a link like this.
How do I do this?

A: The first link you've referenced is a folder, and within that folder is a bunch of services. This is a "Sample Server", as such, it's used to demonstrate different workflows and patterns. Grouped inside this folder is pretty much everything you can do to support Routing workflows.
I'm not real sure exactly what you're asking, but I can try to explain what's inside this service folder.
You see 3 different services types:

*

*Map Service

*Geoprocessing Service

*Network Analyst Service

Each of these services might be using the same data (well, it's highly likely they are), but each service does something different.
The map service is obviously for looking at the data on a map. This will be a feature class of streets and other data layers that provide context for your user.
The geoprocessing service allows a user to actually generate a route or other network function. There's actually 6 different network tools inside the GP Service. The user of the application would send a request to the service where inside network analyst tools run, and provide a result. The application then draws the result on the map.
The network analyst service works similar to the geoprocessing service, but it's used differently. The application consuming the NA service needs to understand how to work with this particular service, specifically how to send a request and handle the response. It's a whole other question/topic why and when you'd use a GP Service vs NA Service.
With the services explained, if you want to do something similar, it all starts in ArcMap or ArcGIS Pro with a streets featureclass. Publish your streets into a map service. Then create a Network Dataset and build/publish GP Services or publish the network into a NA Service. (This paragraph is an incredibly simplified explanation of the entire start to finish, somewhat complex workflow)


text:
Q: find all ordered triples of distinct positive integers i, j, and k less than or equal to a given integer n that sum to a given integer s this is the exercise 2.41 in SICP
I have wrote this naive version myself:
(defn sum-three [n s]
  (for [i (range n)
        j (range n)
        k (range n)
        :when (and (= s (+ i j k))
                   (< 1 k j i n))]
    [i j k]))

The question is: is this considered idiomatic in clojure? And how can I optimize this piece of code? since it takes forever to compute(sum-three 500 500)
Also, how can I have this function take an extra argument to specify number of integer to compute the sum? So instead of sum of three, It should handle more general case like sum of two, sum of four or sum of five etc.
I suppose this cannot be achieved by using for loop? not sure how to add i j k binding dynamically.

A: (Update: The fully optimized version is sum-c-opt at the bottom.)
I'd say it is idiomatic, if not the fastest way to do it while staying idiomatic. Well, perhaps using == in place of = when the inputs are known to be numbers would be more idiomatic (NB. these are not entirely equivalent on numbers; it doesn't matter here though.)
As a first optimization pass, you could start the ranges higher up and replace = with the number-specific ==:
(defn sum-three [n s]
  (for [k (range n)
        j (range (inc k) n)
        i (range (inc j) n)
        :when (== s (+ i j k))]
    [i j k]))

(Changed ordering of the bindings since you want the smallest number last.)
As for making the number of integers a parameter, here's one approach:
(defn sum-c [c n s]
  (letfn [(go [c n s b]
            (if (zero? c)
            [[]]
            (for [i  (range b n)
                  is (go (dec c) n (- s i) (inc i))
                  :when (== s (apply + i is))]
              (conj is i))))]
    (go c n s 0)))

;; from the REPL:
user=> (sum-c 3 6 10)
([5 4 1] [5 3 2])
user=> (sum-c 3 7 10)
([6 4 0] [6 3 1] [5 4 1] [5 3 2])

Update: Rather spoils the exercise to use it, but math.combinatorics provides a combinations function which is tailor-made to solve this problem:
(require '[clojure.math.combinatorics :as c])

(c/combinations (range 10) 3)
;=> all combinations of 3 distinct numbers less than 10;
;   will be returned as lists, but in fact will also be distinct
;   as sets, so no (0 1 2) / (2 1 0) "duplicates modulo ordering";
;   it also so happens that the individual lists will maintain the
;   relative ordering of elements from the input, although the docs
;   don't guarantee this

filter the output appropriately.
A further update: Thinking through the way sum-c above works gives one a further optimization idea. The point of the inner go function inside sum-c was to produce a seq of tuples summing up to a certain target value (its initial target minus the value of i at the current iteration in the for comprehension); yet we still validate the sums of the tuples returned from the recursive calls to go as if we were unsure whether they actually do their job.
Instead, we can make sure that the tuples produced are the correct ones by construction:
(defn sum-c-opt [c n s]
  (let [m (max 0 (- s (* (dec c) (dec n))))]
    (if (>= m n)
      ()
      (letfn [(go [c s t]
                (if (zero? c)
                  (list t)
                  (mapcat #(go (dec c) (- s %) (conj t %))
                          (range (max (inc (peek t))
                                      (- s (* (dec c) (dec n))))
                                 (min n (inc s))))))]
        (mapcat #(go (dec c) (- s %) (list %)) (range m n))))))

This version returns the tuples as lists so as to preserve the expected ordering of results while maintaining code structure which is natural given this approach. You can convert them to vectors with a map vec pass.
For small values of the arguments, this will actually be slower than sum-c, but for larger values, it is much faster:
user> (time (last (sum-c-opt 3 500 500)))
"Elapsed time: 88.110716 msecs"
(168 167 165)
user> (time (last (sum-c 3 500 500)))
"Elapsed time: 13792.312323 msecs"
[168 167 165]

And just for added assurance that it does the same thing (beyond inductively proving correctness in both cases):
; NB. this illustrates Clojure's notion of equality as applied
;     to vectors and lists
user> (= (sum-c 3 100 100) (sum-c-opt 3 100 100))
true
user> (= (sum-c 4 50 50) (sum-c-opt 4 50 50))
true

A: for is a macro so it's hard to extend your nice idiomatic answer to cover the general case. Fortunately clojure.math.combinatorics provides the cartesian-product function that will produce all the combinations of the sets of numbers. Which reduces the problem to filter the combinations:
(ns hello.core
  (:require [clojure.math.combinatorics :as combo]))

(defn sum-three [n s i]
  (filter #(= s (reduce + %))
          (apply combo/cartesian-product (repeat i (range 1 (inc n))))))

hello.core> (sum-three 7 10 3)
((1 2 7) (1 3 6) (1 4 5) (1 5 4) (1 6 3) (1 7 2) (2 1 7)
 (2 2 6) (2 3 5) (2 4 4) (2 5 3) (2 6 2) (2 7 1) (3 1 6)
 (3 2 5) (3 3 4) (3 4 3) (3 5 2) (3 6 1) (4 1 5) (4 2 4)
 (4 3 3) (4 4 2) (4 5 1) (5 1 4) (5 2 3) (5 3 2) (5 4 1)
 (6 1 3) (6 2 2) (6 3 1) (7 1 2) (7 2 1))

assuming that order matters in the answers that is

A: For making your existing code parameterized you can use reduce.This code shows a pattern that can be used where you want to paramterize the number of cases of a for macro usage.
Your code without using for macro (using only functions) would be:
(defn sum-three [n s]
  (mapcat (fn [i]
            (mapcat (fn [j]
                      (filter (fn [[i j k]]
                                (and (= s (+ i j k))
                                     (< 1 k j i n)))
                              (map (fn [k] [i j k]) (range n))))
                    (range n)))
          (range n)))

The pattern is visible, there is inner most map which is covered by outer mapcat and so on and you want to paramterize the nesting level, hence:
(defn sum-c [c n s]
  ((reduce (fn [s _]
             (fn [& i] (mapcat #(apply s (concat i [%])) (range n))))
           (fn [& i] (filter #(and (= s (apply + %))
                                  (apply < 1 (reverse %)))
                            (map #(concat i [%]) (range n))))
           (range (dec c)))))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Edit UITableViewCell inline in same view controller I have a table view controller where I show a shopping bag (or shopping cart). In each cell I show an image view, an a few labels with some information. One of those labels shows the quantity of products for that product. I want that when I press the edit button the quantity label becomes a stepper (or something like that) where I can change the quantity. I have seen that behavior on other apps (specific on Zara for iPhone, a clothes store) but I cannot figure out how to do that. All I have found on the internet is to segue to another view where you can edit an item, but that's not what I want to do.
How is it possible to implement such a behavior?
Thanks a lot!

A: You can try to add the stepper on the label, in the UITableView Method,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

This method allows you to perform actions when a table view cell is selected.


text:
Q: "A student who is researching" vs "a student researching" Can I shorten the sentence like this?

1- This is Peter, a student who is researching nuclear physics at a university .

2- This is Peter, a student researching nuclear physics at a university.

A: Yes
A present participle, like researching, is just an adjective. Applying an adjective to a noun means the same as "(noun) who is (adjective)" or "(noun) that is (adjective)". For example, these mean the same thing:

This is my fat cat.

This is my cat who is fat.

The words "who is fat" in the second form are called a relative clause (because it makes a statement that relates to the original noun).
Probably the only reason this isn't obvious is because in English, adjectives normally precede the noun they modify, but when a participle takes an object, like nuclear physics at a university in your example, the participle normally follows the noun.
Something else you must know
When you word something with a relative clause, you need to be aware of whether you mean the clause restrictively or nonrestrictively. If I know that you know that I have two cats, only one of which is fat, then I mean "who is fat" restrictively: the purpose of the relative clause is to narrow down ("restrict") the meaning of "cat", i.e. to indicate which cat this is—the fat one, not the skinny one.
If I think you do not even know that I have a cat, then the relative clause makes a separate statement in addition to the statement in the main clause. This "nonrestrictive" meaning requires a comma:

This is my cat, who is fat.

That means the same as this longer version, which puts each statement into a separate sentence:

This is my cat. My cat is fat.

In the form with an adjective before the noun ("This is my fat cat"), the language does not distinguish between the restrictive and nonrestrictive meanings; usually the restrictive meaning is understood. The relative clause with the comma is needed if you want to be absolutely sure to convey the nonrestrictive meaning. This is the only circumstance I can think of where you should not reduce a relative clause like the one in your example to a participle that directly modifies the noun.
Your example introduces Peter as a student with the indefinite article a. The comma that you already have, before "a student", makes that whole phrase or clause nonrestrictive in regard to Peter: it's telling you a second fact about Peter, namely that he is a student who is doing research, etc. It's restrictive in regard to "student". So, the form with the relative clause ("Peter, who is…") should not get its own comma (exactly as you have it).


text:
Q: How to populate my tableView in Swift 2 from array of dictionaries? Hi I'm a swift newbie.
I need to populate my app's menu dinamically in a tableview but I'm having trouble appending an array of dictionaries in an associative array.
I have this class for the menu items.
class Menu: NSObject {

    // properties
    var id:String = ""
    var name:String = ""

}

I have this json format from an api ,
[{
    "id": "local",
    "name": "Local"
}, {
    "id": "sports",
    "name": "Sports"
}, {
    "id": "bajacalifornia",
    "name": "Baja California"
},...
]

So in my MenuModel I get the items with json and append to array of objects and notify with a delegate when the data is ready in my menu controller
if let items = json["items"].array {

    for menuitem in items {

   // Create menu objects off of the JSON response
   let menuObj = Menu()

   menuObj.id = menuitem["id"].stringValue
   menuObj.name = menuitem["name"].stringValue

   arrayItems.append(menuObj)
   }

   self.menuArray = arrayItems

  // Notify the delegate that the data is ready
  if self.delegate != nil {
      self.delegate!.menuReady()
  }
} // end let items

I need this data structure in the Menu Controller. So my my problem is that I can't assign the array of objects into Array's key "News" to populate my tableview and show the options in the menu.
I need append self.menuArray into "News" item's array.
// data structure  to fill the menu tableview
let menuSectionHeaders = ["News", "Contact", Media]
var items = [
    "News": [["id":"local","name":"Local"],["id":"sports","name":"Sports"],["id":"bajacalifornia","name":"Baja California"],...more options],
    "Contact": ["comments"],
    "Media": ["Photos","Videos"]
]

My menu's controller code right now works but with  static data in this methods, and works fine but I need to fill the tableview dynamically with that data structure I showed above and I can't.
//Static Data and working code.

let menuSectionHeaders = ["News", "Contact","Media"]
var staticItems = [
    "News" : ["local", "sports", "bajacalifornia"],
    "Contact" : ["comments"],
    "Media" : ["Photos","Videos"]
]

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return menuSectionHeaders.count
}

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 60
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return menuSectionHeaders[section].uppercaseString
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let key = sectionHeaderName(forSection: section)
    return staticItems[key]!.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: UITableViewCell?
    if indexPath.section == 0 {
        cell = tableView.dequeueReusableCellWithIdentifier("newscell", forIndexPath: indexPath) as UITableViewCell
    }if indexPath.section == 1 {
        cell = tableView.dequeueReusableCellWithIdentifier("contactcell", forIndexPath: indexPath) as UITableViewCell
    }
    else {
        cell = tableView.dequeueReusableCellWithIdentifier("mediacell", forIndexPath: indexPath) as UITableViewCell
    }
    let key = sectionHeaderName(forSection: indexPath.section)
    cell!.textLabel?.text = staticItems[key]![indexPath.row].capitalizedString
    return cell!
}

func sectionHeaderName(forSection section: Int) -> String {
    return menuSectionHeaders[section]
}


text:
Q: Fill XFA without breaking usage rights I have an XFA form that I can successfully fill in by extracting the XML modifying and writing back. Works great if you have the full Adobe Acrobat, but fails with Adobe Reader. I have seen various questions on the same thing with answers but they were some time ago so updating an XFA that is readable by Adobe Reader may no longer be doable?
I use this code below and I've utilised the StampingProperties of append as in the iText example but still failing. I'm using iText 7.1.15.
        //open file and write to temp one
        PdfDocument pdf = new(new PdfReader(FileToProcess), new PdfWriter(NewPDF), new StampingProperties().UseAppendMode());
        PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
        XfaForm xfa = form.GetXfaForm();
        XElement node = xfa.GetDatasetsNode();
        IEnumerable<XNode> list = node.Nodes();
        foreach (XNode item in list)
        {
            if (item is XElement element && "data".Equals(element.Name.LocalName))
            {
                node = element;
                break;
            }
        }

        XmlWriterSettings settings = new() { Indent = true };

        using XmlWriter writer = XmlWriter.Create(XMLOutput, settings);
        {
            node.WriteTo(writer);
            writer.Flush();
            writer.Close();
        }

        //We now how to strip an extra xfa line if updating
        if(update)
        {
            string TempXML= CSTrackerHelper.MakePath($"{AppContext.BaseDirectory}Temp", $"{Guid.NewGuid()}.XML");
            StreamReader fsin = new(XMLOutput);
            StreamWriter fsout = new(TempXML);
            string linedata = string.Empty;
            int cnt = 0;
            while (!fsin.EndOfStream)
            {
                if (cnt != 3 && linedata != string.Empty)
                {
                    fsout.WriteLine(linedata);
                }
                linedata = fsin.ReadLine();
                cnt++;
            }
            fsout.Close();
            fsin.Close();
            XMLOutput = TempXML;
        }

        xlogger.Info("Populating pdf fields");

        //Now loop through our field data and update the XML
        XmlDocument xmldoc = new();
        xmldoc.Load(XMLOutput);

        XmlNamespaceManager xmlnsManager = new(xmldoc.NameTable);
        xmlnsManager.AddNamespace("xfa", @"http://www.xfa.org/schema/xfa-data/1.0/");
        string[] FieldValues;
        string[] MultiNodes;

        foreach (KeyValuePair<string, DocumentFieldData> v in DocumentData.FieldData)
        {
            if (!string.IsNullOrEmpty(v.Value.Field))
            {
                FieldValues = v.Value.Field.Contains(";") ? v.Value.Field.Split(';') : (new string[] { v.Value.Field });
                foreach (string FValue in FieldValues)
                {
                    XmlNodeList aNodes;
                    if (FValue.Contains("{"))
                    {
                        aNodes = xmldoc.SelectNodes(FValue.Substring(0, FValue.LastIndexOf("{")), xmlnsManager);
                        if (aNodes.Count > 1)
                        {
                            //We have a multinode
                            MultiNodes = FValue.Split('{');
                            int NodeIndex = int.Parse(MultiNodes[1].Replace("}", ""));
                            aNodes[NodeIndex].InnerText = v.Value.Data;
                        }
                    }
                    else
                    {
                        aNodes = xmldoc.SelectNodes(FValue, xmlnsManager);
                        if (aNodes.Count >= 1)
                        {
                            aNodes[0].InnerText = v.Value.Data;
                        }
                    }
                }
            }
        }
        xmldoc.Save(XMLOutput);

        //Now we've updated the XML apply it to the pdf
        xfa.FillXfaForm(new FileStream(XMLOutput, FileMode.Open, FileAccess.Read));
        xfa.Write(pdf);
        pdf.Close();

FYI I've also tried to set a field directly also with the same results.
        PdfReader preader = new PdfReader(source);
        PdfDocument pdfDoc=new PdfDocument(preader, new PdfWriter(dest), new StampingProperties().UseAppendMode());
        PdfAcroForm pdfForm = PdfAcroForm.GetAcroForm(pdfDoc, true);
        XfaForm xform = pdfForm.GetXfaForm();
        xform.SetXfaFieldValue("VRM[0].CoverPage[0].Wrap2[0].Table[0].CSID[0]", "Test");
        xform.Write(pdfForm);
        pdfDoc.Close();

If anyone has any ideas it would be appreciated.
Cheers

A: I ran into a very similar issue. I was attempting to auto fill an XFA that was password protected while not breaking the certificate or usage rights (it allowed filling). iText7 seems to have made this not possible for legal/practical reasons, however it is still very much possible with iText5. I wrote the following working codeusing iTextSharp (C# version if iText5):
using iTextSharp.text;
using iTextSharp.text.pdf;

string pathToRead = "/Users/home/Desktop/c#pdfParser/encrypted_empty.pdf";
string pathToSave = "/Users/home/Desktop/c#pdfParser/xfa_encrypted_filled.pdf";
string data = "/Users/home/Desktop/c#pdfParser/sample_data.xml";

FillByItextSharp5(pathToRead, pathToSave, data);

static void FillByItextSharp5(string pathToRead, string pathToSave, string data)
{
    using (FileStream pdf = new FileStream(pathToRead, FileMode.Open))
    using (FileStream xml = new FileStream(data, FileMode.Open))
    using (FileStream filledPdf = new FileStream(pathToSave, FileMode.Create))
    {
        PdfReader.unethicalreading = true;

        PdfReader pdfReader = new PdfReader(pdf);
        PdfStamper stamper = new PdfStamper(pdfReader, filledPdf, '\0', true);
        stamper.AcroFields.Xfa.FillXfaForm(xml, true);
        stamper.Close();
        pdfReader.Close();
    }
}

A: PdfStamper stamper = new PdfStamper(pdfReader, filledPdf, '\0', true)
you have to use this line.


text:
Q: How to read and compare data from an SQL Server Express database I am trying to create a select statement in C# to check if the value inserted into a textbox (userName) is in an existing SQL database. I have a database called Employee containing a table called EVUSERS and it has a column called UName.
In my code I have a method which takes the value from a textbox called UserBox. I would like to know if there is a temporary table where the select is stored which I can compare the textbox value to.
Here is the code:
private void CheckLoginExist()
{
            String userName = UserBox.Text;

            string connectionString = @"Data Source=.\SQLEXPRESS;Database=Employee;Integrated Security=true";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand command = connection.CreateCommand())
                {

                    command.CommandText = "SELECT UName FROM EVUSERS WHERE UName = @UName";
                    command.Parameters.AddWithValue("@UName", userName);
                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
}

I currently have a select but I am not sure how to display it and I am able to connect to the DB.

A: You need ExecuteScalar, not ExecuteNonQuery
...
connection.Open();
var name = command.ExecuteScaclar().ToString();
connection.Close();

if (name != null) {
  MessageBox.Show("This name already exists");
  return;
}

A: private void CheckLoginExist()
{
    DataTable dt = new DataTable();
    String userName = UserBox.Text;

   string connectionString = @"Data Source=.\SQLEXPRESS;Database=Employee;Integrated Security=true";
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
         SqlDataAdapter da = new SqlDataAdapter("SELECT UName FROM EVUSERS WHERE UName = '" + userName  + "'", _conn);
         da.Fill(dt);
   }
}

Now you can do whatever you want to do with this DataTable.


text:
Q: How do I Limit asp:Repeater in asp.NET? I'm a beginner with ASP.net and now, I want to limit the item in my asp:repeater (It's a RSS feed)
This is my code :
<asp:Repeater ID="rssRepeater" runat="server">
        <ItemTemplate>

                        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#Eval("link")%>' Text='<%#Eval("title")%>'></asp:HyperLink>

                        <asp:Label ID="Label1" runat="server" Text='<%#Eval("description")%>'></asp:Label>

        </ItemTemplate>
    </asp:Repeater>

EDIT :
Code behind
try
            {

                WebResponse rep = rssReq.GetResponse();

                XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());

                DataSet ds = new DataSet();
                ds.ReadXml(xtr);

                rssRepeater.DataSource = ds.Tables[2];
                rssRepeater.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }

have you got a property to limit the display of items ?
Thank you for your help !

A: There is no properties in the repeater that controls the number of rows but you can control it from the DataSource or the SQL query that binds this repeater


text:
Q: No able to run Elmah on .Net MVC 3 I' m using Elmah  https://github.com/alexanderbeletsky/elmah.mvc for a MVC .net project.
For log/in the error I'm using MS SQL.
After installing the Database and installing Elmah through NutGet, I'not able to visualize the error in the database.
Here my Web.Config could you tell me what I'm doingwrong here? Thanks
<?xml version="1.0" encoding="utf-8"?>

    <configuration>
      <configSections>
        <sectionGroup name="elmah">

        </sectionGroup>
      </configSections>
      <connectionStrings>
        <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
        <add name="MyProjectEventsMobileEntities" connectionString="metadata=res://*/Models.EventsCustom.csdl|res://*/Models.EventsCustom.ssdl|res://*/Models.EventsCustom.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;Initial Catalog=MyProjectEventsMobile;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
      </connectionStrings>
      <appSettings>
        <add key="webpages:Version" value="1.0.0.0" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
        <add key="elmah.mvc.disableHandler" value="false" />
        <add key="elmah.mvc.requiresAuthentication" value="false" />
        <add key="elmah.mvc.allowedRoles" value="*" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.0">
          <assemblies>
            <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
          </assemblies>
        </compilation>
        <authentication mode="Forms">
          <forms loginUrl="~/Account/LogOn" timeout="2880" />
        </authentication>
        <membership>
          <providers>
            <clear />
            <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
          </providers>
        </membership>
        <profile>
          <providers>
            <clear />
            <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
          </providers>
        </profile>
        <roleManager enabled="false">
          <providers>
            <clear />
            <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
            <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
          </providers>
        </roleManager>
        <pages>
          <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Web.WebPages" />
          </namespaces>
        </pages>
        <httpModules>
          <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
          <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
          <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
        </httpModules>
      </system.web>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules runAllManagedModulesForAllRequests="true">
          <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
          <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
          <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
        </modules>
      </system.webServer>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <elmah></elmah>
    </configuration>

A: You need to configure elmah to use your database for the logging:
In your config extend <elmah></elmah> to:
<elmah>
    <errorLog type="Elmah.SqlErrorLog, Elmah"
        connectionStringName="MyProjectEventsMobileEntities" />
</elmah>

You can find more option in the ELMAH sample web.config and in the ErrorLogImplementations  wiki article.


text:
Q: How to Compare my sql columns dynamically I am not able to get idea about the following requirement. The example table follows.
CREATE TABLE `test` (
  `Id` INT NOT NULL,
  `Name` VARCHAR(45) NULL,
  `did_fk` INT NULL,
  `adid_fk` INT NULL,
  PRIMARY KEY (`Id`));

INSERT INTO test (id,name,did_fk,adid_fk)
VALUES
(1,'Rajesh',1,1),
(2,'Neeli',2,2),
(3,'Satish',3,3),
(4,'Ganesh',4,5),
(5,'Murali',9,10);

Here I need to compare the "id" with _fk columns i.e. did_fk & adid_fk. The "id" should be equal to did_fk & as well as adid_fk. If any of them is not true, then I should get that row.Here I need to get the rows 4 & 5.Since "_fk" columns are not equal to "id" value.Problem is "_fk" columns are not fixed. But "id" name is fixed.

A: SELECT * FROM `test` WHERE `Id` != `did_fk` OR `Id` != `adid_fk`

A: If your dynamic columns ends with _fk or some another suffix you can try to create SP like following
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetNonEqualFkValues`(IN tableName varchar(255))
BEGIN

DECLARE c_name VARCHAR(255);
DECLARE done INT DEFAULT FALSE;

DECLARE curs CURSOR FOR select column_name from information_schema.columns where column_name like '%_fk';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN curs;
SET @q = concat("SELECT * FROM ", tableName, " WHERE 1!=1 ");
get_col: LOOP
FETCH curs INTO c_name;
IF done THEN
LEAVE get_col;
END IF;

SET @q = CONCAT(@q, " OR ", c_name," != id");
END LOOP get_col;

 PREPARE stmt1 FROM @q;
  EXECUTE stmt1;
END

And then invoke for concrete table like
call GetNonEqualFkValues('test')

The code isn't perfect, but it works for me and I think idea should be clear.


text: Q: Program not closing properly on Linux I have written an application on C#, and ported it onto Linux server (RHEL) using Mono and mkbundle. It works fine, but for some reason program is not closing properly. Right now there are over 30 instances of the program running in the background (according to task manager), although the program didn't return any error, and when it is running on windows or even Ubuntu VM it is working properly and closes without problems. What can be the reason? How can I ensure that program stops completely after execution is finished?


text:
Q: How to subscribe to changes of snapshot (state) of Recoiljs in webcomponent (shadowDOM)? I am able to change state of App from webcomponent and get initial state using recoil-nexus package. But unable to get changing state. For eg- changed state after state is mutated in webcomponent or in app.
As RecoilRoot internally uses react's context API and Webcomponent (shadowDOM) creates new React tree which do not have access to context of the RecoilRoot. How to get changing state in webcomponent of the atom in App?
Webcomponent reference - https://reactjs.org/docs/web-components.html,
Failed attempts:

*

*Tried creating custom hook to get recoil state after useRecoilSnapshot changes.

*Tried Hook rerun on reference of nexus.get change.

*Tried attaching custom state to window using useRecoilTransactionObserver_UNSTABLE(callback).

*Tried recoil-outside which uses rxjs to observe state.

*Tried recoil-sync but did not received event in 'write' event handler prop in webcomponent. It only works inside RecoilRoot and not outside.

*getRecoilPromise might work but how to use async at top level of the component? Tried in useEffect but it did not work for me.

Nothing seems to refresh state in webcomponent.
Alternate Queries:

*

*How to sync snapshot between two different RecoilRoot (which are not nested)?

React component tree in dev tool -


text:
Q: What are some ways to overload Min in order for it to work with user defined expressions? I have defined size to work with discrete size labels:
ClearAll[size, S, M, L]
SetAttributes[size, {Listable}]

sizes = size @ {S, M, L};

I have endowed size with a natural ordering:
MapIndexed[TagSet[size, order[#1], #2[[-1]]] &, sizes]

such that SortBy[#, order]& @ RandomSample[sizes] always evaluates to {size[S], size[M], size[L]}.
I would like to overload Min (and possibly other related functions in the future, but for the moment I'm interested in Min) in order to work with size. My solution makes use of SortBy:
 size /: Min[x__size] := SortBy[{x}, order] // First

 (* random example *)
 BlockRandom[
   Rule[#, Min @@ #] &@RandomChoice[sizes, 3], RandomSeeding -> 125478963]

The random example given above evaluates to {size[L], size[S], size[L]} -> size[S].

*

*Is there a better way to overload Min eg. not using SortBy?

*and more broadly, is there a different way to approach the problem?

*As an aside, when assigning the natural ordering to size I tried attaching definitions (UpValues) to order instead. That works, but requires some care when handling expressions:
Clear[size, order]

MapIndexed[TagSet[order, {order[#1]}, #2]&, sizes];

(* sorting example *)
BlockRandom[
  Rule[#, SortBy[#, order /* List /* First]] &@RandomChoice[sizes, 3], RandomSeeding -> 21648735]

The example above evaluates to {size[S], size[S], size[L]} -> {size[S], size[S], size[L]}. If order /* List is not used, order[size[_]] does not evaluate to a number and SortBy returns unexpected results.
My motivation for doing this was

*

*it felt better having TagSet[order, {order[#1]}, #2] instead of TagSet[size, order[#1], #2[[-1]]] inside MapIndexed and

*it seems more appropriate to attach a definition about the ordering of size to order instead of size itself. On that note, I figured that perhaps it was more natural to use Set[{order[#1]}, #2] instead. Which approach is more robust ie less error prone when the code scales up?


text:
Q: Unable to connect to Git repository through Jenkins I am unable to connect to git repository through Jenkins it gives
[WARNING] Installed git version too old for credentials support

 git config --local credential.username # timeout=10
 git config --local --remove-section credential # timeout=10 Could not remove the credential section from the git configuration

ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from "repository
name"   at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:763)     at
hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1012)     at
hudson.plugins.git.GitSCM.checkout(GitSCM.java:1043)    at
hudson.scm.SCM.checkout(SCM.java:485)   at
hudson.model.AbstractProject.checkout(AbstractProject.java:1276)    at
hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:607)
    at
jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at
hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529)
    at hudson.model.Run.execute(Run.java:1738)  at
hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)     at
hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:410) Caused by:
hudson.plugins.git.GitException: Command "git config --local
credential.username prajaktam" returned status code 129: stdout:
stderr: error: unknown option `local' usage: git config [options]

Config file location
    --global              use global config file
    --system              use system config file
    -f, --file <FILE    use given config file

Action
    --get                 get value: name [value-regex]
    --get-all             get all values: key [value-regex]
    --get-regexp          get values for regexp: name-regex [value-regex]
    --replace-all         replace all matching variables: name value [value_regex]
    --add                 adds a new variable: name value
    --unset               removes a variable: name [value-regex]
    --unset-all           removes all matches: name [value-regex]
    --rename-section      rename section: old-name new-name
    --remove-section      remove a section: name
    -l, --list            list all
    -e, --edit            opens an editor
    --get-color <slot   find the color configured: [default]
    --get-colorbool <slot>
                          find the color setting: [stdout-is-tty]

Type
    --bool                value is "true" or "false"
    --int                 value is decimal number
    --bool-or-int         value is --bool or --int
    --path                value is a path (file or directory name)

Other
    -z, --null            terminate values with NUL byte

    at
org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1640)
    at
org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1616)
    at
org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1612)
    at
org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1608)
    at
org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1337)
    at
org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:62)
    at
org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:313)
    at
org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:152)
    at
org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler$1.call(RemoteGitImpl.java:145)
    at hudson.remoting.UserRequest.perform(UserRequest.java:120)    at
hudson.remoting.UserRequest.perform(UserRequest.java:48)    at
hudson.remoting.Request$2.run(Request.java:326)     at
hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:68)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)     at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at hudson.remoting.Engine$1$1.run(Engine.java:62)   at
java.lang.Thread.run(Thread.java:744)   at ......remote call to Jenkins
Slave(Native Method)    at
hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1416)
    at hudson.remoting.UserResponse.retrieve(UserRequest.java:220)  at
hudson.remoting.Channel.call(Channel.java:781)  at
org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.execute(RemoteGitImpl.java:145)
    at sun.reflect.GeneratedMethodAccessor428.invoke(Unknown Source)    at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)     at
org.jenkinsci.plugins.gitclient.RemoteGitImpl$CommandInvocationHandler.invoke(RemoteGitImpl.java:131)
    at com.sun.proxy.$Proxy47.execute(Unknown Source)   at
hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:761)    ... 11 more
ERROR: null Archiving artifacts Sending e-mails to:
prasad.msrk@sonata-software.com tridev.k@sonata-software.com
krishnachanikya.d@sonata-software.com Warning: you have no plugins
providing access control for builds, so falling back to legacy
behavior of permitting any downstream builds to be triggered Finished:
FAILURE

A: Context
Here is the problem: Installed git version too old for credentials support
What is the result when you execute git --version ?
Solution
Upgrade git to the latest version and try again.

A: Was facing the same issue - the problem for me was that when installing Git on the machine, I unchecked "Enable credential manager". This caused the error for me.
So I uninstalled Git and reinstalled it and made sure to check the checkbox for "Enable credential manager". Then it worked fine.


text:
Q: Adding more properties to existing CQRS Events We are using NEventStore (the artist formerly known as Jonathan Oliver's EventStore) to store our CQRS events. I would like to know if it is necessary to create a new version of an Event if we wish to add a new property to the Event.
I understand that we should not rename an existing property as that will create a problem when reading the events from EventStore. But, if we are only adding new properties will it create any issues?

A: Depends on how you are serializing the messages. In other words, the best way to phrase this (/ search for an existing answer) is to identify how you are serializing the messages and then find out how that mechanism deals with the issue.
Assuming it's JSON with JSON.NET and simple POCOs, then the answer is that adding a property is handled pretty cleanly - in the absence of any customizations (which is very doable), new fields come in withe default(T), i.e. null or 0 for each relevant value.


text:
Q: Google Adsense in Colorbox in Wordpress I am trying to putting some Adsense Ads inside a color box and have done below:
jQuery(document).bind('cbox_load', function(){
    var $ads = jQuery('

');
    jQuery('#cboxContent').prepend($ads);
});

the result turns out to be:

...

Could someone please help to get this Google Adsense work in Colorbox? Thanks.

A: Try making $ads just a string. Drop the jQuery() bit around it.


text:
Q: How to save each video watched on a streaming site? We all watch many streaming videos such as YouTube, Videobb, or others.  Is there any software or application that automatically capture the video while I am watching it?

A: Replay Media Catcher can do this automatically.

The Replay Media Catcher software can capture any form of audio and video media found on the web with a click of a button – saving you hundreds of dollars in the long-run for you music lovers out there.
What this means is that you can be watching a music video on Youtube and with the click of a button, have the entire video on your computer in a matter of minutes.  Or if you prefer, you can choose to only capture the audio from the video and have the mp3 file on your computer almost instantly.

A: Streaming Video Downloader operates exactly as you describe! When you begin watching a video, be it YouTube, live stream, RTMP, or any other supported format, it will automatically start saving it, at the same time showing you a dialog where you can either confirm or cancel the operation. You can also set it up in a fully automatic mode so that not even a confirmation dialog will be shown.
Disclosure: I am one of the authors.

A: I don't know a solution that captures the video automatically. However, there are several solutions that capture on command. For example Video DownloadHelper for Firefox.


text:
Q: Octave suddenly running scripts slowly after crash I am running Octave 4.4.1 x64 on a Dell Precision 7520 (Core i7-7820HQ @ 2.9 GHz, 16 GB RAM) with Windows 10 Pro, which I installed from the binary provided on the GNU FTP site. I have been running a simple physical model that consists of solving a non-stiff non-linear ODE, using a explicit numerical scheme in a for loop. I've been running the model multiple times while changing model parameters in order to fit the solution to some test data I have. The script takes just a couple seconds to run, so it was expedient to run it multiple times to heuristically estimate the model parameter values.
Octave is very buggy on my PC, and crashes often. Usually I just restart it and carry on. Yesterday after a crash, I reopened Octave and tried to run the model again. At first I thought it was hung up, but it turns out the model execution time had just increased by an order of magnitude or more. I checked some other data processing scripts that I've created in the past that used to run very quickly, and they are also now running very slowly, to the point where they are too slow to be useable.
I can run my model in MATLAB and it still takes just a second or so. I used 'profile' in Octave to see where the hang-up might be, and the sum of all the function executions is less than a second, whereas the difference between the tic and toc at the beginning and end of the file is ~25 s.
I've reinstalled Octave, tried different versions of the installer, and I'm at a bit of a loss now. I've tried searching for others' experience with similar problems and haven't come up with anything. Any advice or input would be very much appreciated. Thanks.


text:
Q: If $A \succeq B$, is it true that $B^{-1} \succeq A^{-1}$? If $A$ and $B$ are two positive definite matrices such that $A - B$ is nonnegative definite, is it true that $B^{-1} - A^{-1}$ is positive definite?
The doubt came to me when working with confidence regions in multivariate statistics that are usually obtained as hyper-ellipsoids.

A: Let $x \in \mathbb R^n$, let $y = A^{-1/2}x$. As $0 < B \le A$, we have
$$ \def\<#1>{\left<#1\right>} 0 < \<A^{-1/2}BA^{-1/2}x,x>  = \<By, y> \le \<Ay,y> = \<x,x>
$$
That is $0 < A^{-1/2}BA^{-1/2} \le {\rm Id}$. Now note that $A^{-1/2}BA^{-1/2}$ is simlar to $BA^{-1}$, so $BA^{-1}$ has all its eigenvalues in $(0,1]$. Hence, its inverse $AB^{-1}$, has all its eigenvalues in $[1,\infty)$, so has the similar matrix $A^{1/2}B^{-1}A^{1/2}$, as this matrix is hermitian, we have ${\rm Id} \le A^{1/2}B^{-1}A^{1/2}$. This gives, arguing as the first step above, $A^{-1} \le B^{-1}$.


text:
Q: watch --color doesn't work when a pipe is involved? The following demonstrates that watch works with color, but not when a pipe is involved.
$ touch test.txt
$ ls | grep --color test.txt
test.txt                                  # This IS colored output

$ watch --color 'ls | grep --color test.txt'
Every 2.0s: ls | grep --color test.txt
test.txt                                  # This is NOT colored output

$ ls | grep --color test.txt
test.txt                                  # This IS colored output

$ watch --color 'ls --color'
Every 2.0s: ls --color
test.txt                                  # This IS colored output

I don't understand why watch --color seems to work in the case of just ls but not when piping the output of ls to grep.

A: Analysis
watch captures the output of the command it runs. Normally in an interactive shell a simple command or the last command in a pipeline prints to the terminal. In watch it prints to a pipe; watch reads from this pipe, processes and writes to its own stdout (which is usually a terminal).
ls and grep can colorize their output, each tool on its own. They support --color=auto option. If auto is used, ls or grep will colorize its output if the stdout is a terminal, but not when it's a pipe, regular file etc.
The most important thing: ls --color seems to be equivalent to ls --color=always, while grep --color seems to be equivalent to grep --color=auto. Investigate this:
unalias ls    # because `ls --color=auto' seems to be a common alias
unalias grep  # just in case

# ls prints to terminal
ls                 # no color
ls --color=never   # no color
ls --color=always  # color
ls --color=auto    # color
ls --color         # color

# ls prints to pipe
ls                | cat  # no color
ls --color=never  | cat  # no color
ls --color=always | cat  # color
ls --color=auto   | cat  # no color
ls --color        | cat  # color                      <-- compare this

# grep prints to terminal
echo foo | grep                foo  # no color
echo foo | grep --color=never  foo  # no color
echo foo | grep --color=always foo  # color
echo foo | grep --color=auto   foo  # color
echo foo | grep --color        foo  # color

# grep prints to pipe
echo foo | grep                foo | cat  # no color
echo foo | grep --color=never  foo | cat  # no color
echo foo | grep --color=always foo | cat  # color
echo foo | grep --color=auto   foo | cat  # no color
echo foo | grep --color        foo | cat  # no color  <-- to this

Explanation
The above difference explains your results:

*

*
$ ls | grep --color test.txt
test.txt                                  # This IS colored output

Because grep --color behaves like grep --color=auto and the stdout is the terminal.

*
$ watch --color 'ls | grep --color test.txt'
Every 2.0s: ls | grep --color test.txt
test.txt                                  # This is NOT colored output

Because grep --color behaves like grep --color=auto and its stdout is not a terminal. Notes:

*

*ls itself is colorless here.

*It doesn't matter a pipe is involved. You can observe a similarly colorless result from
watch --color 'grep --color / /etc/fstab'

and there is no pipe in the command.

*(The third example of yours seems to duplicate the first. Skipping.)

*
$ watch --color 'ls --color'
Every 2.0s: ls --color
test.txt                                  # This IS colored output

Because ls --color behaves like ls --color=always; it doesn't matter its output is not a terminal.

Solution
Invoke
watch --color 'ls | grep --color=always test.txt'

to get colors from grep.


text:
Q: Can people read server side node.js? I have code that I don't necessarily want other people seeing (For copyright purposes). can other people read my server side code if it is written in node.js and run from a server I own?

A: No. As long as the files themselves are not served to the user by the webserver, the code cannot be read unless they gain access to your server.

A: Simple, yet very relevant question, thank you!
Generally client-side javascript code is visible to the client, as it is embedded in the HTML page, and it is done with the knowledge of the code owner, without much copyright issues - as they are mainly used as helper functions to render the page in an efficient and powerful manner.
The server-side javascript code which is run in the server (for example in Node platform), you don't have any reason to push those code which contain confidential business logic to the client - instead, you perform the server side activities and build a response to the client, in the form of an HTML page, optionally embedding java-script code which will enrich the page rendition.
So the bottom line is that only the one which is written to the client in response to the request, will be visible outside.
Hope this helps.


text:
Q: Java build error w/o apperant reason I am working on a project that is going on for several months now.
Suddenly when compiling we get the error:
Note: Some input files use unchecked or unsafe operations
Note: Recompile with -Xlint:unchecked for details.

After adding the -Xlint the above message disappear but the only error we get is:
[javac] 1 error

There are however about 45 warning. most of them not new.
Could it be that there is some new warning that I missed that cause the compilation to fail?
Edit:
I forgot to mention that the project builds properly on eclipse.
once a week we build using ant to product a version for the server.
I just want to know if there is a way to pin point the problem otherwise I guess I would have to review last 30 commits or go fix warning by warning.
Edit 2:
Problem fixed. I am not sure what it was exactly but I suspect that editing the my module.gwt.xml using external editor which might have miss-guessed the file encoding, inserted some non-visible characters with a wrong encoding which in turn caused the compiler to give an error w/o a proper description. (maybe I don't know)
So what lessons should I take from this?  handle all warning? (not sure that is always possible.)
using a jenkins? (as @Jayan suggested) the project manager would never approve investing time on such things in my company.

A: This error normally appears when you use a deprecated version of a class that now takes a Generic parameter. For example, in Java 6 and earlier, JList treated everything as Objects, and it was up to the programmer to cast everything correctly. In Java 7, JList is now JList<E>, with the parameter being the type of Objects contained in the list. JList (without generics) will still work, but you will get an error like the one you are experiencing.
EDIT: The reason, by the way, that these operations are considered unsafe is that, without the generics, types cannot be compared at compile time, and must be checked at runtime.


text:
Q: Postgres - LIKE ANY UPPER() Is there a way to use UPPER with a LIKE ANY()?
I have the following example:
SELECT
....
where skus.number like any ('{"%00130204%", "%00130202"}')

Unfortunately the skus I'm checking here can be of different cases, so I tried doing this:
SELECT
....
where UPPER(skus.number) like any UPPER('{"%00130204%", "%00130202"}'))

Which doesn't work, is there any way to get this working in the query itself?

A: No need to use upper. Use the case insensitive version of like, "ilike" instead.
 SELECT
 ....
 where skus.number ilike any ('{"%00130204%", "%00130202"}')

A: along with being totally with @Joe on his answer as better for you query (and skipping phylosophy behind idea to represent digits in uppercase), I decided to answer the topic of your post

Is there a way to use UPPER with a LIKE ANY()?

yes - here it is:
t=# select UPPER('110013020411') like any (UPPER('{"%00130204%", "%00130202"}')::text[]) comaprison;
 comaprison
------------
 t
(1 row)

after you upper text in array represented as text you need to cast it back inorder to use with ANY (array)


text:
Q: Improve loading speed of dynamic contents over the world I've a website that redistributes dynamic contents.
It takes the data from a database and then it generates dynamic images with them.
Data being updated about every 3 minutes.
My server is located in EU, and now i'm wondering if is better off buy another server located in USA to improve the images loading time.
At the moment i'm using MySQL on a linux based os.
I was thinking to replicate all php pages on the secondary server and connect it to the main server who store my database. Is it convenient?


text:
Q: geodjango check PointField in PolygonField I have two django models:
class Region(models.Model):
    geometry = models.PolygonField()

class Position(models.Model):
    coordinates = models.PointField()

I am trying to check if a Position is  geographically contained inside a Region:
def check(region, position):
    return position.coordinates.intersect(region.geometry)

But it always return False, even when the Position is contained inside the Region (I am rendering both the PointField and the RegionField with django-leaflet).
I also tried using:
def check(region, position):
    return position.coordinates.within(region.geometry)

but no results so far. Here is the test data that I am using (geojson):
{"coordinates": [46.2071762, 11.1245718], "type": "Point"}
{"coordinates": [[[11.102371215820312, 46.21939582902924], [11.106491088867188, 46.22111800038881], [11.134214401245117, 46.22188999070486], [11.140050888061523, 46.21791115519151], [11.141080856323242, 46.21422899084459], [11.137990951538086, 46.207695510993354], [11.13412857055664, 46.20122065978115], [11.12485885620117, 46.198844376182535], [11.102371215820312, 46.21939582902924]]], "type": "Polygon"}

Any hint on what the problem could be?
Thanks in advance!

A: Your mistake is logical, I guess.Point's latitude and longitude should be swapped.
I mean
{"coordinates": [11.1245718, 46.2071762], "type": "Point"}

Instead of
{"coordinates": [46.2071762, 11.1245718], "type": "Point"}


text:
Q: tick marks in matplotlib I am creating a subplot using matplotlib, where the top x-axis is different from the bottom x-axis. I added the xticks and xlabels to the top myself.
I would like there to be xtick marks corresponding to the bottom x-axis at the bottom of the middle and top subplots, where the xticks point outwards (or down) - like at the very bottom. Is there a way to do this?
This is the code I am using so far to customize the ticks:
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=False, sharey=False)
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

ax3.get_xaxis().set_tick_params(direction='out', top='off', which='both')
ax2.get_xaxis().set_tick_params(direction='out', bottom='on', top='off', which='both')

ax1.minorticks_off()
ax1.get_xaxis().tick_top()
ax1.set_xticks([np.divide(1.0,100.0), np.divide(1.0,50.0), np.divide(1.0,35.0),
                np.divide(1.0,20.0), np.divide(1.0,10.0), np.divide(1.0,5.0),
                np.divide(1.0,3.0), np.divide(1.0,2.0), np.divide(1.0,1.0)])
ax1.set_xticklabels([100, 50, 35, 20, 10, 5, 3, 2, 1])

I am finding that since I made customized xticks for the top plot, I can't do this, and specifying the direction to be 'out' in the bottom subplot ruins the tick marks in the middle. Since there is no space between the subplots, the top of the bottom plot shares its x-axis with the bottom of the middle subplot, etc...
Is there a workaround for this?

A: You can draw the middle axes above the bottom axes by setting the respective z orders. The top ticks can be done w/a call to axvline.
import matplotlib.pyplot as plt
import numpy as np

f, (ax1, ax2, ax3) = plt.subplots(3, sharex=False, sharey=False)
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

ax3.get_xaxis().set_tick_params(direction='out', top='off', which='both')
ax2.get_xaxis().set_tick_params(direction='out', bottom='on', top='off', which='both')

ax1.minorticks_off()
ax1.get_xaxis().tick_top()
ax1.set_xticks([np.divide(1.0,100.0), np.divide(1.0,50.0), np.divide(1.0,35.0),
                np.divide(1.0,20.0), np.divide(1.0,10.0), np.divide(1.0,5.0),
                np.divide(1.0,3.0), np.divide(1.0,2.0), np.divide(1.0,1.0)])
ax1.set_xticklabels([100, 50, 35, 20, 10, 5, 3, 2, 1])

for i, ax in enumerate((ax3, ax2, ax1)):
    ax.set_zorder(i)
for tick in ax2.xaxis.get_ticklocs():
    ax2.axvline(tick, ymin=0.9)
plt.show()


text:
Q: finite and infinite subsets of positive integers Prove that the set consisting of all subsets(both finite and infinite) of set , P, of positive integers is uncountable using the following approach. First clearly P is countable so we can list all the integers in P and clearly map each element in this list into a subscript of its location in this list. Write down the first 10 elements in this list. Now suppose we can list all subsets of the set, P in another list. Write down an example first 10 elements of this list. Now neatly complete the argument to prove uncountability using both list.

A: Firstly show that there exists a bijection between $\mathscr P(P\text{ or }\Bbb N)$ and some uncountable set. This would mean that they have the same cardianality.
Take the set $[0,1]\subset\Bbb R$ it is uncountable. Now every real number in between $0$ and $1$ can be shown to be equivalent to a subset of $\Bbb N$ eg your $P$. This is easier to visualize in binary. We can construct a bijective function $\varphi:[0,1]\to\mathscr P(\Bbb N)$ such that $\varphi(0)=\varnothing$ and $\varphi(1\text{ or }0.1111\cdots)=\Bbb N$. Now represent$[0,1]\ni x=\sum^\infty_{n=1}\frac{b_n}{2^n}$ where $b_n$ repersents the nth binary digit now we can define $\varphi:0.b_1b_2b_3\cdots\mapsto\{n\in\Bbb N : b_n=1\}$ therefore for every binary number there is a corresponding subset of $\Bbb N$. You can rigorously show the bijectivity of $\varphi$ if you want. An example to make it clear would be $\varphi(0.010101\cdots)=\{2, 4, 6\cdots\}\tag*{$\square$}$


text:
Q: Running an application on android studio I have created an android application project. I want to run it in a genymotion virtual device, but when i select the virtual device it gives me an error:

Failed to complete Gradle execution. Cause: (nothing written in)

then, when i click ok, it says:

Unexpected Error.
  Local path doesn't exist. Local path doesn't exist. The project may need to be synced with Gradle files.

How can i solve the problem?


text:
Q: plist wont pull into my NSMutableArray. am i missing something? So here's my code. I'm trying to display content from a plist into a table and i keep running into errors. ive been at it all day so i'm probably missing something fairly easy. hope you guys can figure out why when i build, the table is empty.
here is my plist (without headers):
<array>
<dict>
    <key>word</key>
    <string>AWord1</string>
    <key>definition</key>
    <string>here is a definition</string>
    <key>partOfSpeech</key>
    <string>here is a part of speech</string>
</dict>
<dict>
    <key>word</key>
    <string>Bword1</string>
    <key>definition</key>
    <string>here is a definition</string>
    <key>partOfSpeech</key>
    <string>here is a part of speech</string>
</dict>
</array>
</plist>

edit: closing tags were missing due to misformatting - fixed
ok. here is my new code. i NSLog'd and decided to back up to before i went to plist. so, if you could help. how would you suggest i pull this data from plist instead (assuming the data is in the plist)
//Initialize the array.
listOfItems = [[NSMutableArray alloc] init];

NSArray *countriesToLiveInArray = [NSArray arrayWithObjects:@"Iceland", @"Greenland", @"Switzerland", @"Norway", @"New Zealand", @"Greece", @"Italy", @"Ireland", nil];
NSDictionary *countriesToLiveInDict = [NSDictionary dictionaryWithObject:countriesToLiveInArray forKey:@"Countries"];

NSArray *countriesLivedInArray = [NSArray arrayWithObjects:@"India", @"U.S.A", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", @"Test", nil];
NSDictionary *countriesLivedInDict = [NSDictionary dictionaryWithObject:countriesLivedInArray forKey:@"Countries"];

[listOfItems addObject:countriesToLiveInDict];
[listOfItems addObject:countriesLivedInDict];

//Initialize the copy array.
copyListOfItems = [[NSMutableArray alloc] init];

//Set the title
self.navigationItem.title = @"Countries";

//Add the search bar
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;

searching = NO;
letUserSelectRow = YES;

i feel as though i'm still not actually telling it to parse the data from the plist. i've only init'd it. thoughts?

A: Your code seems very incomplete, it doesn't bear much relation to the plist. Here are a few issues

*

*as noted by H2CO3 and Fogmeister, the plist as you show it is missing a closing </array> tag (but lets assume that is a typo in the question)

*you load the entire array into a single entry in a countriesToLiveIn dictionary (against the key "definition")

*countriesToLiveIn becomes a single object in the array listOfItems

*you initialise a copyOfListItems array but then don't do anything with it

Then you do not indicate where the table is getting it's date from.
If it is from copyOfListItems, well that array is empty .: empty table.
If it is from listOfItems you will be parsing the countriesToLiveIn dictionary somehow, but you don't show how.
If it is directly from the plist array countriesToLiveInArray then that missing </array> tag could be a clue. You would also need to be parsing the array's contained dictionaries somehow, and you don't show us that code, there could be something wrong there.
To get further with this I suggest copious use of NSLog to find out how far the data gets in to your objects. Perhaps you could expand your question with the results if you are still getting stuck.
update
Following your updated code, my first suspicion is that there was a problem with your URL.
in your previous edit this is the suspect line
NSMutableArray *wordListArray = [[NSMutableArray alloc] initWithContentsOfURL: [NSURL URLWithString:@"http://url.com/dictpPlist.plist"]];

You need to NSLog right after it:
NSLog (@"wordListArray %@", wordListArray);

To confirm that you are not picking up the plist here. At least then we isolate the problem to this point in your code.
Then we need to question the URL - is it correct? how did the plist get there? can you verify it independently? Is it a local file URL or a network URL?
If you are accessing a network resource, this is quite likely your problem. The initWithContentsOfURL methods should only really be used with local filesystem URLs. See for example
initwithcontentsofurl methods considered harmful.
You should be using NSURLConnection asynchronously instead. Apple is a little cagey about this also:

aURL: The location of a file containing a string representation of an array produced by the writeToURL:atomically: method.

Assuming this is your issue, why don't you get it working with a local filesystem plist first.
Write one in code from your listOfItems array:
- (void) createPlist
{
    NSFileManager* fManager = [NSFileManager defaultManager];
    NSError* error;
    NSURL* docsURL = [fManager URLForDirectory:NSDocumentDirectory
                                          inDomain:NSUserDomainMask
                                 appropriateForURL:nil
                                            create:NO
                                             error:&error];

    NSURL* plistURL = [docsURL URLByAppendingPathComponent:@"testlist.plist"];
    [listOfItems writeToURL:plistURL atomically:YES];
}

Read it back in, verify it works, then sort out how to do the same over a network.

A: try below code
// Path to the plist (in the application bundle)
     NSString *path = [[NSBundle mainBundle] pathForResource:
    @"dictpPlist" ofType:@"plist"];

// Build the array from the plist
     NSMutableArray *array2 = [[NSMutableArray alloc] initWithContentsOfFile:path];

// Show the string values
    for (NSString *str in array2)
      NSLog(@"--%@", str);


text:
Q: Passing a value to a function that accepts a reference In the following example sin.connect accepts a const reference. Why both sig.connect(printHello); and sig.connect(&printHello); compile without problems and produce the same result? What is the difference between passing a val and ref to a function that accept a reference?
#include <boost/signals2.hpp>
#include <iostream>

void printHello()
{
  std::cout << "Hello World" << std::endl;
}

int main(){
    boost::signals2::signal<void ()> sig;
    sig.connect(printHello); // <- slot reference
    sig.connect(&printHello); // <- slot
    // sig.connect(const slot_type &slot) <- signature
    sig();
}


text:
Q: non-static declaration following static declaration Consider these examples:
static int a;
extern int a; //OK -- what linkage does the a have now?

static int a;
int a; //ERROR

extern int a;
static int a; //ERROR

int a;
static int a; //ERROR

extern int a;
int a; //OK as expected

int a;
extern int a; //OK as expected

Why was it OK in the first example but not in the second?
As far as file-scope variables (global-scope) are concerned, these have external linkage and a static duration when no keyword is specified.
Thank you
AFAIK, linkage and storage duration for functions is a bit different.
EDIT:
I've tried compiling using gcc 4.5.2 -Wall -pedantic --std=c99
More on: http://c-faq.com/decl/static.jd.html You can see that the 1st example works there too but 2nd doesn't. However, I don't see what makes them so different.

A: The answer to your first question is found in §6.2.2 of the C standard:

4 For an identifier declared with the storage-class specifier extern
  in a scope in which a prior declaration of that identifier is visible,
  if the prior declaration specifies internal or external linkage, the
  linkage of the identifier at the later declaration is the same as the
  linkage specified at the prior declaration. If no prior declaration is
  visible, or if the prior declaration specifies no linkage, then the
  identifier has external linkage.

So the linkage of a is internal.
For your second question, the second sentence of the immediately following paragraph is apropos:

5 If the declaration of an identifier for a function has no
  storage-class specifier, its linkage is determined exactly as if it
  were declared with the storage-class specifier extern. If the
  declaration of an identifier for an object has file scope and no
  storage-class specifier, its linkage is external.

Because a is an object, not a function, the declaration int a; with no storage-class specifier gives a external linkage.  The same section then has this to say:

7 If, within a translation unit, the same identifier appears with both
  internal and external linkage, the behavior is undefined.

Since, in your second example, a appears with both internal and external linkage, this paragraph is triggered.  One (particularly helpful) manifestation of undefined behaviour is the error that your compiler is producing.
All of your examples can be understood by these rules:

*

*int a; always declares a with external linkage;

*static int a; always declares a with internal linkage;

*extern int a; declares a with whatever linkage it already had, or external linkage if it had none;

*Two declarations of a in the same scope with different linkage give undefined behaviour.

A: I got same error when I forget "{" instead of ";" at the end of a declaration.
Example:
extern void *HASHMP_get(struct HASHMP_wf_s *hmwf_ptr, Uint8 *key);
extern void *HASHMP_remove(struct HASHMP_wf_s *hmwf_ptr, Uint8 *key) {
extern Uint16 HASHMP_clear(struct HASHMP_wf_s *hmwf_ptr);


text:
Q: Mostrar/Ocultar Tab Bar ítem en swift lo que quiero hacer es teniendo una APP que se  que se conecta a un sistema de Admin y usuario. Cuando el admin acceda la Tab Bar muestre elementos que no están disponibles para un usuario que inició sesión no como admin. Hasta ahora lo único que encontré fue como ocultar la barra completa nada más. Agradezco sus respuestas
if let tabBarItem = self.tabBarController?.tabBar.items?[3] as? UITabBarItem {
        tabBarItem.enabled = false
}


text:
Q: Scrolling inside a DIV that does not have position:absolute? I have a website with 5 horizontal divs whom all float:left and have a % width. The left one I want to have text in, and a scrollbar. However, the scrollbar only shows up when I give it a position:absolute. Try it in the jsfiddle. When I do that, the div ignores the other 4 and they get out of line. How do I work around this?
The jsfiddle > http://jsfiddle.net/QN8RS/
Add position:absolute; to the following div in CSS. You will see it working, but the divs get out of place..
#left{
    float:left;
    background-color:#C00;
    width:15%;
    height:100%;
    overflow:auto;
    top: 0px;
    bottom: 0px;
}

A: You haven't specified the height of the <body> so its height is computed as auto.
You specified the height of .main as 100%. This is a percentage so, because the height of its parent (the body) is computed as auto, the computed height is also auto.
You specified the height of #left as 100%. This is a percentage so, because the height of its parent (.main) is computed as auto, the computed height is also auto.
Since the height is auto, the height as is tall as it needs to be to hold all the content.
Since you have set overflow: auto, you only get scrollbars if the content is taller then the element (which it isn't).
Set height: 100% on the html and body elements so that the computed height of #left is the height of the viewport and not auto.

A: I think you are looking for :
overflow-y: scroll
Little Fiddle

A: The reason is that you have specified height:100% on your div .main. 100% of what? Which parent?
If you specify the height of body to 100% then it will work.
html, body { height: 100%; }

Check your updated fiddle: http://jsfiddle.net/QN8RS/2/

A: Instead of using floats, use position: absolute; and left: number%; (you will have to figure out how much % the left is of each element).
Check out the Fiddle:
http://jsfiddle.net/QN8RS/3/


text:
Q: Does irreflexivity guarantee acyclicity? Assume $R$ to be an irreflexive, transitive relation over a set $X$. Let $G=(X,E)$ be its directed graph where $(x,\hat{x})\in E$ if $xR\hat{x}$ is true.
I know irreflexivity means $xRx$ cannot happen for any $x\in X$. Does this guarantee that $G$ is a directed acyclic graph or $DAG$? .
Another question maybe off-topic: if I have two relations $R,\hat{R}$ where both are irreflexive, does it guarantee that $R^*=R\cup\hat{R}$ is also irreflexive for any product strategy $\cup$?

A: A Strict Partial Order can be characterized directly by a DAG. It requires irreflexivity, transitivity, and asymmetry. However the asymmetry is implied by the previous two conditions. Since every irreflexive, transitive relation is a strict partial order, then they are all characterized by DAGs.


text:
Q: como puedo capturar el valor con js de un select dinámico creado con php? tengo el siguiente select creado con php para mostrar el directorio de una carpeta específica.
el select lo creo de esta manera dado que le envío la ruta mediante ajax. luego muestro o cargo el select dentro de un div

$ruta = $_POST['ruta'];

        $cadena = "<select id='ruta_directorio' name='ruta_directorio' class='form-control input-sm'>";
        $cadena = $cadena . '<option value="">Seleccione</option>';

        $directorio = $ruta;
        $ficheros  = scandir($directorio, 1);
        $contador = 0;

        while ($contador < count($ficheros)) {
            if ($ficheros[$contador] != "." && $ficheros[$contador] != "..") {
                $cadena = $cadena . '<option value=' . $ficheros[$contador] . '>' . $ficheros[$contador] . '</option>';
            }
            $contador++;
        }
        echo $cadena . "</select>";

y tengo el siguiente código en js para detectar cuando cambie la selección del select, pero aun sin funcionar, dado que no detecta cuando cambio de opción.

$('#ruta_directorio').on('change', function() {
        dir_select = $('#ruta_directorio').val();
        if (dir_select != "") {
            document.getElementById('referencia_ruta').innerHTML = "/" + dir_select; // le asigno el valor a un label
        }
    });

espero haber sido claro y me puedan ayudar con esto... GRACIAS!

A: Tu código debería funcionar, pero estás cometiendo un error al concatenar en PHP: dentro del while haces esto:
$cadena = $cadena . '<option value=' . $ficheros[$contador] . '>' . $ficheros[$contador] . '</option>';

Así, se rompe todo lo que pusiste antes del while y el select no se crea adecuadamente. Si cambiar por esto:
$cadena .= '<option value=' . $ficheros[$contador] . '>' . $ficheros[$contador] . '</option>';

continuarás concatenando y el select se creará completo, con su id.
Dado que la mezcla de comillas dobles y simples y los puntos y etiquetas del tipo < y > crean un código demasiado confuso en PHP a mi me gusta más este estilo:
    $cadena = "<select id=\"ruta_directorio\" name=\"ruta_directorio\" class=\"form-control input-sm\">
    <option value=\"\">Seleccione</option>";

    $directorio = $ruta;
    $ficheros  = scandir($directorio, 1);
    $contador = 0;

    while ($contador < count($ficheros)) {
        if ($ficheros[$contador] != "." && $ficheros[$contador] != "..") {
            $cadena .=  "<option value=\"$ficheros[$contador]\">$ficheros[$contador]</option>";
        }
        $contador++;
    }
    $cadena .="</select>";
    echo $cadena;

Se trata simplemente de usar comillas dobles para abarcar la cadena, y dentro de ella, usar también comillas dobles donde se necesite, escapándolas con \. Eso te permitirá meter variables dentro de la cadena sin necesidad de concatenar con el punto. Así el código queda más uniforme y más fácil detectar cualquier error.
Dos cosas sobre el código JS:

*

*Puedes usar $(this) simplemente en el código para capturar el valor seleccionado.

*Es más seguro usar textContent que innerHTML
He aquí un ejemplo:

$('#ruta_directorio').on('change', function() {
        dir_select = $(this).val();
        console.log(dir_select); /*Sólo para prueba, luego quitar esta línea*/
        if (dir_select != "") {
            document.getElementById('referencia_ruta').textContent = "/" + dir_select; // le asigno el valor a un label
        }
    });

<select id="ruta_directorio">
  <option value="" selected>–Seleccione una ruta–</option>
  <option value="ruta1">Ruta 1</option>
  <option value="ruta2">Ruta 2</option>
  <option value="ruta3">Ruta 3</option>
</select>


text:
Q: Which one is preferred, return const double& OR return double Given the following scenario, which one of the following is preferred.
m_state is a member rater than a local variable.
class C
{
private:
    double m_state;
public:
    double state() const { return m_state; } // returns double
    double& state() { return m_state; }
}

===========================================
class C
{
private:
    double m_state;
public:
    const double& state() const { return m_state; } // returns const double&
    double& state() { return m_state; }
}

A: I wouldn't do this:
double& state() { return m_state; }

You may as well make m_state public if you did that. Probably what makes the most sense is:
const double & state() const { return m_state; }

Then again, when you're talking about saving the copy of a 64 bit variable (ie micro-optimization) and the fact that the latter version can be recast to whatever you want, I would just copy it:
double state() const { return m_state; }

(not that there's any true security anyway)

A: For something like a double just doing double state() const { ... } would be fine, the copy is fast, you and the caller don't need to worry about whether the return value can be modified, and it can be called from a const or non-const reference to the object.
For something more complex like an object it really depends on if you want to the caller to be able to modify it, perhaps you want them to be able to call non-const members if they are getting an object. If so then MyClass & state() const { ... } is your best bet.

A: It makes more sense to just return a double.  Because you're not returning a reference to a more complex object.  This is likely to be done in registers so it'll be marginally faster.
If you really want to return a reference then make it a const const.
Rule of thumb is, simple types just return them.  Objects - by reference.  Anything else is needless complexity.

A: Rule of thumb:

*

*built-in (int, double, pointer) -> value

*user-defined -> const reference
The following caveat applies: if you know what a POD (Plain Old Data) is, and you have one with a reasonable size, you can return it by value.

A: Are you trying to do a property like structure? If so, why don't you use getState() and setState(...)?

A: I would argue that the second version is preferred:
const double& state() const { return m_state; } // returns const double&

simply because it's consistent with how you would write this type of function if the return value was more complex. In your case, neither version would be any faster or safer than the other anyway.

A: The other answers have addressed the readability and code hygene implications of either approach.
As far as performance on the modern x86 archs is concerned, if the function is inline, it makes no difference either way. If the function is not inline, there is a tiny advantage to returning double rather than const double &, because the double just gets returned on a register, whereas the reference returns a pointer which must then be loaded through. But the one cycle cost of that is totally swamped by the penalty of having a non-inline function.

A: My suggestions :
Never return handle to the private data members of the class by public interface to make sure that client cant't modify it.
Check out effective C++ topic on it by scott mayers.


text:
Q: changing file content - is this a bug in g++ 4.7.2 or am I doing it wrong? While writing some code to update a position in a binary file I noticed something strange. Consider this example code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    char tmp;
    string s;
    fstream fs;

    fs.open("test.txt", fstream::out);
    fs << "blub" << endl;
    fs.close();
    fs.open("test.txt", fstream::in);
    fs >> s;
    cout << s << endl;
    fs.close();

    fs.open("test.txt", ios::in|ios::out|ios::binary);
    if (!fs.is_open() || !fs.good())
        cerr << "could not open!" << endl;

    fs.read(&tmp, 1);
    fs.read(&tmp, 1);
    //fs.tellg(); //<-- required to fix for old g++?
    const char *c = "ah";
    fs.write(&c[0], 1);
    fs.write(&c[1], 1);
    fs.close();

    fs.open("test.txt", fstream::in);
    fs >> s;
    cout << s << endl;
}

In recent g++ versions (at least with 6.2.1), I can just read and then write some bytes without problems - In the example you get the correct output:
blub
blah

Then I compiled the code with g++ 4.7.2 and suddenly the update has no effect, i.e. the second output is still "blub", unless I add fs.tellg() or fs.tellp(). I've found this question, but as I understand, this is a limitation under Windows, but I am working under Linux.
Now I wonder, is this a bug in the old g++ or am I doing it wrong and was just lucky with the modern g++ version, where it just works? Second question, why does asking for the current position fix it?
Thanks in advance!

A:
Now I wonder, is this a bug in the old g++

No, there is no bug in g++ in this regard.

or am I doing it wrong

Yes. This is explained in the answer that you linked.

... output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file.

Which is from C standard but made relevant by:

The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library FILEs.

There is a bug, but it is in your code. Your program doesn't meet the requirements laid out by the standard.

but as I understand, this is a limitation under Windows

That may possibly be the case, but more generally the limitation is in C++ (and C) specification. Whether a standard library has the limitation has no effect on whether the library is standard compliant. Any code that depends on the non-existence of the limitation is not compliant with the standard.

and was [I] just lucky with the modern g++ version

One might say that you were unlucky. It was a stroke of luck when the program didn't work and you discovered the bug.

Second question, why does asking for the current position fix it?

I doubt that tellg is sufficient to make your program compliant with the standard. So, I would say that it "fixes" the program by chance.
You should probably be using std::flush(fs); instead.

this would mean that the NEW version is LESS standard compliant?

No, both versions of g++ are equally compliant in this regard. Your program isn't.


text:
Q: Using Asp.net Core MVC Bootstrap 4 and I can't get the unobtrusive validation working quite right for server side added modelstate errors Everything seems to work great with the validation annotations on the view model. However, I am having issues when, on the server-side (after a form post), I do some additional validations and add modelstate errors. Those errors actually render appropriately and come through in the response from the server, however, the errors that are associated with one of the properties/inputs on the form, those end up getting cleared out some how. Now, if I put the validation summary on the page, the message does show there, but the message related directly to the input doesn't show and the input isn't marked as invalid any longer. Any idea on what might be going on?
I'm using jQuery v2.1.4, jQuery Validation v1.14.0, jQuery Validation Unobtrusive v3.2.6, Bootstrap 4.4.1, and I am using version v2.2.0 of this plugin: https://github.com/brecons/jquery-validation-unobtrusive-bootstrap. I couldn't get any of the BS4 validation stuff working/looking right until I found that plugin that I just mentions. Now it works and looks great, but server-side added modelstate errors don't end up coming through to the client like I would like. And I think that they are coming form the server to the client ok in the response, but I think that there is possibly some script processing that is clearing those error messages. I figure someone has solved this issue by now.
The cshtml setup:

    <input asp-for="Email" class="form-control" type="email" autocomplete="off" autofocus="true" />
    __

the server-side add model error statement:
this.ModelState.AddModelError(nameof(LoginViewModel.Email), "Your account has been disabled.");

The response as it came from the server to the client:

    Email Address
    <input class="form-control input-validation-error" type="email" autocomplete="off" autofocus="true" data-val="true" data-val-required="The Email Address field is required." id="Email" name="Email" value="disabled@rew.com" />
    _Your account has been disabled._

This is from an inspection of the page after the page shows in the browser. As you can see the validation message that came from the server is gone and the input is cleared of the error:

    Email Address
    <input class="form-control input-validation-error is-valid" type="email" autocomplete="off" autofocus="true" data-val="true" data-val-required="The Email Address field is required." id="Email" name="Email" value="disabled@rew.com" style="" aria-required="true" aria-invalid="false" aria-describedby="Email-error">

    __

A: You need to add custom css for this to work

.field-validation-error { color:red; font-size: smaller; }
.input-validation-error{ border-color: #dc3545; }

Because the validation-for in dotnet MVC use this class in the rendered html:

The Name field is required.
<input class="input-validation-error form-control" data-val="true" data-val-length="The field Name must be a string with a maximum length of 255." data-val-length-max="255" data-val-required="The Name field is required." id="Customer_Name" maxlength="255" name="Customer.Name" type="text" value="">

Credit to this blog:
https://dotnetthoughts.net/how-to-use-bootstrap-style-validation-in-aspnet-core/


text:
Q: How to sort a file by name then by score (Python) Hi am wondering how to sort a file  by name (alphabetically) then by score (numerically - highest to lowest).
For example if a name starts with an A (Anna ect) and the other name started with a B (bella) they will be alphabetically sorted, however if bella got a higher score than Anne then belle would go before Anne when the file is printed out.

A: Use following for sort first on name and then number
>>> list = [{'name':'ABC','number':45}]
>>> sorted(list, key = lambda d: (d['name'], d['number']))


text:
Q: Changing JPanel Icon when JButton is clicked The JFrame window needs to display a random dice image. When the button is clicked, the random dice image needs to change. I have figured out how to display the random dice image, but I cannot figure out how to use the actionlistener to generate a new random dice image. I am only in my third Java class, so any guidance would be greatly appreciated!
package guiDice;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.event.ActionEvent;

public class LabGuiDice extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LabGuiDice frame = new LabGuiDice();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public LabGuiDice() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JButton btnRollem = newDiceRoll();
        contentPane.add(btnRollem, BorderLayout.SOUTH);

        JLabel lblDice = newDiceImage();
        contentPane.add(lblDice, BorderLayout.CENTER);
    }

    private JLabel newDiceImage() {
        Random rnd = new Random();
        int rand1 = 0;
        rand1 = rnd.nextInt(6)+1;
        JLabel lblDice = new JLabel("");
        switch (rand1) {
        case 1:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-1.png")));
            break;
        case 2:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-2.png")));
            break;
        case 3:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-3.png")));
            break;
        case 4:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-4.png")));
            break;
        case 5:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-5.png")));
            break;
        case 6:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-6.png")));
            break;
        }
        return lblDice;
    }

    private JButton newDiceRoll() {
        JButton btnRollem = new JButton("Roll 'Em");
        btnRollem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        btnRollem.setBorderPainted(false);
        btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
        btnRollem.setOpaque(true);
        btnRollem.setBackground(new Color(255, 0, 0));
        return btnRollem;
    }
}

A: Create a method that generates the integer and sets the icon to the label. But in order to do that, label should be a field in the class, so all methods can access it. For example:
private void rollDice() {
    Random random = new Random();
    int randomInt = random.nextInt(6) + 1;
    String resource = String.format("/Dice/die-%d.png", randomInt);
    Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
    diceIconLabel.setIcon(icon);
}

and then:
btnRollem.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        rollDice();
    }
});

with full code:
public class LabGuiDice extends JFrame {

    private JPanel contentPane;
    private JLabel diceIconLabel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    LabGuiDice frame = new LabGuiDice();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public LabGuiDice() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JButton btnRollem = newDiceRoll();
        contentPane.add(btnRollem, BorderLayout.SOUTH);

        diceIconLabel = newDiceImage();
        contentPane.add(diceIconLabel, BorderLayout.CENTER);
        rollDice();
        pack();
    }

    private void rollDice() {
        Random random = new Random();
        int randomInt = random.nextInt(6) + 1;
        String resource = String.format("/Dice/die-%d.png", randomInt);
        Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
        diceIconLabel.setIcon(icon);
    }

    private JLabel newDiceImage() {
        JLabel lblDice = new JLabel("");
        lblDice.setHorizontalAlignment(SwingConstants.CENTER);
        return lblDice;
    }

    private JButton newDiceRoll() {
        JButton btnRollem = new JButton("Roll 'Em");
        btnRollem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                rollDice();
            }
        });
        btnRollem.setBorderPainted(false);
        btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
        btnRollem.setOpaque(true);
        btnRollem.setBackground(new Color(255, 0, 0));
        return btnRollem;
    }
}


text:
Q: Magento add Flexslider to homepage I am using the Bitnami Magento https://bitnami.com/stack/magento stack and trying to add flexsliderto the homepage.  I'm getting this error in my custom.js file:
SCRIPT438: Object doesn't support property or method 'flexslider'

for the Home Page I've added this to the CMS->Pages->Design-Custom Layout Design XML
<reference name="head">
    <action method="addCss"></action>
    <action method="addJs"></action>
    <action method="addJs"></action>
    <action method="addJs"></action>
</reference>

All the scripts are loading I've verified with the browser debugger console
This is the custom.js script
$.noConflict();

jQuery(window).load(function () {
    jQuery('.flexslider').flexslider();
});

This is in CMS->Pages->Content for the homepage

Another interesting thing is that when I change the Custom Theme on the page design to anything else besides the rwd default it will load the slider correctly.

A: There is a slider that comes with the RWD theme and I am using that now.  This article explains how to use it.
http://www.creare.co.uk/new-features-magento-ce-1-9-responsive-theme#slider

A: I followed the instructions here https://www.youtube.com/watch?v=AmiM4oWGrLI and got it to work on my site. Your approach seems sound so I suspect there's some sort of conflict with rwd default. Have you Firebuged it to eliminate conflicting classes/ids?