text:
Q: How to populate join table for a HABTM relationship Rails 3, postgresql So after searching long and hard for information that can help us, we've found it difficult to find an answer we can work with.
Our problem is that we have two tables joined through a HABTM relationship called Schools and Organizations. A school is created first, and then an Organization takes the list of schools, allows the user to select one, and then populates a third table OrganizationsSchools with both the school_id and the organization_id.
Models for the three are as follows:
Schools model:
class School < ActiveRecord::Base
  has_and_belongs_to_many :organizations, :join_table => 'organizations_schools'
  attr_accessible :name
  validates :name, :presence => true
end

Organizations model:
class Organization < ActiveRecord::Base
  has_many :materials
  has_many :users
  has_and_belongs_to_many :causes
  has_and_belongs_to_many :schools, :join_table => 'organizations_schools'
  attr_accessible :name, :unlogged_books_num, :id

  validates :name, :presence => true
end

The form for Organizations:
<%= form_for(@organization) do |f| %>
  <% if @organization.errors.any? %>

<%= pluralize(@organization.errors.count, "error") %> prohibited this organization from being saved:

      <% @organization.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

<% @schools = School.all %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :unlogged_books_num %>

    <%= f.number_field :unlogged_books_num %>

    <%= f.label 'School' %>

    <% school_id = nil %>
    <%= collection_select(nil, school_id, @schools, :id, :name) %>

    <%= f.submit %>

<% end %>

And finally, the create function in our Organizations controller
class OrganizationsController < ApplicationController
  .
  .
  .
  def create
    @organization = Organization.new(params[:organization])
    org_id = @organization.id
    school_id = @organization.school_id
    @org_school = OrganizationsSchool.create(:organization_id => org_id, :school_id => school_id)

    respond_to do |format|
      if @organization.save
        format.html { redirect_to @organization, notice: 'Organization was successfully created.' }
        format.json { render json: @organization, status: :created, location: @organization }
      else
        format.html { render action: "new" }
        format.json { render json: @organization.errors, status: :unprocessable_entity }
      end
    end
  end
end

All other functions in our controller are restfully created.
Please also know that I'm not the greatest with databases, and though I'm familiar with rails, I'm not by any stretch of the word proficient at using it.

A: In a has_and_belongs_to_many, there wouldn't be a school_id field for Organization.  It sounds like you actually want:
class Organization < ActiveRecord::Base
  belongs_to :school
  ...
end

class School < ActiveRecord::Base
  has_many :organizations
end

if you really want HABTM, then you could write:
@organization.schools << School.find school_id
EDIT:
Obviously your controller code would need additional changes if you swtiched to a has_many relationship


text:
Q: How to reuse server side class in JAX-WS client? I have a class on server side: ForumEntry, and I have a web service which returns a list of ForumEntry:
@WebService(name="ForumGeneral",serviceName="ForumGeneralService")
public class ForumGeneralService {

  @WebMethod
  public List<ForumEntry> getLatestTopics(String keyword,int count){
  ...
  }
}

When using wsimport to generate webservice client, it finishes fine, but a new ForumEntry type's created based on the web service. That makes sense, as a nature of web service is that client and server sides are decoupled.
But what if I want to reuse the server side ForumEntry and avoid a client side dummy class being created?
I found a post: http://jamablog.blogspot.com/2007/08/how-to-make-jax-ws-client-reuse_22.html.
Follow the idea, I added jaxb annotations to my server side ForumEntry class:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "forumEntry", propOrder = {
    "forumId",
    "forumName",
})
public class ForumEntry

then used schemagen to generate the episode file, then passing it to wsimport using -b parameter. But I got problem as the generated episode file has entries for 'forumEntry':
[ERROR] SCD "~forumEntry" didnt match any schema component

I guess it means 'forumEntry's not showing up in WSDL, which is right:
<message name="getLatestTopics">
<part name="parameters" element="tns:getLatestTopics"></part>
</message>
<message name="getLatestTopicsResponse">
<part name="parameters" element="tns:getLatestTopicsResponse"></part>
</message>

So how do all parts fit together here, to reuse the server side class?

A: You should add a ForumEntry class to the schema, so that the client can generate it, and use that generated class on your server side.  Or add a new class to your schema that contains similar data to ForumEntry, and have the server create those objects on response from your ForumEntry objects, and return those created objects instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UDP Multithreading Server Design issue I am writing a program for UDP Multithreading server.I have written quote based on the inputs and psuedo codes which i have taken from the Stack overflow.When i execute my program my computer is hanging up.Could anyone please correct the issue with the below code and provide me optimal solution for writing a UDP server which handles Multithreading.
public class MyownServer extends JFrame{

    private JTextArea jta = new JTextArea();
    public static void main(String[] args) throws Exception {
    new MyownServer();
    }
    public MyownServer(){
         add(new JScrollPane(jta), BorderLayout.CENTER);
         setVisible(true);
         setSize(400, 400);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setTitle("Server");// It is necessary to show the frame here!
        try{
        DatagramSocket firstsocket = new DatagramSocket(8100);;
        int id = 0;
        while (true) {
            byte[] buf = new byte[256];
            DatagramPacket receivePacket =
                     new DatagramPacket(buf, buf.length);
            ClientServiceThread cliThread = new ClientServiceThread(firstsocket, receivePacket);
          cliThread.start();
        }
        }
        catch(IOException ex) {
         ex.printStackTrace();
         }
        }
    }

public class ClientServiceThread extends Thread {
     private JTextArea jta = new JTextArea();
          DatagramPacket packet;;
              boolean running = true;
              DatagramPacket sendPacket;
              DatagramSocket socket;;

              byte[] buf;

              ClientServiceThread(DatagramSocket socket,DatagramPacket packet) {
                  this.socket=socket;
                 this.packet=packet;
              }
                public void run()
                {
                    try {
                     // Compute and process
                        byte[] data = new byte[256];
                        DatagramPacket response = new DatagramPacket(data, data.length);
                        socket.receive(packet);

                     double rate = Double.parseDouble(new String(buf).trim());
                        sendPacket.setAddress(packet.getAddress());
                        sendPacket.setPort(packet.getPort());
                        socket.send(sendPacket);
                        socket.receive(packet);
                        double years = Double.parseDouble(new String(buf).trim());
                        socket.send(sendPacket);
                        socket.receive(packet);
                        double loan = Double.parseDouble(new String(buf).trim());

                        double monthlyPayment = loan * (rate / 1200) / (1 - (Math.pow(1 / (1 + (rate / 1200)), years * 12)));
                        double totalPayment = monthlyPayment * years * 12;

                        sendPacket.setData(new Double((double)(monthlyPayment * 100) / 100.00).toString().getBytes());
                        socket.send(sendPacket);
                        socket.receive(packet);
                        sendPacket.setData(new Double((double)(totalPayment * 100) / 100.00).toString().getBytes());
                        socket.send(sendPacket);
                        socket.close();
                      jta.append("Interest Rate is " + rate + '\n');
                     jta.append("Number Of years " + years + '\n');
                     jta.append("Loan Amount is " + loan + '\n');
                     jta.append("Monthly payment " + monthlyPayment + '\n');
                     jta.append("Total Payment " + totalPayment + '\n');
                     } catch (Exception e) {
                      e.printStackTrace();
                    }
                  }
                  }

I appreciate your help.Thanks in advance.

A: This section just sits there creating thread after thread forever.
            while (true) {
                byte[] buf = new byte[256];
                DatagramPacket receivePacket
                        = new DatagramPacket(buf, buf.length);
                ClientServiceThread cliThread = new ClientServiceThread(firstsocket, receivePacket);
                cliThread.start();
            }

You should use a ThreadPool.

A: Your server socket should wait to receive connections from the clients inside a infinite loop. You do have a loop but you are missing a receive function call in there.
The receive call shall return the client socket on which then you can communicate with the client henceforth.
Here's a complete example for working with DatagramSockets
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html


text:
Q: Linker Double Redirect (IAR EWARM) I have an IAR STM32 project where I am need to wrap a library function with some custom logic. I do not have the ability to recompile the library itself, so what I would like to do is create a function libfunction_shim that calls into the original libfunction. Using the --redirect linker option (--redirect libfunction=libfunction_shim), I can redirect calls to the original function to the shim, including calls inside the library itself. However, I need to call the original function from the shim.
If I add another redirect (--redirect libfunction_original=libfunction), it ends up redirecting libfunction_original to libfunction_shim, rather than the original libfunction. I've tried reordering the redirects, but it does the same thing regardless of order.
The linker log demonstrates this:
Symbol                     Redirected to          Reason
-------------              ------                 ------
...
libfunction                libfunction_shim       command line
libfunction_original       libfunction_shim       command line

What I would like this:
Symbol                     Redirected to          Reason
-------------              ------                 ------
...
libfunction                libfunction_shim       command line
libfunction_original       libfunction            command line

Is it possible to do this using the linker?

A: This is not possible using linker redirects, you have to write your shim function in a specific way. A complete description is available in the manual (pg 225 in the 8.40.1 version) but to summarize: First you name the shim $sub$$libfunction, where libfunction is the name of the function to shadow. From inside the shim you can use $super$$libfunction to call the original version of libfunction. A minimal example is shown below.
extern void $Super$$foo(void);

void $Sub$$foo(void)
{
  $Super$$foo(); /* calls the original foo() function */
}


text:
Q: Adding a Button to JTable before creating the table I'm working on Reflections and Swings for my project. Using reflections I need to get the information of a particular method, and populate a JTable based on its structure.
The table has the following feature:
 Some columns will be named based on the parameter type present in the selected method.
Its the same structre for all the primitive data types(int,float,double,String,long,boolean), only the column names get Changed based on the data type.
The problem I face is when there is a User Defined object inside the method parameter.
In that scenario , I want a JButton instead of empty cell in the row (under that parameter type).
I tried learningTableCellRenderer and CellEditor but nothing helped me because all the tutorials i have seen are based on a Static data(rows and columns). In my case both rows and columns have to be generated dynamically and I need to create the JTable based on my data(dynamically).
I'm trying the following code:
rowData = new Object[1][colData.length];
        rowData[0][0] = "";
        rowData[0][colData.length - 1] = "";

        int i = 1;
        for (Class tempClass : paramType) {
            if (tempClass.getSimpleName().equals("int")
            //Primitives
                    || tempClass.getSimpleName().equals("float")
                    || tempClass.getSimpleName().equals("long")
                    || tempClass.getSimpleName().equals("double")
                    || tempClass.getSimpleName().equals("boolean")
                    || tempClass.getSimpleName().equals("String")){
                rowData[0][i] = "";
            }
            else{
            //User Defined obj
                rowData[0][i] = new JButton();
            }

            i++;
        }

But the output i'm getting is something like this:

Kindly help me and provide me a hint or kind of tutorial so that i can proceed with this problem. I'm working on the swings for the first time.

A: The pictures you posted don't help me since the text to too small for me to read so I'm not sure what you are trying to demonstrate. Make sure the data is readable when you post a question is the data is in fact important to the question.

nothing helped me because all the tutorials i have seen are based on a Static data(rows and columns).

Maybe this example will help. It shows how to dynamically determine the renderer/editor for a cell based on the class of the data in the cell:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class TablePropertyEditor extends JFrame
{
    public TablePropertyEditor()
    {
        String[] columnNames = {"Type", "Value"};
        Object[][] data =
        {
            {"String", "I'm a string"},
            {"Date", new Date()},
            {"Integer", new Integer(123)},
            {"Double", new Double(123.45)},
            {"Boolean", Boolean.TRUE}
        };

        JTable table = new JTable(data, columnNames)
        {
            private Class editingClass;

            public TableCellRenderer getCellRenderer(int row, int column)
            {
                editingClass = null;
                int modelColumn = convertColumnIndexToModel(column);

                if (modelColumn == 1)
                {
                    Class rowClass = getModel().getValueAt(row, modelColumn).getClass();
                    return getDefaultRenderer( rowClass );
                }
                else
                    return super.getCellRenderer(row, column);
            }

            public TableCellEditor getCellEditor(int row, int column)
            {
                editingClass = null;
                int modelColumn = convertColumnIndexToModel(column);

                if (modelColumn == 1)
                {
                    editingClass = getModel().getValueAt(row, modelColumn).getClass();
                    return getDefaultEditor( editingClass );
                }
                else
                    return super.getCellEditor(row, column);
            }

            //  This method is also invoked by the editor when the value in the editor
            //  component is saved in the TableModel. The class was saved when the
            //  editor was invoked so the proper class can be created.

            public Class getColumnClass(int column)
            {
                return editingClass != null ? editingClass : super.getColumnClass(column);
            }
        };

        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
    {
        TablePropertyEditor frame = new TablePropertyEditor();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

Edit:

instead to get a Button, what should i keep

There is no default renderer/editor for a button, so you will need to store a custom object and create a custom renderer/editor.
Read the section from the Swing tutorial on Editors and Renderers for more information.
Then you have to tell the table about your custom objects with code like:
table.setDefaultRenderer(CustomObject.class, new CustomRenderer());
table.setDefaultEditor(CustomObject.class, new CustomRenderer());

You might be able to use the Table Button Column as the renderer/editor.


text:
Q: InvalidArgumentError (see above for traceback): indices[1] = 10 is not in [0, 10) I am using tensorflow 1.0 CPU on ubuntu and python 3.5.
I adapted an example of tensorflow to work on my own dataset https://github.com/martin-gorner/tensorflow-mnist-tutorial
It works fine as long as the number of outputs is under 10. When the number of outputs is above 10,I get the error:
InvalidArgumentError (see above for traceback): indices[1] = 10 is not in [0, 10)

[[Node: Gather_4 = Gather[Tindices=DT_INT64,
     Tparams=DT_FLOAT,
     validate_indices=true,
     _device="/job:localhost/replica:0/task:0/cpu:0"](grayscale_to_rgb, ArgMax_4)]]

Any help?

A: I also came across the same error, and after fiddling with it for 2 days I came to realize there are 2 main reasons this error was getting thrown for my code and I mentioned them below to help anyone struggling with the same problem:

*

*The dimensions of your data and your labels being different

*In my case, the problem was
that when building my vocabulary I have indexed the words from 1 and
not from 0. But the embedded layer starts indexing from 0. So it
kept giving me the mentioned error. I fixed the error by indexing my
vocabulary from 0.
previous code:
dictionary = Counter(words)
sorted_split_words = sorted(dictionary, key=dictionary.get, reverse=True)
vocab_to_int = {c: i for i, c in enumerate(sorted_split_words, 1)}

to fix it I changed the last line to (removed 1):
vocab_to_int = {c: i for i, c in enumerate(sorted_split_words)}

A: The index of the input word exceeds the length of the vocabulary, or the new words that are not included in the vocabulary.
Please try to enlarge vocabulary length.


text:
Q: Does this ul contain an li with a specfic class? In a html page theres a ul which may have an li like this

I try this to find out if the li exists ...
var subList2 = $this.parent().find('span:first .menu-item-text').parent().parent().parent().find('ul');
alert(index + ':' + subList2.has('.static .selected').length);

But it doesn't seem to work?
thanks
p

A: console.log(subList2.find('li.static.selected').length); // check existance
console.log(subList2.find('li').index($('li.static.selected').eq(0))) // find index


text:
Q: Programar online e de forma compartilhada Gostaria de saber se alguém pode me indicar (se existir) alguma plataforma online de programação C++ para que duas ou mais pessoas possam programar em tempo real e compartilhar esse programa entre elas? Tenho um grupo de trabalho e queremos programar e editar ao mesmo tempo, cada um desenvolvendo uma parte do código, de forma online...isso é possível? Podem me dizer uma plataforma?

A:
Repl.it gives you an instant IDE to learn, build, collaborate, and host all in one place.

Repl.it é um ambiente de programação online, possui um debugger e muitas outras ferramentas que ajudam a programar.
É possível utilizar diversas linguagens, incluindo C++, e é possível que duas ou mais pessoas programem no mesmo projeto em tempo real, compartilhando esse programa entre elas e conversando num chat: repl.it - multiplayer.
Vídeo que mostra as funcionalidades do repl.it multiplayer.
Criar uma conta no repl.it é gratuito, no entanto, na versão gratuita, todos programas são públicos. Para que os programas desenvolvidos sejam privados, e só tornados públicos se o utilizador assim o desejar, é necessário pagar pela versão "Premium". De qualquer forma, repl.it é uma ferramenta muito poderosa, mesmo sem a versão "Premium".
O IDE do repl.it tem a seguinte apresentação:

A: o que nós costumamos usar é o versionador de projetos.
Sendo este uma ferramenta que gerencia toda a vida de um dado projeto, guardando o histórico, ou versão, de cada documento do projeto. Lembrando que documento pode ser qualquer coisa, uma imagem, um código, um pdf, etc.
Com isso temos varias ferramentas com o projeto, por exemplo, restaurar arquivos excluídos em qualquer etapa do projeto, decidir o código usar no caso de dois programadores modificarem o mesmo arquivo.
Hoje temos uma muito utilizada e totalmente gratuita, o Git.
"GIT é uma ferramenta de versionamento amplamente utilizada em projetos com grande número de colaboradores, sem contar que é a plataforma na qual roda o GITHUB, serviço online que provê um servidor GIT gratuito para projetos opensource. Assim sendo, este será a ferramenta utilizada no projeto."
Se ainda não conhece, remendo dar uma olhada nesse artigo do próprio site do Git https://github.com/MuvucaGames/Tutoriais/wiki/%5BWIP%5D-Tutorial-completo-sobre-versionamento-com-GIT.


text:
Q: Applying Pandas iterrows function I was wondering whether somebody could please give me some assistance with the Pandas iterrows package.
I'm currently using an iterative function which works but I was wondering whether using iterrows would make it more efficient to avoid a for loop?
import pandas as pd
import numpy as np

dataframe_1 = pd.read_csv("D\data\2018_19.csv")

def append_date_column(df):

df = df.copy()

df['date_column'] = np.nan

date_range = pd.date_range(start = '01/01/2001', periods = 207, freq = 'M').values

for row in range(df.shape[0]):
    date_number = df.loc[row, "income2"]
    if (not pd.isna(date_number)) and date_number < 207:
        date = date_range[int(date_number) -1]
        df.loc[row, 'date_column'] = date

df_with_date_column = df

return df_with_date_column

Thanks!


text:
Q: Check whether a site redirects to a different URL using phantomjs giving errors for specific websites only I am a newbie to frontend development and this question might be trivial. Please bear with me.
 var page = require('webpage').create(),
 system = require('system');

if (system.args.length === 1) {
  console.log('Usage: useragent.js <some URL>');
  phantom.exit();
}

url = system.args[1];
page.settings.userAgent = 'Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC Desire HD A9191 Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1';
page.open(url,function (status) {
    if (status !== 'success') {
            console.log(url+',,Unable to access network');
    } else {
            var redirectUrl = page.evaluate(function () {
            return document.URL;
            });
    }
    phantom.exit();
});

When I run it for http://www.bebloom.com it works fine and redirects to http://mobile.bebloom.com
However, when I run it for http://www.rueducachemire.com, it gives the following error :
    http://www.rueducachemire.com/skin/m/1382954776/js/prototype/prototype.js,/js/lib/ccard.js,/js/prototype/validation.js,/js/scriptaculous/effects.js,/js/varien/js.js,/js/varien/form.js,/js/varien/menu.js,/js/mage/translate.js,/js/mage/cookies.js,/js/droplicious.js,/j    s/seo_link_crypter.js:748
    http://www.rueducachemire.com/:173

A: This is because the webpage you are trying to load has an error.
Try using
page.onError = function (msg, trace) {
    console.log("[ERRO]:"+msg);
    trace.forEach(function(item) {
    console.log('  ', item.file, ':', item.line);
    })
}

And you will know.


text:
Q: show that $I+tT$ is bijective $t>0$. let $T\in L(H)$ such that $\langle Tx,x \rangle \geq 0$ show that $I+tT$ is bijective $t>0$.
how can i prove this using Lax milgram that i'm not familiar with.

A: We have $$\langle (I+tT)x,x\rangle =\|x\|^2+t\langle Tx,x\rangle \ge \|x\|^2$$ Hence $I+tT$ is injective and its range is closed (see the spoiler).

 Indeed, let $(I+tT)x_n\to y.$ Then the sequence $(I+tT)x_n$ satisfies the Cauchy condition. We have $$\langle (I+tT)(x_n-x_m),x_n-x_m\rangle \ge \|x_n-x_m\|^2$$ Thus $x_n$ satisfies the Cauchy condition. Let $x=\lim x_n.$ Then $(I+tT)x_n\to (I+tT)x.$ Therefore $y=(I+tT)x.$

On the other hand if $y\perp {\rm Im}\, (I+tT)$  then
$$0=\langle y, (I+tT)y\rangle \ge \|y\|^2$$ hence $y=0.$ Thus ${\rm Im}\, (I+tT)=\mathcal{H}.$


text:
Q: Python Scrapy XPathSelector I am trying to crawl data from a site using scrapy crawler. How to get <meta itemprop="rvalue" content="4.0"> content value using select()?

A: item['key'] = xpath.select('//meta[@itemprop="rvalue"]/@content').extract()

It'll return a list, so process it with an item loader.


text:
Q: Simple bash script taking too long to execute I wrote the following function in my .bashrc for use instead of rm * :
function re()
{
   cp . -R /home/glset/ritwik/trash/
   rm *
}

It works .. but it is very slow. Even for small files it takes too long to execute. It is always faster to just fire the two commands one after the other which defeats the purpose of the function in the first place. Am I doing something wrong here ? What makes it take longer ?

A: Running the function or running the two commands separately does not make any measurable difference in execution time.
My guess would be that you ran the function, found that it was slow, then tried the commands separately.
If you did that, then it's likely that the first time, the data was not present in the disk cache, so what you measured was the time to load the data from the disk. The second time, the data was already in the disk cache (because you had just accessed it), so you measured the time to copy the data around in memory.
To do proper benchmarks, you need to start all measurements in the same conditions: either you know that all the data is in the cache, or you know that all the data has to be loaded from the disk.

Copying the data and then removing the original is a really weird way of doing this. Run mv instead! It's instantaneous if you've moving the files inside the same filesystem.
Furthermore, rm * is a very unusual command. If you don't need a directory anymore, remove the directory: rm -r somedir or mv somedir ~/trash/.


text:
Q: Holding information in hashtables or arrays then outputting I am developing a program in c# and am not sure what to do about this problem.
In my program, I have a large amount of checkboxes (Yes and No) and when No is selected, a textbox appears prompting the user to write a comment, example below:
private void checkBox48_CheckedChanged(object sender, EventArgs e)
  {
      if (checkBox48.Checked == true)
      {
          // Create an instance of the dialog
          frmInputBox input = new frmInputBox();
          // Show the dialog modally, testing the result.
          // If the user cancelled, skip past this block.
          if (input.ShowDialog() == DialogResult.OK)
          {
              // The user clicked OK or pressed Return Key
              // so display their input in this form.

              problems = problems + "23. Check Outlet Drainage : " + input.txtInput.Text + Environment.NewLine;
              this.txtProblems5.Text = problems;
              txtProblems5.Visible = true;
          }

          // Check to see if the dialog is still hanging around
          // and, if so, get rid of it.
          if (input != null)
          {
              input.Dispose();
          }
      }
  }

However, temporarily I have the user input just writing to a String called problems. I would like to hold each of these values in separate places.
Would hash tables or an array be suitable? (For example txtInput.Text = Problems[40])

A: Either array or hashtable will work. Hashtable may be a bit more developer-friendly and may carry smaller memory footprint. Here is a small example:
private Dictionary<int, string> problems = new Dictionary<int, string>;

// add key value pair
problems.Add(42, "your problem here");

// get value
string value = "";
if (problems.TryGetValue(42", out value))
{
    // the key was present and the value is now set
}
else
{
    // key wasn't found
}

A: If you use an array, it implies you will have to create entries for each text box as per your example.
Out of preference I would probably use a dictionary<string,string> where the key is the control name.
Then, my textbox value could be:
txtProblem1.text = dictionary.ContainsKey(txtProblem1.Name) ? dictionary[txtProblem1.Name] : "";


text:
Q: How do you find an 'M' by 'M' submatrix in the center of an input 'N' by 'N' matrix? (In Matlab) How do I write a function in Matlab to output the M x M submatrix at the center of an N x N input matrix?  The function should have two input arguments—the N x N input matrix (2D array) and the size of the square submatrix, M, to be extracted from the input matrix.  The sole output should be the M x M submatrix at the center of the input matrix.  The function should use for loops to extract the submatrix and not use colon notation or any built-in functions for this part of the code.  The function should work for any square input matrix where N ≥ 3.  If N is even, M should be even.  If N is odd, M should be odd.
Here is a picture of my flowchart so far.

A: Using For-Loops and Offsetting Indexing
Preface:
Here I like to visualize this question as trimming the matrix. The amount to trim I denote in this example is Trim_Amount. The Trim_Amount dictates the size of the sub-matrix and the start point to begin reading/saving the sub-matrix.

Since the trim amount is always taken from each side you can expect the sub-matrix to have dimensions in the form:
Sub-Matrix Width = M - (2 × Trim_Amount)
2 × Trim_Amount will always result in an even number therefore the following can be said:
if M is even → M - (Even Number) → Even Number
if M is odd → M - (Even Number) → Odd Number

Test Output Results:

I recommend going through the code to filter through any unexpected issues.
Full Script:
Dimension = 7;
Matrix = round(100*rand(Dimension));
Trim_Amount = 1;

[Sub_Matrix] = Grab_Sub_Matrix(Matrix,Trim_Amount);
Matrix
Sub_Matrix

%Function definition%
function [Sub_Matrix] = Grab_Sub_Matrix(Matrix,Trim_Amount)

%Minimum of M must be 5 since N >= 3%
[M,~] = size(Matrix);

%Ensuring the trimming factor does not go over possible range%
Max_Trimming_Factor = M - 3;
if(Trim_Amount > Max_Trimming_Factor)
Trim_Amount = Max_Trimming_Factor;
end

%Fill in the boundaries%
Row_Start_Limit = Trim_Amount + 1;
Column_Start_Limit = Trim_Amount + 1;

%Creating sub-matrix based on amount of trimming%
Sub_Matrix = zeros(M-(2*Trim_Amount),M-(2*Trim_Amount));

for Row = 1: length(Sub_Matrix)
   for Column = 1: length(Sub_Matrix)

%    fprintf("(%d,%d)\n",Row,Column);
   Sub_Matrix(Row,Column) = Matrix(Row + Row_Start_Limit-1,Column + Column_Start_Limit-1);

   end
end

end

Ran using MATLAB R2019b


text:
Q: How to improve performance of unwind operation stage in mongoDb The aggregation is taking very long time when the total number of records increases.
[{
        "$unwind": {
            "path": "$arrays1",
            "preserveNullAndEmptyArrays": true
        }
    }, {
        "$unwind": {
            "path": "$arrays2",
            "preserveNullAndEmptyArrays": true
        }
    }, {
        "$project": {
            "_id": 0
            "field1": "$field1",
            "field2": "$field2",
            "field3": "$arrays1",
            "field4": "$arrays2",
            .......
        }
    },
    {
       "$out" : "AggregatedData"
    }
]

As the total number of records in the collection reached 3 Million+, the aggregation is taking more than 30 minutes to complete. How can I improve the performance of this aggregation?


text:
Q: While loop keeps repeating itself when it should break My goal is to create a pre-written code - or function - that I can apply to multiple questions, where I only need to fill in the information shown on the lower half. The top half code must remain general, because I do not want to replace pieces of the code every time I use it, and would rather have it do so automatically, making it Reusable.
At the moment my code keeps repeating itself even when I type in the correct answers ('Fully', 'Partially', 'None')
def enter_preset_option():
    global subj_desc
    subj_desc = input(question)
    i = 0
    while i < len(options):
        if str(subj_desc.lower()) == options[i]:
            print("Great!")
            break
        else:
            print("Invalid input. Please try again!")
            i += 1
            enter_preset_option()

question = "Is the property fully fenced or partially fenced? (Answer 'Fully', 'Partially' or 'None'): "
options = ['fully', 'partially', 'none']
attribute = "Fenced"
enter_preset_option()
fenced = subj_desc
print(fenced)


text:
Q: React - ES6 - this keyword and arrow function I have written a simple react code that just increases the value of 'numbers' when clicking on the button. It works well.
import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numbers: 1
    };
  }

handleClick = () =>{
  this.setState({
    numbers: this.state.numbers+1
  })
}

  render() {
    return (

Incrementer

        <input type="submit" name="submit" value="increment" onClick={this.handleClick}/>

{this.state.numbers}

    );
  }
}

I have a query regarding the line:
<input type="submit" name="submit" value="increment" onClick={this.handleClick}/>

When I change the above line as shown below, it still works:
<input type="submit" name="submit" value="increment" onClick={() => this.handleClick()}/>

But, if I change it to
onClick={this.handleClick()}

or
onClick={handleClick()}

or
onClick={function clickFunction(){this.handleClick()}}

it does not compile.
onClick={() => this.handleClick()}
I'm not able to understand the difference. Kindly help.


text:
Q: How to accept both touch events and mouse events to detect when a control has been clicked? I have made a virtual keyboard which works fine when using a mouse. However, I am having difficulty getting it to work properly on a touch screen.
For normal operation it works ok. I press the screen and release. This raises a MouseDown event followed by a MouseUp event. This is ok.
I then wanted to add a popup on a key which is trigged by pressing and holding for 500ms. With a mouse this is not a problem but I now see that the mouse events triggered by a touch are only raised after the touch is released. There is no possibility to trigger the popup up after a delay.
Next I added TouchListeners to the virtual keys and thought the problem is solved until I realised that the mouse events still get raised causing 2 'key' presses - one from the touch and one from the mouse.
I would like to keep both options open so that either the touch screen can be used or the mouse. So my question is: how can I prevent the mouse events being raised if I have already handled the events using the TouchListener?
(Using eclipse kepler with Java7 on Windows 10)
TouchListener touchListener = new TouchListener() {
    boolean down = false;
    @Override
    public void touch(TouchEvent e) {
        for (Touch t : e.touches) {
            if(t.primary) {
                if((t.state & SWT.TOUCHSTATE_DOWN) == SWT.TOUCHSTATE_DOWN) {
                    if(!down) {
                        down = true;
                        onKeyDown();
                    }
                }
                if((t.state & SWT.TOUCHSTATE_UP) == SWT.TOUCHSTATE_UP) {
                    if(down) {
                        down = false;
                        onKeyUp();
                    }
                }
            }
        }
    }
};
MouseAdapter mouseListener = new MouseAdapter() {
    @Override
    public void mouseDown(MouseEvent e) {
        onKeyDown();
    }

    @Override
    public void mouseUp(MouseEvent e) {
        onKeyUp();
    }
};

Label myKey = new Label(panel, 0);
myKey.setTouchEnabled(true);
myKey.addMouseListener(mouseListener);
myKey.addTouchListener(touchListener);

A: I think it would be easiest to handle this at a higher level, as a debounce. If you get two onKeyUp() events from one key within a very short time, ignore the second. (Use the Event.time field rather than the time when you process the event)


text:
Q: jQuery chained animation without plugin Before with jQuery I could do a chained animation with a delay between like so:
$("#element").delay(45).animate({ }, 45)
             .delay(45).animate({ }, 45)
             .delay(45).animate({ }, 45);

Now since the update to v1.6.1 instead of doing what it did previously, it now skips to the last animation. Ignoring the previous statements. I know I can do an oncomplete callback for each animation but that just get's messy:
$("#element").delay(45).animate({ }, 45, function(){
    $("#element").delay(45).animate({ }, 45, function(){
        $("#element").delay(45).animate({ }, 45);
    })
})

Does anyone know how I can accomplish this in a simple clean way?

A: Edit: added a Fiddle for you to play with
I wrote this piece of code a while ago, perhaps it's useful for you? (sorry for the messy indenting)
/**
 * Queue.js
 *
 * @author Arend van Waart
 *
 *  This will allow for events to be queued by timestamp
 *
 * @example
 *  queue({
 *  1000: function () {
 *       // element a na 10ms uitfaden, en daar 100ms over doen
 *       $('#menu').fadeOut(2000);
 *  },
 *  500: function () {
 *    // na 50 ms element b en c inzoemen
 *    $('#content').slideUp(2000);
 * }
 * });
 */

var queue = function(queue){
    var self = this;
    // queue
    this.queue = queue;
    // time passed is 0
    this.timePassed = 0;
    // time in ms to sleep between checks.
    this.sleep = 100;

    var time = new Date();
    this.lastTime = time.getTime();
    this.iterate = function(){
        var total = 0;
        var time = new Date();

        // how much time has passed since we slept?
        self.timePassed = self.timePassed + (time.getTime() - self.lastTime);
        self.lastTime = time.getTime();
        for (var t in self.queue){
            if (t <= self.timePassed){
                self.queue[t]();
                delete(self.queue[t]);
            }
            total++;
        }

        if (total == 0){
            return;
        }else{
            setTimeout(self.iterate, self.sleep);
        }
    }
    this.iterate();
}

A: Here is the second way as requested. I post it in another answer, because it is more complex, and perhaps less beautiful. To play with it see: http://jsfiddle.net/LMptt/1/
Usage: use a string with + or - to indicate a relative timestamp. The order matters for relative timestamps (relative to the previous action that is). Use "+0" or '-0' for the same timestamp as the previous one. Absolute timestamps (integers) can be put anywhere in the list.
$(document).ready(function ()
{
    queue([
        [2000, function () {  $('.two').slideUp(); }],
        ['-1000', function () {  $('.one').slideUp(); }],
        [3000, function () {  $('.three').slideUp(); }],
        ['+1000', function () {  $('.four').slideUp(); }]
    ]);

});

/**
 * Queue.js
 *
 * @author Arend van Waart
 *
 *  This will allow for events to be queued by (relative) timestamp
 */

 function queue (queue){
    var self = this;
    // queue
    this.queue = queue;
    // time passed is 0
    this.timePassed = 0;
    // time in ms to sleep between checks.
    this.sleep = 100;

    var time = new Date();
    this.lastTime = time.getTime();
    this.iterate = function(){
        var total = 0;
        var time = new Date();

        // how much time has passed since we slept?
        self.timePassed = self.timePassed + (time.getTime() - self.lastTime);
        self.lastTime = time.getTime();

        for (var i in self.queue) {
            if (self.queue[i][0] <= self.timePassed){
                self.queue[i][1]();
                self.queue.splice(i,1);
            } else {
                // added sorting now, so we don't have to evaluate the rest.
                break;
            }
        }

        if (self.queue.length == 0){
            return;
        }else{
            setTimeout(self.iterate, self.sleep);
        }
    }

    this.parseRelative = function ()
    {
        var absoluteQueue = [];
        var lastAbsolute = 0;
        for (var i in queue)
        {
           var absolute;
           var firstChar = String(queue[i][0]).charAt(0);
           if (firstChar == "+" ||  firstChar == "-")
           {
              absolute = lastAbsolute + parseInt(queue[i][0]);
           } else {
              absolute = parseInt(queue[i][0]);
           }
           lastAbsolute = absolute;
           absoluteQueue.push([absolute, queue[i][1]]);
        }
        this.queue = absoluteQueue;
    }
    this.sort = function (a,b)
    {
        return a[0] - b[0];
    }

    this.parseRelative();
    this.queue.sort(this.sort);
    this.iterate();
}


text:
Q: How to set Socket File Descriptor with FD_SET Unix in C / C++ I'm currently working on a socket programming project.
Let's assume:
fd_set fd_in;

Now I would like to set the file Descriptor for the select function:
FD_SET(socket_fd, &fd_in);

Is that the right way ?
Then I use the select function:
int rc = select(socket_fd + 1, &fd_in, NULL, NULL, NULL);

Having done some research I haven't managed to proceed.
I appreciate your support,
Regards, from Brooks

A: The appropriate manual pages are available on line, for example here.
Nevertheless, it might not be clear to you that before adding any file descriptors to your fd_set, you should first clear it:
FD_ZERO(&fd_in);

Then, yes, you use FD_SET() just as you present in the question:

FD_SET(socket_fd, &fd_in);

That assumes that the value of socket_fd is an open file descriptor.
Having done so, it is reasonable to use a pointer to the resulting fd_set as one of the arguments to select(), again as you present:

int rc = select(socket_fd + 1, &fd_in, NULL, NULL, NULL);

Do note that

*

*that particular call registers interest only in the specified file descriptor becoming available for reading (or for accepting a connection if it is a listening socket), not for writing or exceptional conditions.

*you must check select()'s return value and take appropriate action based on the result.  Since you're using only a single fd_set with a single element, without a timeout, you should expect select to return either 1 (when the file descriptor is ready) or -1 (on error).

*generally speaking, you need to set up the fd_set(s) each time you call select.  Except in certain special cases, the contents of the sets after select() returns are often not the same as they were before the call, and in the event that select reports an error then you cannot afterward rely on anything about them at all.  Thus, when select() is called in a loop, which is common, there generally needs to be fd_set setup code in the same loop.


text:
Q: why is my `lyrics` variable returning an empty string outside async/await function i made a request to an api it returns an object it  has property holding a string i stored the string in a variable named lyrics now if i console log the variable inside the async await function it gives the string but if i console.log the variable outside of async/ await it returns an empty string  which is the value of the variable before i assigned the value of the property to it  from the object
let lyrics='';
async function displayLyrics2(url){
const request = await fetch(url);
   const response= await request.json();
   console.log(response)
   lyrics+= response.result.lyrics;
   console.log(lyrics);
   }
displayLyrics2()
console.log(lyrics)


text:
Q: Terminating multiprocess pool when one of the workers found proper solution I've created a program, which can be sum up to something like this:
from itertools import combinations
class Test(object):
    def __init__(self, t2):
        self.another_class_object = t2

def function_1(self,n):
   a = 2
   while(a <= n):
       all_combs = combinations(range(n),a)
       for comb in all_combs:
           if(another_class_object.function_2(comb)):
              return 1
       a += 1
   return -1

Function combinations is imported from itertools. Function_2 returns True or False depending on the input and is a method in another class object, e.g.:
class Test_2(object):

def __init__(self, list):
    self.comb_list = list

def function_2(self,c):
    return c in self.comb_list

Everything is working just fine. But now I want to change it a little bit and implement multiprocessing. I found this topic that shows an example of how to exit the script when one of the worker process determines no more work needs to be done. So I made following changes:

*

*added a definition of pool into __init__ method: self.pool = Pool(processes=8)

*created a callback function:
all_results = []
def callback_function(self, result):
    self.all_results.append(result)
    if(result):
        self.pool.terminate()

*changed function_1:
def function_1(self,n):
    a = 2
    while(a <= n):
       all_combs = combinations(range(n),a)
       for comb in all_combs:
           self.pool.apply_async(self.another_class_object.function_2, args=comb, callback=self.callback_function)
       #self.pool.close()
       #self.pool.join()
       if(True in all_results):
           return 1
       a += 1
   return -1

Unfortunately, it does not work as I expected. Why? After debugging it looks like the callback function is never reached. I thought that it would be reached by every worker. Am I wrong? What can be the problem?

A: I did not try your code as such, but I tried your structure. Are you sure the problem is in callback function and not the worker function? I did not manage to get apply_async launch a single instance of the worker function if the function was a class method. It just did not do anything. Apply_async completes without error but it does not implement the worker.
As soon as I moved the worker function (in your case another_class_object.function2) as a standalone global function outside classes, it started working as expected and the callback was triggered normally. The callback function, in contrast, seems to work fine as a class method.
There seems to be discussion about this for example here: Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool?
Is this in any way useful?
Hannu

A:
Question: ... not work as I expected. ... What can be the problem?

It's always necessary to get() the Results from pool.apply_async(... to see the Errors from the Pool Processes.
Change to the following:
pp = []
for comb in all_combs:
    pp.append(pool.apply_async(func=self.another_class_object.function_2, args=comb, callback=self.callback_function))

pool.close()

for ar in pp:
    print('ar=%s' % ar.get())

And you will see this Error:
TypeError: function_2() takes 2 positional arguments but 3 were given

Fix for this Error, change args=comb to args=(comb,):
pp.append(pool.apply_async(func=self.another_class_object.function_2, args=(comb,), callback=self.callback_function))

Tested with Python: 3.4.2


text:
Q: Can I convert a statistical significance into a zscore using a normal distribution? Suppose I want to turn statistical significance of 0.05 into a z-score of ~1.64
Can I use a normal distribution to convert these?

A: Try the quantile function of the Normal distribution:
R> qnorm(c(0.05, 0.95))
[1] -1.64485  1.64485
R>

And if you're wondering, the probability distribution function does the inverse:
R> pnorm( qnorm(c(0.05, 0.95)) )
[1] 0.05 0.95
R>

Any decent numerical / statistical library or language will have these; I use R for convenience. Eg for C++ you have Boost Math.


text:
Q: Pass SparseArray from one activity to other (Android) I want to parse SparseArray from one activity to other i tried many ways all not working
it's my last try
SparseArray sa;
after initialize and add data ....
    Intent intent=new Intent(Main.this,Other.class);
    intent.putExtra("sparsearray",(Serializable)sa);
    StartActivity();

this code do so strange thing it return when go to this line intent.putExtra("sparsearray",sa);
so if a toast under it toast never appear so strange really

A: Just wrap your SparseArray in a Bundle and it should work.
Intent intent = new Intent(context, Activity.class);
Bundle bundle = new Bundle();
bundle.putSparseParcelableArray("SPARSE_ARRAY_KEY",sparseArray);
intent.putExtra("BUNDLE_KEY", bundle);

to get the SparseArray back you will need to unwrap the Bundle again.
Hope this helps.


text:
Q: Stratification of a smooth map I am trying to do an exercise. Namely, find the Thom-Boardman stratification of the smooth map
$f(x,y,a,b,c,d)=x^2y+y^3+a(x^2+y^2)+bx+cy$, where $a,b,c$ are parameters. As I have seen, this is also known as the $D_4$ singularity.
I don't know if the concept of Thom-Boardman symbols is well-known by the math community, but I assume it is. I am trying to follow "Singularities of Differentiable Maps: Volume 1: The Classification of Critical Points Caustics, Wave Fronts". In few words, the set $\Sigma^{i_1}(f)$ consists of all points at which the kernel of $Df$ has dimension $i_1$. Then $\Sigma^{i_1,i_2}(f)=\Sigma^{i_2}(\Sigma^{i_1}(f))$ and so on.
So I started by
$$\dfrac{\partial f}{\partial x}=2xy+2ax+b, \; \dfrac{\partial f}{\partial y}=x^2+3y^2+2ay+c.$$
This means that the critical set of $f$ is the set of points $$\left\{(x,y,a,b,c)\in\mathbb R^5 \, |\,  2xy+2ax+b=0 \text{  and  } 3y^2+2ay+c=0  \right\}.$$ Which I "see" as a $3$-dimensional manifold in $\mathbb R^5$. So according to the book, this is $\Sigma^2(f)$.
Next step is to find the critical set of $\Sigma^2(f)$. So we have
$$D\Sigma^2(f)= \begin{bmatrix}
2y+2a & 2x\\
2x & 6y+2a
\end{bmatrix},
$$
and then $|D\Sigma^2(f)|=12y^2+16ay+4a-4x^2$. So,
$$\Sigma^{2,2}(f)=\left\{ (x,y,a,b,c)\in\mathbb \Sigma^2(f) \, |\, 12y^2+16ay+4a-4x^2=0\right\}.$$
Since $\Sigma^2(f)$ is $3$-dimensional, $\Sigma^2\Sigma^2(f)$ as written above is $2$-dimensional. Following the same ideas I obtain
$$\Sigma^{2,2,2}(f)=\left\{ (x,y,a,b,c)\in\mathbb \Sigma^{2,2}(f)\,|\, x=0 \text{  and  } 3y=-2a \right\}, $$
which is a line. But then, I was expecting to find the origin in the next step. After all, the origin is a critical point of $f$ and I am trying to compute the symbol of $f$ at $0$. However, the next derivative is constant, therefore it corresponds to the symbol $\Sigma^{2,2,2,0}$. So although the origin is an element of $\Sigma^{2,2,2}(f)$ it is not a strata??? I was expecting that the origin was a $0-$dimensional strata with symbol $\Sigma^{2,2,2,2,0}(f)$ but ...
Maybe it is something I am misunderstanding. Could anyone please help me? Am I really doing something wrong?


text:
Q: How to properly unpack Protobuf Any type in PHP I'm desperately trying to check whether an "unknown" protobuf payload wrapped within an Any is some specific type (Heartbeat) and unpack it to a Heartbeat object using the code below. Both Heartbeat and StatusChanged are valid generated Protobuf classes.
/* <external service> */
$event = (new StatusChanged)->setId("testId");

$any = new Any;
$any->pack($event);
$protobufBinaryAny = $any->serializeToString();
/* </external service> */

/* $protobufBinaryAny is the incoming binary data */
$anyEvent = new Any();
$anyEvent->mergeFromString($protobufBinaryAny);

if ($anyEvent->is(Heartbeat::class)) {
    $this->processHeartbeat($anyEvent->unpack());
} else {
   throw new UnknownMessageTypeException($anyEvent->getTypeUrl());
}

When running the following code, I'd expect it to throw a UnknownMessageTypeException, however, I get this:
Call to a member function getFullName() on null.

This error happens at $data->is(Heartbeat::class), since the Heartbeat class obviously couldn't be found in the DescriptorPool.
/**
 * Google\Protobuf\Any
 * https://github.com/protocolbuffers/protobuf/blob/440a156e1cd5c783d8d64eef81a93b1df3d78b60/php/src/Google/Protobuf/Any.php#L315-L323
 */
class Any {
    public function is($klass)
    {
        $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
        $desc = $pool->getDescriptorByClassName($klass);
        $fully_qualifed_name = $desc->getFullName();
        $type_url = GPBUtil::TYPE_URL_PREFIX.substr(
            $fully_qualifed_name, 1, strlen($fully_qualifed_name));
        return $this->type_url === $type_url;
    }
}

However, when explicitly initializing the Heartbeat before, it's working, since Heartbeat is now in the DescriptorPool.
foreach ([
    \GPBMetadata\Heartbeat::class,
    \GPBMetadata\StatusChanged::class,
] as $klass) {
    $klass::initOnce();
}

But this manual initialization thing just feels wrong. Am I supposed to do it like that, or did I just miss a fancy autoloading-feature in the non-existing PHP docs?
For the time being, I wrote an autoloader for this case, but it still just feels not right:
trait HandlesProtobufMessages
{
    function initializeProtobufMessages()
    {
        /** @var \Composer\Autoload\ClassLoader */
        $loader = require(__DIR__.'/../../vendor/autoload.php');

        $classes = array_filter(array_keys($loader->getClassMap()), function ($className) {
            $namespace = "GPBMetadata\\";
            return substr($className, 0, strlen($namespace)) === $namespace;
        });

        foreach ($classes as $class) {
            $class::initOnce();
        }
    }
}

Maybe you have more insights into this protobuf jungle and can help me out here, would be glad!
Thank you in advance


text:
Q: NoSQL tree structure I found several answers to this question, but none matches my problem.
http://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/
Tree structures in a nosql database
Most of these examples model a "is a" graph hierarchy. A shoes is a clothing. The tree is about type specialization.
The few one modeling a "has a" relationship, do not support types.
My original problem comes from modeling financial products. To keep it simple:
http://en.wikipedia.org/wiki/Option_style
Description
Assume a tree where each node is either the right or the obligation to swap the assets represented by the two children nodes.
For instance. European call option on Microsoft stock: " I have the right ( no obligation ) to buy Microsoft stock for 50$, January 10th 2016"
==> the exchange is between $ cash and a stock.
But one can also have a call option on another call option. " I have the right ( no obligation ) to buy the above described option for 11$, June 10th 2015"
The tree
The leaves of the tree MUST be a listed product on some market (stock, bond, rate, listed option ... ), or some aggregation basket of such products.
Each node can be of nearly any type:

*

*Path dependent pay off or not ( Asian, look-back ...)

*Exercise type ( Bermudan, American, European )

*Put/Call

*long/short

and may have very different parameter set based on its type, for example:

*

*Bermudan exercise will require an array of date, others only one maturity date.

So I must model a tree expressing a "has a" relationship ( including basket/index aggregation ) where each node can be of very different nature and have very different parameters. But I must also reflect some sort of type inheritance between my node in my DB structure, an american put option "is an" option.
Constaints

*

*I must have enough information to price the booked products. The Given DB + market data access + choose a pricing model ==> price

*One may assume that ACID aspects will be ensured at code level if needed

*speed is the ONLY measure as long as the above is OK

Question
What are my options ? I'm very open, even to file writing and serialization, or whatever crazy idea you may have.
I just need a big brainstorming of big brains storming.
EDIT: Thanks to Christoph
For inheritance in SQL I usually do this
CREATE TABLE OPTION ("isin", "name", "emitter","typeId"); "use American type id"
CREATE TABLE AMERICAN_OPTION ("isin","foo1", "foo2");

The problem is more about its "down links", for instance my american options underlying are not necessarily simple listed products.
CREATE TABLE ASSET ("uniqueIdentifier,"typeId","name","asset1","asset2");
CREATE TABLE ASSET_TYPE_1 ("uniqueIdentifier","DATA_1",..."DATA_N");
CREATE TABLE ASSET_TYPE_2 ("uniqueIdentifier","DATA_1",..."DATA_N");
CREATE TABLE ASSET_TYPE_1_B ("uniqueIdentifier","DATA_1",..."DATA_N");

....

Where "assets" can be pretty much anythnig. This works in most case but some tricks are needed. For instance, the basket case must be design in the way below described by christoph. For instance, an american option on a basket, asset1 is cash, asset2 is of type basket and modeled like this.
ASSET( "XYZT12345", "American", "XYZT__1", "XYZT__2", ...[common admin data(e.g.tradedate,valuationCurrency...] )
ASSET( "XYZT__1", "cash", "NULL", "NULL" )
ASSET( "XYZT__2", "basket", "NULL", "NULL" )

CASH_ASSET( "XYZT__1", "10$" )
BASKET_ASSET( "XYZT__2", "Ric_1" )
BASKET_ASSET( "XYZT__2", "Ric_2" )
BASKET_ASSET( "XYZT__2", "Ric_3" )
VANILLA_OPTION_ASSET( "XYZT12345", "MaturityDate", "strikePrice" ); // both european and american fit in there

if option had been bermudean/carraibean, I probably would have needed a dateSet model table

A: Modelling an "is a" relationship in databases can be achieved by normalizing the data, i.e. if you have an OPTION table and an AMERICAN_OPTION table then they could look like this:
(I am switching to pseudo-SQL but the same works for nosql):
CREATE TABLE OPTION ("isin", "name", "emitter");
CREATE TABLE AMERICAN_OPTION ("isin", "name", "emitter", "foo1", "foo2");

Here, you could interprete this as "AMERICAN_OPTION derives from OPTION and has additional members 'foo1' and 'foo2'".
Alternatively, you can just put everything in one table and leave the unused columns as NULL.
Modelling a "has a" relationship is usually done by creating database indices and relationships between them.
An ETF Basket "has a" 1:n relationship to other products. Make sure that your NoSQL database supports 1:n relationships in some way or the other. Since many NoSQL databases do not support indices out of the box, you might have to model these relationships in your application. This is usually not a big deal if the relationships are not too complex. You can search wikipedia for "Star Schema" for more information.
CREATE TABLE BASKET ("id", "name", "emitter");
CREATE TABLE INSTRUMENT ("id", "name", "emitter");
CREATE TABLE BASKET_TO_INSTRUMENT("etf_id", "instrument_id"); <-- your 1:n relationship

If you would use a graph database then some of this functionality might come out of the box, but i do not have experience with graph databases. I do not think that they're faster, though.
In review it seems that modelling for a NoSQL database is not different from modelling for a SQL database, but there's more work for you as an application developer.
Best regards,
Christoph


text:
Q: How can I tell selenium webserver standalone which firefox version to use? Usually I start my selenium server like this:
java -jar -Dwebdriver.firefox.profile=MyProfile /usr/local/bin/selenium-server-standalone-3.0.1.jar
My programming language is php, so I use mink in which I initialize the Selenium2Driver. By executin my phpunit tests everything works fine, my firefox is started and all the tests run as they should. But selenium always starts my installed firefox version.
How can I start a standalone version? Is there a parameter telling selenium which firefox to start? Or do I have tell mink which one I want to use?

A: Try this:
java -jar -Dwebdriver.firefox.bin="C:\WhateverFolder\youhaveFFON\firefox.exe"


text:
Q: Java c14N Canonicaliser - Attribute name order is in the wrong order Java c14n Canonicalizer is switching up the attribute order of the canonicalized XML assertion.
The canonicalizer is outputting the following string post canonicaliztion:
<saml:Assertion ID="_llhn27aoVN60ug" IssueInstant="2021-11-26T22:10:37.067073Z" Version="2.0" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion
However, according to the canonicalizer documentation , xmlns:saml attribute should come before the SAML: Assertion ID attribute.
This change in the ordering of the attributes is preventing the accurate calculation of the digest value.
I am using the following canonicalizer:
org.apache.xml.security.c14n.Canonicalizer
Does anyone have any idea on as to how this can be fixed ?


text:
Q: Inspecting the values of constant or variable tensors during debug I implemented a model in TensorFlow (Python) that I previously programmed in C++ using Eigen, where it worked as expected. But the model is not working as expected in Python, and it's probably because I am defining tensors incorrectly or I am mixing up dimensions.
I am trying to get a feel for the problems by using Visual Studio's (2017) debugger (if a different IDE is better for this then I'm all ears, but I would prefer to stick with VS), but tensors do not evaluate to anything - and I can understand this because the tensor defines an operation and not a data object (well it only produces a data object after calling a session.run).
However, constant and variable tensors - and any other tensors built solely on top of such tensors - come with predefined data. So hey, why not be able to inspect the value through the debugging UI?
So my question: is there a way to inpect the data with some extension?
For example, if I was working in C++ and with Eigen, I can use Eigen.natvis as described here. Anything similar for TensorFlow? It's not just a matter of seeing the evaluated value, either. It would be nice to see things like the shape, etc... while debugging.
I would also be open to other debugging techniques of TensorFlow code, if anyone has a good suggestion.

A: TensorFlow includes tfdbg, a debugger for TensorFlow models, where you can step through each execution step, check values, stop on NaN, etc. See the programmer's guide TensorFlow Debugger and The Debugger Dashboard for more information.
tfdbg can be a bit cumbersome to setup and use though. A quick alternative to check intermediate values is to use tf.Print operations. TensorFlow includes a few other debugging operations that you may find useful to check for some basic things.
EDIT: Another tool that can be useful is eager execution. This allows you to use TensorFlow operations as if they were regular Python operations (they return the result of the operation instead of the graph object), so it is a good way to check if some particular code does what you expect.


text:
Q: How to debug React Native app with WebStorm? I am new to React Native. I am stuck with debugging. What is the standard way of debugging apps? I mean how should I configure WebStorm debugger for it to connect to the running app and stop on breakpoints I put in IDE?
And is there a way to use WebStorm debugger alongside Flipper (use it instead of Chrome)?
I currently use RN 0.70.6


text:
Q: Disabling or Enabling a Sub-item in Strip-Menu Please, I want to disable or enable a sub item of menu strip through code. How can I do that, please?
Have a look at the following picture:

A: In code, set the Enable property of that menu strip to false to disable, true to enable:
fichierMenuStrip.Enabled = false;


text:
Q: wordpress mu domain mapping problem i installed WordPress mu and WordPress mu domain mapping plugin but the only problem that i have is that i cant park a domain to use for main domain for example my main domain is foo.com and i want the users to redirect to foo.com by entering bar.com to but after i park bar.com using cpanel it redirects to foo.com/wp-signup.php?new=bar.com
I'm currently using cpanel
+ WordPress network 3.2.1 + WordPress mu domain mapping plugin

A: I think you may using shared hosting , If yes then you can only do it with your parent domain

A: Another method may be to simply direct an A record for bar.com to point to the IP of foo.com web host.
There is actually no use of Domain Mapping in this case as it is a single site. The domain mapping plugin is made for Wordpress MU (Multiple Users) in mind, ie. different sites on different domains with only 1 wordpress installation on the server.

A: This is a very late reply, but I share the solution with others who have the same problem
This problem might be related to some fields in database, make sure that in the wp_options table, the "option_name" siteurl is set to the right url site, the same for the option_name "home" must be set to the same url site
If the problem is not resolved, then check wp_blogs table, and verify the domain value is well set
Kind regards


text:
Q: Javascript to html tag ~ passing a variable So my question is, how do I pass variables to javascript functions through html input boxes?
Like, let's say I have a function:
function Call(number, text, callerID, CallerIDName, PassCode)

How would I make an input box in html so that when the user submits a value into the box, it would set the variable for that corresponding box?
All help is appreciated, thanks!

A: Let's say you have an input tag for the "number" parameter:
<input type="text" id="number" />

You can then obtain the value of the field like this;
document.getElementById("number").value

You can find a few examples here. Let me know if I misunderstood your question.

A: Try something like this...
    Name: <input type="text" id="number">

    Text: <input type="text" id="text">

    Caller Id Name: <input type="text" id="CallerIDName">

    Passcode: <input type="text" id="Passcode">

    <button onclick="Call();">Click to Call</button>


text:
Q: Correct way to define Model class, and Dropdown Selected Index change I have to bind a dropdown for country and after selecting the country state should be automatically populated in second dropdown list.
I have defined Model Class in following way.
public class Country
{
    public string Code { get; set; }
    public string Name { get; set; }
}

public class State
{
    public string Code { get; set; }
    public string Name { get; set; }
    public Country CountryName { get; set; }
}

Q1. Is this the correct way to define Model Class?
After this I have a view
  @Html.DropDownListFor(Model => Model.Country,new SelectList(ViewBag.Countries,"Code","Name"))

Q2. How and where should I write code to get states of selected country. (I have a method to get States when Country Code is passed as parameter)
public List<State> GetStates(string CountryCode)

A: Q1:
Your models look correct although I would change the following:
public Country CountryName { get; set; }

to
public Country Country { get; set; }

for better readability.
Q2:
One approach would be to write a controller action to return a list of states based on a country code in JSON format and call this controller action via AJAX when a country is selected.
Controller Action:
public ActionResult GetStates(string countryCode)
{
    var states = _statesService.GetStatesByCountry(countryCode)
                     .OrderBy(x => x.Name.ToUpper());

    return Json(states.Select(x => new { value = x.Code, text = x.Name }));
}

Javascript:
$("#countryDropdownId").on("change", function () {
    var countryCode = $("#countryDropdownId option:selected").val();

    $.getJSON(
        "@Url.Action("GetStates")",
        { countryCode: countryCode },
        function (states) {
            var statesDropdown = $("#statesDropdownId");

            statesDropdown.empty();

            $.each(states, function(index, state) {
                statesDropdown.append($("<option />", {
                    value: state.value,
                    text: state.text
                }));
            });
        }
    );
});


text:
Q:  component in React not printing to screen So I'm trying to make my own chat app with react.js, next.js and firebase.
Everything was going fine but when I compiled my app for web the  box witch was supposed to hold the messages didn't print to the screen.
I tried console logging the messages and the sender and it worked just how I wanted it to. I don't know what's the problem
This is the code for the function with the messages:
export default function Chat() {
    const router = useRouter();
    const { id } = router.query;

    const [user] = useAuthState(auth);

    const q = query(collection(db, `chats/${id}/messages`), orderBy("timestamp"));
    const [messages] = useCollectionData(q);

    const [chat] = useDocumentData(doc(db, "chats", id));
    const bottomOfChat = useRef();

    console.log(messages);

    const getMessages = () => {
        messages?.map(msg => {
            const sender = msg.sender === user.email;
            console.log(msg.text, msg.sender);

            return (
                <Flex key={Math.random()} alignSelf={sender ? "flex-start" : "flex-end"} bg={sender ? "blue.100" : "green.100"} w="fit-content" minWidth="60px" borderRadius="lg" p={3} m={1}>
                    <Text>{msg.text}</Text>
                </Flex>
            );
        });

        useEffect(() => {
            setTimeout(
                bottomOfChat.current.scrollIntoView({
                    behavior: "smooth",
                    block: 'start',
            }), 100)
        , [messages]});
    };

    return (
        <Flex
            h="100vh"
            bg="#323232"
        >

                <title>ChatApp</title>

            <Flex
                flex={1}
                direction="column"
            >
                <Flex
                    flex={1}
                    direction="column"
                    pt={4}
                    mx={5}
                    overflowX="scroll"
                    sx={{scrollbarWidth: "none"}}
                >
                    {getMessages()}

                </Flex>
            </Flex>
        </Flex>
    )
}


text:
Q: Getting Too many Email Invocations: 11 for the test class Getting Too many Email Invocations: 11 error..
have no idea to resolve that error
Any help is much appreciated.
This class is used to send email notification to groups when a case created/updated
apex class

public
with sharing class CaseEmailService{

    public
    static void sendEmailonInsert(List<Case> newCaseList){
        Map<Id,Product_and_Owner_Settings__mdt> prodMap = new Map<Id,Product_and_Owner_Settings__mdt>();

        String prdQueueID;
        List<Product_and_Owner_Settings__mdt> listEmailDomain =
            [SELECT Id,
                    MasterLabel,
                    ProductId__c,
                    Queue_ID__c
              FROM Product_and_Owner_Settings__mdt
                    WITH SECURITY_ENFORCED];

        for(Product_and_Owner_Settings__mdt mdtList: listEmailDomain){
             prodMap.put(mdtList.Queue_ID__c,mdtList);
         }
        //To fetch the Org Default Address
        OrgWideEmailAddress[] owea = [SELECT Id from OrgWideEmailAddress WITH SECURITY_ENFORCED LIMIT 1];

        //TO fetch the Email Template Name
        EmailTemplate emailTemplate = [SELECT Id,Subject,Description,HtmlValue,DeveloperName,Body from EmailTemplate WHERE DeveloperName ='Case_Creation_Email_Template' WITH SECURITY_ENFORCED];
        //List<Messaging.SingleEmailMessage> allmails = new List<Messaging.SingleEmailMessage>();
        for(Case c : newCaseList){
             System.debug('1.Number of Queries used in this apex code so far: ' + Limits.getQueries());
             System.debug('2.Number of rows queried in this apex code so far: ' + Limits.getDmlRows());
              if(string.valueof(c.OwnerId).startsWith('00G') && prodMap.containsKey(c.OwnerId)){
                  prdQueueID = c.OwnerId;
              }
            if(prdQueueID !=null && c.ownerid == prdQueueID){
                List<Messaging.SingleEmailMessage> allmails = new List<Messaging.SingleEmailMessage>();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setSaveAsActivity(false);
                    mail.setToAddresses(getReciepientEmails(prdQueueID));

                    mail.setOrgWideEmailAddressId(owea[0].id);

                    String Casedescription;
                    if(c.Description !=null){
                         Casedescription = c.Description;
                    }else{
                         Casedescription='';
                    }
                    mail.setSubject('[Awesomizer Case Notification] Case assigned to '+c.Case_Owner_Name__c+ 'queue needs attention');
                    String body = 'The following Case was just added to '+c.Case_Owner_Name__c+' queue and needs attention

';
                    body += 'Case #:'+c.CaseNumber+ '
';
                    body += 'Subject :'+c.Subject+ '
';
                    body += 'Description :'+Casedescription+'

';
                    body += 'Click on the link to access the case:'+System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+c.Id+'
';
                    mail.setHtmlBody(body);

                   allmails.add(mail);
                Messaging.SendEmailResult[] results = Messaging.sendEmail(allmails);
                if(results[0].success){
                    system.debug('****Email sent***');
                }else{
                    system.debug('****Email not sent***');
                }
            }

        }

    }

    public
    static void sendEmailonUpdate(List<Case> newCaseList, Map<Id, Case> oldMap){
        Map<id,Product_and_Owner_Settings__mdt> prodMap = new Map<Id,Product_and_Owner_Settings__mdt>();
        Map<Id,Product_and_Owner_Settings__mdt> prodMap1 = new Map<Id,Product_and_Owner_Settings__mdt>();

        String prdQueueID;
          List<Product_and_Owner_Settings__mdt> listEmailDomain =
            [SELECT Id,
                    MasterLabel,
                    ProductId__c,
                    Queue_ID__c
              FROM Product_and_Owner_Settings__mdt
                    WITH SECURITY_ENFORCED];

        //To fetch the product and QueueID configuration
        for(Product_and_Owner_Settings__mdt mdtList: listEmailDomain){
                prodMap.put(mdtList.Queue_ID__c,mdtList);
        }
        //To fetch the Org Defulat Address
         OrgWideEmailAddress[] owea = [SELECT Id from OrgWideEmailAddress WITH SECURITY_ENFORCED LIMIT 1];
        //To Fetch the Custom Email Template
        //EmailTemplate emailTemplate = [SELECT Id,Subject,Description,HtmlValue,DeveloperName,Body FROM EmailTemplate WHERE DeveloperName ='Notify_Queue_Members_for_Case_Updation' WITH SECURITY_ENFORCED];

        for(Case c : newCaseList){
            if(c.ownerId != oldMap.get(c.Id).ownerId && string.valueof(c.OwnerId).startsWith('00G'))
                if(prodMap.containsKey(c.OwnerId)){
                     prdQueueID = c.OwnerId;
                }

             if(prdQueueID !=null && c.ownerid == prdQueueID){
                List<Messaging.SingleEmailMessage> allmails = new List<Messaging.SingleEmailMessage>();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setSaveAsActivity(false);
                    mail.setToAddresses(getReciepientEmails(prdQueueID));

                    mail.setOrgWideEmailAddressId(owea[0].id);

                    String Casedescription;
                    if(c.Description !=null){
                         Casedescription = c.Description;
                    }else{
                         Casedescription='';
                    }
                    mail.setSubject('[Awesomizer Case Notification] Case assigned to '+c.Case_Owner_Name__c+ 'queue needs attention');
                    String body = 'The following Case in '+c.Case_Owner_Name__c+' queue received a new update and needs attention

';
                    body += 'Case #:'+c.CaseNumber+ '
';
                    body += 'Subject :'+c.Subject+ '
';
                    body += 'Description :'+Casedescription+'

';
                    body += 'Click on the link to access the case:'+System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+c.Id+'
';
                    mail.setHtmlBody(body);
                 allmails.add(mail);
                Messaging.SendEmailResult[] results = Messaging.sendEmail(allmails);
                if(results[0].success){
                    system.debug('****Email sent***');
                 }else{
                    system.debug('****Email not sent***');
                }
            }
        }
    }
    public
        static List<String> getReciepientEmails(Id prdQueueID){
           List<String> ReciepentEmais = new List<String>();
            Set<Id>userIds = getGroupEmails(prdQueueID);
            system.debug('1111userIds'+userIds);
           for(User u: [SELECT Id,Email,isActive FROM User WHERE Id In:userIds and isActive=true WITH SECURITY_ENFORCED]){
            if(u.Email !=null){
             ReciepentEmais.add(u.email);
           }
         }
          return ReciepentEmais;
        }

   public
      static Set<Id> getGroupEmails(Id queueId){

        Set<Id>userIds = new Set<Id>();
        Set<Id>groupIds = new Set<Id>();
        groupIds.add(queueId);
        do {
            Set<Id> tempGroupIds = new Set<Id>();
            for(GroupMember objGM : [ SELECT UserOrGroupId FROM GroupMember WHERE GroupId IN:groupIds WITH SECURITY_ENFORCED] ) {
                String strUserOrGroupId = objGM.UserOrGroupId;
                if (strUserOrGroupId.startsWith('005')){
                    userIds.add(objGM.UserOrGroupId );
                 }
                else{
                    tempGroupIds.add(objGM.UserOrGroupId);
                }
            }
             system.debug('userIds111'+userIds);
             system.debug('tempGroupIds'+tempGroupIds);

            groupIds = tempGroupIds;

        } while (groupIds.size() > 0);{
            return userIds;
        }

    }

}```

A: You are facing to the System.LimitException. This usually happens when you do smth in a loop. In your case you are sending emails for each Case cycle. You need to put all emails together and send at once after the for cycle.
Initialize a collection before for
 Messaging.Email[] messages = new Messaging.Email[0];

Instead of
 Messaging.SendEmailResult[] results = Messaging.sendEmail(allmails);

You need to add a message to a list
  messages.add(mail);

And after for clause add
 Messaging.sendEmail(messages);


text:
Q: Replacing a list of indices with a string in python I have a set of indices in a list:
[2 0 3 4 5]

And I want to replace them by values stored in another list:
[a b c d e f g]

And output:
[c a d e f]

I tried this code:
for line in indices:
    print(line)
    for value in line:
        value = classes[value]
    print(line)
    break

which prints the original list twice. Is there a way to replace the elements or am I forced to create a new list of lists?

A: This looks like a good place to use a list comprehension, try this - the idiomatic solution:
idxs  = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

[chars[i] for i in idxs]
=> ['c', 'a', 'd', 'e', 'f']

Of course, we could do the same using explicit looping as you intended, but it's not as cool as the previous solution:
ans = []
for i in idxs:
    value = chars[i]
    ans.append(value)

ans
=> ['c', 'a', 'd', 'e', 'f']

And as a final alternative - I don't know why you want to "replace the elements" in the input list (as stated in the question), but sure, that's also possible, but not recommended - it's simpler and cleaner to just create a new list with the answer (as shown in the two previous snippets), instead of changing the original input:
for pos, val in enumerate(idxs):
    idxs[pos] = chars[val]

idxs
=> ['c', 'a', 'd', 'e', 'f']

A: idxs  = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
map(lambda x : chars[x],idxs)
=> ['c', 'a', 'd', 'e', 'f']

Or
reduce(lambda x,y: x+[chars[y]],idxs,[])
=> ['c', 'a', 'd', 'e', 'f']

A: you can also use chr() function which converts int to characters(ascii table)
>>> a = [2 0 3 4 5]
>>> [chr(i+97) for i in a]
['c', 'a', 'd', 'e', 'f']


text:
Q: What is the difference between a "node stream" and a "filter stream"? I am having difficulty understanding the differences between "node streams" and "filter streams".
I already saw this question.

Node streams {Data sink stream}

*

*Contain the basic functionality of reading or writing from a specific location.

*Types of node streams include files, memory and pipes.

Filter streams {Processing stream}

*

*Layered onto node streams between threads or processes.

*For additional functionality – altering or managing data in the stream.

Can anyone provide some examples to explain the differences more clearly?

A: Node is more like nodeJS while filter is just String function filtering out texts.