Linq to sql table dynamically with ExecuteQuery VB

Question: I am using VB Framework 4.0 and Linq to sql.
I want to choose dynamycally the name of table. I have used the library namedtable.dll and I have mapped all the tables of database and it's Ok.
My problem is when I try to execute executequery. Here my code.
Imports Microsoft.VisualBasic
Imports System.Data.Linq
Imports Prototype.NamedTable.Data
Imports Prototype.NamedTable.Utility

    Public Class tipos

        Private _conexion As String = "conexion"

        Public Sub New()

        End Sub

        ...........

        Public Function getConsulta(byval tableName as String) As IList(Of TIPOS)

            Dim context As New DataContext(_conexion)

            sql = " select COD, NAME from " & tableName

            Dim a = context.ExecuteQuery(Of TIPOS)(sql)

            Return sql.ToList

        End Function
    End Class

but I have an error: "El tipo 'TIPOS' debe declarar un constructor predeterminado (sin parámetros) para que pueda construirse durante la asignación." that in English is:
"The type 'Type TIPOS' must declare a default (parameterless) constructor in order to be constructed during mapping"
I have defined "TIPOS" in other file:
Public Interface TIPOS
    <Column(CanBeNull:=False)> Property COD Integer
    <Column(CanBeNull:=False)> Property NAME As String
End Interface

Public Class ITIPO : Implements TIPO
    Private _cod As Integer
    Private _name As String

    Public Property COD As Integer Implements TIPO.COD
        Get
            Return _cod
        End Get
        Set(ByVal value As Integer)
            _cod = value
        End Set
    End Property

    Public Property NAME As String Implements TIPO.NAME
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

End Class

I need help!
Sorry for my English.
Answer: The solution can be found on codeproject.com in article "Dynamic Table Mapping for LINQ-to-SQL." Below is a static class you can use. Please see the article for instructions on what you must do to use the 4 different generic methods.  Here is an invocation example:
public interface IResult
{
    [Column(IsPrimaryKey = true)]
    int Id { get; set; }

    [Column]
    string Name { get; set; }

    [Column]
    double Value { get; set; }
}

public void TestThis()
{
    var connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False";
    var context = new DataContext(connectionString);
    var table = context.GetTable<IResult>("YourTableName");
    var query = from r in table where r.Id == 108 select r;
    var list = query.ToList();
}

Class Code:
namespace Prototype.NamedTable
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;

///
/// The utility.
///
public static class Utility
{
    #region Constants and Fields

    ///
    /// The named types.
    ///
    private static readonly Dictionary<string, Type> NamedTypes = new Dictionary<string, Type>();

    ///
    /// The _assembly builder.
    ///
    private static AssemblyBuilder _assemblyBuilder;

    ///
    /// The _module builder.
    ///
    private static ModuleBuilder _moduleBuilder;

    #endregion

    #region Properties

    ///
    /// Gets or sets a value indicating whether Verbose.
    ///
    public static bool Verbose { get; set; }

    #endregion

    #region Public Methods

    ///
    /// The clear.
    ///
    public static void Clear()
    {
        _assemblyBuilder = null;
        NamedTypes.Clear();
    }

    ///
    /// Retrieve a table from the data context which implements ITable<TEntity> by T and use ITable<TBack>
    ///
    /// <typeparam name="TEntity">
    /// Entity Type
    /// </typeparam>
    /// <typeparam name="TBack">
    /// Backing Type
    /// </typeparam>
    /// <param name="context">
    /// Data Context
    /// </param>
    /// <returns>
    /// </returns>
    public static ATable<TEntity> GetTable<TEntity, TBack>(this DataContext context) where TEntity : class
        where TBack : class
    {
        // Create the backup table
        Table<TBack> refer = context.GetTable<TBack>();

        // Prepare the cloning method
        Delegate cloneFrom = CompileCloning(typeof(TEntity), typeof(TBack));

        // Construct the table wrapper
        return new ATable<TEntity>(refer, cloneFrom);
    }

    ///
    /// Retrieve a table from the data context which implements ITable<TEntity> uses specific backing table
    ///
    /// <typeparam name="TEntity">
    /// Entity Type
    /// </typeparam>
    /// <param name="context">
    /// Data context
    /// </param>
    /// <param name="name">
    /// Table name
    /// </param>
    /// <returns>
    /// </returns>
    public static ATable<TEntity> GetTable<TEntity>(this DataContext context, string name) where TEntity : class
    {
        // Create/Retrieve a type definition for the table using the TEntity type
        Type type = DefineEntityType(typeof(TEntity), name);

        // Create the backup table using the new type
        ITable refer = context.GetTable(type);

        // Prepare the cloning method
        Delegate cloneFrom = CompileCloning(typeof(TEntity), type);

        // Construct the table wrapper
        return new ATable<TEntity>(refer, cloneFrom);
    }

    /*
    ///
    /// The log.
    ///
    /// <param name="format">
    /// The format.
    /// </param>
    /// <param name="args">
    /// The args.
    /// </param>
    public static void Log(string format, params object[] args)
    {
        if (!Verbose)
        {
            return;
        }

        Console.Write("*** ");

        if ((args == null) || (args.Length == 0))
        {
            Console.WriteLine(format);
        }
        else
        {
            Console.WriteLine(format, args);
        }
    }*/

    #endregion

    #region Methods

    ///
    /// Clone an attribute
    ///
    /// <param name="attr">
    /// </param>
    /// <returns>
    /// </returns>
    private static CustomAttributeBuilder CloneColumn(object attr)
    {
        Type source = attr.GetType();
        Type target = typeof(ColumnAttribute);

        var props = new List<PropertyInfo>();
        var values = new List<object>();

        // Extract properties and their values
        foreach (PropertyInfo prop in source.GetProperties())
        {
            if (!prop.CanRead || !prop.CanWrite)
            {
                continue;
            }

            props.Add(target.GetProperty(prop.Name));
            values.Add(prop.GetValue(attr, null));
        }

        // Create a new attribute using the properties and values
        return new CustomAttributeBuilder(
            target.GetConstructor(Type.EmptyTypes), new object[0], props.ToArray(), values.ToArray());
    }

    ///
    /// Make a delegate that copy content from "source" to "dest"
    ///
    /// <param name="source">
    /// Source Type
    /// </param>
    /// <param name="dest">
    /// Destination Type
    /// </param>
    /// <returns>
    /// Executable delegate
    /// </returns>
    private static Delegate CompileCloning(Type source, Type dest)
    {
        // Input parameter
        ParameterExpression input = Expression.Parameter(source);

        // For every property, create a member binding
        List<MemberBinding> binds =
            source.GetProperties().Select(
                prop =>
                Expression.Bind(
                    dest.GetProperty(
                        prop.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly),
                    Expression.MakeMemberAccess(input, prop))).Cast<MemberBinding>().ToList();

        // Expression of creating the new object
        MemberInitExpression body = Expression.MemberInit(
            Expression.New(dest.GetConstructor(Type.EmptyTypes)), binds);

        // The final lambda
        LambdaExpression lambda = Expression.Lambda(body, input);

        // MJE
        //Log("{0}", lambda.ToString());

        // Return the executable delegate
        return lambda.Compile();
    }

    ///
    /// Create a class based on the template interface
    ///
    /// <param name="template">
    /// </param>
    /// <param name="name">
    /// </param>
    /// <returns>
    /// </returns>
    private static Type DefineEntityType(Type template, string name)
    {
        // Prepare the builders if not done
        if (_assemblyBuilder == null)
        {
            _assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);

            _moduleBuilder = _assemblyBuilder.DefineDynamicModule("Types");
        }

        // Check if there is already a type created for that table
        if (NamedTypes.ContainsKey(name))
        {
            return NamedTypes[name];
        }

        // Create the new type
        TypeBuilder tbuilder = null;
        if (template.IsInterface)
        {
            tbuilder = DefineInterfaceChild(name, template);
        }
        else
        {
            tbuilder = DefineOverriddenChild(name, template);
        }

        Type final = tbuilder.CreateType();

        NamedTypes[name] = final;

        return final;
    }

    ///
    /// The define interface child.
    ///
    /// <param name="name">
    /// The name.
    /// </param>
    /// <param name="template">
    /// The template.
    /// </param>
    /// <returns>
    /// </returns>
    private static TypeBuilder DefineInterfaceChild(string name, Type template)
    {
        TypeBuilder tbuilder = _moduleBuilder.DefineType(
            name, TypeAttributes.Public, typeof(Object), new[] { template });

        // Default constructor
        tbuilder.DefineDefaultConstructor(MethodAttributes.Public);

        // Attach Table attribute
        var abuilder = new CustomAttributeBuilder(
            typeof(TableAttribute).GetConstructor(Type.EmptyTypes),
            new object[0],
            new[] { typeof(TableAttribute).GetProperty("Name") },
            new object[] { name });
        tbuilder.SetCustomAttribute(abuilder);

        List<PropertyInfo> properties = template.GetProperties().ToList(); // May require sorting

        // Implement all properties));
        foreach (PropertyInfo prop in properties)
        {
            // Define backing field
            FieldBuilder fbuilder = tbuilder.DefineField(
                "_" + prop.Name, prop.PropertyType, FieldAttributes.Private);

            // Define get method
            MethodBuilder pgbuilder = tbuilder.DefineMethod(
                "get_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                prop.PropertyType,
                Type.EmptyTypes);

            // Define get method body { return _field; }
            ILGenerator ilg = pgbuilder.GetILGenerator();
            ilg.Emit(OpCodes.Ldarg_0);
            ilg.Emit(OpCodes.Ldfld, fbuilder);
            ilg.Emit(OpCodes.Ret);

            // Define set method
            MethodBuilder psbuilder = tbuilder.DefineMethod(
                "set_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                null,
                new[] { prop.PropertyType });

            // Define set method body { _field = value; }
            ILGenerator ils = psbuilder.GetILGenerator();
            ils.Emit(OpCodes.Ldarg_0);
            ils.Emit(OpCodes.Ldarg_1);
            ils.Emit(OpCodes.Stfld, fbuilder);
            ils.Emit(OpCodes.Ret);

            // Define the property
            PropertyBuilder pbuilder = tbuilder.DefineProperty(
                prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);

            // Set get/set method
            pbuilder.SetGetMethod(pgbuilder);
            pbuilder.SetSetMethod(psbuilder);

            // Attach Column attribute
            foreach (object attr in prop.GetCustomAttributes(false))
            {
                if (attr is ColumnAttribute || attr is AlterColumnAttribute)
                {
                    // MJE
                    //Log("Create column attribute for {0}", prop.Name);
                    pbuilder.SetCustomAttribute(CloneColumn(attr));
                    break;
                }
            }
        }

        return tbuilder;
    }

    ///
    /// The define overridden child.
    ///
    /// <param name="name">
    /// The name.
    /// </param>
    /// <param name="template">
    /// The template.
    /// </param>
    /// <returns>
    /// </returns>
    private static TypeBuilder DefineOverriddenChild(string name, Type template)
    {
        TypeBuilder tbuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, template);

        // Default constructor
        tbuilder.DefineDefaultConstructor(MethodAttributes.Public);

        // Attach Table attribute
        var abuilder = new CustomAttributeBuilder(
            typeof(TableAttribute).GetConstructor(Type.EmptyTypes),
            new object[0],
            new[] { typeof(TableAttribute).GetProperty("Name") },
            new object[] { name });
        tbuilder.SetCustomAttribute(abuilder);

        List<PropertyInfo> properties = template.GetProperties().ToList(); // May require sorting

        // Implement all properties));
        foreach (PropertyInfo prop in properties)
        {
            // Define get method
            MethodBuilder pgbuilder = tbuilder.DefineMethod(
                "get_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                prop.PropertyType,
                Type.EmptyTypes);

            // Define get method body { return _field; }
            ILGenerator ilg = pgbuilder.GetILGenerator();
            ilg.Emit(OpCodes.Ldarg_0);
            ilg.Emit(OpCodes.Call, template.GetMethod("get_" + prop.Name));
            ilg.Emit(OpCodes.Ret);

            // Define set method
            MethodBuilder psbuilder = tbuilder.DefineMethod(
                "set_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                null,
                new[] { prop.PropertyType });

            // Define set method body { _field = value; }
            ILGenerator ils = psbuilder.GetILGenerator();
            ils.Emit(OpCodes.Ldarg_0);
            ils.Emit(OpCodes.Ldarg_1);
            ils.Emit(OpCodes.Call, template.GetMethod("set_" + prop.Name));
            ils.Emit(OpCodes.Ret);

            // Define the property
            PropertyBuilder pbuilder = tbuilder.DefineProperty(
                prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);

            // Set get/set method
            pbuilder.SetGetMethod(pgbuilder);
            pbuilder.SetSetMethod(psbuilder);

            // Attach Column attribute
            foreach (object attr in prop.GetCustomAttributes(false))
            {
                if (attr is ColumnAttribute || attr is AlterColumnAttribute)
                {
                    // MJE
                    //Log("Create column attribute for {0}", prop.Name);
                    pbuilder.SetCustomAttribute(CloneColumn(attr));
                    break;
                }
            }
        }

        return tbuilder;
    }

    #endregion

    ///
    /// A table wrapper implements ITable<TEntity> backed by other ITable object
    ///
    /// <typeparam name="TEntity">
    /// </typeparam>
    public class ATable<TEntity> : ITable<TEntity>
        where TEntity : class
    {
        #region Constants and Fields

        ///
        /// Cloning method
        ///
        private readonly Delegate _clone;

        ///
        /// Backing table
        ///
        private readonly ITable _internal;

        #endregion

        #region Constructors and Destructors

        ///
        /// Initializes a new instance of the <see cref="ATable{TEntity}"/> class.
        /// Construct from backing table
        ///
        /// <param name="inter">
        /// </param>
        /// <param name="from">
        /// </param>
        public ATable(ITable inter, Delegate from)
        {
            this._internal = inter;
            this._clone = from;
        }

        #endregion

        #region Properties

        ///
        /// Gets ElementType.
        ///
        public Type ElementType
        {
            get
            {
                // Use the backing table element
                return this._internal.ElementType;
            }
        }

        ///
        /// Gets Expression.
        ///
        public Expression Expression
        {
            get
            {
                // Use the backing table expression
                return this._internal.Expression;
            }
        }

        ///
        /// Gets Provider.
        ///
        public IQueryProvider Provider
        {
            get
            {
                // Use the backing table provider
                return this._internal.Provider;
            }
        }

        #endregion

        #region Implemented Interfaces

        #region IEnumerable

        ///
        /// The get enumerator.
        ///
        /// <returns>
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IEnumerable<TEntity>

        ///
        /// The get enumerator.
        ///
        /// <returns>
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public IEnumerator<TEntity> GetEnumerator()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region ITable<TEntity>

        ///
        /// The attach.
        ///
        /// <param name="entity">
        /// The entity.
        /// </param>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public void Attach(TEntity entity)
        {
            throw new NotImplementedException();
        }

        ///
        /// The delete on submit.
        ///
        /// <param name="entity">
        /// The entity.
        /// </param>
        public void DeleteOnSubmit(TEntity entity)
        {
            // Directly invoke the backing table
            this._internal.DeleteOnSubmit(entity);
        }

        ///
        /// The insert on submit.
        ///
        /// <param name="entity">
        /// The entity.
        /// </param>
        public void InsertOnSubmit(TEntity entity)
        {
            // Input entity must be changed to backing type
            object v = this._clone.DynamicInvoke(entity);

            // Invoke the backing table
            this._internal.InsertOnSubmit(v);
        }

        #endregion

        #endregion
    }

    ///
    /// The alter column attribute.
    ///
    public class AlterColumnAttribute : Attribute
    {
        #region Constants and Fields

        ///
        /// The _can be null.
        ///
        private bool _canBeNull = true;

        ///
        /// The _update check.
        ///
        private UpdateCheck _updateCheck = UpdateCheck.Always;

        #endregion

        #region Properties

        ///
        /// Gets or sets AutoSync.
        ///
        public AutoSync AutoSync { get; set; }

        ///
        /// Gets or sets a value indicating whether CanBeNull.
        ///
        public bool CanBeNull
        {
            get
            {
                return this._canBeNull;
            }

            set
            {
                this._canBeNull = value;
            }
        }

        ///
        /// Gets or sets DbType.
        ///
        public string DbType { get; set; }

        ///
        /// Gets or sets Expression.
        ///
        public string Expression { get; set; }

        ///
        /// Gets or sets a value indicating whether IsDbGenerated.
        ///
        public bool IsDbGenerated { get; set; }

        ///
        /// Gets or sets a value indicating whether IsDiscriminator.
        ///
        public bool IsDiscriminator { get; set; }

        ///
        /// Gets or sets a value indicating whether IsPrimaryKey.
        ///
        public bool IsPrimaryKey { get; set; }

        ///
        /// Gets or sets a value indicating whether IsVersion.
        ///
        public bool IsVersion { get; set; }

        ///
        /// Gets or sets UpdateCheck.
        ///
        public UpdateCheck UpdateCheck
        {
            get
            {
                return this._updateCheck;
            }

            set
            {
                this._updateCheck = value;
            }
        }

        #endregion
    }
}
}

Comment: Plz use comment for sharing links
Comment: I have updated my answer and posted relevant code as suggested.
Comment: @mesterak Thanks for updating. I've retracted my down vote, but I cannot retract my delete vote. Posting links is okay, but we expect an explanation of why the linked resource is relevant, how it can be used, or at the very least, what the key piece of information is. It would've been sufficient (at least for me) if you had just posted your `IResult` interface with example code as well as the link to the class. Please read http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers
Comment: Thank-you for providing guidance on posting. For those wanting a link to the code source above, here it is: http://www.codeproject.com/Articles/333249/Dynamic-Table-Mapping-for-LINQ-to-SQL
Answer: Linq-to-Sql cannot materialize interfaces. It needs a class specification to know what instances it should create from a query. The exception message is elusive, to say the least. I don't know why it isn't more to the point.
Note that the class you want to materialize must have been mapped, or: it must be in the dbml. I say this because your ITIPO class is not partial, which makes me wonder how you can make it implement an interface (well, maybe you just slimmed down the code).
Side note: don't use all capitals for class names, and prefix an interface specification with "I", not a class.
Comment: thank for your answer. I have edit my question with more information.
Comment: Yes, but did you understand my answer: you can't do `ExecuteQuery(Of TIPOS)` because `TIPOS` is an interface. No matter how much code you're going to show, this fact won't change.


Diagonal morphism of regular variety is a regular embedding

Question: Let $X$ be a regular $k-$variety (i.e. all of its local rings are regular) of pure dimension $d$. Then I would like to show that the diagonal morphism $X\rightarrow X\times_k X$ is a regular embedding of codimension $d$, to be able to prove exercise $12.2.M$ in Ravi Vakil's "Foundations of Algebraic Geometry".
The preceding exercise shows that any closed embedding $Y \rightarrow Z$ with $Y$ regular and $Z$ regular at all points in the image of $Y$ is a regular embedding. I'd like to use this (particularly because Vakil lists $12.2.M$ as a consequence of the preceding exercise), only I'm having trouble proving that $X \times_k X$ is regular at points on the diagonal. Thus what I would really like to know is:

Let $X$ be a regular $k-$variety. Then $X \times_k X$ is regular at points on the diagonal.

Since $X$ is finite type, I can explicitly describe the local rings of $X$ as quotients of local rings of affine space, and use the kernels involved to explicitly describe the local rings of $X \times_k X$ as quotients of the local rings of $X$, but I can't then do very much with this, and I'm not sure that this is even the right approach.
Edit: Some of the answers suggest that regularity is not enough to show that the diagonal is a regular embedding. One provides an example of a regular scheme $W$ where $W \times W$ isn't regular at the diagonal, so the approach taken in this question is certainly flawed.
Comment: @Hoot Ah, proving smoothness translates over would be easier, because you could explicitly compute the Jacobian of $X \times_k X$ as just two copies of the Jacobian of $X$ in a block diagonal matrix (I think), but you're right that it's not the same (and I wouldn't know how to prove that this implied the embedding was regular). For what it's worth, smoothness was the condition I found this theorem usually stated with (e.g. in Fulton's intersection theory) although I couldn't find a proof for that case either.
Comment: Interesting. It's very doable if $X$ is _smooth_ but that's not quite the same.
Answer: Without some hypothesis on $k$ I don't think it's true that the diagonal embedding $X \to X \times_k X$ is regular. Like take everybody's favorite regular but non-smooth scheme over the non-perfect field $k:= \Bbb{F}_p(t)$. Namely, the scheme $\operatorname{Spec} \Bbb{F}_p(t)[x]/(x^p - t)$. We first compute the tensor product
$$\begin{eqnarray*} \Bbb{F}_p(t)[x]/(x^p - t) \otimes_{\Bbb{F}_p(t)} \Bbb{F}_p(t)[y]/(y^p - t) &\cong& \Bbb{F}_p(t)[x,y]/(x^p - t, y^p - t) \\
&\cong& L[y]/(y-\alpha)^p \end{eqnarray*}$$
where $L := \Bbb{F}_p(t)[x]/(x^p-t)$ and $\alpha$ is the image of $x$ in $L$.
We see that the tensor product is a local non-reduced  of dimension $0$. Hence the diagonal $X \to X \times_k X$ is a map from a point to a fat point and so is not regular.
Edit: Ravi told me via email that there is indeed an error in the notes with regards to this question.
Comment: I think you want to say $x - y$. Anyway, this is great. Sort of disturbing that his varieties aren't closed under product but oh well. I wonder if demanding that they be geometrically reduced patches things up?
Comment: @Ben To clarify, we're not looking for regularity, we're looking for regularity at points on the diagonal, in this case that's a single point. Thus the non-reducedness doesn't a priori imply that it's not regular at the diagonal. However, this scheme is NOT regular at the diagonal (the point $P$ corresponding to the prime $(X-Y, X^p-t, Y^p-t)$). Since $(0) \lneq (X^p-t) \lneq (X-Y, X^p-t, Y^p-t)$ is a maximal chain of primes in $\mathcal{A}^2_k$, $P$ is minimal and so the local ring at $P$ is $0-$dimensional. [continued below]
Comment: However, the tangent space to $X \times X$ at $P$ is cut out from the tangent space to $\mathbb{A}^2_k$ at $P$ by the equations $X^p-t, Y^p-t \mod{P_P}^2$. But since these are the same $\mod{P_P}^2$, the tangent space to $X \times X$ at $P$ is one dimensional, so the local ring is in fact, not regular. We could certainly have used that $(X-Y)^p = 0$ is still true in the local ring, but it's not immediately clear to my why $(X-Y) \not= 0$ in the stalk (I'm wary of explicit computations with elements in localisations of non-integral domains).
Comment: Anyway, if you'd update your answer to reflect the comments above, I'd be happy to accept it since this shows that this is actually a counter example to the question as posed.
Comment: @TomOldfield I think his ring only has one prime, so it's already local as written. Maybe it's easier to see this if you view it like this: $L = \mathbb F_p(t)[x]/(x^p - t)$ is a field. Let $\alpha$ be the image of $x$ in $L$. Now I form $L[y]/(y - \alpha)^p$.
Comment: My point, I think, is that you don't need to do any explicit computations with the tangent space (although that's fun too). Just the fact that regular local rings are domains. Someone should probably tell Ravi (after checking everything a bunch of times).
Comment: @Hoot Ah, that's a lot better, thanks! I forgot $L$ was a field, it's been a while since I properly thought about characteristic $p$. Yeah, once you know it's a local ring (and indeed, a $0-$dimensional one), the local ring at the maximal ideal is just the ring itself, which is not reduced and so not regular.

I'm going to send Vakil an e-mail in the next few days, about this and another potential error in the same chapter (I was waiting for some clarity on this and to check the other error before sending it).
Comment: I usually leave comments on his blog so others can see.
Comment: @Hoot Good idea, I'll probably do that then.
Comment: @TomOldfield I edited my answer. Btw I think Ravi is at a conference right now; he hasn't replied any of my emails lately.
Comment: @Hoot I edited my answer.
Answer: If $X$ is a flat locally noetherian scheme over $S$ (and in particular in your case), it is (formally) smooth over $S$ if and only if the diagonal is a regular embedding. So you are trying to prove that your variety is smooth over $k$. This is true for instance if $k$ is algebraically closed or of characteristic zero, but not in general.
For a proof of the first claim, see Bourbaki, Algèbre Commutative chap. 10, §
7 n. 10 Théorème 4, (i) ⟺ (v). As in most of this section of that book, there are some finiteness hypotheses on the morphisms, but they are not necessary if instead of "smoothness" you want to obtain "formal smoothness for the discrete (and so for any other) topology" (though the proof without them is more dificult). If you are interested in the proof in general I can sketch one here, but using deep homological methods.
For "regular does not imply smooth" you have examples in https://en.wikipedia.org/wiki/Geometrically_regular_ring
Comment: Thanks for the answer, would you be able to provide a proof of the fact you've mentioned, or at least a reference? I've seen it claimed several times that smooth implies that the diagonal is a regular embedding, but not the converse (and I haven't seen a proof either way).
Comment: @Tom I have edited the answer answering to that.
Comment: Thanks for the reference, but unfortunately I don't have access to that. Moreover I don't know what formally smooth means, or how it relates to smoothness, so the diagonal being regular being equivalent to the formal smoothness doesn't show that this theorem fails (since it might, perhaps be true that regular implies formal smoothness). Could you maybe clarify exactly what you're claiming? (i.e., for a k variety $W$, the diagonal is a regular embedding iff it $W$ is formally smooth and there exist regular, but not formally smooth $k-$ varieties)
Comment: I'm sorry I do not know any other reference. It should be also somewhere in EGA IV, but I am not able to find it. Smooth = formally smooth (for any topology) + morphism of finite type, so if your variety is of finite type (as usual in most books), smooth = formally smooth = regular diagonal.
Comment: And in general, formally smooth is equivalent to geometric regularity (you can find this in EGA 0$_{IV}$, both Matsumura's, etc.), so regular does not imply formal smoothness (same link as in the answer).
Comment: Ah, okay, thanks. I'll have a dig around and see if I can make sense of this, I'll let you know once I understand the problem a little better.
Answer: This is an answer to a question in Hoot's comments (I'm sorry not been able to post it as a comment by lack of reputation): "I wonder if demanding that they be geometrically reduced patches things up?"
No, $X\times_kX$ is regular (if and) only if $X$ is smooth over $k$. More generally, if $A$ is a noetherian ring, $B$ a local flat $A$-algebra such that $B\otimes_AB$ is regular, then $B$ is an essentially of finite type smooth $A$-algebra. The finiteness condition follows from Corollaire (3.6) in Ferrand, Monomorphismes et morphismes absolument plats. An then, for the smoothness, if $B\otimes_AB$ is regular, then $B$ is regular since it is a retract, and therefore the surjective map $B\otimes_AB \to B$ is a closed regular embedding. We apply now Bourbaki, Algèbre Commutative chap. 10, § 7 n. 10 Théorème 4, (i) ⟺ (v).
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](http://math.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](http://math.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/643134)
Comment: This was useful to me; thank you.
Comment: @Emily I would like to have posted it as a comment, but not because it does not answer the question. In fact, this answer shows more: that there is no necessity of an explicit new example, any example of regular but not smooth gives an example of $X\times_kX$ not regular (though maybe regular at the diagonal) with $X$ regular.
Comment: In such a case, it is perfectly acceptable to pose and answer your own question; that way, the corpus of knowledge is more comprehensive and organized :)
Comment: @emily, while that is generally so, in this case A.G.'s answer is more useful and to the point here than anywhere else.
Comment: @MarianoSuárez-Alvarez Fair enough, although I find it a bit out of sync with the typical flow.
Comment: The "typical flow" is very nuch at odds, from time to time, with the way math questions are dealt with in the real world.
Answer: Sadly I cannot comment. In any case:
(1) make clear what $k$ is (any field?) It depends greatly on the properties of $k$, as was already mentioned by A.G.
(2) unlike what some people think, there is no standard definition of "variety". E.g. everyone assumes *of finite type" (I think), but some assume irreducible, geometrically integral, whatever. For that reason you should always state what you mean by it.
(3) Over any field "smoothness" is equivalent to geometric regularity (see EGA IV), and thus "smoothness" is equivalent to regularity over a perfect field.
(4) The notion of smoothness is superior to regularity, exactly because it behaves very well with respect to base change. Over nonperfect fields I think regularity is less interesting.
Comment: $1)$ As best I can tell, $k$ is indeed allowed to be any field. $2)$ For me, a variety is a reduced, separated, finite type $k-$scheme. With regards to $3$ and $4$, I am aware that smoothness is the more useful and better behaved condition and that smoothness implies regularity, whereas regularity only implies smoothness for finite type $k-$schemes when $k$ is perfect. Are you agreeing with A.G that the diagonal being a regular embedding is equivalent to some sort of smoothness, and therefore that the problem as stated is incorrect?


Connecting to IBM MQ over TLS with JMS

Question: I'm trying to connect over TLS to IBM MQ with JMS. I'm setting TLS_RSA_WITH_AES_256_CBC_SHA256 as SSL cipher spec on the channel in the IBM MQ console.
On the connection factory I do this:
<code>cf.setSSLCipherSuite("TLS_RSA_WITH_AES_256_CBC_SHA256")
</code>
And I get:

Caused by: com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with compcode '2' ('MQCC_FAILED') reason '2400' ('MQRC_UNSUPPORTED_CIPHER_SUITE')`

I've walked through the steps here:
https://developer.ibm.com/answers/questions/472052/how-do-i-configure-ssl-tls-between-java-client-and/
I'm unsure if this error means the handshake is failing (due to cert/keystore misconfiguration) or something else.
Comment: `System.setProperty('javax.net.debug', 'ssl');` usually helps in understanding the cause of those errors.
Comment: If you are using a non-IBM jre you need this setting  `System.setProperty("com.ibm.mq.cfg.useIBMCipherMappings", "false");`
Comment: Possible duplicate of [Problem Connecting a Java Client (JMS) to a IBM MQ](https://stackoverflow.com/questions/52775733/problem-connecting-a-java-client-jms-to-a-ibm-mq)
Comment: I should have mentioned that I am setting that - but via application.properties file. I will try the programmatic version, just to be sure. Also, I will go over the other posting to see what I find.
Comment: What version of mq jar files are these?  The version is 4 digits.  Ex. 184.108.40.206 or 188.8.131.52.
Comment: Our version is 22.214.171.124
Comment: Can you double check the manifest.mf of `com.ibm.mq*.jar` matches what you expect?
Comment: FYI - getting back to this after being pulled onto other things - I did the programmatic setting above, and apparently what I was doing prior was not getting picked up, as I now get a new error: com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with compcode '2' ('MQCC_FAILED') reason '2397' ('MQRC_JSSE_ERROR') - so I will work through that.
Comment: Sean did you get this working?
Comment: Yeah, I hope to get back to this. Odd you asked today as I started up with this again this morning...looking at doing this: https://developer.ibm.com/answers/questions/472052/how-do-i-configure-ssl-tls-between-java-client-and/ and also using this to troubleshoot: https://www.ibm.com/support/pages/troubleshooting-javajms-ssl-configurations#2
Comment: Okay, I did get this working, now the rather strange question I have is how to make this optional, on the client side. I put a switch into the application to make TLS something that one can turn on/off, for development uses. I did this on the channel: alter channel(DEV.APP.SVRCONN) chltype(svrconn) sslcauth(optional) sslciph(TLS_RSA_WITH_AES_256_CBC_SHA256) so one would think it would be optional, however not setting the cipher suite on client side makes it fail with AMQ9641: Remote CipherSpec error for channel.
Comment: Add that to your question and I'll include in my answer.  That is `SSLCAUTH` which is short for SSL Client Auth.  This is whether the client must have a private key or not, it is optional.  If the client has one it must be trusted.   If `SSLPEER` is filled in this makes it act as if  it was `REQUIRED`.  You can not have a single `SVRCONN` that works with both TLS and without.  If you do not want TLS you must blank `SSLCIPH`.
Answer: I think you might need to use SSL_RSA_WITH_AES_256_CBC_SHA256 instead of TLS_RSA_WITH_AES_256_CBC_SHA256.
The Knowledge Center documents the differences between IBM and Oracle JREs.

Connecting to IBM MQ over TLS with JMS


ListBox Displaying Horizontal Images WPF

Question: I'm trying to create a control in wpf/xaml that will display a horizontal list of images. The width of the listbox to be fixed (no scrollbar). When a new item is added the existing items reduce the amount of the image diplayed to accomodate it (the actual image doesn't reduce just the amount of the image shown). The functionality would be similar to adding a new column to a grid with a relative width property ("*") and the column contains an image with a fixed width. Here's my code so far:
<Window.Resources>
    <ItemsPanelTemplate x:Key="ListBox_HorizontalItems">
        <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>

    <DataTemplate x:Key="ListBox_DataTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="50" />
            </Grid.ColumnDefinitions>
            <Image Width="150" Source="{Binding ImageSource}" />
        </Grid>
    </DataTemplate>

</Window.Resources>

<Grid>
    <ListBox Name="lbxImages" Style="{StaticResource ListBox_Style_Horizontal}" Width="250"  Height="100" />
</Grid>

Which is very close to what I need! However I can't work out how to reduce the amount of the image shown when a new item is added to the list. Currently a scrollbar appears when a new item is added. Incase I'm not explaining myself very well here are some screenshots showing the functionality I need:

Can anybody show me how to achieve this? Thanks for any help!
Answer: Use the following UniformGrid as ItemsPanel:
<ItemsPanelTemplate>
    <UniformGrid Columns="{Binding Path=Items.Count,RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"/>
</ItemsPanelTemplate>

Disable horizontal scrolling:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">

Modify ItemTemplate:
<DataTemplate>
    <Image Source="{Binding ImageSource}"
           Stretch="None"
           HorizontalAlignment="Center"/>
</DataTemplate>

Comment: Thanks for this, it works great! I've never used "UniformGrid" before, looks pretty useful...
Answer: I find that replacing the ItemsPanelTemplate is not enough to get rid of the scroll bar, because that ItemsPanelTemplate is embedded inside a ScrollViewer, somewhere inside the ListBox. You may also need to remove that ScrollViewer.
I replaced the entire ListBox's Template:

        </Setter.Value>
    </Setter>
</Style>

Also, there is no need to find out the number of columns in the UniformGrid. The system just uses the number of ListBoxItems.
IsItemsHost="True" does that for you, I think.


ASIHTTPRequest Download cache problem - unable to save/load date in cache

Question: I am trying to save data into cache using ASIHTTP (http://allseeing-i.com/ASIHTTPRequest/How-to-use#using_a_download_cache). I am not sure what I am doing wrong but it seems not to be storing data into cache. The output of the following code is this:
2010-08-12 15:44:13.801 TabBar[51728:207] Success is YES
2010-08-12 15:44:13.802 TabBar[51728:207] Success is NO
2010-08-12 15:44:13.804 TabBar[51728:207] Success is YES
2010-08-12 15:44:13.805 TabBar[51728:207] S-----------
2010-08-12 15:44:13.874 TabBar[51728:207] Success is YES
2010-08-12 15:44:13.874 TabBar[51728:207] Success is NO
2010-08-12 15:44:13.876 TabBar[51728:207] Success is YES

Here is the code:
[[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:
                              ASICacheForSessionDurationCacheStoragePolicy];
[[ASIDownloadCache sharedCache]
                    setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL
                                URLWithString:@"http://www.nytimes.com/"]];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request startSynchronous];

request = [ASIHTTPRequest requestWithURL:[NSURL
                                URLWithString:@"http://www.nytimes.com/"]];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request startSynchronous];
BOOL success = ([request responseStatusCode] == 200);
NSLog(@"Success is %@\n", (success ? @"YES" : @"NO"));

success = [request didUseCachedResponse];
NSLog(@"Success is %@\n", (success ? @"YES" : @"NO"));

success = ([[request responseData] length]);
NSLog(@"Success is %@\n", (success ? @"YES" : @"NO"));

NSLog(@"S-----------");
request = [ASIHTTPRequest requestWithURL:[NSURL
                    URLWithString:@"http://www.nytimes.com/"]];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request startSynchronous];
success = ([request responseStatusCode] == 200);
NSLog(@"Success is %@\n", (success ? @"YES" : @"NO"));

success = [request didUseCachedResponse];
NSLog(@"Success is %@\n", (success ? @"YES" : @"NO"));

success = ([[request responseData] length]);
NSLog(@"Success is %@\n", (success ? @"YES" : @"NO"));

Can someone give me some code snippet on how to accomplish this?
Thanks!
-----------------------------------------------------------------------
NEW CODE REVISION:
NSURL *url = [NSURL URLWithString:imageURL];

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
[request setSecondsToCache:60*60*24*30]; // Cache for 30 days

[request startSynchronous];//startAsynchronous];

BOOL success = [request didUseCachedResponse];
NSLog(@"------------>>>>>>> Success is %@\n", (success ? @"YES" : @"NO"));

NSData *responseData = [request responseData];
UIImage *image = [[UIImage alloc] initWithData:responseData];

This only works with [request startSynchronous]; if I try Asynchronous method, it dosent call this function:
- (void)requestFinished:(ASIHTTPRequest *)request

Comment: I meant to say data, not date in the title :P
Comment: It would be nice if you could format your code sensibly.
Answer: You are missing something like this,
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
[request setSecondsToCache:60*60*24*30]; // Cache for 30 days
[request setDelegate:self]; // A delegate must be specified
[request setDidFinishSelector:@selector(requestFinished:)]; // And an appropriate selector specified

And you should also have
- (void)requestFinished:(ASIHTTPRequest *)request {
  BOOL success = [request didUseCachedResponse];
  NSLog(@"------------>>>>>>> Success is %@\n", (success ? @"YES" : @"NO"));

  NSData *responseData = [request responseData];
  UIImage *image = [[UIImage alloc] initWithData:responseData];

  ...
}

This should do the trick.
Answer: nytimes.com sets a lot of "don't cache me" type headers:

    $ HEAD http://www.nytimes.com/
    200 OK
    Cache-Control: no-cache
    Date: Fri, 13 Aug 2010 07:14:46 GMT
    Pragma: no-cache
    Server: Sun-ONE-Web-Server/6.1
    Content-Length: 121266
    Content-Type: text/html
    Expires: Thu, 01 Dec 1994 16:00:00 GMT

So I would expect these are the problem.
You could try setting:
[[ASIDownloadCache sharedCache] shouldRespectCacheControlHeaders:NO];

Comment: yeah I tried, but still getting no caching... I used
  [[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
Comment: Apologies for that typo - what you have is correct (I've fixed my answer now). I suggest you try single stepping through storeResponseForRequest in ASIDownloadCache.m, and if that appears to be storing the response correctly then try stepping through cachedHeadersForRequest and then out to it's caller.
Comment: so I tried to put breakpoint in "" its going into this if condition all the time:

   if (policy == ASIIgnoreCachePolicy) {
  [[self accessLock] unlock];
  return;
   }
Comment: I was talking about "storeResponseForRequest" method
Comment: Well done! I am not sure why that is happening though; you should be getting the policy you're setting, ASIOnlyLoadIfNotCachedCachePolicy. I think you'll need to debug a bit further.
Comment: OK so I have got caching to work... but it only works with synchronous requests... how to make it work with [request startAsynchronous]? Will I have to run my own thread in background with Synchronous request? Will that cause any problem with caching?
Comment: The caching works fine for asynchronous requests. Have you changed your code over to looking for the result in the requestFinished: selector and setup the delegate? Can you post the full new code?
Comment: Hi Joseph,
I have pasted the new code above under my question. Please have a look :)
Comment: I think you need a call to [request setDelegate:self]; before the startAsynchronous
Comment: Oh yeah! I totally forgot about that... That solved the problem, its all working flawlessly now, at least one of my life's problem is now solved :)
Thanks for all the help! Have a wonderful day!
Comment: Glad to hear it - if you're happy with the solution you can mark this answer as accepted (click the tick to the top left of the answer) and upvote it by clicking on the up arrow. Thanks
Comment: i was having issues with the cache as well. I finally narrowed down the problem to this line of code in the main method of ASIHTTPRequest:

    if (![[self requestMethod] isEqualToString:@"GET"]) {
   [self setDownloadCache:nil];
  }


For Divisors, do we use order of the point or multiplicity of the point?

Question: This is from the Book Mathematical Cryptography by Silverman, Pipher etc.
From the book where they describe Rational Functions & their Divisors on Elliptic Curves

5.8.2 Rational functions and divisors on elliptic curves
We keep track of the zeros and poles of $f(X)$ and their multiplicities by defining the divisor of $f(X)$ to be the formal sum

$div(f(X)) = b_1[{\alpha}_1] + b_2[{\alpha}_2] + ... + b_r[{\alpha}_r] - d_1[{\beta}_1] - d_2[{\beta}_2] - ... - d_r[{\beta}_r]$ --- (A)

Here the book describes ${\alpha}_1$, ${\alpha}_2$ etc as the zeroes, $b_1$, $b_2$ etc as their multiplicities & similarly for the poles ${\beta}_1$ etc.
Few pages ahead in the book, where it describes a Weil Pairing with an example, we see this
$e_m(P, Q)$ is described as the Weil Pairing map for all $P, Q \in E(m)$ for $m$-torsion points on Elliptic Curve $E$.
So $e_2$ will be the map for the 2-torsion points.
Now the example

Example 5.40. We are going to compute $e_2$ directly from the definition. Let $E$ be given by the equation $Y^2 = X^3 + Ax + B = (X − {\alpha}_1)(X − {\alpha}_2)(X − {\alpha}_3)$.
Note that ${\alpha}_1 + {\alpha}_2 + {\alpha}_3 = 0$, since the left-hand side has no $X^2$ term. The points $P1 = ({\alpha}_1, 0), P2 = ({\alpha}_2, 0), P3 = ({\alpha}_3, 0)$, are points of order 2, and as noted earlier,

$div(X − {\alpha}_i) = 2[P_i] − 2[\mathcal O]$ --- (B)

In (A), the book says that in the term $b_r[{\alpha}_r]$, $b_r$ is the multiplicity of the Point ${\alpha}_r$.
However, in (B) while writing down the divisor, he uses the order $2$ of the point $P$ instead of it's multiplicity. How can this be explained?
UPDATE:
The question has been partly answered but there are areas of confusion for me.

As per this - https://crypto.stackexchange.com/a/55427/3941 they calculate that there are just 2 zeros & hence by Bazout's, hence the divisor is $2[P] - 2[\mathcal O]$. Whereas in the answer below, the same result is arrived at in a very different way - $(2[P_i]+[\mathcal{O}])-(3[\mathcal{O}])=2[P_i]-2[\mathcal{O}]$

Is $[0:1:0]$ a zero? $f$ evaluates to $\frac {0 -{a_i}0}{0}$ at $[0:1:0]$ - it's a divide by zero. So is it really a zero? It works only if we calculate zeros of numerator separately without including the denominator.
Answer: In (B), the term "order" is referring to the order of the point in the group law on the elliptic curve. It is not so simple as "point of order $n$" implies "that point appears in some divisor with multiplicity $n$" - there is actual math happening there.
To calculate the divisor of $f=X-a_i$, we first write the rational function $f$ on the affine open subset $D(Z)\cap E$ of $E$ as a ratio of homogeneous polynomials of the same degree, which will let us more easily determine the behavior of our function away from $D(Z)\cap E$. To do this, we homogenize with respect to $Z$ and then divide by $Z$ to the degree of the resulting polynomial. Here, homogenizing $f$ with respect to $Z$ gives $X-a_iZ$, and then we divide by $Z$ to obtain $f=\frac{X-a_iZ}{Z}$. Now we determine the divisor of $f$ by counting with multiplicity the intersections of $V(X-a_iZ)$ and $V(Z)$ with $E$ and taking their difference.
$V(X-a_iZ)$ meets $E$ at $[a_i:0:1]$ and $[0:1:0]$. From the construction of the group law on elliptic curves using lines, a point $P$ of order two has a vertical tangent which meets the curve with multiplicity two at $P$. Therefore $V(X-a_iZ)$ meets $E$ at $[a_i:0:1]$ with multiplicity two and therefore the divisor $V(X-a_iZ)\cap E$ is $2[P_i]+[\mathcal{O}]$. $V(Z)$ meets $E$ at $[0:1:0]$, so the divisor of $V(Z)\cap E$ is $3[\mathcal{O}]$. Subtracting the two gives $div(f) = 2[P_i]-2[\mathcal{O}]$.

Addressing the update:

Yes, there are two zeroes of $f$: $P_i$ twice. This is exactly what the above calculation shows. (I would push back a little on the phrasing that "the same result is arrived at in a very different way" - the linked answer from the cryptography site does not explain their method. In fact, by writing $X-a_i$ as $\frac{X-a_iZ}{Z}$, there is a suggestion that they might be doing it the same way I am.)

This is like asking "to what order does the function $\frac{x^n}{x^m}$ on $\Bbb R$ vanish at zero?" Well, $x^n$ vanishes to order $n$, and $x^m$ vanishes to order $m$, so the total order of vanishing is $x^{n-m}$. To be specific, the local ring of every point on the curve $E$ is a valuation ring, so we can ask what the valuation is of $f$ in the local ring at $\mathcal{O}$. Valuations add over multiplication, so it really does work exactly the same as the example. The calculation here is that first we dehomogenize the numerator and denominator with respect to $Y$, so $f$ can be written as $\frac{(X-a_iZ)/Y}{Z/Y}$. Now both the numerator and denominator are functions defined on the affine open neighborhood $D(Y)\cap E$ of $\mathcal{O}$, so we can compute their valuations, which are exactly equal to the intersection multiplicities of numerator and denominator with $E$ at $\mathcal{O}$. So the numerator has valuation $1$ and the denominator has valuation $3$, leading to a total valuation of $-2$. So $f$ has a pole of order $2$ at $\mathcal{O}$.
Comment: I don't understand the "subtract the Intersections with multiplicity of $Z$" - why are you doing this? And how do you calculate the Intersections with multiplicity of $Z$?
Comment: The divisor associated to a rational function is the divisor of zeroes minus the divisor of poles. For an elliptic curve embedded by a Weierstrass equation, there is only one point on the line $Z=0$, so the intersection multiplicity there must be 3 by Bezout.
Comment: I understand that number of zeros is number of poles - I am confused about how you got from $X-{a_i}Z$ to $\frac {X-{a_i}Z}{Z}$ & where the $+[\mathcal O]$ comes from? From your answer, I can understand where the $2[P_i]$ comes from - it's because $P$ is the tangential intersection - so the multiplicity of $P$ is 2. But where does the $+[\mathcal O]$ come from. Once I get that, then the number of poles will be obvious.
Comment: The function $X-a_i$ is written in affine coordinates on $D(Z)$, so to write it as a ratio of homogeneous polynomials of equal degrees, we need to homogenize and then divide by an appropriate power of $Z$. Homogenization looks like turning $a_i$ in to $a_iZ$, and then we divide by $Z$ since our numerator is of degree 1. The $+\mathcal{O}$ comes from the fact that the line $V(X-a_iZ)$ intersects our elliptic curve in projective space at $\mathcal{O}$: plugging $[0:1:0]$ in to $X-a_iZ$ gives zero. The multiplicity is one because this line is not the tangent line at $\mathcal{O}$.
Comment: Sorry, if I am being dumb here, but from what I have read, if we homogenize ${x^2}y - y +4$, it becomes ${x^2}y -y{z^2} + 4{z^3}$, it's not expressed as a ratio & we don't add a denominator. Why when homogenizing $X-{a_i}$, we don't stop at $X-{a_i}Z$, but also add a denominator (1) & homogenize that also?
Comment: Our goal isn't just to homogenize our function - we want to write our function as a ratio of homogeneous polynomials so that we can calculate the poles and zeroes by looking at the numerator and denominator. Our function $x-a_i$ is already an element of $k(E)$, the fraction field of our elliptic curve, but it's not immediately clear how it behaves off the affine patch where it's defined. Writing it as a restriction of a ratio of homogeneous polynomials makes it easier to understand it's behavior globally.
Comment: Thank you very much. Just one more thing, I am not sure if $[0:1:0]$ is a zero, because $f$ evaluates to $\frac {0 -{a_i}0}{0}$ at $[0:1:0]$ - it's divided by 0 & hence not a zero - so there is just this zero $[{a_i}:0:1]$ (of multiplicity 2) & by Bezout's there will 2 poles & hence the div = $2[P] - 2[\mathcal O]$ - this seems to gel with another answer I found also - https://crypto.stackexchange.com/a/55427/3941
Comment: The point $[0:1:0]$ is a zero of the *numerator* of order one and a zero of the *denominator* of order 3, which gives a total multiplicity of $-2$, corresponding to the coefficient of $-2$ on $\mathcal{O}$.
Comment: @user93353 I've made an edit addressing your updated questions.
Comment: Thank you very much


Why are some of my modules reporting missing inter-module dependencies after migration?

Question: I'm troubleshooting modules after a host migration--did I miss something? Before I changed my host I backed up MySQL database, made a list of all my used modules and burned a dvd of the Drupal root directory. Now, after I've successfully restored the database of 5/6 sites, three modules report missing inter-module dependencies within their module groups:

Event- Calendar Signup   - 6.x-2.x-dev - Depends on: Signup
(missing)
Rules- Rules Simpletest - 6.x-1.4 - Depends on: Simpletest
(missing)
Services -

servers - REST Server - 6.x-3.0-rc1    - Depends on:
Autoload (missing)
authentication - OAuth Authentication  6.x-3.0-rc1 - Depends on: Oauth_common (missing)

How can these other modules be missing if they were there before the migration? The folders are still the same. Do some modules "make" other modules in the database? Something like cTools 'makes' the css directory.
All of my sites are in the sites directory and share the same modules, though they each have their own database. Each is missing the same module dependencies.
Answer: Are those missing modules in your sites/all/modules folder? I'm not sure why they would have been left out of a file migration, but anything's possible.
Modules do not 'create' other modules (except possibly Features, I haven't used that in awhile) in the sense that you're referring to w/ the cTools example, though there are modules that exist as part of the parent module package.
Comment: These are child-parent modules.


Need to limit Commerce Shipping Condition to only fire if there are no items that do not match

Question: We need the condition to trigger only if the cart items match the categories listed and there are no products that do not match.
Is there a way to limit Commerce Shipping Method Conditions (Product->Order Contains Product Categories) to trigger only if the order products match the categories and there none that do not match?
Answer: Unfortunately, the way that condition was written, it only matches for, "Order contains any products from these categories." The logic you're looking for is, "Order contains only products from these categories." For that, you'd need to write a custom condition plugin. This would be a reasonable core feature request for Drupal Commerce and would apply for the other "contains" conditions as well ... which leads me to believe we might implement it as an "operator" select list on the condition itself.
Comment: Thank you Ryan. Yep, I already created the custom condition. It was quite easy, using the core 'order contains categories' condition and modifying.
Comment: @quantumized Oh, nice! Congrats on figuring that out. Does it seem like something you'd want to use to kick off a core feature request that we apply to each of those Order condition types?
Comment: yes, I think it would be a useful feature to have. What do I need to do to 'kick off a core feature request'? Just submit a require in the issue queue? Should I submit a patch with the code too?
Comment: @quantumized Yep! Just open the issue in https://www.drupal.org/project/issues/commerce and feel free to link back to this discussion. A patch as a starting point would be great!


Is there any way to improve composing?

Question: Beside playing drums I'm toying with software to create music. The problem is when I need to advance further. I may have some good, let's say "riffs" (or pieces, or melodies, or ideas), and I'm pretty harsh with everything I create (until I'm really proud out it, it's crap to me), but have no idea how to make it longer. I have lots of "samples", short melodies, but I just can't make them last longer.
Is there any way to make creating music little easier? Some music theory stuff? And how to connect pieces, how to extend existing one? That are things I'm really interested in.
I would be very grateful for any answer., I love both music and creating it, but the lack of ability to "continue" is getting me down.
And I know that there was thread for composing, but it was aimed for guitar, and I'm seeking more general tips.
Comment: See also http://music.stackexchange.com/questions/7165/general-methods-for-turning-a-riff-into-a-song - my question is posdibly a dup of this..
Comment: Brainstorming. Just sit there and jam in your head with what you already have, ideas will come eventually.
Comment: If you find that you're struggling to come up with transition material, that in itself can be a thing to work on. Take two segments that you think could be in the same song, and try to find many different ways to connect them. Identifying what it is that you have difficulty with is the first step towards improvement. You can give yourself exercises for very specific tasks *without* the pressure of creating entire pieces right away. Find short-term goals to work towards.
Answer: Listen to as much music as possible in as many styles as possible and force yourself to listen to music that you aren't familiar with or even don't like. You can't progress from a point of no reference. Like when you learn to speak, you learn vocabulary from practice and by emulating others. Then, after you've built up a broad vocabulary, you can start to talk like your own self. The same is true with composing (or playing for that matter).
Technically speaking, theory certainly won't hurt. If you learn proven and accepted ways of doing things "right", then you can be more confident when you break those theory "rules". But remember, it is all still theory. You need to let your own ear guide you through.
Also, don't spend all your time writing at the computer if you can help it. A computer is a great tool and can certainly ease a lot of pain when writing, but it is just a tool. The music still comes from you. Use a pencil and paper and you'll see the difference. They both have their places.
Finally, for some practice, try to write every single day, even when it feels difficult. If you can only write a couple of bars in a day, then that's still better than nothing. If you need some structure around that, try just writing melodies and don't pay attention to key or even a time signature. Just work on melody. If you do that and practice it, you'll start to learn to incorporate that into your compositions in a practical way. Melody is king.
Answer: I write rock music, but I also write classical music. One set of techniques that classical composers use to create better melodies also allows you to start with a simple idea and create something much larger. I use these techniques to write rock music. This set of techniques is called motif development.
This is a long list, but you can chose just a couple to begin with. Once you've mastered those, you can learn a few more and so on.
An example of motif development would be Beethoven's fifth. The famous, da, da, da, dum at the beginning is called a motif. It's like the classical music version of a riff. Beethoven only had four notes in that motif, yet according to the third link at the bottom, he wrote 506 measures by developing that four note motif. So if you want "study with a master of motif development", check out Beethoven's music.
You didn't say if you read music. If not, don't worry. You can still use them.
The jargon may make this sound complicated, but it is just a list of ways to modify a motif, by rearranging the notes in various ways kind of like a puzzle. After you get familiar with a few of these, you probably come up with a few of your own.
Motif Development
First you write a motif. It's just a short group of notes you think sound good.
Then you will repeat that motif after it has been changed by one or more of these techniques. Then you change it another way and repeat it again. You can write a lot of music this way. Beethoven was a master of this.

The first technique is just plain old repetition. You just repeat the motif.
The next one is called sequence. You repeat it but you have shifted it higher or lower in pitch. This is how Beethoven wrote that opening theme to that movement. He moved those four notes up and down to create most of that music.
Interval change An interval is the distance between two notes. C to D is an interval of a whole step. When you change it to go from C to Db, you have contracted the interval to a half step. If you go from C to Eb, you have expanded the interval to a minor third.
-Interval change is where you repeat the motif but change the distance between notes in one or more places in the motif. If Beethoven had followed da da da dum with da da da doo, it would be interval change.
The next one is called rhythm change. When you repeat it, you change the rhythm.
The next one is called fragmentation. It is where you repeat just a part of the motif. You could follow that with a different piece of the motif. If your motif is long enough, you can create a melody using just this technique alone.
Next is extension. This is where you add some new material (a new set of notes) before the last note of the motif when you repeat it.
Compression is where you remove notes from the middle of the sequence.
Expansion is where you add some new material (a new set of notes) after the last note of the motif when you repeat it.
Inversion is where you flip your motif upside down. Where the motif goes up in pitch, the inversion goes down in pitch and vice versa. This is good for a call in response. The "response" (the inversion) is similar enough to the original motif to sound like a response to the "call" of the motif.
Introversion is where you break the motif into fragments that make musical sense unto themselves and you change the order of the fragments to create the introverted motif.
Diminution is where you shorten all of the note values. Half notes become quarter notes. Quarter notes become eights and so on. The modified motif is twice as fast.
Augmentation is where you lengthen all of the note values. Half notes become whole notes. Quarter notes become half notes and so on. The modified motif is twice as slow.
Ornamentation is harder to explain. You keep the same basic motif, but add fancy devices called ornaments to it. It could be as simple as adding extra notes between the notes of the motif to fancier things like trills and turns. For your purposes, just think of it as dressing up the motif to make it fancier.
The final technique I have for your is thinning. This is where you eliminate notes. Beethoven does this in the first theme where he reduces da, da, da, dum to single notes at the end of the theme. You can eliminate any number of notes.

You can combine these. You can do two or more of these when you repeat your motif the first time. For example, you could repeat a fragment at a higher pitch with a slightly different rhythm.
When you have found the right combination, it will sound right. It works. It will sound organic, like it belongs with the motif.
For me it's inspiring when this happens. My process is to flounder around trying things out, but nothing inspires me. Then a day or two later something gels and then I am glad I learned these techniques.
If you learn these techniques, you will start hear them in all kinds music. A lot of songwriters do these things intuitively.
I wish you luck with your songwriting.
Further study/Sources
If you want to know more about motif development, check out these links:
These two links are the ones I use to remind me what the techniques are and are my source for this list:
http://jkornfeld.net/motive_development_1.pdf
http://jkornfeld.net/motive_development_2.pdf
Here is one I found that uses Beethoven's fifth as the example:
http://tobyrush.com/theorypages/pdf/0210motivicdevelopment.pdf
Answer: In addition to tptcat's nice answer:
Besides just listening to music you could try and copy music for yourself -- record it or write it down. This will force you to observe all the details of the music you are listening to. And when you've copied a song (as best you can), think about what riffs, pieces, melodies, or ideas there are (that you could have made) and how the songmaker extended these or connected them together. This might give you ideas to build on and develop for your own material.
Comment: @Dreat: You could try to search for sources like [this](http://pianofeeling.blogspot.se/2012/06/16-making-melody-right-hand-pattern.html). Perhaps that one's not your cup of tea, but with some clever searching you might find other idea spurring sites or sources.
Comment: Just to add a little detail: "Copying music" is technically coined "transcription". Transcription is a great tool for a musician and should certainly be valued highly.
Answer: Harmony is king, learn to write music 'improvising', 'rehearsing' on a real instrument.
contrary to @tptcat I don't write music on paper. And I don't think it can be easy for a drummer that don't play a multi-tonal instrument (strings or keys).
Harmony is the fact of putting several notes together. For example, managing a bass line and one line of melody, is already harmony. The bread and butter of many western tunes.
My favourites instruments for composition are the guitar and the piano or synth.
Though it takes years to master them, it happens quickly that one can play simple pieces on them very fast. Playing a bass line and a melody line for example ( 2 notes progression).
But best is to try 3 notes progression, so as to instinctively learn and feel in the guts the movements between the modes, basically the circle of the fifth, that gives (given an start point, let's say a C Major) the 5 other possible chords you could play next step almost blindly and that will always sound good (Am, GM, Em, FM, Dm)... though sometimes not enough exotic or surprising ;-)
Then you could interest yourself in all the modes, Major, Minor of course, but also Ionian, Dorian, etc...  that could show you paths for making melodies.
I think that before imagining music in your head (that's what writing with pencil and paper means, and means years of training for me), you have to feel music in your fingers, just like you play drums.
On the other side: @tptcat's argument to listen to any sorts of music to improve the hear... yeah, that's a really good advice. +1.
Answer: Try to sing one of your favourite songs out of key.  Then sing it in key. Ask yourself  - what makes it work.
Change a few bars of your favorite song and see what you get. Dont worry if you destroy it in the process. Just add on a few bars of your own and keep going.
Try to learn how to improvise?
Ask yourself what  works for you  (not me)?  Try this exercise even if you do not feel like doing it (everyday).
Comment: Nice tip about singing out of key. Another might be to re-write it in a different mode. Could get some interesting results!
Answer: I believe compositions are generated out of the experiences of one's life. Live you life to the fullest, rest will come chasing you. Let your feeling guide you for a while you will see the difference.
Importantly always appreciate your composition if it comes out of your life experiences and the feeling that came within you going through that.
Finally, Keep Practising!
Comment: Yes, but how do you translate that into music? It's not as simple as "I'm happy, I'll write in a major key!"
Comment: as Paul McCartney said "Remember to let it into your heart, then you can start to make it better..."
Answer: Another potentially helpful way to compose:
Take a look at different forms that are used in classical music, and use those as a guide for your own music. For example, take ternary form: https://en.wikipedia.org/wiki/Ternary_form where the pattern is A-B-A.
Create an interesting melody A, then maybe perform a key change to a new melody B, then come back to A with some extra stuff added. Put those melodies together one after another, and you have a piece of music with some interesting development. Or you could try binary form, 32-bar form, etc etc.
More information on different types of forms here: https://en.wikipedia.org/wiki/Musical_form
Note: Take the above with a grain of salt. I'm just beginning to compose myself.
Answer: Well, I'm guessing you are referring to songs with a melodic line, and not drum solos. Therefore, it would be much easier for you, I think, to write down what you are working on if you have a pitched instrument on hand. (I play drums but haven't ever written a song on them. Guitar, piano, and French horn have lead me to some interesting ideas though.) Software such as MuseScore, Finale, and Sibelius are a definite help when writing songs (at least for me) for many reasons. Sorry if this isn't helpful...
And don't worry if you get songwriter's block; I'm actually just coming out of a bout of that and it's pretty exciting, actually. Just don't give up!
Answer: Well one way to make a longer tune would be to "string together" some of those short melodies you have. Some theory would help a lot in that regard, because you might need to do some transposition and/or modulation, if you want the whole thing in the same key or you want to do some key changes.
If you want to be able to conjure some music out of thin air, one way to simplify the process is to establish a bunch of parameters, within which you can play around until you come up with something. Settle on a key, decide if you want minor or major, maybe pick a mode, decide on a time signature... you're a drummer so now take advantage of that fact; make up some simple pattern in the time signature you chose, then write down the notes. You can use that as the base for the melody, just using the timing of those notes, and the silences; then assign a real note to each drum hit. You may like what you hear or not, but now you have a starting point, you can fiddle with that melodic pattern until you like it or start again from scratch...
Answer: Late to the party but I'd like to offer this heartfelt advice anyway:
LEARN A LITTLE PIANO
No matter what else you do as a drummer, producer, musician -- do learn a little piano.
AT a minimum, get a cheap keyboard, take a few lessons, get at least to the point where you can play a few chords with the left and a simple melody with the right. It won't take long, but it will make a huge difference for you, from that moment onward, not only with composing, but in many other ways.

Is there any way to improve composing?


NAudio: Convert IEEE Float input stream to MP3 output stream in WCF

Question: I have WAV data in IEEE float at 16000Hz, 32-bit, 1-channel format in a byte array (from database). I would like to convert that to mp3 on the fly and stream it out via the response object from a WCF service.
Working with NAudio package, so far what I have working is using MediaFoundationEncoder.EncodetoMp3() to write to a file.  But once that file is written out to the response, though, it's useless.  I would like to just skip the file writing step and output to a stream or byte array and write that to the response object.
Is there a way to get MediaFoundationEncoder to output an mp3 in some kind of memory object (without a file)?
Alternatively, trying to use the LameMP3FileWriter, which does write to streams,
I can send the IEEE float wav input directly to LameMP3FileWriter but the resulting mp3 stream sounds like a loud hiss seemingly regardless of the output format I use (44100,16,1), (22050,16,1), (11025,16,1),...
When I try to convert the IEEE float source to a PCM or upsample it using WaveFormatConversion, it errors out with

AcmNotPossible calling acmStreamOpen

if I use Wave32to16Stream on the IEEE float source, it does not error but there is no audio.  This chain is not working for me:
<code>    byte[] bytes = (Byte[])dt.Rows[0]["AudioContent"];//this is the dataTable from the database query containing the WAV audio

    var ms = new MemoryStream(bytes);
    var OLDfmt = WaveFormat.CreateIeeeFloatWaveFormat(16000,1);
    var NEWfmt = new WaveFormat(16000, 16, 1);//tried many
    var readr = new RawSourceWaveStream(ms,OLDfmt);

    //the following line errors on 'AcmNotPossible calling acmStreamOpen'
    //var wav16 = new WaveFormatConversionStream(NEWfmt, readr);

    //the following does not error but no mp3 streams out at the end
    var wav16 = new Wave32To16Stream(readr);

    var outptMP3 = new MemoryStream();
    var writr = new LameMP3FileWriter(outptMP3, NEWfmt, LAMEPreset.STANDARD);
    wav16.CopyTo(writr);
    HttpContext.Current.Response.BufferOutput = true;
    HttpContext.Current.Response.AddHeader("Content-Type", "audio/mpeg");
    HttpContext.Current.Response.BinaryWrite(outptMP3.ToArray());
</code>
The raw audio plays fine in Chrome (as a WAV stream) if I just do a BinaryWrite of the ms MemoryStream, so I think the IEEE float source data is valid.
Correct me if wrong, but that error (AcmNotPossible) appears to mean there is no ACM codec on my machine for the IEEE float format?  I query my machine and there appear to be no 32-bit ACM codecs, which is why I'm trying the Wave32To16Stream conversion.
Is there an interim step of the Lame MP3 pipeline to go from IEEE float 32-bit to mp3?
Answer: Sorry there were so many sub-questions to my main question about transcoding a IEEE float 32-bit wave to an mp3 stream, but I can at least tell you how I got it to work using ACM codecs (I think) on my simple WCF service:

change the return type on the service to a Stream
set the MemoryStream position to 0 before returning

Otherwise the chain above actually does work for me.  I will give the complete code, with all the extraneous SQL stuff, for the sake of completeness and because I found the answer in an unrelated SO issue:
<code>public Stream playWAVEFileFromDB() {
        //if using the file output method, I change the return type to string and return text instead of streams
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "SELECT theWAVEColumn FROM myTable WHERE allThoseAudiosAreStored";
            SqlDataAdapter sda = new SqlDataAdapter();
            DataTable dt = new DataTable();

            conn.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);

            //read the raw audio from database into a byte array
            byte[] bytes = (Byte[])dt.Rows[0]["colName"];
            var ms = new MemoryStream(bytes);
            var NEWfmt = new WaveFormat(16000, 16, 1);
            var OLDfmt = WaveFormat.CreateIeeeFloatWaveFormat(16000,1);//how its stored
            var readr = new RawSourceWaveStream(ms,OLDfmt);
            var wav16 = new Wave32To16Stream(readr);
            var outptMP3 = new MemoryStream();
            var writr = new LameMP3FileWriter(outptMP3, NEWfmt, LAMEPreset.STANDARD);
            wav16.CopyTo(writr);
            outptMP3.Position = 0;

            HttpContext.Current.Response.BufferOutput = true;
            HttpContext.Current.Response.AddHeader("Content-Type", "audio/mpeg");

            conn.Close();
            conn.Dispose();
            sda.Dispose();

            return outptMP3;
        }
            catch (Exception e)
        {
            //do the error logging stuff
            return Stream.Null;
        }
    }
</code>


How to schedule script through CRONJOB in LINUX

Question: I have created a script which will parse my already existing file. I want to apply cronjob in it in which I want to give timings that after every minute my script should execute automatically.How can I do it in linux script?
Answer: Add the following to your crontab:
* * * * * /path/to/your/script

Use the command crontab -e to edit your crontab.
Comment: My answer was for your personal crontab, which you update using `crontab -e`, not the system-wide `/etc/crontab` file.
Comment: Thanks for your reply.I have added it in crontab.
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
* * * * *  /op/wrd/send_mail.sh             #my script path
Comment: is this corrct way?How do i execute my script now?
Answer: You could follow Barmar's answer and have a script running every minute thru a crontab(5) entry.
However, since you want to trigger some action when a file has changed, on Linux specifically, you could also use inotify(7) facilities, and have something run when a particular file has been modified. Then use incron


emacs can't find its things in its own load path

Question: the following is output from a terminal session demonstrating that I, hopefully actually set this up right.
~ $cat .emacs
(require 'package)
(custom-set-variables
 ;;lots of comments generated by computer
 '(package-archives (quote(("gnu" . "http://elpa.gnu.org/packages")
                           ("marmalade" . "http://marmalade-repo.org/packages")
                           ("melpa" . "http://melpa.milkbox.net/packages/")
                           ("org" . "http://orgmode.org/elpa")))))

(custom-set-faces
 ;;again lots of comments added by the computer
)

(add-to-list 'load-path "/usr/share/emacs/24.3/site-lisp/mu4e")
~ $ ls /usr/share/emacs/24.3/site-lisp/mu43
#there are a lot of files here, but I am only going to show 2 right now
mu4e.elc
mu4e.el

... and yet emacs M-x mu4e returns [no match]. I have checked to load-path variable, and it is there. What am I doing wrong?
Comment: In your `ls` command you have `mu43` as the directory name rather than `mu4e`. I'm guessing it's just a mistype in your question but pointing  it out just in case.
Answer: You need to add one more thing so that mu4e is loaded. There are two different ways to do this.
First, you could add (require 'mu4e) after you've added the path to your load-path. This will immediately load mu4e.
Alternatively, you could add the following:
(autoload 'mu4e "mu4e" "Launch mu4e and show the main window" t)
This will tell Emacs to load it lazily (i.e. not until you actually use it). Autoloading is documented here. (This is essentially done for you for packages installed via package.el - it's the same mechanism, you just don't need to specify it yourself).
The benefit of autoloads is that Emacs's initial startup is faster, since rather than loading every package right away it waits until you use them.


How to insert 1000 blank rows in sql server

Question: I have an empty table named tbl_emp. In this table I have more than 7 columns.
Columns are formatted like this:
Id, name, section branch, company, grade and so on.

Now I want to insert 1000 records, which only shows
1,
2
3,
.,
.
.
1000

in id section as autoid.
But the other columns are blank.
Please help to insert such data.
Answer: If Id is not an IDENTITY column then do this
INSERT INTO tbl_emp (Id, [name], sectionBranch /*etc etc*/)

SELECT TOP 1000
    Id = ROW_NUMBER()OVER(ORDER BY (SELECT NULL))
    ,NULL
    ,NULL
    /*, etc etc*/
FROM
    master.dbo.spt_values

If Id is an IDENTITY column then try this
SET IDENTITY_INSERT tbl_emp ON;

    INSERT INTO tbl_emp (Id, [name], sectionBranch /*etc etc*/)

    SELECT TOP 1000
        Id = ROW_NUMBER()OVER(ORDER BY (SELECT NULL))
        ,NULL
        ,NULL
        /*, etc etc*/
    FROM
        master.dbo.spt_values

SET IDENTITY_INSERT tbl_emp OFF;

Answer: Try something like this (If you keep Id as Auto Increment, you don't need to use @i in insert statement) :
declare @i int
set @i = 1

while (@i <=1000)
begin
     insert into tbl_emp values (@i, .....,.....)
     set @i = @i + 1
end

Comment: A loop is an inefficient choice. The bad habit of not specifying a column list for the insert statement is also highly discouraged.
Answer: Cool_Br33ze solution looks cool performance-wise, but here is mine:
CREATE TABLE Test(Id INT IDENTITY, Val VARCHAR(100))

INSERT INTO Test VALUES (NULL)
GO 100

Answer: Try this:
with cte as(
  select 1 as n, '' c1, '' c2, '' c3, '' c4, '' c5, '' c6, '' c7
  union all
  select n+1,c1,c2,c3,c4,c5,c6,c7 from cte where n < 1000
)

select *
into my_table
from cte option (maxrecursion 1000)


Compare sort results by custom score

Question: I have one numeric score S1 to (ascending) sort a dataset. Now I have developed another method that returns a numeric score S2 that should sort the dataset in similar way. My question: with what methods can I evaluate the sorted results to compare performance of S2 to the "ground truth" S1?
If S1 returns ABCDEFG and S2 returns ADEFGBC , how can I compare the result of this permutation to the ground truth?
Answer: I would suggest metrics from information retrieval which are comparing ordered list of search results to assess the quality of a search engine. Try looking at MRR (Mean reciprocal rank) or Spearman rank correlation (but if not mistaken, the later needs a score associated to each ordered item).
Comment: Thanks, I'll into it. I also had the idea to simply count the number of required swaps to get the original list back. but Spearman rank makes sense, too. I would use the original sorted score vector and correlate it to the new score vector.

Compare sort results by custom score


How to add facebook iframe code directly to block?

Question: I am trying to display a facebook plugin as a block. I created a new block from the block admin page, and in the "Text" for the block entered the following iframe code and tried a couple of things (none worked) - all show the raw iframe code in the block.

Tried 'Input Format' as FULL HTML (doesnt work)
Tried 'Input Format' as "PHP" (doesnt work, even tried adding  tag.)

Following is the iframe code I am trying:

Comment: while hideous, using the PHP input format and  *should* work fine...just be sure to wrap it all in single quotes.
Comment: Thanks @Jimajamma - I tried this, didn't work. THanks for the help though.
Answer: Just use "Full HTML" input format and paste the iframe snippet in the source view of the block (e.g click "Source" on rich-text editor toolbar first )
Answer: please make sure that you use full html (no filtering) and make sure you direct html and not using that through TinyMCE or any wysing Editor


Nest.JS/Multer: UploadedFile undefined

Question: I've got some strange problem here: I've setup file upload just like in the nest.js tutorials. On my machine (Windows 10) everything works fine but when I deploy the project on my dev server everything builds just fine, but when I try to upload a file the uploadedFile parameter is undefined.
I've checked the request and found out that in the rawHeaders section my submitted data is missing. On my machine the api's request object contains this under rawHeaders:
<code>    'User-Agent',
    'PostmanRuntime/7.29.0',
    ...
    'Content-Type',
    'multipart/form-data; boundary=--------------------------584912758523510642468219',
    'Content-Length',
    '312047'
</code>
On my dev server, that same request suddenly only contains this data:
<code>    'User-Agent',
    'PostmanRuntime/7.29.0',
    ...
    'Content-Length',
    '0'
</code>
I guess that is the reason why my file variable is undefined, but why? Any idea how this could ever happen? I'm a bit lost here... I've already deleted my node_modules and rebuilt it, but no success. Versions of npm and node are equal on both systems.
My code is currently just this:
<code>@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@Req() req : Request, @UploadedFile() file: Express.Multer.File) {
  console.log(req);
  console.log(file);
}
</code>
Greets,
Bruno
Answer: I've spent whole day today to find the solution for this bug.
And I found that another small library can close this issue for us.
Enjoy!
nestjs-form-data
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Maybe you use some global pipes ( app.useGlobalPipes(new ValidationPipe()); ) wich used across the whole application, for every controller and every route handler.
Check and  try to comment it app.useGlobalPipes(new ValidationPipe());

Nest.JS/Multer: UploadedFile undefined


How to send numberInput as a parameter? Or how I can receive numberInput box inside a loop data from controller?

Question: I'm trying to build up a Point of sale. But I can't receive the quantity from a numberInput box. All other's is okay. Plz help me in this regard.I have tried by using Html.BeginForm(). But in case of quantity it's showing null.
I'have tried with html.BegingForm. But as the NumberInputBox is inside a loop the controller action method getting null values.
Here is my View code from where I'm trying to send the number,
@using (Html.BeginForm())
{

                @Html.DisplayNameFor(model => model.ProductCode)

                @Html.DisplayNameFor(model => model.ProductName)

                @Html.DisplayNameFor(model => model.SellingPrice)

            Qty

        @foreach (var item in Model)

        {

                        @Html.DisplayFor(modelItem => item.ProductCode)

                        @Html.DisplayFor(modelItem => item.ProductName)

                        @Html.DisplayFor(modelItem => item.SellingPrice)

                        **<input type="number" class="numberInput" name="SaleQuantity" id="SaleQuantity" min="1">**

                        +

        }

}

And below is my controller code, in where I'm trying to get it
public ActionResult GetProductInReceipt(int id, int **SaleQuantity**)
{

    ProductSale productSale = db.ProductSales.FirstOrDefault(a => a.ProductId == id);
    Product product = db.Products.FirstOrDefault(a => a.ProductId == id);

    List<ProductSale> ProductSales = (List<ProductSale>)Session["ProductSale"];
    if (ProductSales == null)
    {
        ProductSales = new List<ProductSale>();
    }

    ProductSales.Add
    (
        new ProductSale()
        {
            ProductId = product.ProductId,
            SaleId = (db.Sales.Max(a => a.SaleId))+1,
            SalePrice = product.SellingPrice,
            SaleQuantity = **SaleQuantity**,
            TotalPrice = SaleQuantity * product.SellingPrice,
            Product = db.Products.FirstOrDefault(a => a.ProductId == product.ProductId)
        }
    );
    Session["ProductSale"] = ProductSales;}

But in sale quantity is getting null.
Comment: If you are using @using(Html.BeginForm()) then it should contain a Submit button to submit the data. And also pass the ViewModel Name in parameter.
Comment: I think you can use ajax for this. If you want, I can post a sample.
Comment: Unfortunately, no ajax call is working on my project. I'm trying to fix it. Once I'm done with fixing I'll use ajax. Please,  post your sample. Thank you
Answer: If you don't want to use ajax you can simply send both of the parameters together. Please try this one.
In your view

       @{ var i = 0;}

                            @foreach (var item in Model)
                            {

                                        @Html.DisplayFor(modelItem => item.ProductCode)

                                        @Html.DisplayFor(modelItem => item.ProductName)

                                        @Html.DisplayFor(modelItem => item.SellingPrice)

                                        <input type="number" value="1" class="numberInput" name="SaleQuantity@(i)" id="SaleQuantity@(i)" min="1">

                                        <input type="button" value="+" onclick="firstname.lastname@example.com("GetProductInReceipt", "Sale")?qty=' + document.getElementById('SaleQuantity@(i)').value + '&email@example.com'" />

                                i++;
                            }

And in your Controller:
public ActionResult GetProductInReceipt(string qty,int productId)
{
    // Handle as per your software
}


Preciso criar uma extensão para Google Chrome que execute um .exe ou Algo similar

Question: Preciso fazer com que meu Website execute um sistema local (seu .exe), passando alguns atributos pelo executavel, quero fazer uma extensão para Google Chrome que eu possa passar os parâmetros pra ela executar o programa. Como faço isso? Caso não seja possível, tem como fazer algo similar?
Comment: Isso tipicamente é feito server-side: a sua extensão faria uma requisição para um servidor, instruindo ele a fazer a emissão
Comment: Isso esta me cheirando vírus no micro dos usuários hein, extensão do Chrome que execute um .exe rs
Comment: Preciso passar as informações da venda para realizar a emissão do SAT CF-e pelo sistema desktop.
Comment: Você ja começou a desenvolver alguma coisa? Já tem algum código pronto? a dúvida em si é de programação ou uma estratégia de como fazê-lo?
Comment: Tenho um emissor desktop, ele recebe parâmetros pelo seu arquivo exe no momento da execução para abrir e realizar a emissão, mas como estou desenvolvendo uma aplicação web, preciso de passar essas informações do navegador para o emissor e executa-lo para ele realizar a emissão
Answer: Isto não é possivel, não existe maneira de contornar pois é intencional que não seja possivel (por razões de segurança) que seja possivel disparar um executável
O que você pode fazer é tentar recriar o seu .exe como uma WebExtension ou como um ChromeApp, no caso do ChromeApp você pode chama-lo pela primeira extensão usando https://developer.chrome.com/extensions/runtime#method-connectNative
Era possivel anteriormente usar NPAPI para carregar dlls, mas o NPAPI foi removido.
Todavia note que é possível usar NPAPI para carregar DLLs por exemplo:
O manifest.json deve estar assim:
<code>{
  "name": "My extension",
  ...
  "plugins": [
    { "path": "extension_plugin.dll" }
  ],
  ...
}
</code>
O uso deve ser algo como:
<code><embed type="application/x-my-extension" id="pluginId">
<script>
  var plugin = document.getElementById("pluginId");
  var result = plugin.myPluginMethod();  // call a method in your plugin
  console.log("my plugin returned: " + result);
</script>
</code>
Comment: NPAPI foi removido de forma permanente do Chrome em setembro de 2015 https://support.google.com/chrome/answer/6213033?hl=pt-BR
Comment: @rodorgas bem lembrado, editado
Answer: Uma ideia é disponibilizar um instalador adicional (um serviço do windows por exemplo) que abra uma porta de comunicação http, e você se comunicar diretamente com ele via localhost.


Blacklist and whitelist of domains on Debian Linux router

Question: I have to create blacklist and whitelist in small office for two groups of employees.
I divided the users into two group:
First group has block all webpages except about 80 domains which i want to add to whitelist. They have ip address 10.10.10.100-150
Second group has access to all webpages except few domains added to blacklist. They have ip 10.10.10.2-100.
My first thought about solutions was iptables. Two script (whitelist and balcklist) included to the main firewall.conf script but some domains can use more than one ip and some rules probably will fail in this way.
Can you give me a better solution to resolve this problem?
Answer: Squid used as a proxy is your friend.


Como implementar um reduce para transformar um array em um objeto

Question: // 30) Escreva um algoritmo que percorre um vetor de inteiros e defina o maior e menor valor dentro do vetor.
const maiorEMenorValor = (vetor) => {
  return vetor.reduce((prev, current) => {
    if(prev.maiorValor < current) {
      return prev.maiorValor = current
    }else if(prev.menorValor > current) {
      return prev.menorValor = current
    }
  },{menorValor: 0, maiorValor: 0})
}
const vetor2 = [20, 16, 3, 12, 5, 34, 6, 13, 71, 178, 24332, 1, 88]
console.log(maiorEMenorValor(vetor2))

Answer: No fim das contas basta retornar o objeto a cada iteração do reduce no array...
const maiorEMenorValor = (vetor) => {
  return vetor.reduce((acc, el) => {
    let novoMaiorValor
    let novoMenorValor
    if(acc.maiorValor < el) {

      novoMaiorValor = el
      novoMenorValor = acc.menorValor

    }else if(acc.menorValor > el) {

      novoMaiorValor = acc.maiorValor
      novoMenorValor = el

    }
    return {
      maiorValor: novoMaiorValor ? novoMaiorValor : acc.maiorValor,
      menorValor: novoMenorValor ? novoMenorValor : acc.menorValor
    }
  },{ maiorValor: 0, menorValor: vetor[0]})
}
const vetor2 = [20, 16, 3, 12, 5, 34, 6, 13, 71, 178, 242, 1, 88]

console.log(maiorEMenorValor(vetor2))

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).