text:
Q: How to search for an int[] in List and remove item in c# Supposing I have a List<int> its easy to search for an integer, lets say 6
List<int> list = new List<int>(){1, 2, 3, 4, 5};
if(list.Contains(6))
   Console.Write("6 exists");

but how would I search for a int[] in a List<int[]>
List<int[]> example = new List<int[]>();
example.Add(new int[4]{0,1,2,3});
example.Add(new int[4]{10,11,12,13});
example.Add(new int[4]{20,21,22,23});

How to search for {0,1,2,3} and also delete that index on list?
int[] toFind = new int[4]{0,1,2,3};
foreach (int[] item in list)
{
   if(item.Length == toFind.Length)
   {
       bool found = false;
       for(int i=0; i < item.Length;i++)
       {
          if(item[i] == toFind[i])
          {
              found = true;
          }
           else
          {
              found = false;
           }
       }
   }
}

I was trying to first compare wanted item  length with each item length, the compare each item on array.
There must be a better way to do this...

A: You can use FindIndex() and the Linq extension SequenceEquals:
int index = list.FindIndex(arr =>  arr.Length == toFind.Length && arr.SequenceEqual(toFind));
if (index >= 0) list.RemoveAt(index);

Note that SequenceEqual returns true only if the elements in the sequence are in the same order. So {1,2,3,4} is not the same as {2,1,4,3}.

A: You aren't allowed to change a List object in a foreach loop, but you can use a for loop instead.
private void removeFromList(List<int[]> list, int[] compare) {
   for (int i = 0; i < list.Count; i++) {
      if (list[i] == compare) {
         list.RemoveAt(i);
       }
     }
}


text:
Q: How I can simplify this code? convert file json to array json I have this json file, and I'm turning into a json array, everything works fine, but the real json file contains more data.
How to simplify this code could either change the javascript or json file.
{
"Subject1":{
    "Biology":{
        "Category":{
            "Cell":{
                "question1":{
                    "que1":"what's....?"
                },
                "question2":{
                    "que2":"what's....?"
                },
                "question3":{
                    "que3": "what's....?"
                }
            },
            "Bactery":{
                "question1":{
                    "que1":"what's....?"
                },
                "question2":{
                    "que2": "what's....?"
                },
                "question3":{
                    "que3": "what's....?"
                }
            }
        }
    }
}

}
this is my code witch convert the file json into array json of javascript:
var exa = [];
function show() {
    $.getJSON('questions.json', function (json) {
        for (var key in json) {
            if (json.hasOwnProperty(key)) {
                var item = json[key];
                exa.push({
//I want to simplify this part, because the real json file have more questions
                    que1: item.Biology.Category.Cell.question1.que1,
                    que2: item.Biology.Category.Cell.question2.que2,
                    que3: item.Biology.Category.Cell.question3.que3,

                    que11: item.Biology.Category.Bactery.question1.que1,
                    que12: item.Biology.Category.Bactery.question2.que2,
                    que13: item.Biology.Category.Bactery.question3.que3

                });
            }
        }
        //return Books;
        console.log(exa)
    })
}

A: Instead of que1, que2, etc., just have the questions in an array
"Cell": [
    "what's this?",
    "what's that?"
]

A: You can use json-path and write JsonPath.read(json, "$..question"); to get all questions. You need to change all que[*] in your file to question too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Apps Script to list all Google Classroom courses and put them in a Google Spreadsheet I am trying to create a Google Apps Script that will list all the Google Classroom courses that are active and archived, along with the ID, NAME, SECTION, and COURSESTATE. Everything works except that I have no idea how to fix the .getRange so that it will put all the information in the Google Spreadsheet. The error I get is "Incorrect range height, was 4 but should be 10". If I put the .getRange as simply "A1:D1", it will overwrite what is there for each Class until the script finishes, so I know the rest of the script works, but I can't figure out how to put the range so that all the Classes can be listed. What I have up to now is this:
function listCourses() {
var response = Classroom.Courses.list();
var courses = response.courses;
 if (courses && courses.length > 0) {
  for (i = 0; i < courses.length; i++) {
   var course = courses[i];
   var ids = course.id;
   var title = course.name;
   var sec = course.section;
   var state = course.courseState;
   var arr1 = [];
   arr1.push(ids,title,sec,state);
   var arr2 = [];
   while(arr1.length) arr2.push(arr1.splice(0,1));

var s = SpreadsheetApp.getActiveSpreadsheet();
var sh = s.getSheetByName('LISTS');

  for (var x=0; x<arr2.length; x++){
  var newRow = sh.getLastRow() + 1;

// Here in the .getRange is where it gives me the error. A new row should be added for each Class until all the Classes (with the information mentioned above) are listed.

  sh.getRange(1, 1, newRow, arr2[0].length).setValues(arr2);
  }

}}}

A: Try something like this:
I don't use Classroom API much and I only have one class in it but this works for it.
function listCourses() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('LISTS');
  var response = Classroom.Courses.list();
  var courses = response.courses;
  var arr=[];//You could put column headers in here
  for (i = 0; i < courses.length; i++) {
    var course = courses[i];
    var ids = course.id;
    var title = course.name;
    var sec = course.section;
    var state = course.courseState;
    arr.push([title,sec,state]); //you could also go sh.appendRow([title,sec,state]); here if you wish and avoid the use of the two dimensional array all together as suggested in the other answer.
  }
  sh.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}

A: Jason. You could bypass the range issue by using append row. This will however mean manipulating the data so that each class's details is on one row. I prefer this approach because it is let prone to errors. Also it automatically finds the next empty row in the sheet, so you don't need to get the last row.
function appendRow() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1');

  // Try is added to catch failures on automated scripts
  try {
    sheet.appendRow(['cell1','cell2','cell3'])
  } catch (e){
    Logger.log(e)
    // Could send an email here to alert script failure
  }
  // In a loop
  var data = [['row 1 cell 1','row 1 cell 2'],['row 2 cell 1','row 2 cell 2 ']]
  data.forEach(function(item){
    sheet.appendRow(item)
  })
}


text:
Q: password and confirmpassword validation in angular using reactive forms i have attached my code below .im facing problem in adding password mismatch validation.im not getting validation error if i type mismatching password
register.component.html

 UserName:*
<input kendoTextBox required type="text" class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your UserName " formControlName="username"/>

UserName  is required

Password:*
<input kendoTextBox type="password" required  class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your passowrd " formControlName="password"/>

password  is required

minimum of 6 characters required

   ConfirmPassword:
*
<input kendoTextBox required type="password" class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your new password " formControlName="confirmpassword"/>

 confirm password  is required

minimum of 6 characters required

                              Passwords don't match.

    enter code here

registercomponent.ts file
here i have used formBuilder.other things are working fine  ,only validation for mismatching not working
 this.registerForm3 = this.formBuilder.group({
    username:['', Validators.required],
    password: ['', [Validators.required, Validators.minLength(6)]],
    confirmpassword:['', [Validators.required, Validators.minLength(6)]],
  },
  {validator: this.passwordMatchValidator},
  );

passwordMatchValidator(frm: FormGroup) {
eturn frm.controls['password'].value ===
frm.controls['confirmpassword'].value ? null : {'mismatch': true};
    }
 get f2() {
    return this.registerForm3.controls;
  }

A: I didn't think that you could use a component member function (method) for your custom validator. I assumed it needed to be a function external from your class.
Mine looks like this:
function emailMatcher(c: AbstractControl): { [key: string]: boolean } | null {
  const emailControl = c.get('email');
  const confirmControl = c.get('confirmEmail');

  if (emailControl.pristine || confirmControl.pristine) {
    return null;
  }

  if (emailControl.value === confirmControl.value) {
    return null;
  }
  return { 'match': true };
}

And I attach the validator to a child formGroup like so:
this.customerForm = this.fb.group({
  firstName: ['', [Validators.required, Validators.minLength(3)]],
  lastName: ['', [Validators.required, Validators.maxLength(50)]],
  emailGroup: this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    confirmEmail: ['', Validators.required],
  }, { validator: emailMatcher }),
  phone: ''
});

You could put your validator in a separate file, or in the same file either above or below your component class. Something like this:
function passwordMatchValidator(frm: FormGroup) {
  return frm.controls['password'].value ===
frm.controls['confirmpassword'].value ? null : {'mismatch': true};
}

Then you would define the validator without the this keyword:
{validator: passwordMatchValidator},

You can find the complete example here: https://github.com/DeborahK/Angular-ReactiveForms/tree/master/Demo-Final

A: For angular 8 you can use a custom validation like this.
Import the required libraries
import { FormGroup, FormControl, Validators, ValidatorFn, ValidationErrors } from '@angular/forms';

const passwordErrorValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const password = control.get('a');
  const repeatPassword = control.get('b');
  return password.value != repeatPassword.value ? { 'passwordError': true } : null;
};

Init form like  this
 heroForm = new FormGroup({
    'a': new FormControl(),
    'b': new FormControl()
  }, { validators: passwordErrorValidator });

And in component
 <form [formGroup]="heroForm" (ngSubmit) ="createUser(heroForm.value)">
                <input id="a" name="a" class="form-control"
                required minlength="4"
                formControlName="a">
                <input id="b" name="b" class="form-control"
                required minlength="4"
                formControlName="b" >

                  password mismatch

              <input type="submit" class="btn btn-primary" value="Submit" />
            </form>

A: You can try this its working for me...
In your form
this.passwordForm = this.fb.group({
        newPassword: ['', [Validators.required, Validators.minLength(6)]],
        confirmNewPassword: ['', [Validators.required, Validators.minLength(6), (control => ValidationService.confirmPassword(control, this.passwordForm, 'newPassword'))]]
    });

ValidationService file
static confirmPassword(control: FormControl, group: FormGroup, matchPassword: string) {
    if (!control.value || group.controls[matchPassword].value !== null || group.controls[matchPassword].value === control.value) {
        return null;
    }
    return { 'mismatch': true }
}

A: finally i found my solution
export class ConfirmPasswordValidator {
    static MatchPassword(control: AbstractControl) {
       let password = control.get('password').value;

       let confirmpassword = control.get('confirmpassword').value;

        if(password != confirmpassword) {
            control.get('confirmpassword').setErrors( {ConfirmPassword: true} );
        } else {
            return null
        }
    }
}

A: You can check form value of both like below.

    Passwords don't match.


text:
Q: How to Add Serialized LINQ to SQL Entities to a Word 2007 Document I built a template-based document generator using the Open XML SDK (1.0), the Word 2007 Content Control Toolkit and LINQ to SQL (using the CodeSmith PLINQO templates). To do this, I serialized the LINQ to SQL entities to XML by retrieving the entity using DataLoadOptions specified in the source code.
This works great, except that to initially populate the XML in my template, I currently have to copy and paste the XML from the Immediate window in VS2008 into the Content Control Toolkit, and it still has all the data from the current entity.
I'm looking for two solutions:
1) Is this a good way to build a document generator with Word 2007?
1) How can I generate just the XML I need without the data? I've thought of creating an XSD and then creating an empty XML document, but wasn't sure how to do that programatically so that a business user can get the XML for the template. (That's not a requirement, just a nice-to-have.)
Thanks for your feedback,
Ryan

A: I finally got this working, thanks to the genius of Mr. Eric White. I've even managed to remove the use of one of the tools mentioned above (Word 2007 Content Control Toolkit). Here are the steps I'm now taking:

*

*Make the template data-bindable.

*Make a copy of the template to which to save changes.

*Retrieve the Custom XML from the template using LINQ to XML and the Open XML SDK.

*Serialize the LINQ to SQL entity using the DataContractSerializer.

*Use LINQ to XML to find the appropriate descendant based on a) the entity name and b) the property name.

*Clone the Custom XML and fill it with the values from the serialized LINQ to SQL entity (this uses a modified version of Eric's Clone() method).

*Replace the Custom XML in the document with the cloned and filled Custom XML (courtesy Brian Jones).

*Done!

I've attached the extension methods I'm using for the above steps below:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;

namespace OpenXmlDocGenerator
{
    /// <summary>
    /// Adds extensions for making the Open XML SDK and LINQ to XML easier to use.
    /// </summary>
    public static class OpenXmlExtensions
    {
        #region fields

        private static readonly XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
        private static readonly XName r = w + "r";
        private static readonly XName ins = w + "ins";
        private static readonly XNamespace ds = "http://schemas.openxmlformats.org/officeDocument/2006/customXml";

        #endregion

        #region methods

        /// <summary>
        /// Adds the custom XML part to the main document part.
        /// </summary>
        /// <param name="document">The main document part.</param>
        /// <param name="customXml">The custom XML.</param>
        /// <returns>The <see cref="CustomXmlPart" />.</returns>
        public static void AddCustomXmlPart(this MainDocumentPart document, XDocument customXml)
        {
            CustomXmlPart customXmlPart = document.AddNewPart<CustomXmlPart>();
            customXmlPart.PutXDocument(customXml);
        }

        /// <summary>
        /// Adds the custom XML part with a custom XML properties to the main document part.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        /// <param name="customXml">The custom XML.</param>
        /// <param name="customXmlProperties">The custom XML properties.</param>
        public static void AddCustomXmlPart(
            this MainDocumentPart mainPart, XDocument customXml, XDocument customXmlProperties)
        {
            CustomXmlPart customXmlPart = mainPart.AddNewPart<CustomXmlPart>();
            CustomXmlPropertiesPart customXmlPropertiesPart = customXmlPart.AddNewPart<CustomXmlPropertiesPart>();
            customXmlPropertiesPart.PutXDocument(customXmlProperties);
            customXmlPart.PutXDocument(customXml);
        }

        /// <summary>
        /// Clones the specified element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>The cloned <see cref="XElement" />.</returns>
        public static XElement Clone(this XElement element)
        {
            return new XElement(element.Name,
                       element.Attributes(),
                       element.Nodes().Select(n =>
                          {
                              XElement e = n as XElement;
                              if (e != null)
                              {
                                  return e.Clone();
                              }

                              return n;
                          }
                       ),
                       (!element.IsEmpty && !element.Nodes().OfType<XText>().Any()) ? string.Empty : null
                   );
        }

        /// <summary>
        /// Fills the specified element with the provided <paramref name="entityMap"/>.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="entityMap">The entity map between the custom XML elements and the entity values.</param>
        /// <returns>The filled <see cref="XElement"/>.</returns>
        public static XElement Fill(this XElement element, IDictionary<string, object> entityMap)
        {
            return new XElement(element.Name,
                       element.Attributes(),
                       element.Nodes().Select(node =>
                          {
                              XElement childElement = node as XElement;
                              if (childElement != null)
                              {
                                  // If the child element does not have elements,
                                  // attempt to insert the value from the entity map;
                                  // otherwise, recursively call the Fill() to find
                                  // child elements to fill.
                                  return !childElement.HasElements
                                             ? InsertValue(childElement, entityMap)
                                             : childElement.Fill(entityMap);
                              }

                              return node;
                          }
                       ),
                       (!element.IsEmpty && !element.Nodes().OfType<XText>().Any()) ? string.Empty : null
                   );
        }

        /// <summary>
        /// Gets a descendant element of the specified element the by the descendant's name.
        /// </summary>
        /// <param name="element">The element from which to find the descendant element.</param>
        /// <param name="descendantElementName">Name of the descendant element.</param>
        /// <returns>The descendant <see cref="XElement" />.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="element"/> is null.</exception>
        public static XElement GetDescendantByName(this XElement element, string descendantElementName)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            return element.Elements().DescendantsAndSelf().FirstOrDefault(e => e.Name.LocalName == descendantElementName);
        }

        /// <summary>
        /// Gets the custom XML from the main document part.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        /// <returns>The custom XML as a <see cref="XElement" />.</returns>
        public static XElement GetCustomXml(this MainDocumentPart mainPart)
        {
            CustomXmlPart customXmlPart = mainPart.GetPartsOfType<CustomXmlPart>().FirstOrDefault();
            return customXmlPart == null ? null : customXmlPart.GetXDocument().Root;
        }

        /// <summary>
        /// Gets the XDocument from the document part.
        /// </summary>
        /// <param name="part">The document part.</param>
        /// <returns>The XDocument.</returns>
        public static XDocument GetXDocument(this OpenXmlPart part)
        {
            XDocument xdoc = part.Annotation<XDocument>();
            if (xdoc != null)
            {
                return xdoc;
            }

            using (StreamReader streamReader = new StreamReader(part.GetStream()))
            using (XmlReader xmlReader = XmlReader.Create(streamReader))
            {
                xdoc = XDocument.Load(xmlReader);
            }

            part.AddAnnotation(xdoc);
            return xdoc;
        }

        /// <summary>
        /// Determines whether the specified document is bindable.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>
        ///     <c>true</c> if the specified document has a <see cref="CustomXmlPart" />; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsBindable(this WordprocessingDocument document)
        {
            return document.MainDocumentPart.GetPartsCountOfType<CustomXmlPart>() > 0;
        }

        /// <summary>
        /// Serializes the XDocument back into the package.
        /// </summary>
        /// <param name="part">The document part.</param>
        /// <param name="xdoc">The <see cref="XDocument" />.</param>
        public static void PutXDocument(this OpenXmlPart part, XDocument xdoc)
        {
            if (xdoc != null)
            {
                using (Stream stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite))
                using (XmlWriter partWriter = XmlWriter.Create(stream))
                {
                    xdoc.Save(partWriter);
                }
            }
        }

        /// <summary>
        /// Removes the custom XML parts.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        public static void RemoveCustomXmlParts(this MainDocumentPart mainPart)
        {
            if (mainPart.CustomXmlParts.Count() > 0)
            {
                mainPart.DeleteParts(mainPart.CustomXmlParts);
            }
        }

        /// <summary>
        /// Replaces the custom XML in the main document mainPart.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        /// <param name="customXml">The custom XML.</param>
        public static void ReplaceCustomXml(this MainDocumentPart mainPart, XElement customXml)
        {
            if (customXml != null)
            {
                mainPart.RemoveCustomXmlParts();

                CustomXmlPart customXmlPart = mainPart.AddNewPart<CustomXmlPart>();
                using (Stream stream = customXmlPart.GetStream(FileMode.Create, FileAccess.ReadWrite))
                using (XmlWriter writer = XmlWriter.Create(stream))
                {
                    customXml.Save(writer);
                }
            }
        }

        /// <summary>
        /// Translates the <paramref name="source"/> collection using the <paramref name="translate"/>,
        /// then concatenates and returns the result.
        /// </summary>
        /// <typeparam name="T">The type of the items in the source.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="translate">The translation function to perform on each item in the source.</param>
        /// <returns>The concatenated contents of the source collection.</returns>
        public static string StringConcatenate<T>(this IEnumerable<T> source, Func<T, string> translate)
        {
            return source.Aggregate(new StringBuilder(), (s, i) => s.Append(translate(i)), s => s.ToString());
        }

        /// <summary>
        /// Concatenates the items in the <paramref name="source"/> and returns the result.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns>The concatenated contents of the source collection.</returns>
        public static string StringConcatenate(this IEnumerable<string> source)
        {
            return source.Aggregate(new StringBuilder(), (s, i) => s.Append(i), s => s.ToString());
        }

        /// <summary>
        /// Creates a bindable version of the <see cref="WordprocessingDocument" />.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>The <see cref="WordprocessingDocument" />.</returns>
        /// <seealso cref="http://blogs.msdn.com/ericwhite/archive/2008/10/19/creating-data-bound-content-controls-using-the-open-xml-sdk-and-linq-to-xml.aspx"/>
        public static WordprocessingDocument ToBindable(this WordprocessingDocument document)
        {
            foreach (MainDocumentPart mainPart in document.GetPartsOfType<MainDocumentPart>())
            {
                mainPart.RemoveCustomXmlParts();

                Guid id = Guid.NewGuid();
                XDocument customXml = mainPart.CreateCustomXml();
                XDocument customXmlProperties = CreateCustomXmlProperties(id);
                mainPart.AddCustomXmlPart(customXml, customXmlProperties);

                XDocument partXDoc = mainPart.GetXDocument();
                AddDataBinding(partXDoc, id);
                mainPart.PutXDocument(partXDoc);
            }

            return document;
        }

        #region --private

        /// <summary>
        /// Adds data binding to the content controls.
        /// </summary>
        /// <param name="mainDocumentXDoc">The main document <see cref="XDocument" />.</param>
        /// <param name="id">The id.</param>
        private static void AddDataBinding(XDocument mainDocumentXDoc, Guid id)
        {
            foreach (XElement sdt in mainDocumentXDoc.Descendants(w + "sdt"))
            {
                sdt.Element(w + "sdtPr")
                    .Element(w + "placeholder")
                    .AddAfterSelf(
                    new XElement(w + "dataBinding",
                        new XAttribute(w + "xpath",
                            "/root/" + sdt.Element(w + "sdtPr")
                                .Element(w + "tag")
                                .Attribute(w + "val").Value),
                        new XAttribute(w + "storeItemID",
                            "{" + id.ToString().ToUpper() + "}")
                    )
                );
            }
        }

        /// <summary>
        /// Creates the custom XML from the existing content controls.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        /// <returns>The custom XML as a <see cref="XDocument" />.</returns>
        private static XDocument CreateCustomXml(this MainDocumentPart mainPart)
        {
            XElement customXml =
                new XElement("root",
                    mainPart
                    .GetXDocument()
                    .Descendants(w + "sdt")
                    .Select(sdt =>
                        new XElement(
                            sdt.Element(w + "sdtPr")
                                .Element(w + "tag")
                                .Attribute(w + "val").Value,
                             GetTextFromContentControl(sdt).Trim())
                    )
                );

            return new XDocument(customXml);
        }

        /// <summary>
        /// Creates the custom XML property part contents.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>The contents of the custom XML properties part.</returns>
        private static XDocument CreateCustomXmlProperties(Guid id)
        {
            return new XDocument(
                       new XElement(ds + "datastoreItem",
                           new XAttribute(ds + "itemID",
                               "{" + id.ToString().ToUpper() + "}"),
                           new XAttribute(XNamespace.Xmlns + "ds",
                               ds.NamespaceName),
                           new XElement(ds + "schemaRefs")
                       )
                   );
        }

        /// <summary>
        /// Gets the text from content control.
        /// </summary>
        /// <param name="contentControlNode">The content control node.</param>
        /// <returns>The string representation of the value in the content control.</returns>
        static string GetTextFromContentControl(XElement contentControlNode)
        {
            return contentControlNode.Descendants(w + "p")
                .Select(p => p.Elements()
                                 .Where(z => z.Name == r || z.Name == ins)
                                 .Descendants(w + "t")
                                 .StringConcatenate(element => (string)element) + Environment.NewLine)
                .StringConcatenate();
        }

        /// <summary>
        /// Inserts the value from the <paramref name="entityMap"/> into the <paramref name="childElement"/>.
        /// </summary>
        /// <param name="childElement">The child element.</param>
        /// <param name="entityMap">The entity map.</param>
        private static XElement InsertValue(XElement childElement, IDictionary<string, object> entityMap)
        {
            string name = childElement.Name.LocalName;

            if (entityMap.Keys.Contains(name))
            {
                childElement.SetValue(entityMap[name] ?? string.Empty);
            }
            else
            {
                childElement.SetValue(string.Empty);
            }

            return childElement;
        }

        #endregion

        #endregion
    }
}


text:
Q: Is it possible for me to reload only a bootstrap modal, without having to execute location.reload()? I want to reload a bootstrap modal on its hidden event, so it will execute all my js functions over again once I open it later. It works if I execute location.reload, but it's kind of annoying having to wait for my page to reload in order for me to open my modal again. Is there any solution for it?

A: You can use jQuery Ajax to get data for the model.
$('#myModal').on('hidden.bs.modal', function () { //modal hidden event
    $.ajax({
        url: "data.json",
        success: function(result){
            $('#myModal').html(result); //set new data to modal
            $('#myModal').modal('show'); //show the modal
        }
    });
});

Modal event for Bootstrap 3 and 4
Bootstrap 4 and Bootstrap 3


text:
Q: .htaccess rewriterule to change image on a specific page This is working:
RewriteEngine On
RewriteCond %{REQUEST_URI} foobar
RewriteRule /foobar /barfoo [R=301,L]

With this rule, going to

https://www.somewhere.com/foobar

will redirect to

https://www.somewhere.com/barfoo

Easy and simple. Now, I'm trying the same technique to change an image on a specific page:
RewriteEngine On
RewriteCond %{REQUEST_URI} about
RewriteRule /wp-content/uploads/2018/01/logo.png /wp-content/uploads/logo/logo.png [R=301,L]

But it's not working. Both /wp-content links are working. I have another rule which is working fine tough with the geoip module:
RewriteEngine On
RewriteCond %{ENV:GEOIP_REGION} !^(COUNTRY)$
RewriteRule logo.png https://%{HTTP_HOST}/wp-content/uploads/logo/logo-new.png [L]

Which means, if the user is not in COUNTRY, then give him a different logo image.
UPDATE:
This works:
RewriteEngine On
RewriteRule ^.*/logo.png$ https://website.com/new-logo.png [L]

But this doesn't:
RewriteEngine On
RewriteCond %{REQUEST_URI} about
RewriteRule ^.*/logo.png$ https://website.com/new-logo.png [L]

The RewriteCond works. The RewriteRule works. But not when they are being used together.
ALTERNATIVE SOLUTION:
Would have been great to do it in htaccess but cannot find the solution. Instead I went another way by modifying the template in PHP.
if ( ($_SERVER['GEOIP_REGION'] <> 'COUNTRY') && (!stristr($_SERVER['SCRIPT_URL'], 'about')) )
  echo '';
else
  echo '';

A: You should make clear that, for the below RewriteRule:
RewriteCond %{REQUEST_URI} about
RewriteRule /wp-content/uploads/2018/01/logo.png /wp-content/uploads/logo/logo.png [R=301,L]

If users are requesting the page http://example.com/about, the %{REQUEST_URI} is /about, which matches the RewriteCond. But the RewriteRule pattern, /wp-content/uploads/2018/01/logo.png does not match /about.
The logo is another request, http://example.com/wp-content/uploads/2018/01/logo.png. The %{REQUEST_URI} is /wp-content/uploads/2018/01/logo.png, that does not match the RewriteCond.
That's the reason why the RewriteRule does not work in this case.
If you want to change the logo only in about page, there is one simple trick to do that. When the logo is first loaded on the about page, browser will add the referer header to the request headers. The referer header can be http://example.com/about, or the css file, depending on which last resource requesting the logo.
RewriteCond %{HTTP_REFERER} about
RewriteRule /wp-content/uploads/2018/01/logo.png /wp-content/uploads/logo/logo.png [L]

Make sure that you clear the browser cache. The flag R=301 is permanent redirect which is cached by the browser.


text:
Q: How and Which tool should use to make API-Gateway for polyglot Microservice Platform? In the case of Microservice Architecture, there are a bunch of services built on different stack and communicate with each other and also the client via REST.
So what I'm asking for, to make that gateway a single entry point from a client or consumer e.g api.domain.com which will redirect the request to the corresponding service based on the endpoint as we know about purpose of api-gateway.
Well, It's possible by load-balancer like nginx-plus or HAProxy simply balancing load and passing proxy. But my expectations (mostly about authentication-authorization based) are below :

*

*The consumer will authenticate with credentials, server will return back small access_token (minimal e.g user_id as payload) which will store into client app. For further each request client will send this token as authorization how JWT or Token based authentication does.

*Before passing the request to another service Gateway-service will decode that small auth_token and will make another authorization token (let's say Big Token) with associated users all information (query by small token decoded payload) which will pass as Authorization to actual service and internal service to service call from where content will serve.

*That (Gateway-service generated) Big-Token and payload will store into redis for a while to reduce api call to get user information every time.

*Request caching and balancing load.

I'm not sure is it possible to achieve by nginx-plus or HAproxy probably NO! cause there we have few database query, api calling and caching into redis etc. Which is not possible by nginx or HAProxy or whatever like those.
I found two services for Node.js/Express.js for passing proxy Node-HTTP-Proxy and Express-Gateway which is only for expressjs api-services but here I'm using polyglot framework or languages.

Note: Here services are built with python flask, Django and ExpressJS, few of them hosted into Unix VM where using nginx as load balancer and few of them hosted into azure app service where they use IIS as load balancer.

Thanks for reading and understanding, It would be great if you can suggest anyway or recommend anything.

A: I would recommend that you check out Ambasador - https://www.getambassador.io - it sounds like it would suit your needs. Another solid choice that has a lot of support and a large community is Kong - https://konghq.com. Other choices are Nginx, Loopback and Tyk.

A: I am actually gonna recommend Node-HTTP-Proxy.
You could use a node server for api.domain.com that could use Node-HTTP-Proxy . It can be used to consume micro services eg. serviceone.com and servicetwo.com. It will not care what you have used to build this micro services(eg. python flask, Django and ExpressJS) as long as you have them exposed as REST/SOAP api.
Say you have some endpoints like serviceone.com/rone and servicetwo.com/rtwo,
You can make a request to api.domain.com/rone or api.domain.com/rtwo where you custom proxy server will use Node-HTTP-Proxy and send request to serviceone.com/rone or servicetwo.com/rtwo. You can read headers from request and do something with it and change headers before sending request to micro services. Which would solve your authentication problem. You can use redis and caching here.
Worked nicely for me. Hope it helps.

A: I would recommend Kong for the use cases you have mentioned:

*

*For the specific way of authentication you have mentioned, you will need to write a plugin using Lua. Kong has many authentication support built-in, but your requirement is a bit different.

*Kong caches all of its data including consumers in-memory. So you don't need to implement another Redis based solution. When you have a new user, you will need to add that user as a consumer at Kong using its admin API.

*Kong has load balancing support. And as it is built on top of Nginx, you can also configure the core Nginx if you need.

*For request caching at the gateway level, Kong has a plugin for its enterprise edition. There are some open source community-built plugins as well.
Regarding the custom authentication, you should think twice why you need it at two levels. At the gateway level, you can authenticate and use ACL, the underlying services can trust the upcoming requests. You may need to implement service level middleware to identify the user that Kong is passing through, for resource level authorization.
One caution: While working with Kong, I felt the necessity of proper thorough documentation.


text:
Q: Does select top 10 * from tablename give same result every time? I want to know that Does select top 10 * from tablename give same result every time?
Thanks in advance

A: No.  The result set is unordered unless you specify an order by clause.  Even then, the order by needs to be stable, meaning that the keys have no ties (you accomplish this by putting the primary key as the last keys for the ordering).
There are several reason why results might differ.  Obviously, the underlying data might change, but I am guessing that is not the gist of your question.
The primary reason is on a multi-threaded machine, where different threads are reading the data.  Which thread returns the data is indeterminate, so you don't know what the first ten rows will be (without an order by).
SQL itself does not guarantee that tables are read in order for processing queries.  However, in practice, I do think that SQL Server does read the pages in order.

A: No. It varies when new data are added. Also you should always use ORDER BY Clause explicitly if you use TOP operator


text:
Q: Gradle: Declaring dependency in top level and sub module- which is used? When different versions of dependencies are declared in the top-level build.gradle and sub-module build.gradle, which one takes precedence?
For example if in my top level build.gradle I had junit:junit:4.8.2 but in a sub-module had junit:junit:4.10 ?
Also, what does declaring a dependency in the top level build.gradle do? Should all dependencies just be declared in sub-modules?

A: Having
// root build.gradle
subprojects {
    dependencies {
        compile "junit:junit:4.10"
    }
}

and
// submodule build.gradle
dependencies {
    compile "junit:junit:4.8.2"
}

is essentially the same as just having
// submodule build.gradle
dependencies {
    compile "junit:junit:4.8.2"
    compile "junit:junit:4.10"
}

This means you have two version of junit declared in your submodule. Now Gradle conflict resolution kicks in here. The default resolution for
dependency conflicts is to choose the newer version. So junit 4.10 will be picked. To change this behaviour you can configure the resolution strategy.


text:
Q: Making a Popup ViewController out of a UICollectionViewController I'm working with a UITableViewController and when clicking a cell i would like to have a UICollectionViewController be popped up.
I've been successful in presenting the UICollectionViewController from a UITableViewController. However, I'm not able to figure out on how to present it like a pop-up only taking portion of the screen. It currently feels the entire view.
I searched on stackoverflow but couldn't find a working solution.
UITableViewController
class SearchViewController: UITableViewController, UISearchBarDelegate {

let cellId = "cellId"
var filteredArray = [String]()
let books = Model().books

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white
    navigationItem.titleView = navSearchBar
    setupView()
}

// Views.
let navSearchBar = NavSearchBar()
func setupView() {
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
    tableView.delegate = self
    tableView.dataSource = self
    navSearchBar.delegate = self
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { // Cancel button is touched.
    self.dismiss(animated: true, completion: nil)
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        book = books[indexPath.row]
    }
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
    cell.textLabel?.text = book
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    let cellLabelContent = cell!.textLabel!.text // Gets cell name.
    let cellLabelIndex = bibleBooks.firstIndex(of: cellLabelContent!) // searches books array to get correct index of cell name.
    print("Book name:", cellLabelContent!+",", "index:", cellLabelIndex!)
    let notificName = Notification.Name(rawValue: searchedBookIndex)
    NotificationCenter.default.post(name: notificName, object: cellLabelIndex)
    dismiss(animated: true, completion: nil)
    **HERE is where i present the collectionView**
    let layout = UICollectionViewFlowLayout()
    var topVC = UIApplication.shared.keyWindow?.rootViewController
    while((topVC!.presentedViewController) != nil) {
        topVC = topVC!.presentedViewController
        let navController = UINavigationController(rootViewController: ChapterNumbersCollectionView(collectionViewLayout: layout))
        topVC?.present(navController, animated: true, completion: nil)

    }
}

UICollectionViewController
class ChapterNumbersCollectionView: UICollectionViewController {

let reuseIdentifier = "CellId"

override func viewDidLoad() {
    super.viewDidLoad()
    setupCollectionView()
    setupNavigationItem()
}

private func setupCollectionView() {
    collectionView.backgroundColor = .yellow
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}

private func setupNavigationItem() {
    let button = UIButton(type: .system)
    button.setTitle("cancel", for: [])
    button.addTarget(self, action: #selector(handleDismiss), for: .touchUpInside)
    button.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}

@objc func handleDismiss() {
    dismiss(animated: true, completion: nil)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 200
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    cell.backgroundColor = .red
    return cell
}

A: One approach would be to use view controller containment. You'd instantiate ChapterNumbersCollectionView in didSelectRow, but instead of presenting, add it as a child view controller.
Then, having added its view as a subview, animate it in using animateWithDuration.


text:
Q: Show that if $T(n) \in O(n)$ , then $T(n) \notin \Theta (n^2)$ The proposition I would like to prove:

Proposition. If $T(n) \in O(n)$ , then $T(n) \notin \Theta (n^2)$

Since different sources seem to be using slightly different definitions (although I guess all of them are equivalent) , firstly I will list all the relevant definitions:

If $f,g$ are functions from positive integers to non-negative real numbers, then $f(n) \in O(g(n))$ if and only if for some real $M > 0$ and some natural number $N ≥ 1$ and for all $n ≥ N$, we have $f(n) ≤ Mg(n)$. Also, $f(n) \in \Omega(g(n))$ if and only if for some real $M > 0$ and some natural number $N ≥ 1$ and for all $n ≥ N$, we have $f(n) ≥ Mg(n)$. Finally, $f(n) \in \Theta(g(n))$ if and only if $f(n) \in O(g(n))$ and $f(n) \in \Omega(g(n))$.

My attempt:
For the sake of contradiction, suppose that $T(n) \in \Theta (n^2)$ and $T(n) \in O(n)$. Since $T(n) \in \Theta (n^2)$, it follows that $T(n) \in \Omega (n^2)$, and thus for some real $c > 0$ and for some natural $N ≥  1$,
$$\tag 1cn^2 ≤T(n), \forall n ≥ N$$
Also, since $T(n) \in O(n)$, for some real $k > 0$ and for some natural $M ≥ 1$, we have
$$\tag 2 T(m) ≤ km, \forall m ≥ M$$
Combining results $(1)$ and $(2)$, we can conclude that
$$cn^2 ≤ T(n) ≤ kn, \forall n ≥ \max(N,M)$$
Since $\max(N,M)≥ 1$, it follows that $cn^2 > 0$, and thus we can divide all sides by $cn^2$ to obtain
$$1 ≤ \frac{k}{cn}, \forall n ≥ \max(N,M)$$
Since the sequence $(\frac{k}{cn})_{n=1}^{\infty}$ is convergent, we can take limits of both sides to get
$$1 ≤ \lim_{n \rightarrow \infty} \frac{k}{cn} = 0$$
contradiction. $\Box$

*

*Is the proof correct?

*Are there any shorter alternatives?


text:
Q: How do I control the order of the segments of a Python Plotly Pie chart I have a simple pair of Pie charts plotting in Plotly.go.  I have ordered the Values and Labels in the order I want (i.e. Labels - Low to high).  When I produce the plot, the order is scrambled. I have read through the Plotly documentation and examples but I can't find out how to fix the ordering.
As a second question, how do I eliminate the stick/spik? showing the Zero labels.
import plotly.graph_objects as go
from plotly.subplots import make_subplots

labels = ["0","0.5", "1","1.5", "2","2.5", "3","3.5", "4","4.5", "5","5.5","6"]

# Create subplots: use 'domain' type for Pie subplot
fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])

fig.add_trace(go.Pie(labels=labels, values=[0,0,3,0,4,0,1,0,1,0,0,0,0], name="Wind Force",textinfo='label'),
              1, 1)
fig.add_trace(go.Pie(labels=labels, values=[0,0,2,1,0,1,3,0,0,1,0,0,1], name="Wave Height",textinfo='label'),
              1, 2)

# Use `hole` to create a donut-like pie chart
fig.update_traces(hole=.4, hoverinfo="label+percent+name")

fig.update_layout(
    title_text="Wind and Wave conditions on site",
    # Add annotations in the center of the donut pies.
    annotations=[dict(text='Wind (Force)', x=0.17, y=0.5, font_size=20, showarrow=False),
                 dict(text='Wave (m)', x=0.82, y=0.5, font_size=20, showarrow=False)])
fig.show()

Question Update:
I have now edited the Labels and Values to remove the Zero values. This obviously needs to be edited for every plot and isn't a universal answer.
labelsW = ["1", "2", "3", "4"]
labelsS = ["1","1.5","2.5", "3","4.5","6"]

# Create subplots: use 'domain' type for Pie subplot
fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])

fig.add_trace(go.Pie(labels=labelsW, values=[3,4,1,1], name="Waver Height",textinfo='label', direction='clockwise', sort=False),
          1, 1)
fig.add_trace(go.Pie(labels=labelsS, values=[2,1,1,3,1,1], name="Wind Force",textinfo='label', direction='clockwise', sort=False),1,2)

A: I can answer the first question for sure, but the second answer might not be satisfactory.
1.) To have the order contained the way you provided it with, pass these 2 arguments to the go.Pie() class (direction and sort);
fig.add_trace(go.Pie(labels=labels, values=[0,0,3,0,4,0,1,0,1,0,0,0,0], name="Wind Force",textinfo='label', direction='clockwise', sort=False),
          1, 1)
fig.add_trace(go.Pie(labels=labels, values=[0,0,2,1,0,1,3,0,0,1,0,0,1], name="Wave Height",textinfo='label', direction='clockwise', sort=False),
              1, 2)

Note: you may want to set sort=True, and see whether it suits you better than sort=False.
2.) Changing the parameter textinfo to 'none' will remove all labels. This is why I noted that this may not be a fully satisfactory answer, as it will remove not only the labels from the zeros, but from all other entries as well.
fig.add_trace(go.Pie(labels=labels, values=[0,0,3,0,4,0,1,0,1,0,0,0,0], name="Wind Force",textinfo='none', direction='clockwise', sort=False),
          1, 1)
fig.add_trace(go.Pie(labels=labels, values=[0,0,2,1,0,1,3,0,0,1,0,0,1], name="Wave Height",textinfo='none', direction='clockwise', sort=False),
              1, 2)

I hope that at least the first part is helpful.


text:
Q: Select chain of a queriers with reference I have this table which I would like to store a chain of records.
CREATE TABLE table_name (
    id INT,
    unique_id varchar,
    reference_id varchar,
);

I want to implement JPA query which prints all records by unique_id with all record reference_id. Something like this:
| id | unique_id | reference_id |   |   |
|----|-----------|--------------|---|---|
| 43 | 55544     |              |   |   |
| 45 | 45454     | 55544        |   |   |
| 66 | 55655     | 45454        |   |   |
| 78 | 88877     | 55655        |   |   |
| 99 | 454       | 34345        |   |   |

I would like when I select record 55544 to get all transactions because each other are using reference_id which points to them. How I can implement this JPA?
Expected result for record with unique_id 55544:
| id | unique_id | reference_id |   |   |
|----|-----------|--------------|---|---|
| 43 | 55544     |              |   |   |
| 45 | 45454     | 55544        |   |   |
| 66 | 55655     | 45454        |   |   |
| 78 | 88877     | 55655        |   |   |


text:
Q: The name 'AutomationId' does not exist in the current context I have assembly with UI automation tests (White).
I've introduced a class with all Autination Id's to be reused in this assembly:
public static class AutomationId
{
    public static class Toolbar
    {
        public const string MyControl = "MyControlId";
    }
}

And now i'm trying to use it in my test class (the same assembly):
var control = mainWindow.Get<Button>(AutomationId.Toolbar.MyControl);

This code can be compiled locally. But on TeamCity I'm getting a such error:
The name 'AutomationId' does not exist in the current context

A: It's a C# 6 feature. Similar problem: The name 'nameof' does not exist in the current context
I encountered this problem just now, which lead me here. My research indicates that you need to update Teamcity:
http://dave.ninja/2015/08/06/upgrading-teamcity-to-support-visual-studio-2015/
We still have to do this, as well. The post above shows a lot of solutions to issues that they encountered while upgrading. Didn't seem a too painful process.


text:
Q: Erro em ListActivity, provavelmente relacionado a OnItemClickListener Eu estou com um problema para entender o que está dando de errado neste código, sinto que o problema pode estar relacionado ao OnItemClickListener. Quando tento emular ele responde com uma mensagem assim: "Unfortunately, MyAplication has stopped.".
    public class MainActivity extends ListActivity {

private ArrayList<ViewListing> arrayList;
private ListView list = (ListView) findViewById(R.id.listview);

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    arrayList = new ArrayList<ViewListing>();
        arrayList.add(new ViewListing(0, R.drawable.anjelly, "Item 1"));
        arrayList.add(new ViewListing(1, R.drawable.construct, "Item 2"));
        arrayList.add(new ViewListing(2, R.drawable.darkdestroyer, "Item 3"));

        ListViewAdapter adp = new ListViewAdapter(getApplicationContext(), arrayList);

    setListAdapter(adp);
    list.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch(position) {
                case 1:
                    Toast.makeText(getApplicationContext(), "1 Selected", Toast.LENGTH_SHORT).show();
                case 2:
                    Toast.makeText(getApplicationContext(), "2 Selected", Toast.LENGTH_SHORT).show();
                case 3:
                    Toast.makeText(getApplicationContext(), "3 Selected", Toast.LENGTH_SHORT).show();
            }

        }
    });
   }
}

A: Vejo pelo menos 3 problemas no código:
1 - A ListView list está a ser inicializada fora do método onCreate().
2 - É necessário chamar o método setContentView(), caso o seu layout não seja apenas uma ListView.
3 - Para poder usar o método setAdapter() da ListActivity, o id da listView tem de ser @android:id/list.
O método findViewById() procura a view dentro do layout passado ao método setContentView(), tem por isso ser usado depois.
Altere esta parte do código assim:
public class MainActivity extends ListActivity {

    private ArrayList<ViewListing> arrayList;
    private ListView list;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);//Altere se o nome do layout for outro.

        list = getListView();//O id da listView tem de ser @android:id/list.

        ......
        //restante do código
}

Para mais informações ver ListActivity na documentação.


text:
Q: Python pattern-matching. Match 'c[any number of consecutive a's, b's, or c's or b's, c's, or a's etc.]t' Sorry about the title, I couldn't come up with a clean way to ask my question.
In Python I would like to match an expression 'c[some stuff]t', where [some stuff] could be any number of consecutive a's, b's, or c's and in any order.
For example, these work:
'ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat'
but these don't:
'cbcbbaat', 'caaccbabbt'
Edit: a's, b's, and c's are just an example but I would really like to be able to extend this to more letters. I'm interested in regex and non-regex solutions.

A: Not sure how attached you are to regex, but here is a solution using a different method:
from itertools import groupby

words = ['ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat',  'cbcbbaat', 'caaccbabbt']
for w in words:
    match = False
    if w.startswith('c') and w.endswith('t'):
        temp = w[1:-1]
        s = set(temp)
        match = s <= set('abc') and len(s) == len(list(groupby(temp)))
    print w, "matches" if match else "doesn't match"

The string matches if a set of the middle characters is a subset of set('abc') and the number of groups returned by groupby() is the same as the number of elements in the set.

A: I believe you need to explicitly encode all possible permutations of as, bs and cs:
c(a*b*c*|b*a*c*|b*c*a*|c*b*a*|c*a*b*|a*c*b*)t

Note that this is an extremely inefficient query which may backtrack a lot.

A: Not thoroughly tested, but I think this should work:
import re

words = ['ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat',  'cbcbbaat', 'caaccbabbt']
pat = re.compile(r'^c(?:([abc])\1*(?!.*\1))*t$')
for w in words:
    print w, "matches" if pat.match(w) else "doesn't match"

#ct matches
#cat matches
#cbbt matches
#caaabbct matches
#cbbccaat matches
#cbcbbaat doesn't match
#caaccbabbt doesn't match

This matches runs of a, b or c (that's the ([abc])\1* part), while the negative lookahead (?!.*\1) makes sure no other instance of that character is present after the run.
(edit: fixed a typo in the explanation)

A: I don't know the Python regex engine, but it sounds like you just want to write out the 6 different possible orderings directly.
/c(a*b*c*|a*c*b*|b*a*c*|b*c*a*|c*a*b*|c*b*a*)t/

A: AFAIK there's no "compact" way of doing this...
c(a*(b*c*|c*b*)|b*(a*c*|c*a*)|c*(a*b*|b*a*))t


text:
Q: Pyside2 - QOpenGLFunction object has no attribute glShaderSource I'm trying to use QOpenGLFunctions with PySide2. Everything was good until I tried to use glShaderSource() which appears to be missing in the PySide2 implementation of QOpenGLFunctions

AttributeError: 'PySide2.QtGui.QOpenGLFunctions' object has no attribute 'glShaderSource'

Furthermore, glShaderSource is also missing in the https://doc.qt.io/qtforpython-5/PySide2/QtGui/QOpenGLFunctions.html
Isn't it a bug which is not resolved for a long time? Because I am using PySide 5.12 and the linked documentation is for 5.15. Does anyone use QOpenGLFunctions with PySide2? Because how then you can use it without shaders?

from OpenGL import GL
from PySide2 import QtGui

if __name__ == "__main__":
    app = QtGui.QGuiApplication()
    off_screen = QtGui.QOffscreenSurface()
    off_screen.create()
    if off_screen.isValid():
        context = QtGui.QOpenGLContext()
        if context.create():
            context.makeCurrent(off_screen)

            ###
            f = QtGui.QOpenGLFunctions(context)
            shader = f.glCreateShader(GL.GL_VERTEX_SHADER)
            f.glShaderSource(shader, "") # <-AttributeError
            f.glCompileShader(shader)
            ####


text:
Q: Segmentation error with 1D array Here, I know that A is just a 1D array of length 170.
subroutine gonewrong(q,e,A)

implicit none

integer, dimension(:) :: q

integer, dimension(:,:), intent(in) :: e

integer, dimension(size(e,1)*2), intent(out) :: A
print *, A(2)
end subroutine gonewrong

When I try to find A(2), for example, it gives me a segmentation fault! e has dimension (85,2).
Would it be because I declared A as an allocatable array in the program I used to compile it with?
The program I used:
program prog_1
use module_1
implicit none
integer::qm,a,b,c
integer,allocatable,dimension(:)::q
integer,allocatable,dimension(:,:)::e
!integer, dimension(size(e,1)*2) :: A
a = 5
b = 3
c = 10
allocate(q(a+c))
allocate(e(a+b*c,2))

call subr1(a,b,c,qm,q,e) !Outputs are qm,q and e.
call gonewrong(q,e,A) !gonewrong takes q and e as arguments
end program prog_1

A: Another issue to consider is that in the declaration:
integer,allocatable,dimension(:,:)::e
integer, dimension(size(e,1)*2) :: A

the size of e is undefined (zero?) at the time A is declared. If the size of A depends on the size of e, you'll need to either fix the size of e at compile time or set A to be allocatable and separately allocate it once the size of e has been set. The takeaway is that A won't dynamically adjust its size as the size of e changes. In this case, it looks like A is declared with zero length because size(e) returns zero because only the shape of e has been defined, not its size. Referencing A(2) would likely throw a segmentation violation (reading off the end of the array) which would be consistent with what you're observing.
Aside: Many people coming to Fortran from dynamic languages don't realize that Fortran routines are split into at least three "zones"; an initial section containing use statements for importing external resources, a declaration section where arguments and local variables are declared, and the body of the routine where executable statements are placed (pedants are encouraged to read the language spec; I'm generalizing here for pragmatism's sake). The implicit statement separates the imports from the declarations, and by convention, I separate declarations from executable statements with a  bare continue statement. continue is considered executable, so the compiler should complain if declarations appear after this first continue.

A: The error is quite clear:
integer::qm,a

makes a a single integer number (scalar).
The subroutine requires an array:
integer, dimension(size(e,1)*2), intent(out) :: A

So you are passing the wrong thing there in:
call gonewrong(q,e,A) !gonewrong takes q and e as arguments

because Fortran is case insensitive! You are passing the scalar integer a/A to the subroutine which expects an array.
It is much better to use the same (:) inside the subroutine for A and let the compiler tell you that you are making an error.
The argument is an array so you must pass an array there.
Note: in your original code you had this line commented out
! integer, dimension(size(e,1)*2) :: A

when you have both lines
integer::qm,a
integer, dimension(size(e,1)*2) :: A

the program will not compile because a/A is declared twice.

What less clear to me is your actual intention. Your comment
!gonewrong takes q and e as arguments

is really confusing. All three things are arguments of gonewrong. q, e and A.


text:
Q: How to deal with model classes in iOS application I am a newbie in iOS application development, but I am trying to learn how to deal with Cocoa in the best way.
I got stuck trying to understand how to keep and reference the model objects properly.

*

*many say to write an app delegate property to hold the model and then reference it through the convenience methods for the app delegate singleton.

*others say to "inject" in the view controller only the part of model which it needs (or its subviews needs), but I don't understand how to do this. Via a property? Via an initWithModel: method (and in this case, how can I say to IB to use that method?)

*others again say that the model should be a singleton

*and again, others say to use global variables (!)

Could you please give me some hint (and code samples)? I would like to learn the things in the proper manner, considering that soon I will be moving towards Core Data.

A: Abstract: I read carefully the topic Where to place the "Core Data Stack" in a Cocoa/Cocoa Touch application suggested by Brad Larson and I wrote a possible solution on how to deal with a model and different view controllers. The solution doesn't use Core Data, but I believe that the same design may be applied to Core Data  apps.
Scenario: let's consider a simple application which stores information about products, such as name, description and price/unit. Once launched, the application shows a list of products (with a UITableView); when the user taps on a product name, the application presents product details in another view, updating the navigation bar with the product name.
Architecture The model is pretty simple here: an array of Product objects, each one with a name, a description and a price property.
The application has got three main views, mostly created by the Navigation template of Xcode: a UINavigationView (managed by the UINavigationController, instantiated in the app delegate), the default UITableView (managed by RootViewController and which is the first view shown by the UINavigationController) and a DetailView (managed by the DetailViewController class we have to write).
Let's see what's the big plan from the model point of view:

*

*The model is instantiated/loaded by the Application delegate as a NSMutableArray of Product objects;

*The pointer to the model is now passed to the first view controller of our hierarchy, UITableViewController, through a property. Actually, one could argue that the first controller in the hierarchy is the UINavigationController, so we should pass the reference to it and from it to the UITableViewController but... Apple says that UINavigationController shouldn't be subclassed, so we cannot add any property/method. And actually it makes sense, because the responsibility of an UINavigationController is always just the visualization management, not the model manipulation.

*When the user select a UITableCell, the UITableViewController creates a new DetailViewController (with the associated DetailView), passes the single selected product as a property and pushes the DetailView on the top of the UINavigation stack.

Here some code snippets:
Creation of the model:
// SimpleModelAppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // products is a protected ivar
    products = [[NSMutableArray alloc] init];

    Product *p1 = [[Product alloc] initWithName:@"Gold" andDescription:@"Expensive metal" andUnitPrice:100];
    Product *p2 = [[Product alloc] initWithName:@"Wood" andDescription:@"Inexpensive building material" andUnitPrice:10];

    [products addObject:p1];
    [products addObject:p2];

    [p1 release];
    [p2 release];

    // Passing the model reference to the first shown controller
    RootViewController *a = (RootViewController*)[self.navigationController.viewControllers objectAtIndex:0];
    a.products = products;

    // Add the navigation controller's view to the window and display
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)dealloc
{
    // The app delegate is the owner of the model so it has to release it.
    [products release];
    [_window release];
    [_navigationController release];

    [super dealloc];
}

The RootViewController can receive the model reference, since it has a NSMutableArray property:
// RootViewController.h

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController

@property (nonatomic, retain) NSMutableArray *products;

@end

When the user taps on a product name, the RootViewController instantiates a new DetailViewController and passes the reference to the single product to it using a property again.
// RootViewController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];

    // Passing the model reference...
    detailViewController.product = [products objectAtIndex:indexPath.row];

    [self.navigationController pushViewController:detailViewController animated:YES];

    [detailViewController release];
}

And, at the end, the DetailViewController shows the model information setting its outlets in the viewDidLoad method.
// DetailViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = product.name;
    self.descriptionLabel.text = product.description;
    self.priceLabel.text = [NSString stringWithFormat:@"%.2f eur", product.unitPrice];
}

You can download the full project here: http://dl.dropbox.com/u/1232650/linked/stackoverflow/SimpleModel.zip
I will really appreciate any comment to my solution, I am eager to learn ;)

A: More experienced colleagues recommend to have relevant property in AppDelegate.
IMO it is better to use specific set of models in specific controller.

A: I'm a noob too but here's what I did. It's most like #2.
In applicationDidFinishLaunching, the app delegate creates an instance of the model.
My view controllers declare a property pointing to the model, but the type is a protocol (in my case id <GameModel>. Many of the properties in the protocol are declared as readonly.
In applicationDidFinishLaunching, the app delegate sets the property to point to the model it created.
What I don't like about:
One. Your view controllers shouldn't have to know about the structure of your app delegate. You might reuse the same view controller in another app, with a different app delegate type. You could make simple changes to your view controller code to fix that, or there are other ways to get around it, but why make it hard?
Three. I am not as fond of singletons as most people. The problem is they're single. What if you want to have multiple models loaded?
Four. ?!?!


text:
Q: How can I make Multiplication Matrix in Python Code? I'd be happy if you tell me, what I need to change in the code "This Is My Code" to get "This is My Target"
This Is My Code:
for a in range(1,11):
    for b in range(1,11):
        print(f'{a*b:3d}' , end = '|')
    print()

Output of This Is My Code:
  1|  2|  3|  4|  5|  6|  7|  8|  9| 10|
  2|  4|  6|  8| 10| 12| 14| 16| 18| 20|
  3|  6|  9| 12| 15| 18| 21| 24| 27| 30|
  4|  8| 12| 16| 20| 24| 28| 32| 36| 40|
  5| 10| 15| 20| 25| 30| 35| 40| 45| 50|
  6| 12| 18| 24| 30| 36| 42| 48| 54| 60|
  7| 14| 21| 28| 35| 42| 49| 56| 63| 70|
  8| 16| 24| 32| 40| 48| 56| 64| 72| 80|
  9| 18| 27| 36| 45| 54| 63| 72| 81| 90|
 10| 20| 30| 40| 50| 60| 70| 80| 90|100|

This Is My Target:
  1|  2|  3|  4|  5|  6|  7|  8|  9| 10|
  2|  4|   |   |   |   |   |   |   |   |
  3|   |  9|   |   |   |   |   |   |   |
  4|   |   | 16|   |   |   |   |   |   |
  5|   |   |   | 25|   |   |   |   |   |
  6|   |   |   |   | 36|   |   |   |   |
  7|   |   |   |   |   | 49|   |   |   |
  8|   |   |   |   |   |   | 64|   |   |
  9|   |   |   |   |   |   |   | 81|   |
 10|   |   |   |   |   |   |   |   |100|

A: This works :
for a in range(1,11):
    for b in range(1,11):
        if a == b or a == 1 or b == 1:
            print(f'{a*b:3d}' , end = '|')
        else:
            print(f'   ' , end = '|')
    print()

To remove the | and get quite the same thing as in the image you provided, switch end = '|' for end = ''
for a in range(1,11):
    for b in range(1,11):
        if a == b or a == 1 or b == 1:
            print(f'{a*b:3d}' , end = '')
        else:
            print(f'   ' , end = '')
    print()


text:
Q: Script not working for On Click and Selected navigation states Trying to have my navigation have an on click and selected state, but I am not able to do so with this code (website is: http://bit.ly/rgwsite )
$('nav li a').click(function() {
$(this).parent().addClass('on').siblings().removeClass('on');
});

nav li is as follows

    Home

The reason we need to use a jquery/javascript action to add the class to the navigation is because it doesn't refresh when a new page loads. For instance, when you're on the home page and click on the tab "Experience RGW", it only loads the content for that page below the header (within the "#ajax" div). Currently, none of these scripts are working. There is no reason they shouldn't... could there be something else causing the page not to recognize the jquery script and run it on-click? The main reason I ask is because I've tried to test the function and add an alert, but even that didn't work
Thanks in advance!

A: siblings has your current element selected, you don't want to remove his 'on' class.
$('nav li a').click(function() {
  $(this).parent().siblings().removeClass('on');
  $(this).parent().addClass('on');
});

edit : nvm, your code works fine : look at this jsfiddle.
re-edit : I'm totally wrong, siblings does not contain the current element.
re-re-edit : If you link to another page (href="index.php"), the page will be reloaded (or a new one will be loaded) and your JavaScript click action will be forgotten, could it be the error?

A: You might wanna try it like this:
$(this).parent().siblings().removeClass('on');
$(this).parent().addClass('on');

What you did is add the class "on" to the LI and then removed it with .siblings().removeClass('on');


text:
Q: Sequence of step functions satisfying $\frac{\int^1_0\phi (t)dt}{||\phi_n||_{\infty}}\rightarrow 0 \text{ as $n \rightarrow \infty$}$ Is there a sequence of step functions $\phi_n :[0,1] \rightarrow \Bbb R (n \in \Bbb N)$ that satisfy $\int^1_0 \phi_n(t)dt \gt 0$ and $$\frac{\int^1_0\phi_n (t)dt}{||\phi_n||_{\infty}}\rightarrow 0 \text{ as $n \rightarrow \infty$}$$
I can't seem to conceive a function that would satisfy such conditions.

A: If $\psi_n(t)=1$ for $t \leq \frac 1  2$ and $-1$ for $t >\frac 1 2$ the $\int_0^{1} \psi_n (t)dt=0$ for all $n$ and $\|\psi_n\|_{\infty}=1$ for all $n$. Now take $\phi_n =\frac  1 n+\psi_n$. Note that $\|\phi_n\|_{\infty}\geq 1-\frac 1 n$.

A: For $n=1,2,\dots$ define $\phi_n = 1$ on $[0,1/n]$ and $0$ elsewhere. Then for each $n,$ $\phi_n$ is a step function, $\|\phi_n\|_\infty=1,$ and $\int_0^1\phi_n = 1/n.$ We're done.


text:
Q: addthis sharing some facebook async issue The problem is somehow connected with Javascript: load AddThis upon clicking, but not really the same.
So I have some content uploading with AJAX.
There I have a new AddThis toolbox with the correct code, just as I have in other places, white are loaded statically and work fine.
When I update my content I call addthis.toolbox() which generates the toolbox from the code, but Facebook button does not work, and Twitter and .addthis_button_compact work.
I use the very simple compact buttons style.
Does not work http://d.pr/i/K1QH - nor upon hover, nor upon click (loaded dynamically).
Works fine on hover http://d.pr/i/OilR - loaded statically
Unfortunately cannot show it on the live site - but it is just like in the example http://jsfiddle.net/beshur/mjncS/ ( and here it works)
Any ideas?
Or put it another way: Is there a way just to open a new window on click on the Facebook icon (like it happens with Twittwe) ? Just the simple sharer link.
Thank you.

A: You're getting the hover because you're logged into AddThis.  That window is the Instant Share feature.  If you log out of AddThis, that should go away and work the way you expect it.


text:
Q: Concatenate file weight less than the sum of the files I have done these commands to concatenate the files into one file:
$ ls -1 | wc -l
16916
$ ls -1 *.txt | wc -l
16916
$ ls -lh | head -1
total 93M
$ cat *.txt > ../nectar_3.txt
$ ls -lh ../nectar_3.txt
-rw-r--r-- 1 llopis llopis 52M May 25 16:03 ../nectar_3.txt

Why is the resulting file size half of the sum of the size of all files? The only explanation I can found is about rounding in the ls -lh command, but I couldn't find anything (using ls -lk outputs almost the same 92.76953125M)

A: The total is rounded, and is not guaranteed to be accurate:
Simple example:
marc@panic$ ls -lk
total 24
-rw-r--r-- 1 marc marc 6000 May 25 08:39 test1.txt
-rw-r--r-- 1 marc marc 7000 May 25 08:39 test2.txt
-rw-r--r-- 1 marc marc 8000 May 25 08:39 test3.txt

Three simple files, total size = 21,000 bytes, yet the total shows 24.


text:
Q: iOS: Using @min and @max in a core data predicate I have a core data entity, Client, which has a discountproperty. I want to fetch the the client with the smallest discount.
I am using the following NSPredicate:
[NSPredicate predicateWithFormat:@"@min.discount"];

However, I am getting the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "@min.discount"'

What am not doing right?

A: I don't think NSPredicate has support for functions like this unless it is part of a boolean predicate expression (i.e. involving things like "greater than").
You should read this CoreData documentation which gives some examples, specifically using max as an example:

There are a number of steps to follow to create and use the expression
  description.
First you need to create expressions (instances of NSExpression) to represent the key-path for the value you're interested in, and to
  represent the function you want to apply (such as max: or min:):
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"salary"];
NSExpression *maxSalaryExpression = [NSExpression expressionForFunction:@"max:"
                                                  arguments:[NSArray arrayWithObject:keyPathExpression]];

For a full list of supported functions, see expressionForFunction:arguments:.
You then create the expression description and set its name, expression, and result type.
The name is the key that will be used in the dictionary for the return value. If you want to retrieve multiple values—such as the
  largest and the smallest salaries in an Employee table—the name of
  each expression description must be unique for a given fetch request.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"maxSalary"];
[expressionDescription setExpression:maxSalaryExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];

Finally, you set the request's properties to fetch just the property represented by the expression:
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];


text:
Q: How to add Maven to existing Java WebApplication in IntelliJ? There is standard Java WebApp project. I need to use Maven to build/compile/deploy project to online server. There is an option to create new maven module module or to import project using pom.xml. Following probaby won't work because:

*

*Project doesn't have maven project and pom.xml

*Creating new maven module probably would mess up my existing project structure.
How to add Maven support to existing Java WebApplication in IntelliJ 12?

UPDATE:
I selected Add framework Support... > Maven. Generated pom.xml at project's root. Added maven-war-plugin. The following structure I have got. Is it any good / correct?

A: You should use maven standard project structure for maven applications. However, if you cannot change it, then you have to tell Maven where to look for specific files. Consider:
Using maven using non standard directory layout
Standard Maven structure
Also here are some interesting things to remember: http://wiki.jetbrains.net/intellij/Maven_FAQ


text:
Q: UnityContainer.Resolve crashes when .NET Native tool chain is enabled We have a Windows 10 UWP app that runs fine under Debug builds and crashes under Release builds. What it is about release builds that makes it crash is that .NET Native tools chain is enabled - disabling that allows the app to run. But that's not a real fix as it needs to run with .NET Native tool chain if you intend to publish to the store.
We use Microsoft.Practices.Unity for DI. Here's an example of how we register some classes:
container.RegisterType<IBoardView, BoardView>();

And then, in our app we resolve it as follows:
container.Resolve<IBoardView>();

It works fine unless I run it with .NET Native, in which case I get the following exception:

An exception of type 'Microsoft.Practices.Unity.ResolutionFailedException' occurred in Microsoft.Practices.Unity.dll but was not handled in user code
Additional information: Resolution of the dependency failed, type = "WindowsUniversal.ViewModels.Interfaces.IBoardViewModel", name = "(none)".
Exception occurred while: while resolving.

And in the output window I get:

Exception thrown: 'System.NullReferenceException' in System.Linq.Expressions.dll
Exception thrown: 'System.NullReferenceException' in Microsoft.Practices.Unity.dll
Exception thrown: 'Microsoft.Practices.Unity.ResolutionFailedException' in Microsoft.Practices.Unity.dll
An exception of type 'Microsoft.Practices.Unity.ResolutionFailedException' occurred in Microsoft.Practices.Unity.dll but was not handled in user code
Additional information: Resolution of the dependency failed, type = "WindowsUniversal.ViewModels.Interfaces.IBoardViewModel", name = "(none)".
Exception occurred while: while resolving.
Exception is: NullReferenceException - Object reference not set to an instance of an object.
At the time of the exception, the container was:
Resolving WindowsUniversal.ViewModels.Interfaces.IBoardViewModel,(none)

All this works under Debug or Release when .NET Native is disabled. Now I know .NET Native has it's limitations, reflection being one of them. I guess I'm asking how to get around this?
Any insights would be greatly appreciated, thanks.


text:
Q: How do I connect to a local Socket in C#? I'm trying to adapt this python code I found for connecting to the Dropbox daemon:
def connect(self, cmd_socket="~/.dropbox/command_socket", iface_socket="~/.dropbox/iface_socket"):
    "Connects to the Dropbox command_socket, returns True if it was successfull."
    self.iface_sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    self.sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        self.sck.connect(os.path.expanduser(cmd_socket)) # try to connect
        self.iface_sck.connect(os.path.expanduser(iface_socket))
    except:
        self.connected = False
        return False
    else: # went smooth
        self.connected = True
        return True

Here is what I have so far:
public bool Connect (int port) {
    return Connect ("~/.dropbox/command_socket", "~/.dropbox/iface_socket",
                    port);
}

public bool Connect (string cmdSocket, string ifaceSocket, int port)
{
    IfaceSocket = new Socket (AddressFamily.Unix, SocketType.Stream,
                              ProtocolType.IP);
    CmdSocket = new Socket (AddressFamily.Unix, SocketType.Stream,
                            ProtocolType.IP);

    try {
        // ExpandUser replaces a leading "/~" with the user's home directory
        IPAddress [] CmdIPs = Dns.GetHostAddresses (ExpandUser (cmdSocket));
        CmdSocket.Connect (CmdIPs [0], port);
        IPAddress [] IfaceIPs = Dns.GetHostAddresses (ExpandUser (ifaceSocket));
        IfaceSocket.Connect (IfaceIPs [0], port);
    } catch (Exception e) {
        // Debug
        Console.WriteLine (e);

        Connected = false;
        return false;
    }

    Connected = true;
    return true;
}

This compiles fine, but when I try to run it, I get System.Net.Sockets.SocketException: No such host is known. I assume this is because cmdSocket and ifaceSocket are paths, not IP addreses. Python appears to handle this automatically, how do I do it in C#? This is my first foray into socket programming, so please point out any obvious mistakes.

A: You need to use Mono.Unix.UnixEndPoint from Mono.Posix.dll instead of an IPEndPoint. Everything else is the same. See an example of how XSP uses it here.


text:
Q: What is the name (if any) for this kind of tree? I have this tree which, for each node, has exactly 10 childnodes (0-9). Each node has some associated data (say, for example, a name and a tag and a color) which, I guess, isn't important for this question. Each of the childnodes has exactly 10 childnodes. A node can be null (which 'ends' the branch') or contain another node.
To visualize what I'm talking about I made this diagram (fear my paintz0r skillz!):

A black box is a null-node. A white box is a node which contains data and childnodes. As you can see, even the root, each node has exactly 10 childnodes. Because of simplicity and to keep the diagram sane I have drawn some nodes very tiny but you can imagine these tiny nodes being the same.
This structure allows me to traverse a path consisting of digits very quickly: a path of 47352 would lead me down the "orange path" to the final destination; 4->7->3->5 where the final 2 cannot be resolved because that last one is a null-node (although colored red) and contains no childnodes.
My question is pretty simple actually: what is this kind of tree called? I have gone through all trees on Wikipedia's Tree (data structure) lemma and the closest I (think I) could get is the Octree and/or K-ary tree. Along those lines of reasoning my tree would be called a Dectree, Decitree, 10-ary tree or 10-way tree or something. But there might be a better name for this. So: anyone?

A: K-ary tree with K=10

In graph theory, a k-ary tree is a rooted tree in which each node has
no more than k children
It is also sometimes known as a k-way tree, an N-ary tree, or an M-ary
tree. A binary tree is the special case where k=2.

A: This is something like B-Tree.


text:
Q: Async .eachLimit callback Error not called I the following code in my node.js project.
async.eachLimit(dbresult, 1, function (record, callback) {
  var json = JSON.stringify(record)
  var form = new FormData()
  form.append('data', json)
  form.submit(cfg.server + '/external/api', function (err, res) {
    if (err) {
     callback(err)
    }
    if (res.statusCode === 200) {
      connection.query('UPDATE selected_photos set synced = 1 WHERE selected_id = "' + record.selected_id + '"', function (err, result) {
        if (err) {
          console.log(err)
          callback(err)
        } else {
         callback()
        }
      })
    } else {
      console.log(res.statusCode)
    return callback(err)
    }
  })
}, function (err) {
// if any of the file processing produced an error, err would equal that error
if (err) {
   // One of the iterations produced an error.
   // All processing will now stop.
   console.log('A share failed to process. Try rerunning the Offline Sync')
     process.exit(0)
    } else {
      console.log('All files have been processed successfully')
      process.exit(0)
    }
 })
}

res.statusCode = 302 So this should error out. But the the error callback is never triggered. How do it get it to trigger the error so that it stops eachLimit and the shows the
console.log('A share failed to process. Try rerunning the Offline Sync')

A: You have:
if (err) {
in first line of form submit handler. After that, you are sure that there was no error. So when you check response statusCode and try to call back with error, you are calling back with empty value.
That is why you do not get error when checking for it in your final callback function.
Try to create new Error('Status not OK: ' + res.statusCode) when calling back from your form submit handler.


text:
Q: Can not change innerHTML of a table via Javascript to add rows In my application I am using Javascript to call a VB side function via PageMethods. When the onSuccess function is hit, I am attempting to add the returned string into the inner html of a table. Listed below is the Javascript I am trying to use to do this, but I keep getting a:

"Microsoft JScript runtime error: Unknown runtime error"

Below is the table (I would like to keep this how it currently is if possible, this was already in place when I inherited this project).
            <asp:Table id="tblResults" Runat="server" CssClass="detailTable" CellSpacing="0" CellPadding="4"
                Width="100%">
                <asp:TableRow CssClass="detailRow">
                    <asp:TableCell Width="1%"> </asp:TableCell>
                    <asp:TableCell Width="10%">
                        ID</asp:TableCell>
                    <asp:TableCell>
                        Title</asp:TableCell>
                    <asp:TableCell>
                        Manager</asp:TableCell>
                    <asp:TableCell>
                        Start Date</asp:TableCell>
                    <asp:TableCell>
                        End Date</asp:TableCell>
                    <asp:TableCell>
                        Status</asp:TableCell>
                </asp:TableRow>
            </asp:Table>

The innerHTML of the table when the JS function is called:

ID
Title
Manager
Start Date
End Date
Status

And here is the javascript of the success function - What I did was I cut off the /TBODY ending of the innerHTML, want to add in the return string (text that contains html for other rows of the table) - then add /TBODY back to close the table:
function saveSuccess(c) {
var oldInner = document.getElementById('tblResults').innerHTML;
var index = oldInner.indexOf("
");
oldInner = oldInner.slice(0, index);
document.getElementById('tblResults').innerHTML = oldInner + c + '
';
}

can anyone see why I am getting this error and why the table is not updating to show the returned html?

A: From MSDN:

The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.

You have to rebuild the whole table, or else use DOM APIs to modify/add content.


text:
Q: How to show a watermark for 3 second on a MP4 using FFmpeg I need to add a 3-second watermark to a Camera recorded video in Android. I'm using FFmpeg static build to execute the commands.
Approach I
I had tried the below command using latest version of FFmpeg(version N-60108-gda25a65) in my Desktop running Linux Mint, the command works fine.
ffmpeg -y -itsoffset 3 -i input.mp4 -i myImage.jpg -filter_complex "[0:v][1:v]overlay=0:0:enable=between(t\,0\,3)"  -codec:a copy output.mp4

In Android I'm using the FFmpegv1.2 with below config to execute the command.
 *******Starting FFMPEG
    ***ffmpeg version 1.2 Copyright (c) 2000-2013 the FFmpeg developers***
    ***  built on Mar 31 2013 23:44:57 with gcc 4.6 (GCC) 20120106 (prerelease)***
    ***  configuration: --arch=arm --target-os=linux --enable-runtime-cpudetect --enable-pic --disable-shared --enable-static --cross-prefix=/opt/android-ndk-r8e/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/arm-linux-androideabi- --sysroot=/opt/android-ndk-r8e/platforms/android-8/arch-arm --extra-cflags='-march=armv6' --extra-ldflags= --enable-ffmpeg --disable-ffplay --disable-ffprobe --disable-ffserver --disable-network***
    ***  libavutil      52. 18.100 / 52. 18.100***
    ***  libavcodec     54. 92.100 / 54. 92.100***
    ***  libavformat    54. 63.104 / 54. 63.104***
    ***  libavdevice    54.  3.103 / 54.  3.103***
    ***  libavfilter     3. 42.103 /  3. 42.103***
    ***  libswscale      2.  2.100 /  2.  2.100***
    ***  libswresample   0. 17.102 /  0. 17.102***

Java Code to run the FFmpeg command:
String[] ffmpegCommandToAddWatermark = {
            mFfmpegInstallPath, "-y", "-itsoffset","3",
             "-i", INPUT_VIDEO_PATH, "-i", WATERMARK_IMAGE_PATH,
             "-filter_complex","[0:v][1:v]overlay=0:0:between(t\\,0\\,3)",
             "-strict","-2",
             "-codec:a","copy",OUTPUT_VIDEO_PATH};
        try {
        Process ffmpegProcess = new ProcessBuilder(ffmpegCommandToAddWatermark)
            .redirectErrorStream(true).start();

        String line;

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(ffmpegProcess.getInputStream()));
        Log.d(TAG, "*******Starting FFMPEG");
        while ((line = reader.readLine()) != null ) {

            Log.d(TAG, "***" + line + "***");
        }
        Log.d(null, "****ending FFMPEG****");

        } catch (Exception e) {
        e.printStackTrace();
        }

The command execution failed with following error:
***[overlay @ 0x271f770] No option name near 'between(t,0,3)'***
***[AVFilterGraph @ 0x2711530] Error initializing filter 'overlay' with args '0:0:between(t,0,3)'***
***Error configuring filters.***

The same command executes successfully when :enable=between(t\,0\,3) is removed, but the resulting output video has the watermark throughout the timeline, but I need watermark only for the starting 3 seconds.
Approach II:
I tried to convert WaterMarkImage to WaterMarkVideo
ffmpeg -y -loop 1 -r 30 -i WaterMarkImage.jpg -b:v "4096k" -vf "scale=640:480" -t 3 WaterMarkVideo.mp4

And then merge the WaterMarkVideo.mp4+CameraRecordedVideo.mp4 using the concat command:
ffmpeg -y -f concat -i inputs.txt -c copy output.mp4

The resulting output is corrupt due to BitRate,FrameRate,etc., mismatch. Any idea to solve the problem?.

A: FFmpeg 1.2 does not have timeline editing support. Please refer to your local FFmpeg documentation when using old releases. The online FFmpeg documentation is synced daily with the source code, and because FFmpeg development is very active the online documentation may not be suitable for your old release.
Releases are intended for distributors. General users should use the most recent source code from git master.


text:
Q: iOS "URL schemes found in your app are not in the correct format" while uploading app I am getting the error below while uploading an app to the App Store.

ERROR ITMS-90158: "The following URL schemes found in your app are not in the correct format: [5063495]. URL schemes need to begin with an alphabetic character, and be comprised of alphanumeric characters, the period, the hyphen or the plus sign only. Please see RFC1738 for more detail."

I am using Facebook, Google+, Instagram and LinkedIn Login in my app.
Info.plist file code
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fb***************</string>
            <string>5063495</string>
        </array>
    </dict>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.googleusercontent.apps.************-juag6bl6uqrrd0ivf80anjics6j92ehp</string>
        </array>
    </dict>
</array>

A: According to the error message:

*

*you must start URL schemes with a letter (so, in OP's example, the URL scheme 5063495 needs to be removed)

*you can only use alphanumeric characters (a-z, 0-9), a period (.), a hyphen (-) or a plus sign (+), so if you have a character in your URL scheme that's none of the above, remove it

The message also states that you can check out RFC1738 for more details, which is a document describing the syntax and semantics for URLs.

A: You have to remove the line
<string>5063495</string>

From Info.plist
If this is a facebook URL scheme,
you can write as <string>fb5063495</string>