text:
Q: Overriding trait method with default parameter Assume the following example - when executed returns - "fatherfather"
trait Action {
    def doSomething(s:String = "father") = s
}

class RevokeAction extends Action{
    override def doSomething(s:String) = {
        s + s
    }
}

object HelloWorld {
  def main(args: Array[String]): Unit = {
    val revokeAction = new RevokeAction()
    revokeAction.doSomething()
  }
}

Looking at what the compiler does - gives a better explanation of what is going on
package <empty> {
  abstract trait Action extends Object {
    def doSomething(s: String): String = s;
    <synthetic> def doSomething$default$1(): String = "father";
    def /*Action*/$init$(): Unit = {
      ()
    }
  };
  class RevokeAction extends Object with Action {
    <synthetic> def doSomething$default$1(): String = RevokeAction.super.doSomething$default$1();
    override def doSomething(s: String): String = s.+(s);
    def <init>(): RevokeAction = {
      RevokeAction.super.<init>();
      RevokeAction.super./*Action*/$init$();
      ()
    }
  };
  object HelloWorld extends Object {
    def main(args: Array[String]): Unit = {
      val revokeAction: RevokeAction = new RevokeAction();
      {
        revokeAction.doSomething(revokeAction.doSomething$default$1());
        ()
      }
    };
    def <init>(): HelloWorld.type = {
      HelloWorld.super.<init>();
      ()
    }
  }
}

Can please elaborate why this is the expected behavior?

A: Because that is how the Scala specification says it should work. Section 5.1.4 (Overriding):

An overriding method inherits all default arguments from the
  definition in the superclass. By specifying default arguments in the
  overriding method it is possible to add new defaults (if the
  corresponding parameter in the superclass does not have a default) or
  to override the defaults of the superclass (otherwise).

Internally, Scala implementation which directs the JVM has to store the default parameter as a member of the declaring class, since the JVM doesn't directly support default arguments on methods.

A: In Scala, the default parameter, will create a default field to keep this value, and when you call the method without parameter, the compiler will auto set the default parameter as this method's parameter. like:
revokeAction.doSomething(revokeAction.doSomething$default$1());

As your decompile code, The default parameter is setted by in class Action:
<synthetic> def doSomething$default$1(): String = "father";

and when you call doSomething method without parameter s, it's calling:
revokeAction.doSomething(revokeAction.doSomething$default$1());

with the default parameter: revokeAction.doSomething$default$1(), since RevokeAction  not override def doSomething$default$1(), so default parameter is still father:
<synthetic> def doSomething$default$1(): String = RevokeAction.super.doSomething$default$1();


text:
Q: Linq with subquery with Let What I'm trying to get from this Linq query is a list of all Adverts where the most recent associated Log with a LogType.IsStatus == true has a LogType.Name of either Confirmed or Renewed. To be clear, an Advert has many Logs and each Log has one LogType. So far I have the following, but it's giving me an error System.NotSupportedException on the LastOrDefault.
var adverts = (from a in database.Adverts
                      let lastLog = (from l in a.Logs
                                     where l.LogType.IsStatus == true
                                     orderby l.Created_at
                                     select l).LastOrDefault()
                      where (lastLog != null)
                            &&
                            (lastLog.LogType.Name == "Confirmed" || lastLog.LogType.Name == "Renewed")
                            orderby a.Created_at descending
                      select a).ToList();

A: LastOrDefault() is not supported in LINQ to Entities (see here).
You can work around this by changing the order by clause in your let subquery to an order by descending and then use FirstOrDefault() instead.
var adverts = (from a in database.Adverts
               let lastLog = (from l in a.Logs
                              where l.LogType.IsStatus == true
                              orderby l.Created_at descending
                              select l).FirstOrDefault()
               where (lastLog != null)
                     &&
                     (lastLog.LogType.Name == "Confirmed" || lastLog.LogType.Name == "Renewed")
                      orderby a.Created_at descending
               select a).ToList();

A: try this
var lookingType = new string[]{"Confirmed", "Renewed"};

var result = database.Adverts
  .Where(entry
    => entry.Logs.Count() > 0 && entry.Logs.Any(log => log.LogType.IsStatus))
  .Select(entry
    => new { data = entry,
       lastLog = entry.Logs.OrderByDescending(log => log.Created_at).First()
    })
  .Where(entry => lookingType.Contains(entry.lastLog.LogType.Name))
  .Select(entry => entry.data).ToList();

redpajama_set_name: RedPajamaStackExchange


text:
Q: use PHP to create an HTML table from a MSQL query, without duplicate rows? I'm creating a display for a student module webpage that displays in this format
2001/02

*

*Computer Science

*Biology

*Lorem Ipsum

2002/03

*

*Subject

*Subject

*Subject

In that style
The data base I'm using contains information such as

*

*year(2001/02)

*credit(10)

*mods.mid(CS500)

*mtitle(module title - software engineering, biology, chemistry...etc)

the PHP code I have displays every module title, so literally I giant list of modules whereas I want to split it out like up there described, Years displayed THEN every module for that year. Any one people help me? Code down below:
<?php
echo "
";
$query2 ="SELECT  mods.mid, ayr, mtitle, credits FROM stud, smod, mods WHERE stud.sid = '".$_POST['stuNo']."' and stud.sid = smod.sid and smod.mid = mods.mid order by ayr ASC";

$result = mysql_query($query2) or die(mysql_error());

echo "Enrolment and progress";
echo "
";

echo " Module Selection	";
echo"".$row["ayr"]."	";

while ($row = mysql_fetch_array($result))
{
  $temp_year=$row["ayr"];
echo "
";

 if ($temp_year!=$row["ayr"]){
     echo "" . $row["ayr"] . "	";
 }

echo "" . $row["mid"] . "	";
echo "" . $row["mtitle"] . "	";
echo "" . $row["credits"] . "	";

echo "
";
}
echo "
";

?>

I wouldn't know how to seperate it by year, any help is great. thank you.

A: I would probably code it like this, probably not the only way but should work based on what I believe you are trying to achieve. Please make sure to add the "order by" to your SQL query as well.
echo "
";
$query2 = "SELECT mods.mid, ayr, mtitle, credits FROM stud, smod, mods WHERE stud.sid = '".$_POST['stuNo']."' and stud.sid = smod.sid and smod.mid = mods.mid ORDER BY ayr DESC";

$result = mysql_query($query2) or die(mysql_error());

echo "Enrollment and Progress";
echo "
";
echo "
Module Selection
";
$year = "";
while ($row = mysql_fetch_array($result)) {
    if ($year != $row["ayr"]) {
       echo "
" . $row["ayr"] . "
";
       $year = $row["ayr"];
    }
    echo "
";
    echo "" . $row["mid"] . "	";
    echo "" . $row["mtitle"] . "	";
    echo "" . $row["credits"] . "	";
    echo "
";
}
echo "
";


text:
Q: How to get TinyMVC .NET class Library to work on ASP.NET MVC 2? I am trying to implement the TinyMCE Spellcheck plugin that uses GoogleSpell. The thing is I am trying to install it in an MVC environment.
I started by referencing the .NET class Library DLL (MoxieCode.TinyMCE) in my project.
Then, I added this code to my web.config:
<system.webServer>
    <handlers>
      <add name="TinyMCE" verb="GET,HEAD,POST" path="TinyMCE.ashx" type="Moxiecode.TinyMCE.Web.HttpHandler,Moxiecode.TinyMCE" />
    </handlers>
    <!--previously existing rules-->
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

I then added these lines to my tinyMCE.init({}); call:
        plugins: "spellchecker",
        theme_advanced_buttons3: "spellchecker",
        spellchecker_languages : "English=en",
        spellchecker_rpc_url : "TinyMCE.ashx?module=SpellChecker",

These steps are outlined in the tutorial here. I then followed instructions from this stack overflow post which recommended the following modification to global.asax to make it mvc friendly:
        routes.IgnoreRoute("TinyMCE.ashx");
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

Everything seems fine accept that when I browse to /TinyMCE.ashx i get this error:

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
Requested URL: /TinyMCE.ashx

Why can't asp.net mvc process that url?

A: Make sure the handler is being applied at the correct element in the web.config.
IIS supports 2 types of modes, an integrated mode and a classic mode.
The classic mode is the how versions previous to IIS 7 worked. Depending on that, you put the handlers in the web.config section that applies to asp.net, or in the section that is picked by IIS directly.

A: After a fair bit of frustration I stopped messing with it on localhost in VS 2010. I suspected that it was a problem relating to IIS configuration, so I uploaded the site to a sub-domain of the live server. It worked without any problem.
I'm not sure why the code didn't work on localhost but evidently, the steps I followed to execute TinyMCE .NET and GoogleSpell were correct because they work on the live server.


text:
Q: How to catch raised exception in rake task I have a rake task that loops through rows in CSV file, and inside that loop, there's a begin/rescue block to catch any possible raised exception. But when I run it, it keeps on saying 'rake aborted!' and it is not entering the rescue block
CSV.foreach(path, :headers => true) do |row|
  id = row.to_hash['id'].to_i
  if id.present?
    begin
      # call to mymethod
    rescue => ex
      puts "#{ex} error executing task"
    end
  end
end
...
def mymethod(...)
  ...
  begin
    response = RestClient.post(...)
  rescue => ex
    raise Exception.new('...')
  end
end

Expected: It should finish looping all the rows of the CSV
Actual result: It stops after reaching the 'raise' exception saying that:

rake aborted!
Exception: error message here
...
Caused by:
RestClient::InternalServerError: 500 Internal Server Error

A: You can use next to skip the faulty step of loop:
CSV.foreach(path, :headers => true) do |row|
  id = row.to_hash['id'].to_i
  if id.present?
    begin
      method_which_doing_the_staff
    rescue SomethingException
      next
    end
  end
end

And raise the exception inside your method:
def method_which_doing_the_staff
  stuff
  ...
  raise SomethingException.new('hasd')
end

A: I solved this issue by just commenting out the line that is raising an exception because it seems like it the quickest fix for now.
# raise Exception.new('...')

I'm still open to other suggestions if there are any better ways to do it.


text:
Q: Different view-options in Rails What is the best practise for creating a view page in Rails with different view-options, such as a basic view with mostly text and an advanced view with graphical features? More specifically, I would like to have a view page where the the user can toggle between a basic/advanced show view. Clicking the toggle button renders one set of divs corresponding to selected view. Should this be done though a form_for/if-else statement in html markup or is it better do to do it in javascript? I guess turning the
 on/off could be done in javascript through:
$("#id").show()
$("#id").hide()

I have a problem understanding how a rails implementation is done, where do I put the if-else statement (i.e. if user basic view is toggled render
, else
)?
<%= form_for ??? do |f| %>
  ...
  <%= f.submit ??? %>
<% end %>

Edit 2:

        Basic
        Advanced

  This is the basic view

  This is the advanced view

Now in javascript I have the following:
$("#basic").toggle();
$("#basic-advanced").click(function (){
  $("#basic").toggle();
  $("#advanced").toggle();
});

I have added the above code, but how do I keep track of which viewing mode that the page is in? From the answers it seems like one could set an instance variable, @viewing_mode, to a value corresponding to the mode, but how should this be done? Through a form?
Update: I managed to achieve a toggle using a session variable, and an if/else statement, the procedure is described here: Session variable not persisting after switch.

A: If you are using jQuery.show() and jQuery.hide() that means you need both the basic and advanced div tags rendered. Rails needs to render them both. You can just have toggle  display:hidden css, here I did that with variable @use_advanced.
<div id="advanced" <%= (@use_advanced) ? '' : ' style="display:hidden"' %>>...

<div id="basic" <%= (@use_advanced) ? ' style="display:hidden"' : '' %>>...

To toggle between the two you could have a button: <button>toggle</button>
$('button').click(function () {
  $('#advanced').toggle();
  $('#basic').toggle();
});

A: There are some different cases:
1) if you are able to change your view using CSS only - then you should enclose all the page inside classified div:

  ...

2) if first solution is not applicable then you may use if-else statement:
<% if @my_style_selected %>

My style

<% else %>

Default

<% end %>

3) finally, if neither solution suits you. You may write some JS to dynamically replace your divs. The best solution is to replace some parts of the page using AJAX. If you will render both variants and hide one of them - that will almost double your page load time.

A: Given that yiou are using rails I would look into using layout for different views rather than having conditional logic.
For more info see rails 3, how add a view that does not use same layout as rest of app?

A: Here's a JavaScript object (written in CoffeScript) that will allow you to switch between as many modes as you like using a convention:
class ModeSwitcher
  constructor: ($area, modes) ->
    $area = $ $area
    me = this

    bindToggle = (mode) ->
      $area.find('a.toggle.' + mode).click ->
        me.toggle mode

    $ ->
      bindToggle(mode) for mode in modes

  toggle: (mode) ->
    $('.mode').hide()
    $('.' + mode + '.mode').show()

Here's an example of how you could construct the object (JavaScript/jQuery):
  var switcher = new ModeSwitcher('body', ['basic', 'advanced']);
  $(function() {
    switcher.switch("<%= @mode %>");
  });

The @mode instance variable is set in the Rails controller and says which mode the view should start out in:
@mode = params[:mode] || 'basic'
As for how it works by convention, you would have sections like this:

...

...

And you would have links like this:
Switch to advanced mode
Switch to basic mode

When constructed, the object will iterate through all the declared modes and look for the toggle links. It will then bind the toggling function to those links.


text:
Q: Crear un ListView personalizado a partir de uno básico Tengo una aplicación que lee el contenido de un XML remoto, lo guarda en el ArrayList UnCurso y me muestra por medio de un ListView básico los titulares de cada entrada del XML.
Quiero personalizar el ListView para que, además de mostrar los titulares, me muestre también la imagen que va asociada a cada titular. Para ello he creado también un Layout con el modelo de cada entrada o ítem del ListView llamado ítem_List.
Hasta aquí todo correcto, pero me he quedado atascado, no sé cómo debo modificar el ArrayAdapter para que me cree cada entrada del ListView con su Titular y su Imagen. Os dejo el código para que le echéis un vistazo y me orientéis sobre cómo debo modificar el ArrayAdapter para que me muestre en el ListView la información que quiero.
Este es el MainActivity
public class MainActivity extends AppCompatActivity {

    private URL url;
    private ArrayList<ElCurso> UnCurso;
    private String[] titulares;
    private ListView listadoTitulos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy permiso = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(permiso);

        listadoTitulos = (ListView) findViewById(R.id.vtTitulares);
        UnCurso = new ArrayList<ElCurso>();

        try {
            url = new URL(" http://www.videotutoriales.es/android-xml/cursos.xml");
            leerxml();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        // Este es el adptador que quiero modificar para que me muestre el titular y una imagen
        ArrayAdapter adaptador  = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,titulares);
        listadoTitulos.setAdapter(adaptador);

        listadoTitulos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent (MainActivity.this,Detalle_curso.class);
                intent.putExtra("CURSO", UnCurso.get(position));
                startActivity(intent);
            }
        });
    }

    private void leerxml() {
        XmlPullParserFactory factory;
        XmlPullParser xml;

        int evento;

        boolean titulo;
        boolean precio;
        boolean imagen;
        boolean detalle;

        ArrayList<String> titulos;
        ArrayList<String> precios;
        ArrayList<String> imagenes;
        ArrayList<String> detalles;

        titulo = false;
        precio = false;
        imagen = false;
        detalle = false;

        titulos = new ArrayList<String>();
        precios = new ArrayList<String>();
        imagenes = new ArrayList<String>();
        detalles = new ArrayList<String>();

        try {
            factory = XmlPullParserFactory.newInstance();
            xml=factory.newPullParser();
            xml.setInput(url.openStream(), "UTF-8");

            evento=xml.getEventType();

            while (evento != XmlPullParser.END_DOCUMENT){

                switch (evento){
                    case XmlPullParser.START_TAG:
                        if (xml.getName().equals("titulo")){
                            titulo = true;
                        }
                        if (xml.getName().equals("precio")){
                            precio = true;
                        }
                        if (xml.getName().equals("imagen")){
                            imagen = true;
                        }
                        if (xml.getName().equals("detalle")){
                            detalle = true;
                        }
                        break;
                    case XmlPullParser.TEXT:
                        if (titulo){
                            titulos.add(xml.getText());
                        }
                        if (precio){
                            precios.add(xml.getText());
                        }
                        if (imagen){
                            imagenes.add(xml.getText());
                        }
                        if (detalle){
                            detalles.add(xml.getText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if (xml.getName().equals("titulo")){
                            titulo = false;
                        }
                        if (xml.getName().equals("precio")){
                            precio = false;
                        }
                        if (xml.getName().equals("imagen")){
                            imagen = false;
                        }
                        if (xml.getName().equals("detalle")){
                            detalle = false;
                        }
                        break;

                }
                evento= xml.next();
            }

            titulares = new String[titulos.size()];
            for (int i = 0; i < titulos.size(); i++){
                UnCurso.add(new ElCurso(titulos.get(i), detalles.get(i), imagenes.get(i), precios.get(i)));
                titulares[i] = titulos.get(i);
            }

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Este es el XML ítem_List con la interfaz de cada objeto del ListView
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/Imagen"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_gravity="center|center_horizontal"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginRight="10dp"
    android:scaleType="fitXY"
     />

<TextView
    android:id="@+id/LblTitulo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="Titulo"
    android:textAlignment="center"
    android:textSize="30sp"
    android:textStyle="bold" />

</LinearLayout>

Y aquí está el objeto donde guardola información leída del xml
public class ElCurso implements Serializable{
    private String titulo;
    private String detalle;
    private String imagen;
    private String precio;

    public ElCurso(String titulo, String detalle, String imagen, String precio) {
        this.titulo = titulo;
        this.detalle = detalle;
        this.imagen = imagen;
        this.precio = precio;
    }

    public String getTitulo() {
        return titulo;
    }

    public String getDetalle() {
        return detalle;
    }

    public String getImagen() {
        return imagen;
    }

    public String getPrecio() {
        return precio;
    }
}

Aqui está el Detalle_curso donde cargo el detalle de cada curso en un nuevo layout.
public class Detalle_curso extends Activity{
private TextView txtTitulo;
private TextView txtDetalle;
private TextView txtPrecio;

private ImageView vistaImagen;
private Bitmap imagenCargada;
private String direccionImagen = "http://www.videotutoriales.es/android-xml/";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detalle);

    txtTitulo = (TextView) findViewById(R.id.tvTitulo);
    txtDetalle = (TextView) findViewById(R.id.tvDetalle);
    txtPrecio = (TextView) findViewById(R.id.tvPrecio);
    vistaImagen = (ImageView) findViewById(R.id.ivImagen);

    try {
        obtenerCurso();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void obtenerCurso() throws IOException {
    Intent intent  = getIntent();
    ElCurso uncurso = (ElCurso) intent.getSerializableExtra("CURSO");
    txtTitulo.setText(uncurso.getTitulo());
    txtDetalle.setText(uncurso.getDetalle());
    txtPrecio.setText(uncurso.getPrecio() + "Euros");
    direccionImagen = direccionImagen + uncurso.getImagen();

    descargarImagen(direccionImagen);
}

private void descargarImagen(String direccionImagen2) throws IOException {
    URL imagenURL = null;
    try {
        imagenURL = new URL(direccionImagen2);
        HttpURLConnection conn  = (HttpURLConnection) imagenURL.openConnection();
        conn.connect();
        imagenCargada = BitmapFactory.decodeStream(conn.getInputStream());
        vistaImagen.setImageBitmap(imagenCargada);

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

}

A: Para eso debes implementar un clase que extienda de Base Adapter
ej:
 public class AdapterCursos extends BaseAdapter {
    Context context;
    List<ElCurso> lista;

    public AdapterContactos(Context context, List<ElCurso> lista) {
        this.context = context;
        this.lista = lista;

    }

    @Override
    public int getCount() {
        return lista.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View v = inflater.inflate(R.layout.fila_contacto, viewGroup, false);
        ImagenView imagen = v.findViewById(R.id.Imagen)
        TextView tv = v.findViewById(R.id.LblTitulo);
        tv.setText(lista.get(position).getTitulo())

        return v;
    }
}

Y en tu Actividad llamarlo:
ArrayAdapter adaptador  = new AdapterCursos(this,cursos);//curos es una lista de tus objetos
listadoTitulos.setAdapter(adaptador);

A: Lo que pasa es que tu estas llamadole adaptador a lo que es tu objeto Curso ese objeto va a apasar al adapter
public class ElCursoAdapter extends ArrayAdapter<ElCurso> {
    // Este es un adaptador custom

    private static class ViewHolder {
        TextView name;
    }

    public ElCursoAdapter(Context context, ArrayList<ElCurso> elCurso) {
       //Constructor del adaptador donde Pones tu arraylist
       super(context, R.layout.item_user, users);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       // Obtener data por la posición
       User user = getItem(position);
       // Verificar si la vista se va a reutilizar sino se infla la vista
       ViewHolder viewHolder;
       if (convertView == null) {
          // Se infla la vista
          viewHolder = new ViewHolder();
          LayoutInflater inflater = LayoutInflater.from(getContext());
          convertView = inflater.inflate(R.layout.item_ElCurso, parent, false);
          viewHolder.name = (TextView) convertView.findViewById(R.id.tvName);//Algun tv
          //Algun otro parametro lo pasas de la misma forma por ejemplo tu ImageView
          convertView.setTag(viewHolder);
       } else {
           //Cuando la vista se reutilzia
           viewHolder = (ViewHolder) convertView.getTag();
       }

        //Asignamos los datos de la lista En el viewHolder

       viewHolder.name.setText(user.name);
       // Se regresa la vista
       return convertView;
   }

}

Ahora Solo debes de asignar el Adaptador a tu ListView
//Se Crea El adaptador
ArrayList<ElCurso> arregloCursos = new ArrayList<ElCurso>();
ElCusoAdapter adapter = new       ElCursoAdapter(this, arregloCursos );
//Se lo asignamos al ListView
ListView listView = (ListView) findViewById(R.id.lvCurso);
listView.setAdapter(adapter);

Fuente


text:
Q: Why $x^T M y \leq \lambda_\max(M) | x \cdot y |$ I am reading a proof regarding the eigenvalue bound in communication complexity (in Arora and Barak book on computational complexity), and the proof uses the fact that for all unit vectors $x,y$, where $M$ is symmetric real matrix the following inequality holds:
$$
x^T M y \leq \lambda_\max(M) \big| x \cdot y \big|,
$$
where $x\cdot y$ is the dot product of the two vectors.
I don't see this fact immediately. The closest trace I could find is about matrix norms, but matrix norm is about $x^T M x$ not $x^T M y$. Another problem also is that the vectors the proof actually uses are binary vectors (characteristic function of a certain set), not unit vectors as the hypothesis of this claim.
Edit: Every entry in $M$ will either be 1 or -1, so it can not be diagonal (as in paul garrett's comment below).
The statement is used in proof of Lemma 12.13 (Eigenvalue bound) in this chapter draft of the book.

A: Ok. I took a look at the book via the link provided by the OP. As I suspected to some extent the inequality they are using is actually the familiar one
$$
X^TMY\le \lambda_{max}|X|\cdot |Y|,
$$
but they have bungled up the presentation by adding an errorneous intermediate step that may easily confuse the reader. The ingredients are the following. $M$ is, indeed, a symmetric real matrix. The symmetricity is not listed in the statement of this Lemma, but holds for all the matrices $M(f)$ defined earlier. I can only assume that this is an omission, for otherwise it should be easy to find counterexamples. Anyway, $\lambda_{max}$ is the magnitude of the largest eigenvalue (i.e. the largest absolute value). Given this (assuming that it matches with all the uses of this result), the proof is easy. Because $M$ is real and symmetric, its eigenvalues are all real, and we can find an orthonormal set of eigenvectors $\{\vec{x}_1,\ldots,\vec{x}_n\}$ such that $M\vec{x}_i=\lambda_i\vec{x}_i$.
We can write $Y$ using this eigenbasis as follows $Y=\sum_i b_i\vec{x}_i$, so
$MY=\sum_i b_iM\vec{x}_i=\sum_i \lambda_ib_i\vec{x}_i$. Then by Cauchy-Schwarz we get
$$
X^TMY=\langle X, MY\rangle\le |X||\sum_i \lambda_ib_i\vec{x}_i|= |X|\sqrt{\sum_i \lambda_i^2b_i^2}\le|X|\lambda_{max}\sqrt{\sum_i b_i^2}=\lambda_{max}|X||Y|,
$$
as claimed.
In that proof we have $X=1_A$ = the characteristic function of a set $A$, so $|X|=\sqrt{|A|}$ as the authors claim. Similarly $Y=1_B$, so $|Y|=\sqrt{|B|}$. Putting these pieces together we get
$$
X^TMY=1_A^TM1_B\le \lambda_{max}\sqrt{|A|\cdot|B|}
$$
recovering the claim of the authors. Their intermediate step does, indeed, involve the inner product $1_A^T1_B$, but the value of that inner product is $|A\cap B|$, and we don't see that anywhere in the final claim, so this is IMVHO a booboo. This is a draft version after all.
I obviously didn't read all of the chapter, just skimmed thru it to see the definition of $M(f)$ = a symmetric matrix with entries in $\{0,1\}$. If they apply the lemma to non-symmetric matrices as well, then we need to take a closer look.
=================================================
Edit: To make it clear. IMHO the authors made a mistake in claiming the sequence of inequalities:
$$
1_A^TM1_B\le\lambda_{max}|1_A^T1_B|\le\lambda_{max}\sqrt{|A|\cdot|B|},
$$
when it should have read
$$
1_A^TM1_B\le\lambda_{max}|1_A|\cdot|1_B|=\lambda_{max}\sqrt{|A|\cdot|B|}.
$$
In the end it makes no difference, because their proof only needs the inequality
$$
1_A^TM1_B\le\lambda_{max}\sqrt{|A|\cdot|B|}.
$$
IOW, my guess is that the authors knew where they were heading, and accidentally inserted an incorrect intermediate step.

A: If $\lambda_\max>0$ I have the following proof. In addition, as mentioned by thei, whether $x,y$ are unit-length does not matter.
Since $M$ is symmetric, it can be decomposed as $M=U^T\Lambda U$ with $U$ as an orthogonal matrix and $\Lambda$ as a diagonal matrix with the eigenvalues of $M$ as its diagonal entries.
$$x^TMy=x^TU^T\Lambda Uy=\bar{x}^T\Lambda \bar{y}=\sum \bar{x}_i\bar{y}_i \lambda_i\le\sum|\bar{x}_i\bar{y}_i \lambda_i|\le\sum |\bar{x}_i\bar{y}_i| \lambda_\max$$
$$=|\bar{x}\cdot \bar{y}| \lambda_\max=|x\cdot y| \lambda_\max$$
Correction: Thanks Ben and paul. $\sum|\bar{x}_i\bar{y}_i|\ne|\bar{x}\cdot\bar{y}_i|$ in general.


text:
Q: How to do a cors request to a node app in Bluemix i'm making a nodeapp on bluemix that is bounded to the business rules service and i have another application hosted on mobilefirst where i created my application UI. and i want to send data from the mobilefirst application and receive data, i've been told to use a cors request but i don't know how to do this.
here is my app.js file :
var app = require("express")(),
restler = require("restler"),
bodyParser = require("body-parser");

app.use(bodyParser.json());

app.use(function(request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type, Accept");
    next();
});

app.post("/", function(request, response) {
    var options = {
        username: "resAdmin",
        password: "replace"
    };

    var url = "https://brsv2-6855bc66.ng.bluemix.net/DecisionService/rest" +  "/vacationsRuleApp/1.0/vacationsRuleProject/json";

    restler.postJson(url, request.body, options).on('complete', function(data) {
        response.send(data);
    });
});

app.listen(process.env.VCAP_APP_PORT || 8080);

and here is my client code :
$.post(
    "http://businessrules-vacationsruleapp.mybluemix.net/",
    {
        "employeeID": "jujuju",
        "loanAmount": 10517320,
        "theEmployee": {
        "seniority": 3,
        "annualSalary": 10517320,
        "nbOfExtraVacationDaysBasedOnSeniority": 10517320
    },
    "creditAmount": 20000,
    "__DecisionID__": "string",
    "AnnualSalary": 20000 },
    function( data ) {
        alert(JSON.stringify(data));
        console.log(data);
    }
);

A: You would need to include the following in app.js.  The following will allow CORS on requests.
app.js
var app = require("express")(),
 restler = require("restler"),
 bodyParser = require("body-parser");

app.use(bodyParser.json());

app.use(function(request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

app.post("/", function(request, response) {
    var options = {
        username: "replace",
        password: "replace"
    };

    var url = "https://brsv2-6855bc66.ng.bluemix.net/DecisionService/rest" + "/vacationsRuleApp/1.0/vacationsRuleProject/json";

    restler.postJson(url, request.body, options).on('complete', function(data) {
        response.send(data);
    });
});

app.listen(process.env.VCAP_APP_PORT || 8080);

Then client side with JQuery you could do the following.

$.ajax ({
    url: "https://businessrules-vacationsruleapp.mybluemix.net",
    type: "POST",
    data: JSON.stringify({
    "employeeID": "jujuju",
    "loanAmount": 10517320,
    "theEmployee": {
        "seniority": 3,
        "annualSalary": 10517320,
        "nbOfExtraVacationDaysBasedOnSeniority": 10517320
    },
    "creditAmount": 20000,
    "__DecisionID__": "string",
    "AnnualSalary": 20000 }),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data){
        console.log(data);
        $(".result").text(JSON.stringify(data));
    }
});

Whatever object you send from the post call will get sent to the Business Rules Service.

A: The CORS npm module makes this very easy to use with Express.
var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());

https://www.npmjs.com/package/cors


text:
Q: Under what circumstances would a LINQ-to-SQL Entity "lose" a changed field? I'm going nuts over what should be a very simple situation. In an ASP.NET MVC 2 app (not that I think this matters), I have an edit action which takes a very small entity and makes a few changes. The key portion (outside of error handling/security) looks like this:
Todo t = Repository.GetTodoByID(todoID);

UpdateModel(t);
Repository.Save();

Todo is the very simple, small entity with the following fields: ID (primary key), FolderID (foreign key), PercentComplete, TodoText, IsDeleted and SaleEffortID (foreign key). Each of these obviously corresponds to a field in the database.
When UpdateModel(t) is called, t does get correctly updated for all fields which have changed.
When Repository.Save() is called, by the time the SQL is written out, FolderID reverts back to its original value. The complete code to Repository.Save():
public void Save()
{
    myDataContext.SubmitChanges();
}

myDataContext is an instance of the DataContext class created by the LINQ-to-SQL designer. Nothing custom has been done to this aside from adding some common interfaces to some of the entities.
I've validated that the FolderID is getting lost before the call to Repository.Save() by logging out the generated SQL:
UPDATE [Todo].[TD_TODO]
SET
    [TD_PercentComplete] = @p4,
    [TD_TodoText] = @p5,
    [TD_IsDeleted] = @p6
WHERE
    ([TD_ID] = @p0) AND
    ([TD_TDF_ID] = @p1) AND /* Folder ID */
    ([TD_PercentComplete] = @p2) AND
    ([TD_TodoText] = @p3) AND
    (NOT ([TD_IsDeleted] = 1)) AND
    ([TD_SE_ID] IS NULL) /* SaleEffort ID */
-- @p0: Input BigInt (Size = -1; Prec = 0; Scale = 0) [5]
-- @p1: Input BigInt (Size = -1; Prec = 0; Scale = 0) [1] /* this SHOULD be 4 and in the update list */
-- @p2: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [90]
-- @p3: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text]
-- @p4: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [0]
-- @p5: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text foo]
-- @p6: Input Bit (Size = -1; Prec = 0; Scale = 0) [True]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 4.0.30319.1

So somewhere between UpdateModel(t) (where I've validated in the debugger that FolderID updated) and the output of this SQL, the FolderID reverts. The other fields all save. (Well, OK, I haven't validated SaleEffortID yet, because that subsystem isn't really ready yet, but everything else saves.)
I've exhausted my own means of research on this: Does anyone know of conditions which would cause a partial entity reset (EG, something to do with long foreign keys?), and/or how to work around this?

A: The only thing I can think of, is if something forces the datacontext to load the related entity (which would be Folder in this case, I think) before the call to UpdateModel.
If you try to change FolderID after the Folder entity has been loaded, it will silently fail and retain it's old value. This can be kindof annoying. I don't know if this is the case here, however as you appear positive that the values are updated by the UpdateModel call.
Normally, if the foreign key is changed before the datacontext tries to load the related entity, then the correct entity will be loaded (the one with the new key), but somehow, maybe something happens that triggers a mysterious behaviour in this case - I know it's not much to go on, but I would definitely expect this to have something to do with deferred loading of the related entity.


text:
Q: MYSQL Interval - Same day of the week one year in the future Does anyone have a snippet of MYSQL code that will give me the new datetime of a day one year in the future that is the same day of the week?
SELECT new_day = ADDDATE(new_day,INTERVAL 364 DAY) FROM my_table

Works on non-leap years.  Any ideas how to deal best with leap years?

A: Given that a normal year is 52 weeks and 1 day long and a leap year is 52 weeks and 2 days long, your new date will be one or two days earlier in the year than it was in the old year.  For any date after New Year's Day in a regular year, or any date after the 2nd of January in a leap year, adding 52 week or 364 days gives you a date in the next year that is on the same day of the week and occurs 1 or 2 days earlier in the month (or at the end of the prior month).
That leaves you with the problem of what to do with the first two days of the year.  Presumably 'next year' is crucial, so the simple answer that 2013-12-31 is 52 weeks later than 2013-01-01 is not OK.  In this case, you have to write a conditional expression, spelled CASE in SQL.
SELECT CASE WHEN YEAR(DATEADD(ref_date, INTERVAL 364 DAY)) = YEAR(ref_date)
       THEN DATEADD(ref_date, INTERVAL 371 DAY)
       ELSE DATEADD(ref_date, INTERVAL 364 DAY)
       END
  FROM ...wherever...

A: how do you wish it to deal with leap years? either save month and date and compare if 364 or 371 are closest to first day, and pick regardingly, or do nothing and face inaccuracy after a couple of years.

*

**saved_date* is the very first date before created new dates based on it

**passed_years* is increasing for every new since the first
date_add(last_date, INTERVAL (case when datediff(date_add(saved_date, INTERVAL passed_years YEAR), date_add(last_date, INTERVAL 371 DAY)) <= 3 then 371 else 364 end)) DAY)
The idea of this is to either fetch 52 or 53 weeks of the next year. leap years doesn't affect weekdays, but they "contribute" to an already existing problem; the date gets lower for each passing year if you only add 52 weeks each year without above solution.

A: Why not simply
CURDATE() + INTERVAL 52 WEEK`

Sure, it will be 1 or 2 days earlier in the 'calendar'.
mysql> SELECT NOW(), CURDATE() + INTERVAL 52 WEEK;
+---------------------+------------------------------+
| NOW()               | CURDATE() + INTERVAL 52 WEEK |
+---------------------+------------------------------+
| 2017-09-05 15:50:46 | 2018-09-04                   |
+---------------------+------------------------------+

If you need it to be 'later', then use 53.


text:
Q: Kubernetes - Get Node Label from Container Is there any way to get a node labels from within a container for use as an environment variable?
It's similar to this https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/, but I need to use a label from the node for injecting into the container instead.
Thanks in advance!

A: You will not be able to get node labels without sending some requests to the k8s api server. You could do that - but that would mean every pod will need read access and that's not great security wise.
How about an alternate solution - if you need to make sure the pod is running on nodes with specific labels, you can use taints and tolerations to achieve that more easily.


text:
Q: iPhone Simulator: SpringBoard failed to launch application with error: 7 Building an iPhone project results in:

Failed to launch simulated application: SpringBoard failed to launch application with error: 7

And the app doesn't install on the simulator. What's this all about? What's SpringBoard and what is error 7?

A: No need to quite the simulator or delete the app..
Just select simulator, press command + shift + h + h and remove the app from background process(long press on app icon) then run your app again.

A: I started with a new project in Xcode and got the error 3 message, but otherwise same deal.  New damn project - so no problems with broken code I added or name mistakes or anything else.  But the app would build but fail to run in Simulator with the Springboard -3 error code.  I've seen this before lots of times, and the basic kill-the-app-in-simulator, clean-and-run would work, but not this time.
Turns out my old 2007 iMac barely has enough RAM and disk space free any more.  I'm running Mavericks, and I hid everything but Xcode and the Simulator, then ran a memory cleaning utility to free up every bit of RAM available (got back up to 1GB free or so), and then the app runs in the Simulator without a hitch. No more Springboard error.
I hadn't seen "too little RAM" listed as a reason for this error yet, so this may be useful for somebody else.

A: Springboard is the app that launches apps.  It's the home screen of the iPhone.  I had tons of problems when I tried to get my app running on the phone -- turns out that I had an older version of the SDK that was incompatible with the version of the OS my phone had.  Reinstalling the latest SDK did the trick.
Also, have heard that clearing the XCode cache sometimes helps (didn't for me) -- XCode menu->Clear cache...

A: Maybe this will help: http://discussions.apple.com/thread.jspa?threadID=1605042&tstart=72
I had similar issues when I was trying to install my current development on the iPhone and this information about the AppID fixed it.
For quick reference, the AppID you created when you started creating certificates for development and provisioning of your iphone asked you to create a reverse domain name identifier. Something like: QS32H9XPNE.domain.subdomain.companyname.*
To correctly link up your application to the AppID would require you to set the identifier in the application to domain.subdomain.companyname.application.*
Hope this helps

A: I had the same problem but this solution works...!!!
1)Deleting the app from simulator.
2)Quitting simulator.
3)Restart simulator.

A: I had the exact same problem - I reset the iphone simulator and then quit the simulator (i.e. command q) then started it again.
Worked.

A: Boy, is the answer to this one hard to find, but I came up with a workaround.  The simulator gives this error if it has any problems with accessing files in ~/Library/Application Support/iPhone Simulator/.  This could be a permissions problem, but in my case it was even more subtle: my home directory is NFS mounted, and that seems to somehow be the source of the problem.
The basic workaround is to create a directory local to the machine, and link the iPhone Simulator's directory to that local directory.  You shouldn't need to move your source files or project directory; it's just the simulator targets that are the problem.
Here is one series of steps to accomplish the workaround, to be typed in at the terminal
(1-3 done on every machine you'll be developing on, 4-6 once in your NFS-mounted home directory):

*

*sudo mkdir /usr/local/iphone-dirs

*sudo chmod 777 /usr/local/iphone-dirs

*mkdir /usr/local/iphone-dirs/my-dir

*cd "~/Library/Application Support/"

*rm -rf "iPhone Simulator/"

*ln -s /usr/local/iphone-dirs/my-dir/ "iPhone Simulator"
There are obviously many variations on this theme; I suspect that using a locally-hosted directory in /tmp would be fine (and not require admin privs, but would have to be redone every time the system is rebooted).  As given, steps 1 and 2 are good if you will have multiple users using these machines that you don't want to collide with each other.  If you have your own personal machine but NFS-mount your homedir, you could probably just skip to something like step 3 (and sudo it).  Just make sure that whatever dir you create in step 3 is the dir that you symlink to in step 6.

A: XCode menu->Clear cache solved my problem.

A: This happens to me when i switch from testing on the device to testing on simulator. Restarting Xcode and simulator gets rid of this error for me.Silly.

A: I initially solved this by restarting the iPhone Simulator. But this shouldn't be the answer.
The error came from editing the info plist.
Check that you didn't change any values that were set before provisioning your app for your device.
I wanted to change my Bundle Identifier, but had to go back to the default one after having this error.
Now it's fixed.
Next step will be to get a new provision Id with the Bundle Id changed.

A: I had same problem, the Simulator would just hang. This is on a fresh install of XC 3.2.5 GM and using Simulator with 4.2 SDK. Apps would run fine on a real device but the simulator would just hang.
I ended up changing the iPhone App Support directory and all sub dirs to 777 access permissions. Not a great idea to 777 -R, but I was desperate and it worked.
$sudo chmod -R 777 ~/Library/Application Support/iPhone Simulator/

A: For me this was solution. If you have enable background fetch mode. Remove this option if you are getting this alert during run app in simulator.

A: I had the same problem.
It happens as follow...
I had a folder storing images in some sub-folders.
If I add the root image folder as "directory", I receive this error.
If I add the root image folder as "group", simulator runs fine.
weird...

A: It happens to be related to folder name as well.  My image folder was originally named "contents" and I got the error described.
Changed the folder name to "image_files" and reimport it to Xcode project as "folder".  It works!
This is totally random...

A: That did it for me, too:

This happens to me when i switch from
  testing on the device to testing on
  simulator. Restarting Xcode and
  simulator gets rid of this error for
  me.Silly.

A: When a home directory mounted in NFS you have the problem with the simulator.
To get rid of it, you need to to create a couple of directories in some local place where you have permissions to write, "iPhone Simulator" and "Interface builder". Then remove "~/Library/Application Support/iPhone Simulator" and "~/Library/Application Support/Interface Builder 3.0". And finally create symlinks at the exact places of the removed directories pointing to the local directories.

A: For mine, I got the error when I tried to change the App bundle ID setting in my info.plist file for the sake of running a test.  Changing it back cured the problem, but didn't do me any good for the test. Thankfully, the app had loaded in the simulator and I ran it manually for my test.
As far as I can tell, the problem stemmed from having a bundle ID that matched both a specific ID and a wild-card ID.  The App IDs I've tried that match only a specific ID/Profile haven't shown a problem.

A: Check your console and you will get a better idea of what the error might be. That error number is pretty generic. In my case I had an error in my Plist file. I chenged something that I shouldn't have. But I realized this was the problem because the console had a more detailed error message:
2010-09-13 23:30:27.149 Appname[5580:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle:

... and it goes on.

A: I have had this problem frequently, and generally just quitting and restarting Xcode works.
However, I just had this problem again and nothing seemed to fix it - quitting the sim, Xcode, rebooting… What was strange was some targets worked (I have multiplied build targets for this project), and other projects worked. But one target failed to launch no matter what I did.
In the end, I found the problem: In the target's properties the executable name $[EXECUTABLE_NAME] got accidentally deleted ! Replace it, and it works.
Worth remembering…

A: I got same error. This is how i solved it. Hope this helps.

*

*To show all hidden files type below from command line
$ defaults write com.apple.finder AppleShowAllFiles TRUE; killall Finder

*Access DerivedData folder and delete it's content(under DerivedData). Basically this is Simulator Cache which sometimes does not get deleted from XCode. Library is a hidden folder
and that is why we  run Step 1.
/Users/your username/Library/Developer/Xcode/DerivedData

A: Quit and re-open simulator , it will work i also got an issue like this and this helped me.

A: I am facing the exact same issue very frequently, what I do is
1) I quit the iphone simulator
2) and if after following step 1, if issue still the same, then reset the simulator
And it has resolved my issue all the time from step 1 itself.


text:
Q: Send and Receive Email in ASP.NET I am creating Contact Us web page in ASP.NET where user can enter all his details. After entering details when he click on submit buttons I; as a admin should receive all his details he enter into contact us page and he; as a user should receive thanks or confirmation message. I tried to search and follow number of blog but all those blog explain how to send email.
I am able to send email to user once he/she click on submit button but I; as an admin not able to receive user info he entered into Web Page.
Can someone provide me sample code or guide me how should I achieve this task in ASP.NET and C#.
Thanks in advance.

A: This is how I do it. This includes ajaxControlToolkit as well, but you do not need this. But I would recommend the required field validator.  I have 3 textboxes. One is for their name, 2nd is for their email, and the 3rd is the description of what they want or need.
HTML

            <asp:Label ID="lblYourName" runat="server" Text="Your Name: ">
            </asp:Label><asp:TextBox ID="tbEmployeeName" runat="server" Width="151px" CausesValidation="true"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmployeeName" runat="server" ForeColor="red" ErrorMessage="Email is Required!" ControlToValidate="tbEmployeeName"></asp:RequiredFieldValidator>
            <ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
                TargetControlID="tbEmployeeName"
                FilterType="Custom, UppercaseLetters, LowercaseLetters"
                ValidChars=" "/>

            <asp:Label ID="lblYourEmailAddress" runat="server" Text="Your E-mail: ">
            </asp:Label><asp:TextBox ID="tbEmployeeEmail" runat="server" Width="150px" CausesValidation="true"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmployeeEmail" runat="server" ForeColor="red" ErrorMessage="You're Email Address is Required!" ControlToValidate="tbEmployeeEmail"></asp:RequiredFieldValidator>
            <ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server"
                TargetControlID="tbEmployeeEmail"
                FilterType="Custom, UppercaseLetters, LowercaseLetters, Numbers"
                ValidChars=".@"/>

            Explain why you would like to have an account.

            <asp:TextBox ID="tbEmployeeRequest" runat="server" TextMode="MultiLine" Width="250px" CausesValidation="true"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmployeeRequest" runat="server" ForeColor="red" ErrorMessage="Message is required!" ControlToValidate="tbEmployeeRequest"></asp:RequiredFieldValidator>
            <ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender2" runat="server"
                TargetControlID="tbEmployeeRequest"
                FilterType="Custom, UppercaseLetters, LowercaseLetters, Numbers"
                ValidChars=". ;!?'" />

            <asp:Button ID="btnSubmit" runat="server" Text="Submit" Font-Size="Small" Height="33px" Width="72px" OnClick="btnSubmit_Click" CausesValidation="true"/>

Behind Code
protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid)
            {
                MailMessage msg = new MailMessage();
                HttpContext ctx = HttpContext.Current;
                msg.To.Add(new MailAddress("toEmail@Email.com"));
                msg.From = new MailAddress(tbEmployeeEmail.Text);
                msg.Subject = tbEmployeeName.Text + " requests an account!";
                msg.Priority = MailPriority.High;
                msg.Body = tbEmployeeRequest.Text;

                //CONFIGURE SMTP OBJECT
                SmtpClient smtp = new SmtpClient("mail.yoursmtpclient.com");

                //SEND EMAIL
                smtp.Send(msg);

                tbEmployeeEmail.Text = null;
                tbEmployeeName.Text = null;
                tbEmployeeRequest.Text = null;

                lblMessage.Text = "Your request has been sent. Please wait 2-3 days for a response.";
            }
        }

As you can tell, I use a label to tell them that their response will take a few days. What you can then use instead of the label like I do, is use a jQuery Modal popup that says thank you and any other information you need. If you do not know how to use jQuery, this is a good way to start. http://jqueryui.com/demos/ . If you wanted to send an email message back that says whatever you want it to say, you can manipulate the code above to do so. Instead of having the msg.To.Add(new MailAddress("toEmail@email.com") you could put msg.To.Add(new MailAddress(tbEmployeeEmail.Text); and send the email to them. I think (as an end user) this would be annoying though to check my email to see if I get a reponse, I'd rather know straight from the page. I hope this helps!


text:
Q: Replacing a nested array inside an array of objects with new array of objects This is the structure of my data document
{
"_id": "6287a6c5975a25cc25e095b0",
"userName": "Robot",
"projectName": "TestProject",
"projectTypeName": "fixed project",
"profitMargin": 50,
"versions": [
    {
        "ver": 0,
        "data": [
            {
                "totalResources": 2,
                "costToCompany": 31000,
                "profitToCompany": 15500,
                "costToClient": 46500,
                "resources": [
                    {
                        "genericDesignationName": "Development",
                        "designationName": "Backend Developer",
                        "departmentName": "web development",
                        "calculationFactor": 1,
                        "_id": "6287a6c5975a25cc25e095b3"
                    }
                ],
                "addOns": [
                    {
                        "genericDesignationName": "Design",
                        "designationName": "Graphic Designer",
                        "addOnCost": 30000,
                        "_id": "6287a6c5975a25cc25e095b4"
                    }
                ],
                "_id": "6287a6c5975a25cc25e095b2"
            }
        ],
        "_id": "6287a6c5975a25cc25e095b1",
        "createdAt": "2022-05-20T14:33:41.335Z",
        "updatedAt": "2022-05-20T14:33:41.335Z"
    },
    {
        "ver": 1,
        "data": [
            {
                "totalResources": 4,
                "costToCompany": 2200,
                "profitToCompany": 1100,
                "costToClient": 3300,
                "resources": [
                    {
                        "genericDesignationName": "Development",
                        "designationName": "Backend Developer",
                        "departmentName": "web development",
                        "calculationFactor": 1,
                        "_id": "6287a6de975a25cc25e095c2"
                    },
                    {
                        "genericDesignationName": "Development",
                        "designationName": "Frontend Developer",
                        "departmentName": "web development",
                        "calculationFactor": 1,
                        "_id": "6287a6de975a25cc25e095c3"
                    }
                ],
                "addOns": [
                    {
                        "genericDesignationName": "Design",
                        "designationName": "Graphic Designer",
                        "addOnCost": 100,
                        "_id": "6287a6de975a25cc25e095c4"
                    },
                    {
                        "genericDesignationName": "Design",
                        "designationName": "UI/UX Designer",
                        "addOnCost": 100,
                        "_id": "6287a6de975a25cc25e095c5"
                    }
                ],
                "_id": "6287a6de975a25cc25e095c1"
            }
        ],
        "_id": "6287a6de975a25cc25e095c0",
        "createdAt": "2022-05-20T14:34:06.794Z",
        "updatedAt": "2022-05-20T14:34:06.794Z"
    }
],
"createdAt": "2022-05-20T14:33:41.335Z",
"updatedAt": "2022-05-20T14:34:06.795Z",
"__v": 1

}
My question is that How to replace the version[1].data[] with new values that will be come from the client side..
New data will look like
"data": [
            {
                "totalResources": 4,
                "costToCompany": 2200,
                "profitToCompany": 1100,
                "costToClient": 3300,
                "resources": [
                    {
                        "genericDesignationName": "Development",
                        "designationName": "Backend Developer",
                        "departmentName": "web development",
                        "calculationFactor": 1,

                    },
                    {
                        "genericDesignationName": "Development",
                        "designationName": "Frontend Developer",
                        "departmentName": "web development",
                        "calculationFactor": 1,

                    }
                ],
                "addOns": [
                    {
                        "genericDesignationName": "Design",
                        "designationName": "Graphic Designer",
                        "addOnCost": 100,

                    }
                ],
                               }
        ],

    }
]

A: You can simply achieve that by iterating versions array :

const data = {
  versions: [{
    ver: 0,
    data: []
  }, {
    ver: 1,
    data: []
  }, {
    ver: 2,
    data: []
  }]
};

const replacedData = ['abc'];

data.versions.forEach(obj => {
    if (obj.ver === 1) {
    obj.data = replacedData
  }
});

console.log(data);


text:
Q: Update location in background? I want to update user's location in background.
To perform tasks in background, i used this package, workmanager.
Link to that: https://pub.dev/packages/workmanager
But i can not update the location, it seems like it can't work with async code?
here is my code,
void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    await _HomeScreenState().updateUserLoc();
    print('it is working?');

    return Future.value(true);
  });
}
//Inside my stateFul Widget,

 void initState() {
    super.initState();

    Workmanager.initialize(
      callbackDispatcher,
      isInDebugMode: true,
    );

    Workmanager.registerPeriodicTask(
      "1",
      fetchBackground,
      frequency: Duration(minutes: 15),
    );
  }

updateUserLoc() async {
    print("executi9ng the updateUserLocccccc");
    await getusersLocation();
    print("executi9ng the updateUserLoc");
    GeoFirePoint point = geo.point(latitude: lat, longitude: long);
    _firestore.collection('locations').document(widget.userid).setData(
      {'position': point.data},
      merge: true,
    );
  }

Is there any other way of updating the users's location in background?

A: You have to call the call the code inside the updateUserLoc() directly inside the callbackDispatcher. Just make the callbackDispatcher async function.


text:
Q: I want key `A` to be held for at least three seconds without a break. Make sure that is the case I want key A to be held for at least three seconds without a break. If the key press is interrupted, the three-second period should apply again.
This is my previous program. Unfortunately, while the timer() procedure is running, the program does not notice anything about the release of the button or pressing it again.
My question to you is: what can I do?
I want to stay in C.
My IDE is Microsoft Visual Studio Community 2019, version 16.11.2.
I work with Windows 10.
#pragma warning(disable : 4996) // Visual Studio doesn't want to see old functions like 'scanf'.

#include <stdio.h>
#include <Windows.h>
#include <cstdint>
#include <time.h>

bool supposed_to_run = true;
VOID KeyEventProc(KEY_EVENT_RECORD);
long long waited = 0ll;
time_t Time_of_the_keydown_event;
bool triggered = false;

void timer()
{
    Time_of_the_keydown_event;
    time_t _to = time(&_to) + 3ll;

    do
    {
        Time_of_the_keydown_event = time(&Time_of_the_keydown_event);
    } while (Time_of_the_keydown_event < _to && triggered);

}

void Logic(INPUT_RECORD rec)
{
    if (rec.Event.KeyEvent.wVirtualKeyCode == 0)
    {
        return;
    }

    if (!rec.Event.KeyEvent.bKeyDown)
    {
        triggered = false;
        return;
    }

    switch (rec.Event.KeyEvent.wVirtualKeyCode)
    {
    case VK_SHIFT:
        break;
    case VK_CONTROL:
        break;
    case VK_SPACE:
        break;
    case VK_LEFT:
        break;
    case VK_UP:
        break;
    case VK_RIGHT:
        break;
    case VK_DOWN:
        break;
    case 0x41: /*A*/
        triggered = true;
        timer();

        printf("A\n");
        break;
    case 0x51: /*Q*/
        break;
    case 0x5A:  /*Z*/
        supposed_to_run = false;
        break;
    default:
        break;
    }
}

int main(void)
{
    INPUT_RECORD rec{};
    HANDLE hConInp = GetStdHandle(STD_INPUT_HANDLE);
    DWORD ReadCount = 0;

    //Change_size_position_and_color();

    while (supposed_to_run)
    {
        ReadConsoleInput(hConInp, &rec, 1, &ReadCount);
        Logic(rec);
    }

    // end program
    printf("\nProgramm wird beendet. Dr\x81 \bcken Sie eine Taste und \x27 \bEnter\x27 \b.\n");
    getchar();
    return 0;
}

A: I recommend that you use the function WaitForSingleObject. That function allows you to wait for new console input to become available, and also allows you to specify a timeout, which should be 3 seconds in your case.
Depending on the return value of that function, you will know whether new console input has occurred or whether the timeout has expired.
switch ( WaitForSingleObject( hConInp, 3000 ) )
{
case WAIT_OBJECT_0:
    //handle new console input
    //ReadConsoleInput will not block if called now
    break;
case WAIT_TIMEOUT:
    //handle timeout
    break;
default:
    //handle error
}

However, this solution has one problem. While holding down the key, the key will automatically repeat, generating new input events. Therefore, the timeout of 3 seconds will probably never expire (unless you have configured your operating system to have a very long repeat delay).
Therefore, you will have to ignore these key down events and call WaitForSingleObject again, but this time not with a timeout of 3 seconds again. Instead, the new timeout should be the remaining time of the original 3 seconds.
In your code, you are using the ISO C function time. However, this function has a precision of only one second, which may not be accurate enough. Therefore, you may want to use the platform-specific function GetTickCount instead.
I believe I was able to get your program to work, by making the changes mentioned above. Here is my code:
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

bool supposed_to_run = true;
bool triggered = false;
bool require_release = false;
DWORD remaining_timeout;

void Logic( INPUT_RECORD *p_rec )
{
    //only handle keyboard events
    if ( p_rec->EventType != KEY_EVENT )
        return;

    if (!p_rec->Event.KeyEvent.bKeyDown)
    {
        if ( triggered )
        {
            printf( "removing trigger\n" );
            triggered = false;
        }
        else if ( require_release && p_rec->Event.KeyEvent.wVirtualKeyCode == 0x41 )
        {
            printf( "key has been released and timeout may now be triggered again\n" );
            require_release = false;
        }
        return;
    }

    switch (p_rec->Event.KeyEvent.wVirtualKeyCode)
    {
    case VK_SHIFT:
        break;
    case VK_CONTROL:
        break;
    case VK_SPACE:
        break;
    case VK_LEFT:
        break;
    case VK_UP:
        break;
    case VK_RIGHT:
        break;
    case VK_DOWN:
        break;
    case 0x41: /*A*/
        if ( !triggered && !require_release )
        {
            printf( "triggering timeout\n" );
            triggered = true;
            remaining_timeout = 3000;
        }
        break;
    case 0x51: /*Q*/
        break;
    case 0x5A:  /*Z*/
        supposed_to_run = false;
        break;
    default:
        break;
    }
}

int main(void)
{
    INPUT_RECORD rec;
    HANDLE hConInp = GetStdHandle(STD_INPUT_HANDLE);
    DWORD ReadCount;

    while (supposed_to_run)
    {
        if ( triggered )
        {
            bool timeout_expired = false;

            DWORD start_time = GetTickCount();

            switch ( WaitForSingleObject( hConInp, remaining_timeout ) )
            {
            case WAIT_OBJECT_0:
                break;
            case WAIT_TIMEOUT:
                timeout_expired = true;
                break;
            default:
                fprintf( stderr, "unexpected error!" );
                exit( EXIT_FAILURE );
            }

            DWORD time_expired = GetTickCount() - start_time;

            if ( !timeout_expired )
            {
                //It is possible that WaitForSingleObject did not report
                //a timeout, but that GetTickCount now reports that the
                //timeout expired. We should consider this also a timeout.
                if ( time_expired >= remaining_timeout )
                    timeout_expired = true;
            }

            if ( timeout_expired )
            {
                triggered = false;
                require_release = true;
                printf( "A\n" );
                continue;
            }
            else
            {
                remaining_timeout -= time_expired;
            }
        }

        ReadConsoleInput( hConInp, &rec, 1, &ReadCount );
        Logic( &rec );
    }

    return 0;
}

After the user holds down the key A for three seconds, it will display that character on the screen. Afterwards, a new timeout will not be triggered until the user releases the key and then presses it again.


text:
Q: Пользовательский конструктор копирования/перемещения Правильно ли я понимаю, что будет плохой техникой реализовывать конструкторы копирования/перемещения, используя соответствующие операторы присваивания?
Т.е. лучше ли использовать списки инициализации, соответственно, в случае перемещения в них надо указывать дополнительно при надобности приведение к rvalue с помощью std::move(), а в теле перемещающего конструктора «обнулить» rhs (это по соглашению проекта)? Ну и какие-то дополнительные операции в теле, например, копирование поэлементное массива или логирование.

A: Вообще говоря, да, это будет странной техникой.
С общей точки зрения попытки реализовать конструктор копирования через копирующий оператор присваивания будут страдать от проблемы "двойной инициализации": так как оператор присваивания ожидает на вход уже сконструированные объекты, в конструкторе придется сначала конструировать какой-то (пустой) объект, а лишь затем вызывать для него оператор присваивания, который будет "переконструировать" этот объект по-новому.
В устоявшихся идиомах обычно делают наоборот: копирующий оператор присваивания реализуется через конструктор копирования. Так это делается, например, в известной идиоме Copy-And-Swap.


text:
Q: Ubuntu Windows 10 Dual boot with TPM & Bitlocker I have the factory installed copy of Windows 10 with Bitlocker enabled (I don't want to disable it), the EFI partition exists (System Reserved Partition). I installed Ubuntu 18.04 so I can dual boot, while installing I chose a 3 different partitions on my SSD for "/", "/home" and swap area. I chose to install the GRUB bootloader on the SSD as a whole not a specific partition on it so I guess that would make it install GRUB in the EFI partition?
Current state: boots into GRUB menu and if I chose Windows, it asks for the recovery key every time.
I want to uninstall grub and return to the Windows Bootloader/boot manager without reinstalling Windows. Then boot by default into it and have the option to chose to go to GRUB or Ubuntu directly as this tutorial https://stomp.colorado.edu/blog/blog/2011/12/05/on-dual-booting-tpm-linux-windows-and-bitlocker/ says.

A:
I chose to install the GRUB bootloader on the SSD as a whole not a specific partition on it so I guess that would make it install GRUB in the EFI partition?

Yes it would. The question whether to install GRUB into a disk vs partition doesn't even make sense on UEFI.

the EFI partition exists (System Reserved Partition)

That's not the same partition.

I want to uninstall grub and return to the Windows Bootloader/boot manager without reinstalling Windows. Then boot by default into it and have the option to chose to go to GRUB or Ubuntu directly as this tutorial https://stomp.colorado.edu/blog/blog/2011/12/05/on-dual-booting-tpm-linux-windows-and-bitlocker/ says.

The tutorial is written for PC BIOS systems. It does not apply to UEFI – the special partitions are different, bootloaders live elsewhere, the whole boot process is nothing like BIOS boot.
For UEFI, the Windows Boot Manager refuses to start any other boot programs except for what comes with Windows itself. You can still add the corresponding entries, but they won't work.
However, for UEFI, your EFI System Partition already has both bootloaders installed and the firmware itself has a boot menu that allows you to choose between them. Hold Esc or F12 or whatever your computer uses; you'll find an entry for "Windows Boot Manager" and an entry for "Ubuntu".
Within Linux you can manage these boot entries using efibootmgr. For example:
# efibootmgr
BootCurrent: 0001
Timeout: 0 seconds
BootOrder: 0000,0001
Boot0000* Windows Boot Manager
Boot0001* Ubuntu

To swap them around (make Windows primary), you can again use the firmware settings screen, or you can change the BootOrder variable:
# efibootmgr --bootorder 0001,0000

To boot into Windows once while keeping Ubuntu as default, you can set BootNext:
# efibootmgr --bootnext 0000

And vice versa, if you're using Windows, to boot into Ubuntu just once:

*

*Use bcdedit /enum firmware to find the Windows BCD GUID for the Ubuntu entry.

*Use bcdedit /set {fwbootmgr} bootsequence {UBUNTU_GUID_HERE} to program the BootNext variable.


text:
Q: ses and outer semidirect products of groups Let $\phi : H \to Aut(N)$ be an action ($N,H$ are groups), and let $G = H \rtimes_\phi N$ be the semidirect product ($N$ is normal in $G$). I know that when $\phi$ is the action by conjugation, there is a ses $1 \to N \to G \to H \to 1$ with a section $ H \to G$. My question is

for a general $\phi$, is there also a ses $1 \to N \to G \to H \to 1$?


text:
Q: Nested fieldsets in django admin page Trying to understand Django Admin a bit better, but facing a problem when placing nested fieldsets in django admin
I want to group my model fields as shown in below image.
I tried using this code, but no success.
    class ContactAdmin(admin.ModelAdmin):
        fieldsets = (
                     ("Main Info", {'fields': ("user", "website")}),
                     ("Phones", {'fields': (
                          ("Primary", {'fields': (("primary_phone_country", "primary_phone_area", "primary_phone_number"),)}),
                          ("Secondary", {'fields': (("secondary_phone_country", "secondary_phone_area", "secondary_phone_number"),)}),
    )}),
)

    admin.site.register(Contact, ContactAdmin)

Any Solutions to solve the above issue?

A: If I understand this Django ticket correctly, nested fieldsets are not supported. Although the ticket is 4 years old, it was updated 9 months ago, plus there is no reference to nested fieldsets in the Django documentation.
Having said that, the ticket includes a patch to implement that functionality. Have you tried using it?


text:
Q: C# - cannot convert from double to [variable name] I'm implementing LU decomposition in C#. In MainWindow.xaml.cs I read matrix elements from the form, convert them into double, and use the LowerUpper.cs class and its functions (edited out for easier reading) for calculation. This is the problem segment:
using System;
using System.Linq;
using System.Windows;

namespace NM1test
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Compute()
        {
            double A11 = Convert.ToDouble(a11.Text);
            double A12 = Convert.ToDouble(a12.Text);
            double A13 = Convert.ToDouble(a13.Text);

            double A21 = Convert.ToDouble(a21.Text);
            double A22 = Convert.ToDouble(a22.Text);
            double A23 = Convert.ToDouble(a23.Text);

            double A31 = Convert.ToDouble(a31.Text);
            double A32 = Convert.ToDouble(a32.Text);
            double A33 = Convert.ToDouble(a33.Text);

            LowerUpper lu = new LowerUpper(A11, A12, A13, A21, A22, A23, A31, A32, A33);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Compute();
        }
    }
}

I found similar inquiries but they were mostly about mismatched variable types, typos, or using Convert.ToDouble wrong. I'm sure none of that is the case. I don't see why A11 is somehow a type? Those are perfectly normal functional doubles.
I also have an error in LowerUpper.cs when declaring LowerUpper(): "The type or namespace 'A11' could not be found (are you missing a using directive or an assembly reference?)".
using System;
using System.Linq;
using System.Windows;

namespace NM1test
{
    class LowerUpper
    {
        public LowerUpper(A11, A12, A13, A21, A22, A23, A31, A32, A33)
        {

        }
    }
}

I don't have lots of experience with Visual Studio projects so these errors are really confusing. What am I doing wrong?

A: The reason you have this error is that you forgot to specify the types of the arguments in the LowerUpper constructor. That's why Visual Studio thinks that A11-A33 are types.
Your LowerUpper class should look like this:
using System;
using System.Linq;
using System.Windows;

namespace NM1test
{
    class LowerUpper
    {
        public LowerUpper(double A11, double A12, double A13, double A21, double A22, double A23, double A31, double A32, double A33)
        {
            // initialization code here
        }
    }
}


text:
Q: What are valid values for R Shiny's fileInput's accept parameter? I'm working with an existing shiny app designed to take in a csv file as input. I'd like to expand on the functionality of the app to let it take both csv files and xlsx files as input, however, I'm not clear on what values to use for fileInput's accept parameter. This is what is currently contained in the accept parameter:
accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv')

Firstly, I'm not clear on why all three values are needed, and would appreciate clarification on why each is there. Secondly, how can I let the app take in xlsx files correctly? I can get it to take in xlsx files like this:
accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv', 'xlsx')

However, since three strings were being used for csv files, I'm unsure if I will be missing functionality using only one string for xlsx files. Is there a better way to implement this?

A: From the source code for fileInput:

\item{accept}{A character vector of MIME types; gives the browser a hint of what kind of files the server is expecting.}

This answer gives a good explanation of what MIME types are and how they are used.
This list of MIME types indicates that application/vnd.ms-excel is used with the .xls extension and application/vnd.openxmlformats-officedocument.spreadsheetml.sheet is used with .xlsx.


text:
Q: Why the App is installed twice? When I run the Android App Studio, the cell is the App is "installed" twice: There are two apps one called "SplashScreenActivity" and other "Doctor Quiz" (my app), the two are equal. If I uninstall one, the other also uninstalls. Why does this happen? How do I "install" just my app? (DoctorQuiz)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.morais.daniela.doctorquiz" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <provider android:authorities="com.facebook.app.FacebookContentProviderXXXX"
        android:name="com.facebook.FacebookContentProvider"
        android:exported="true" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/medicine_box_icon2"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
        <activity
            android:name=".Activity.SplashScreenActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_splash_screen"
            android:theme="@style/FullscreenTheme">
        <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
        </activity>
        <activity
            android:name=".Activity.QuestionsActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Activity.ResultActivity"
            android:label="@string/title_activity_result" >
            <activity android:name="com.facebook.FacebookActivity"
                android:configChanges=
                    "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
                android:theme="@android:style/Theme.Translucent.NoTitleBar"
                android:label="@string/app_name" />
        </activity>

    </application>

</manifest>

Screenshot

A: The app is not installed twice. You are not looking at apps. You are looking at launchable activities, ones with this <intent-filter>:
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

You have two activities with that <intent-filter>, and so you will have two activities in the home screen launcher. If you do not want both of those activities in the home screen launcher, remove that <intent-filter> from one of them.

A: Most probably you have specified two activities as launcher in manifest file. This invokes this issue.

change it to


text:
Q: GitHub: Would my Fork get updated when the master is changing?
Possible Duplicate:
Can I update a forked project, on git, to the original/master copy?

I've created a Fork as I would like to change some of the code in the master project: https://github.com/DennisMadsen/PullToRefreshView. I would like my Fork and its repository to get updated, when any new files are pushed into the master repository. Would that happen automatically or what should I do?

A: It won't update automatically, but you can use git to pull the changes from the master repository. See documentation here: http://help.github.com/fork-a-repo/


text:
Q: Unable to add the Remote URL https://th-superbadge-apex.herokuapp.com/equipment Hi am attempting Challenge2  : Synchronize Salesforce data with an external system of the Apex Specialist Superbadge
but unable to add the below url to Remote Site settings
https://th-superbadge-apex.herokuapp.com/equipment
It saves as https://th-superbadge-apex.herokuapp.com - donot know why ?
Can someone help ..

A: The Remote Site "URL" simply specifies the protocol (http/https) and server domain. The path, query parameters, and payload (body) is specified in the code that calls the endpoint, not in the Remote Site setting itself. Salesforce automatically removes any path or query string information, since it does not restrict by path, only by domain.


text:
Q: Would real Moody have taught 4th year students about Unforgiveable curses? Would real Moody have taught 4th year students about Unforgiveable curses the way fake Barty Crouch Moody did?
In other words, did Barty teach about them (leaving aside his hands-on teaching approach) just to satisfy his Death Eater wishes, or did he teach them as part of his cover as Moody impersonator because Moody would have taught about them?

A: I'd say it's probably a combination of the two, though mostly part of his cover. Barty Crouch, Jr. likely wouldn't have passed up the opportunity to use the Unforgivable curses, but it also doesn't seem out of character for the real Mad-Eye Moody to give a practical demonstration to fourth year students.

"... I'm not supposed to show you what illegal Dark curses look like until you're in the sixth year. You're not supposed to be old enough to deal with it till then. But Professor Dumbledore's got a higher opinion of your nerves, he reckons you can cope, and I say, the sooner you know what you're up against, the better. ..."

Assuming that we can take the statement that it was approved by Dumbledore as the truth - and I see no reason why we can't, it would be very difficult to keep performing the Unforgiveables in front of students secret from the other teachers - then it seems that it was indeed part of the cover.
Crouch's job was to disguise himself as Moody and make sure that Harry won the Triwizard Cup, so he's not going to push heavily in favour of something that wouldn't be considered normal for Moody because it would raise questions. I suppose the beauty of impersonating Moody, as opposed to anybody else, is that he's viewed as pretty unstable by a lot of people anyway. Any slightly questionable actions - such as turning Draco Malfoy into a bouncing ferret - aren't going to make anybody suspicious.

A:
I'm not supposed to show you what illegal Dark curses look like
  until you're in the sixth year. You're not supposed to be old enough to deal with it till then. But Professor Dumbledore's got a higher opinion of your nerves, he
  reckons you can cope, and I say, the sooner you know what you're up against, the
  better...

It seems like the curriculum for fourth year students does not include the Unforgivable curses. However Barty Eyed Mad Moody Crouch says that he received special permission from Dumbledore to teach them to fourth years. It is very unlikely that he lied about getting permission, as the students would undoubtedly be talking about the lesson outside of class, and he would not want to risk being found out so early in the year over something seemingly trivial.
Mad-Eye Moody may have done the same, though from the interactions that Harry has with him in later books, he seems like a by the books, strict, no nonsense individual. It would be impossible to know how he would have taught them however, and unfortunately we can no longer ask him.
However, teaching the lesson to the fourth year students definitely helped along Barty Crouch Jr.'s plans, so I think it is very likely that the lesson was part of the overall Death Eater plot that he had schemed. Though to be fair, it likely also helped out his cover since the motivation for Mad-Eye's actions to most people seemed dubious at best.
After the lesson, Neville is visibly shaken from the experience and is consoled by Barty and given the book, Magical Water Plants of the Mediterranean that Barty Crouch Jr. had hoped would help Harry get through the second challenge. It is possible that Barty needed an excuse to be overly generous to Neville, and used the lesson to upset him so much that he needed consoling. Barty Crouch Jr. was one of the Death Eaters responsible for torturing Neville's parents into insanity with the Cruciatus curse, so he would be well aware that performing it in front of Neville would likely elicit the response he was looking for.

A: That's a tricky one. Moody was fanatical when it came to his hatred of dark wizards, but he does also strike me as someone who would try to make his students aware of the stakes, and make sure that they were prepared.
I don't know about using the curses on students, but I could see him showing them the curses. That seems completely feasible. You have to remember, Barty was supposed to be as convincing as possible, so it seems likely that even if the real Moody wouldn't do that, his reputation and/or his personality made people who knew him believe he was capable of it. In fact, if Barty had thought it would arouse suspicion by using the curses, he would never have used them.
I could also see him comforting Neville, and probably being even more of a mentor to him than the fake was. As an auror and a member of the Order of the Phoenix, Moody would have felt a sense of camaraderie with the Longbottom family (he even talks about them when showing Harry the picture of the original Order). He might have even felt he owed them to teach Neville to defend himself and that Neville had a right to be able to take revenge. With his background, Neville might have been one of the only people Moody felt he could trust.
He might even have seen Neville as someone who would hate dark wizards as much as Moody himself, if not more, and could want to train him to be a sort of successor.
To be entirely fair, we like to make antagonists completely evil. Barty might have had a little good left in him when he took Neville under his wing. Barty hated death eaters who were never punished, and his father for not protecting him, but he had no real problem with Neville. He might even have felt a little guilty about what he did to the Longbottoms, even if giving Neville that book was intended to give Harry a clue.
His devotion to Voldemort may have been because of his long imprisonment in Azkaban, then at his father's hands. Voldemort freed him from prison, but when he was sent to trial, he didn't show any of his later fanatic devotion, even denying that he had anything to do with the Death Eaters. It may simply have been loyalty. As for the Longbottoms, I always got the impression that it was a random senseless act of violence brought on by poor decisions by Bellatrix than a planned move directed by Voldemort.
Barty praises Harry several times, and he might actually have liked him as a person, as he never personally seemed to hold a grudge. He only wanted to kill Harry out of his devotion to Voldemort. It might be possible he genuinely enjoyed teaching and actually cared a little for his students, so long as they were not obstacles to his master.

A: Well, yes, he does mention Dumbledore's permission, but I'm sure he was referring to be able to cope with things out of the fourth year curriculum, rather than Unforgivable Curses.
I feel fake Moody taught them Unforgivable Curses hoping that Harry might use it on his opponents, and it would be creepy for him to call Harry and show him some dead, tortured and Imperioused spiders.


text:
Q: float2 cufftcomplex to fftw_complex I want to using FFTW library on my code. I have cast float2 data type to fftw_complex. But I get:

Segmentation fault

This is my code.
test.cu
typedef float2 cplx;
int DoFFT_Operation( cplx* DatafftOneSlice, float* out, int *dim)
{
    cout << "DO CPU FFT RSS Operation" << endl;
    int xdim = dim[0];
    int ydim = dim[1];
    cout << "XDIM " << std::to_string(xdim) << " YDIM " << std::to_string(ydim) << endl;
    // int slicedim = dim[2];
    int bitdim = 1;
    // int sizeOneSlice = xdim*ydim*bitdim;
    int sizeOneImage = xdim*ydim;

    //FFTW PLAN
    fftw_plan pfftw;

    pfftw = fftw_plan_dft_1d(sizeOneImage, reinterpret_cast<fftw_complex*>(DatafftOneSlice), reinterpret_cast<fftw_complex*>(DatafftOneSlice), FFTW_BACKWARD, FFTW_ESTIMATE);

    fftw_execute(pfftw);

    // fft_it(DatafftOneSlice, sizeOneImage);
    // cplx* input, float* out, int N, int x, int y, int bit
    DoSomething(DatafftOneSlice, out, sizeOneImage, xdim, ydim, bitdim);

    fftw_destroy_plan(pfftw);

    fftw_cleanup();

    return 0;
}

How to casting float2 (CUDA) to fftw_complex?

A: I have solved my problem,
I am just change fftw_ to fftwf_, because fftw_ has double data type and fftwf_ has float data type.
test.cu
typedef float2 cplx;
int DoFFT_Operation( cplx* DatafftOneSlice, float* out, int *dim)
{
    cout << "DO CPU FFT RSS Operation" << endl;
    int xdim = dim[0];
    int ydim = dim[1];
    cout << "XDIM " << std::to_string(xdim) << " YDIM " << std::to_string(ydim) << endl;
    // int slicedim = dim[2];
    int bitdim = 1;
    // int sizeOneSlice = xdim*ydim*bitdim;
    int sizeOneImage = xdim*ydim;

    //FFTW PLAN
    fftwf_plan pfftw;

    pfftw = fftwf_plan_dft_1d(sizeOneImage, reinterpret_cast<fftwf_complex*>(DatafftOneSlice), reinterpret_cast<fftwf_complex*>(DatafftOneSlice), FFTW_BACKWARD, FFTW_ESTIMATE);

    fftwf_execute(pfftw);

    // fft_it(DatafftOneSlice, sizeOneImage);
    // cplx* input, float* out, int N, int x, int y, int bit
    DoSomething(DatafftOneSlice, out, sizeOneImage, xdim, ydim, bitdim);

    fftwf_destroy_plan(pfftw);

    fftwf_cleanup();

    return 0;
}


text:
Q: Search internal substrings in hibernate search I've defined my entity as following.
@Entity
@Indexed
@AnalyzerDef(name = "ngram_index", tokenizer = @TokenizerDef(factory = WhitespaceTokenizerFactory.class),
    filters = {
        @TokenFilterDef(factory = LowerCaseFilterFactory.class),
        @TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
        @TokenFilterDef(factory = NGramFilterFactory.class,
                        params = {
                            @Parameter(name = SearchConstants.MIN_GRAM_SIZE_NAME, value = SearchConstants.MIN_GRAM_SIZE_VALUE),
                            @Parameter(name = SearchConstants.MAX_GRAM_SIZE_NAME, value = SearchConstants.MAX_GRAM_SIZE_VALUE)
                        })
    })
@AnalyzerDef(name = "ngram_query", tokenizer = @TokenizerDef(factory = WhitespaceTokenizerFactory.class),
    filters = {
        @TokenFilterDef(factory = LowerCaseFilterFactory.class),
        @TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
    })
@NormalizerDef(name = "lowercase",
    filters = {
        @TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
        @TokenFilterDef(factory = LowerCaseFilterFactory.class)
    }
)

@Table(name = "ORDER")
public class Order {
    @Id
    @DocumentId
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Field(analyzer = @Analyzer(definition = "ngram_index"))
    @Field(name = "name_Sort", store = Store.YES, normalizer= @Normalizer(definition="lowercase"))
    @SortableField(forField = "name_Sort")
    @Column(name = "NAME")
    private String name;

    //other fields, getters and setters omitted for brevity

I then tried to overwrite the default analyzer that is being used during indexing for querying in another class that is not an entity.
public abstract class AbstractHibernateSearcher<S extends SearchableEntity> {
    // other fields and methods omitted here

    protected Query buildInputSearchQuery(String[] searchableFields) {
        if(Strings.isNullOrEmpty(searchRequest.getQuery()) || searchableFields.length == 0) {
            return null;
        }
        SimpleQueryStringMatchingContext simpleQueryStringMatchingContext = queryBuilder.simpleQueryString().onField(searchableFields[0]);
        for(int i = 1; i < searchableFields.length; i++) {
            simpleQueryStringMatchingContext = simpleQueryStringMatchingContext.andField(searchableFields[i]);
        }
        Query inputSearchQuery = simpleQueryStringMatchingContext
            .withAndAsDefaultOperator()
            .matching((searchRequest.getQuery()).toLowerCase()).createQuery();

        QueryBuilder queryBuilder = getNGramQueryBuilder(searchableFields);
        return queryBuilder.bool().must(inputSearchQuery).createQuery();
    }

    protected QueryBuilder getNGramQueryBuilder(String[] searchFields) {
        if (searchFields.length == 0) {
            return null;
        }
        EntityContext entityContext = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(clazz);
        for(String field : searchFields) {
            entityContext = entityContext.overridesForField(field, "ngram_query");
        }
        return entityContext.get();
    }
}

This gives me the following error when I do a query search.
{message: "HSEARCH000353: Unknown analyzer: 'ngram_query'. Make sure you defined this analyzer.",…}
exception: "RuntimeException"
message: "HSEARCH000353: Unknown analyzer: 'ngram_query'. Make sure you defined this analyzer."
I found this from the official document.
You can use @AnalyzerDef on any:
@Indexed entity regardless of where the analyzer is applied to;
parent class of an @Indexed entity;
package-info.java of a package containing an @Indexed entity.
Since I am seeing the unknown analyzer, I guess the class where I tried to overwrite with "ngram_query" analyzer has no visiblity on this analyzer?

A: Yes, you can create ngrams for each word: use a WhitespaceTokenizerFactory for your tokenizer, and add NGramFilterFactory to your token filters (note it's not the same class you mentioned: it's a token filter, not a tokenizer).
You will also need to use a different analyzer at query time, one that does not create ngrams. Otherwise a user typing "manhantan" may get a match for documents containing "man", for example.
See https://stackoverflow.com/a/56107399/6692043 for information on how to do that.
Note that ngrams can lead to very large indexes, especially if you're not careful with the value of the "minGramSize" and "maxGramSize" parameters.
Another solution would be to use your original analyzer and a wildcard query, but unfortunately it ignores analysis and can be quite slow when using leading wildcards (which is what you need here).
    protected Query inputFilterBuilder() {
        String[] searchableFields = getSearchableFields();
        if(searchableFields.length == 0) {
            return null;
        }
        TermMatchingContext termMatchingContext = queryBuilder.keyword().wildcard().onField(searchableFields[0]);
        for(int i = 1; i < searchableFields.length; i++) {
            termMatchingContext = termMatchingContext.andField(searchableFields[i]);
        }
        return termMatchingContext
            .matching(("*" + searchRequest.getQuery() + "*").toLowerCase()).createQuery();
    }

Note the code above will only work if there is a single search term. As soon as there are spaces in searchRequest.getQuery(), you won't get any result. There can be spaces in the indexed text, however, which is what you wanted, if I understood correctly.


text:
Q: Generate colums w/ Angular Material using an *ngFor I'm using a tutorial that takes data from the component.
Here I have to insert every column by myself, instead I want to generate them like the example on the bottom of the page.

    <ng-container matColumnDef="id">
       Id
       {{user.id}}
    </ng-container>

    <ng-container matColumnDef="firstName">
       Name
       {{user.firstName}}
    </ng-container>

Here I wasn't using Material, I generated every column from a string[]:
getColumns(): string[] {
  return ['id', 'firstName', 'lastName', 'age'];
}//this is in my service

So if I delete or modify a column in my service, it will be removed in the table.

  {{col}}

  {{user[col]}}

How can I apply the same method in the ng-container, th and td's?

A: You Can Use Like This.

                                        Product
                                        Qty
                                        Amount

                                        {{kotitems.Product}}
                                        {{kotitems.Qty}}
                                        {{kotitems.Amt}}

                                        Total
                                        {{getSum()}}


text:
Q: R MySQL data base package I am trying to install RMySQL package, but cannot find it via the package search utility in RStudio not can I install it via command line .
Do I have the wrong package
Version details:
R 3.0.2
RStudio 0.98.501
thanks