text:
Q: MEVN stack unable to deploy I have a project where I try to locally and on Heroku run a MEVN application. Both are not working at the moment.
I have my server.js file in the main folder. Then inside the 'client' folder is the Vue 3 project. Inside there I have run npm run build which created a dist folder containing the index.html file.
When I run both locally and on Heroku I can go to '/api/users' and the JSON is shown in the browser. But when I navigate to '/'
I have tried changing the public in the server.js to dist but this did not fix the problem.
I get the following error: Error: ENOENT: no such file or directory, stat /Users/stephen/Documents/stephen/project/client/build/index.html
My server.js file looks like this:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");

const app = express();

//Bodyparser Middleware
app.use(bodyParser.json());

app.enable("trust proxy");
app.use(cors());

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Credentials", true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
  next();
});

//DB Config
const db = require("./config/keys").mongoURI;

//Connect to Mongo
mongoose
  .connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("MongoDB Connected"))
  .catch((error) => console.log(error));

app.get('/api/users', (req, res) => {
  res.json({ user: 'test' })
})

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '/client/build/index.html'));
});

const port = process.env.PORT || 3000;

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));

  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

app.listen(port, () => console.log("Server starter on port " + port));


text:
Q: How to access adapter class textview in fragment This is my adapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {

List<ListData> listData;

public RecyclerViewAdapter(List<ListData> listData) {
    this.listData = listData;
}

@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);

    return new MyHolder(view);
}

public void onBindViewHolder(MyHolder holder, int position) {
    ListData data = listData.get(position);
    holder.name.setText(data.getName());
    holder.message.setText(data.getMessage());
}

@Override
public int getItemCount() {
    return listData.size();
}

class MyHolder extends RecyclerView.ViewHolder {
    TextView message, name, badge;

    public MyHolder(View itemView) {
        super(itemView);
        name = itemView.findViewById(R.id.tv_email);
        message = itemView.findViewById(R.id.tv_message);
        badge = itemView.findViewById(R.id.badge);

    }
}

This is my Fragment class.
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    badge = view.findViewById(R.id.badge);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    hashMap = new HashMap<>();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();

            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message))
                       hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                    }
                } else
                    hashMap.put(nameCaps, message)
            }
            list = convertHashToObjectList(hashMap);
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);
        }
        @Override
        public void onCancelled(DatabaseError error) {

        }
    });
    return view;
}

private ArrayListconvertHashToObjectList(HashMap hashMap) {
    ArrayList<ListData> listData = new ArrayList<>();
    for (Map.Entry<String, String> entry : hashMap.entrySet()) {
        listData.add(new ListData(entry.getKey(), entry.getValue()));
    }
 return listData;
}

I want to use the textview badge in fragment class. How to access the adapter class textview in fragment class. When i instantiated the textview in Fragment class it shows the error null object reference.

A: Here is code for same:
  for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (!updateMessage.containsKey(nameCaps)) {

                    updateMessage.put(nameCaps,false);
                }
                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message)) {

                        hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                      updateMessage.put(nameCaps,true);

                    }
                } else
                    hashMap.put(nameCaps, message);

            }
            list = convertHashToObjectList(hashMap);

            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list,updateMessage);

"updatemessage" is a hashmap which holds the changes in message.

A: The way to update some items in a RecyclerView is by updating your data set, then notifying the adapter that the data set has changed.
So first you need to update the data for badge in your List<ListData>.
Then you need to notify change for the adapter. Here's an example
The code goes inside your adapter
public void updateData(List<ListData> newData) {
    listData = newData;
    notifyDataSetChanged();
}

And make sure in your onBindViewHolder() to set the value of badge if exists.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Auto-Interval precision in MS Chart I'm currently using the charting within .NET using System.Windows.Forms.DataVisualization.Charting.Chart. Thus far it seems very powerful, and works great. However, there is a huge problem in terms of how it is auto-calculating intervals. I use a lot of double values, and in libraries like ZedGraph, it handles this perfectly. It selects min/max/interval just fine. However, in MS Chart, it may select 206.3334539832 as a minimum, and intervals of a similar decimal precision. Obviously this looks quite ugly.
So, I tried simply making the axis format {0.00} and it works great when it loads the chart. Except when you zoom in, you need greater precision, maybe at 4 decimal places instead of 2. It seems I'm either stuck with 9 decimal places all the time, or else a constant fixed number that may break when someone requires greater precision. I'd rather it pick up the precision based on the level of zoom currently applied. Libraries like ZedGraph and Dundas (which I believe MS is even using!) tend to pick good values that change as you zoom in and out.
Is there any way to have the intervals change precision as the zoom frame changes? It's probably some simple property I have set wrong, but it's hard to tell with the millions of properties this thing has (especially when there's about 14 places that represent the concept of Interval).

A: I had the exact same problem when zooming.  I added code to format the axis labels and call it from the Paint handler.  The Axis View objects have an IsZoomed property and have functions to get the current axis limits (GetViewMinimum/Maximum).  I set the Axis LabelStyle.Format to "N" for all cases unless the Max-Min=range is less than 1.  Then I set the format to "F#" where # is calculated based on the axis range.
# = Convert.ToInt32(Math.Abs(Math.Log10(range) - .5)) + 1;

A: Having played around with the chart control I haven't been able to find a simple solution to your problem. However the following may help:
Have you considered setting the maximum and minimum values for the axes yourself? If you round the actual maximum and minimum values to the nearest sensible "round" number (5, 10, 0.5, 0.01) this should make the calculated intervals a bit more friendly.
I understand this is not an ideal solution but by carefully choosing the maximum and/or minimum values you can ensure the intervals are "nicer" numbers. If the range of your axes is say divisible by 2, 5 & 10 it should result in fairly nice intervals.

A: Why not modify number format string.
Create format string
string formatString = "{0.00";

Identify zoom level, say zoomLevel = 2;
formatString = formatString.PadRight(5+zoomLevel, '0');
formatString += "}";

Now use this format on axis legend. Use string builder or some better way to modify the format string.

A: To provide the result with minimal cost you can use exponential scientific format

A: You can attach to customize event.
From there, you can modify the labels on x-axis:
var xAxisLabels = chart1.ChartAreas[0].AxisX.CustomLabels;
...
xAxisLabels[0].Text = ...

set min. and max. values:
 chart1.ChartAreas[0].AxisX.Maximum = ...;

etc.

A: you can dynamically update the max and min based on your data set. each time user zooms in, you do a FOREACH on every point and get the stats and based on that set your max and min

A: It helps to set the IntervalOffset of the axis, here an example:
Private Sub chMap_AxisViewChanged(sender As System.Object, e As System.Windows.Forms.DataVisualization.Charting.ViewEventArgs) Handles chMap.AxisViewChanged
  'the grid ticks are rounded values
  e.Axis.IntervalOffset = -e.Axis.ScaleView.ViewMinimum
End Sub


text:
Q: MediaWiki uploads file path vs. "File:" URL I have a mediawiki but for some reason the filepaths for uploads (which are disabled, i manually put the files i want in the images folder via ssh) are totally wrong
Im getting this: http://aaaa.com/bbb/index.php/File:Justgivingcms.jpg
When i should be getting this: http://aaaa.com/bbb/images/File:Justgivingcms.jpg (i assume)
I've had a scout about on the internet and changed a few settings/tried to change the filepath but nothing is working. Is there a specific setting anyone knows to specify the image filepath?

A: http://aaaa.com/bbb/index.php/File:Justgivingcms.jpg is a path to a file page, not to the file itself, and it looks perfectly normal (depending on you short url settings). compare with https://en.wikipedia.org/wiki/File:MediaWiki-smaller-logo.png


text:
Q: prove or disprove about the statement for a limit of a sequence Let $(a_n)$ be a sequence of numbers such that $\displaystyle\lim_{n\rightarrow\infty}a_{n+1}=L$. Does this imply that $\displaystyle\lim_{n\rightarrow\infty}a_{n}=L$?

A: Yes, a limit of a sequence is determined by the "infinite tail" of the sequence.
Let $\varepsilon > 0$. Then there exists $N \in \mathbb{N}$ such that:
$$ n > N \Rightarrow |a_{n+1} - L| < \varepsilon $$. Take $N+1$, then for every $m > N+1 > 1$ we can write $m = n+1$ and then
$$ | a_m - L | = |a_{n+1} - L | < \varepsilon $$
since $m > N+1 \Rightarrow n+1 > N+1 \Rightarrow n > N$.


text:
Q: Riemann zeta and quantum physics? Sometimes I read about connections between "advanced math" and quantum physics, but I am skeptical of these claims. I can believe or understand the connections to calculus, vector calculus, differential equations, or linear algebra, but when I read about connections with prime numbers and the Riemann zeta function, I get very skeptical and confused. As a "toy model" or a math exercise for physics students, okay, but is it seriously used in physics?
I'm not an expert at math nor quantum physics but I will let the links speak for themselves:

*

*Prime numbers are directly related to quantum physics

*Prime numbers get hitched
And others. What are they talking about? Is this real? What is meant with energy levels? What does the real and imaginary part in the domain and range of zeta mean physically? Is the position of the zeros of the zeta function related to the radii of the electrons around a nucleus?
I have never seen this in school!

A: First let me say that this article was published in 2009 and obviously the buzz doesn't seem to have concretized, so I'll take it with caution.
I haven't read the article yet (maybe later, it is quite a long one...).
Although this is not the first time we see such convergence of phenomena. For instance when Conway showed some resemblance between nuclear disintegration process and look-and-say sequence, it felt really surprising at the time. But apparently it stayed at the curiosity stage and deeper examination showed discrepancies with the current knowledge.
I'm guessing it is possibly the same with these prime numbers vs levels of energy, but why not, lets be open minded, someday it could result in a fascinating theory.
Anyway, you mentioned the relation of quantum physics and the zeta function, there is actually a well known one which is the Casimir effect.
When calculating the force between two plates, we have to sum the energy modes of the vacuum for all frequencies, something like $\sum\frac{n\pi}{\delta}$ appears, although this sum is infinite.
Yet in fact the waves are vanishing when their wavelength do not agree anymore with the (very small) distance $\delta$ separating the plates. The calculation uses the wave functions that act as what we call smoothing functions in mathematics and we find the famous $\sum n=\frac{-1}{12}=\zeta(-1)$ as a proportionnality factor for the amplitude of the force. So at least in this case, zeta and quantum physics were related.

A: The precise theorem is that suppose you take the zeroes of the Riemann zeta function as $1/2+i \gamma_n$. Then you look at the normalized differences between neighboring zeroes. If you pretend these were drawn from a random variable and calculate the correlations, you get the same result as if you just took a random Hermitian matrix like the kind that is used to model heavy nuclei. The statement is not about them being equivalent, but that there is a universal property in the sense that they are asking two questions that have the same answers. If you ask a different question about the Riemann zeta function, there is no reason for it to still keep this connection.
You can look up this as it was known as Montgomery's pair correlation conjecture.

A: Best to read where the author is coming from, and where he wants to go to.
In the blog you quoted, the author says "The landscape created by the Riemann hypothesis it turns out, directly matches the quantum energy levels of atoms. This is amazing! It's like in the Matrix where neo sees the code that builds his world."
But when you read his source, extract below, you get this:

Mathematicians have long suspected that there might be a way to convert the Riemann hypothesis into an equation similar to those used in quantum physics. The zeros of the zeta function could then be calculated the same way physicists calculate the possible energy levels for an electron in an atom, for example.
Following ideas by Keating and Michael Berry of the University of Bristol and also by Alain Connes of the Collège de France in Paris, Sierra and Townsend have now made that connection a bit more concrete. They have suggested that an electron constrained to move in two dimensions, and subjected to electric and magnetic fields, might have energy levels that precisely match the zeros of the zeta function. Demonstrating the existence of such a system, even on paper, would confirm the Riemann hypothesis.

If you subject an electron to electronic and magnetic fields, and constrain it to 2 dimensions, well you can get it to fit pretty much any pattern you want.........

A: As Countto10 pointed out, the claim in the blog is at best hyperbole and at worst nonsense. This is not to say that there are no connections/applications of Riemann Zeta to physics. There is a good paper that goes over some of the ways in which this function is used in physics: Physics of the Riemann Hypothesis. Another connection is Montgomery's Conjecture.
Many times these claims of connections are tenuous at best, but there is undoubtedly deep connections between higher math and physics - definitely more than just vector calc, diff eq's, and linear algebra.
Incidentally, I found this post that has a few more examples, including the two above.


text:
Q: Does android have a scope bar similar to IOS? Does android have scopebar like IOS? any idea how to build it? the only option i can think about is manually using xml draw the layout
any more stylish and more convenient way to build search scope bar or option? i wish some search by certain column instead of search all.
thanks


text:
Q: Почему не сравнивы 2 множества?

Как это вообще работает?.
отношение частичного порядка - это отношение которое рефлексивно, семметрично, и транзитивно,
здесь <= - єто я так понял обозначение частичное упорядочение,
с определения следует что 2 элемента a и b частично упорядоченного множества (S, <=)сравнимы если a <= b или b <= a
А цепь если каждые два элемента частично упорядоченного множества (S, <=) сравнимые.
ну а с фото примера 2.50?.
получим {a,b} <= ∅ или  ∅ <= {a,b} - они типо сравнимы или что?.  а множества {a,b} <= {b,c} или  {b,c} <= {a,b} не сравнимы?

A: В примере 2.45 отношение частичного порядка задается как "множество X является подможеством множества Y". И тогда говорим, что X сравнимо с Y.
По-этому, да - {a,b} и ∅ сравнимы, так как пустое множество является подмножеством множества {a,b}.
Для пары же множеств {a,b} и {b,c}, ни одно из них не является подмножеством другого. А значит они несравнимы.
В этом примере еще может сбивать с толку использование символа ≤, так как для чисел это отношение полного порядка, т.е. для любых двух чисел a и b либо a≤b либо b≤a. Но в литературе именно этот символ используется для обозначения частичного порядка.
Хочу ответить на вопросы из комментариев о способах задания или определения отношений. Отношение это всегда множество пар. Но задать это множество можно по разному.
Первый способ, это просто перечислить все элементы множества R (т.е. все пары (A, B), которые входят в R). У этого способа сразу два неудобства:

*

*очень долго записывать

*посмотрев на элементы из R непросто сообразить, а какое правило это отношение задает

Второй способ, это задать правило, которое описывает отношение в общем виде. Вот как в примере R = {(T, V) для T ∈ X, V ∈ X и T ⊆ V}. Обратите внимание, что тут мы задали (или по другому сказать определили) точно то же отношение.
Третий способ, это сказать словами R - это бинарное отношение "является подмножеством" над множеством X. И опять же, этим определением, мы задаем точно то же отношение.
Все три способа, это просто разные способы задать некое множество пар.
И все следующие высказывания эквивалентны:

*

*({1}, {1, 2}) ∈ R

*{1} является подмножеством {1, 2}

*{1} ≤ {1, 2}
И да, если элементы принадлежат отношению порядка (или по другому находятся в отношении порядка), то они "сравнимы". Т.е. смысл такой, что мы можем их сравнить между собой. Отношения порядка задает, собственно, порядок для элементов, которые входят в отношение, т.е. возможность сказать какой из них больше или меньше. И именно в этом смысле используется термин "сравнимы", их можно сравнить между собой.


text:
Q: Can't boot to Ubuntu 13.04 after installing I know that there is lots of people with the exact same problem, but I can't get an answer from another place (I've really been trying for hours), so here is my problem.
I got Ubuntu 13.04 on my CD and I installed it beside Windows. Something went wrong and it said

"Executing 'grub-install /dev/sda' failed. This is a fatal error"

I could choose where to install the bootloader and I selected /sda . But after rebooting, I went to Windows, which I didn't wanted to. I tried the boot-repair (recommended) and it said:

Boot successfully repaired.
You can now reboot your computer. Please do not forget to make your
  BIOS boot on sdb (500GB) disk!

I rebooted and I got ubuntu, just like I wanted. But then after an hour of using, I pressed at 'Shut down'. Like 2 hours after, I came Again but saw the Windows logo another time. I tried to use the boot-repair and it said the exact same thing, but when I rebooted I just went to Windows Again.
So That's my problem. I have the link for the first boot-repair 'installation' right here: http://paste.ubuntu.com/5631563/.
Does anybody have an idea of what to do? Can I activate something that will make the computer asking me for which OS I wanna use when I start up (It did after the first boot-repair)? Or can't I just make ubuntu my default?
UPDATE:
In BIOS Settings, I can choose between these:

*

*International CD/DVD ROM DRIVE

*USB Diskette on Key/USB Hard Disk

*USB CD/DVD ROM Drive

*Notebook Hard Drive (Really think this is Windows)

*! USB Floppy

*! Network Adaptor

A: You have two 500 GB hard drives. It seems like there are multiple windows systems installed on the first drive (sda1, sda2, sda3), and a Ubuntu system on the second drive (sdb6). To reach the GRUB menu, you simply need to set your BIOS to boot from the second HDD, as boot-repair told you, because GRUB is installed in the MBR of sdb.


text:
Q: Issue constructing a has_many relation with scope using multiple join tables I have a tag system on multiple models that are linked together.
The system works like this:

*

*A Top has many Middles

*A Middle has many Lows

*Tops, Middles and Lows have many Tags

*A tag associated to Top level is supposed to qualify every Middle and Low associated to it.

*Same goes for a tag that would be associated to a Middle, every Low associated to it would 'inherit' from the tags.

This mechanic is not on a database level, in the end in what concerns the database, Tops, Middles and Lows all have their own tag collection, and i initially implemented instance methods on each model so that when you call, for example, low_instance.all_tags, it concatenates the tag collections of it's parent Middles, and the one of its Top.
Here is what the models look like:
#          ______________________________
#         /                              \
#      (1)                                (*)
#    [Top] (1) __ (*) [Middle] (*) __ (*) [Low]
#      (*)               (*)              (*)
#        \_______________ | ______________/
#                         |
#                         *
#                       [Tags]

class Low < ApplicationRecord
  has_many :low_tags, dependent: :destroy
  has_many :tags, through: :low_tags
  has_many :middle_foos, dependent: :destroy
  has_many :middles, through: :middle_foos
end

class Middle < ApplicationRecord
  belongs_to :top
  has_many :middle_tags, dependent: :destroy
  has_many :tags, through: :middle_tags

  has_many :middle_lows, dependent: :destroy
  has_many :lows, through: :middle_lows
end

class Top < ApplicationRecord
  has_many :middles, dependent: :destroy
  has_many :lows, dependent: :destroy
  has_many :top_tags, dependent: :destroy
  has_many :tags, through: :top_tags
end

### Join tables
class MiddleLow < ApplicationRecord
  belongs_to :middle
  belongs_to :low
end

class LowTag < ApplicationRecord
  belongs_to :low
  belongs_to :tag
end

class MiddleTag < ApplicationRecord
  belongs_to :middle
  belongs_to :tag
end

class TopTag < ApplicationRecord
  belongs_to :top
  belongs_to :tag
end

That actually works like a charm. The issue is that i want to be able to search my Lows with the awesome Ransack gem and using the full tag collection of a Low (its self tags, plus the ones inherited from the parent Middles and Top)
Problem: Ransack only works with ActiveRecord::Relations. So from Ransack's point of view, i can only search my Lows using their self-tags and not the full inherited collection as this does not exist on the database level.
The initial solution to this problem i wanted to implement is to add a "copy" full tag collection on the database level that updates with the rest and that i could use to search with Ransack.
But I'm sure i don't have to add anything to the database as all the info is already here in the join tables and i kind of don't want to duplicate that info which is not super cool i think and would make the code base less understandable.
I have seen potential solutions using has many with scopes like so:
has_many :all_tags, ->(low) {
  unscope(.........).
  left_joins(..........).
  where(.........)
  # Returs self tags (Low) + tags from associated Middles + tags from the Top
}

I'm pretty sure this would be the best solution, but I'm really not good when it comes to database querying especially with so much models and join tables. I get confused and can't seem to find what to put in that scope so that i get this full collection of tags.
So if anybody has a clue about that, any help would be greatly appreciated!
By the way, using Rails 6.1 and Ruby 2.7

A: So found the solution to the query I wanted to construct in the end.
The scope looks like following:
    has_many :full_tags, lambda { |low|
        where_clause = 'top_tags.top_id = ? or low_tags.low_id = ?'
        where_args = [low.top_id, low.id]
        if low.middles.any?
          where_clause += ' or middle_tags.zone_id IN ?'
          where_args << low.middle_ids
        end
        unscope(where: :low_id)
          .left_joins(:middle_tags, :top_tags, :low_tags)
          .where(where_clause, *where_args).distinct
      }, class_name: 'Tag'

Calling xxx.full_tags on any instance of low returns the whole collection of tags from every middle it belongs to , plus those from the top it belongs to, plus its own tags, and the distinct makes it a unique collection.
That being said, that didn't fully fixed my problem because the whole purpose was to pass this scoped has_many relation as an attribute used by the Ransack gem to filter out my Low models, out of their full inherited collection of tags.
Big disappointment it was when i discovered that Ransack performs eager loading when it comes to search on associations:
Rails does not support Eager Loading on scoped associations
So i ended up implementing a whole other solution for my tagging system. But hey, i learned a lot.


text:
Q: HTML Styling code not working in JSP file I am using Eclipse Kepler to create a web application and and trying to get my jsp files designed before starting my functionality. When I create the following code as a basic html file, it can be opened in the browser with perfect design. But when I write this code in a jsp file with the additional
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

as the first two lines, the file loses all of its positional styling. If you run the code in a jsp, you will notice that bordering and link coloration remain the same, but everything is positioned in the same spot.
Any one know how to deal with this? Thank you.

<title>Home</title>

    Welcome, User1

    Logout

Timecard Management

User Management

Customer Management

Admin

Reports

Recent Activity:

    <textarea id='feedtext' readonly>

    </textarea>

A: Change positions other than 0 to have glued to it "px".
top: 20px;

Or remove the DOCTYPE as that requires the HTML/CSS to be considered correct (though it is not).
Tip:
Also you might consider using "Windows-1252" in Java. The browsers will interprete ISO-8859-1 as Windows-1252 (even on Mac and Linux). And some special characters like comma-like quotes that MS Word so likes, will be present. HTML-5 makes this hidden functonality an official specification.

A: With the line <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> you are changing the html version from something that will be probably parsed as 5 (without doctype, you end up using some kind of quirks mode, wchich even works with your style that is missing px) to 4.01 Transitional. And that's what happen, when you do that. Different version - different results.
You have to decide which version do you want to use (if html 5 - then use <!DOCTYPE html>). Also I suggest using UTF not the 8859-1 (but that is an option).
Try changing encoding in that line <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>.


text:
Q: Parse JSON array to tabular format in SQL Server I have a JSON object like this
'{
    "car": [ "Ford", "BMW", "Fiat"],
    "car owner": ["Alex", "Tom", "Jane"]
}'

I need to parse it to tabular format in SQL Server
Car   | Car owner
Ford    Alex
BMW     Tom
Fiat    Jane

I've tried
SELECT *
FROM OPENJSON(@json)
WITH (
  [Car] NVARCHAR(50) '$.Car[0]',
  [Car owner] NVARCHAR(50) '$."Car owner"[0]'
)

It returns the first item in the array but I cannot return all records with just '$.Car' and '$."Car owner"' in the same WITH clause.

A: The easiest way is probably to open each array as a table with a separate OPENJSON call and join them by the generated key to match up the positions;
DECLARE @json NVARCHAR(MAX) = N'{
    "car": [ "Ford", "BMW", "Fiat"],
    "car owner": ["Alex", "Tom", "Jane"]
}'

SELECT a.value car, b.value owner
FROM OPENJSON(@json, '$.car') a
JOIN OPENJSON(@json, '$."car owner"') b
  ON a."key" = b."key"

This will give the result;
car     owner
-------------
Ford    Alex
BMW     Tom
Fiat    Jane

A DBfiddle to test around with


text:
Q: vba compile error function or interface marked as restricted VBA Error when interfacing from Access to .NET com dll I have a com dll created in VB.NET that has been working for a number of years. The dll takes information from MS Access and creates orders on eBay using their Soap api. All of a sudden I started getting the error message "vba compile error function or interface marked as restricted, or the function uses an automation type not supported in Visual Basic" when I compile the Access application. The error is on a line where a property of type decimal in the dll is updated with data of type decimal from an DAO recordset. This part of the code has been stable for quite a while so I am at a loss as to why all of a sudden this error starts. Any suggestions would be appreciated.

A: For future reference. It appears that MS Access type decimal is not equivalent to VB.NET type decimal. MS Access sees VB.NET double as equivalent to its type decimal. Once I converted my property to a double data type the compile error went away.


text:
Q: "413 Request Entity Too Large" Error on Office 365 Graph API for SendMail using MIME I was happy to see Microsoft added support to SendMail and using a MIME file.  But, it seems it has the issue most graph APIs had (or have) and that is the 4mb limit.  And because the MIME needs to be base64 encoded, that means we're down to about 2.8MB in actuality.
Error returned when over the limit is:
"413 Request Entity Too Large"
In 2022 that limit is pretty small as most customers are now emailing PDF attachments of POs (a lot of them raster image PDFs, so bigger), invoices, etc.  Just wondering if there is a workaround or if MS is planning on updating this feature as it is a GREAT feature to have (like GMail, et all have).
I have a lot of customers using my software and this feature will make their transition from in house exchange servers or other online email clients to Office 365.


text:
Q: A problem about details in the proof of the theorem 6.5.3( principal eigenvalue for nonsymmetric elliptic operators) in Evans' PDE We consider in this section the boundary-value problem
$$\left\{\begin{aligned}
L w &=\lambda w \quad \text { in } U \ \ \ \ \ \ (1)\\
w &=0 \quad \text { on } \partial U
\end{aligned}\right.$$
where $U$ is open and bounded,
$$L u=-\sum_{i, j=1}^{n} a^{i j} u_{x_{i} x_{j}}+\sum_{i=1}^{n} b^{i} u_{x_{i}}+c u .$$
Let us for simplicity assume that  $a^{i j}, b^{i}, c \in C^{\infty}(\bar{U})$ , that  $U$  is open, bounded and connected, and that  $\partial U$  is smooth. We suppose also  $a^{i j}=a^{j i}(i, j=   1, \ldots, n)$  and
$$c \geq 0 \quad \text { in } U$$
THEOREM 3 (Principal eigenvalue for nonsymmetric elliptic operators).
(i) There exists a real eigenvalue  $\lambda_{1}$  for the operator  $L$ , taken with zero boundary conditions, such that if  $\lambda \in \mathbb{C}$  is any other eigenvalue, we have
$$\operatorname{Re}(\lambda) \geq \lambda_{1}$$
(ii) There exists a corresponding eigenfunction  $w_{1}$ , which is positive within  $U$ .
(iii) The eigenvalue  $\lambda_{1}$  is simple; that is, if  $u$  is any solution of (1), then  $u$  is a multiple of  $w_{1}$ .
Proof . 1. Choose  $m=\left[\frac{n}{2}\right]+3$  and consider the Banach space  $X=   H^{m}(U) \cap H_{0}^{1}(U)$ . According to Sobolev Embedding Theorem, $X \subset C^{2}(\bar{U})$ . We define the linear, compact operator  $A: X \rightarrow X$  by setting  $A f=u$ , where  $u$  is the unique solution of
$$\left\{\begin{aligned}
L u=f & \text { in } U \\
u=0 & \text { on } \partial U
\end{aligned}\right.$$
Next define the cone
$$C=\{u \in X \mid u \geq 0 \text { in } U\} .$$
According to the maximum principle,  $A: C \rightarrow C$

*Hereafter fix any function  $w \in C$, $w \not \equiv 0$ . Employing the strong maximum principle and Hopf's Lemma, we deduce
$$v>0  \ \ in \ \  U, \frac{\partial v}{\partial \nu}<0 \ \  on\ \   \partial U \ \ \ (2)$$
for  $v=A(w)$ .
Remember that  $w=0$  on  $\partial U$ . So in view of  (2)  there exists a constant  $\mu>0$  so that

$$\mu v \geq w \quad \text { in } U$$
My problem is: why such constant $\mu>0$ exists? I know we only need to consider the point near the boundary of $U$ and notice that $w=0$ on $\partial U$,we may need to apply Tailor's formula, and I believe the conclusion is true, but I just can't prove it clearly.
Can someone help me? I would be appreciated if you could help me.

A: Since $v > 0$ (strictly positive) you can just define the function
$$
g = \frac{w}{v},
$$
and then take $\mu = \sup_U g$ so that $\mu \geq g$ a.e. in $U$ and therefore
$$
\mu \geq \frac{w}{v} \implies \mu v \geq w.
$$
Remark that since $w \in C$ and $v > 0$, it holds $g \geq 0$ and therefore $\mu \geq 0$. We can see that $g = 0$ a.e. only if $w=0$ a.e., but in this case since $v > 0$ we can take any $\mu > 0$ and $\mu v > w$ would hold.


text:
Q: How to linkify hashtag in react I use the linkify-react module with the hashtag plugin
import Linkify from 'linkifyjs/react';
import * as linkify from 'linkifyjs';
import hashtag from 'linkifyjs/plugins/hashtag';
hashtag(linkify);

I'm not find any solution to let the hashtags links work directly in jsx component, it's possible?
   <Linkify options={linkifyOptions} >{content}</Linkify>

in alternative I'm trying to use the plugin. Whit the plugin I retrieve an array of all hashtag in the content
const pTag = linkify.find(p.content || '');

// here the output
{
  "type": "hashtag",
  "value": "#tag",
  "href": "#tag"
}

How I can replace all the hashtag with a link in the text? I've tried this solution but not works
    pTag.forEach( (tag) => {
        content.replace(tag, 'example.com/'+tag);
    })

A: You can use formatHref property to add URL to each hashtag as per Linkify's documentation
https://soapbox.github.io/linkifyjs/docs/options.html
var linkifyOptions =
    {
        formatHref: function (href, type) {
          if (type === 'hashtag') {
            href = 'https://twitter.com/hashtag/' + href.substring(1);
          }
          return href;
        }
      }

var content = 'Linkify is #super #rad2015';
return <Linkify options={linkifyOptions}>{content}</Linkify>;

Checkout complete code here
https://codesandbox.io/s/linkify-sxt8c?fontsize=14


text:
Q: Absolute Positioning height I have a div containing text absolutely positioned inside a relative div containing an image. I am designing a fluid layout. The idea being the title text appears on the image in a consistent position.
I have two problems. The first is if I set height 0 on the text div, it should align with the top of the image div. However, it jumps above this to the top of the doc. I cannot work out why, I though absolute divs, position to the first relative div.
The second problem is as I change the width of the image div/browser, the vertical position changes. So lets say at the browsers widest, the top of the title text starts an 8th of the way down the title image. When I reduce the browser size, the top of the title text starts to creep towards the top of the image div and can even go above it over the top menu. Both the title text and title image size based on the width so this should remain constant.
Thanks for any help.
HTML

<img src="/photos/<?php echo $row1['cover']; ?>.jpg" style="width:100%;" alt="banner">

  <h1 class="voyage_to" style="text-shadow: 0 0 0.2em <?php echo $colour; ?>, 0 0 0.2em <?php echo $colour; ?>;">xxxxxxxx

  <h1 class="bold_title" style="text-shadow: 0 0 0.2em <?php echo $colour; ?>, 0 0 0.2em <?php echo $colour; ?>;"><?php echo $row1['name']; ?>

CSS
.header_image{
width:100%;
position:relative;
}

.header_text {
    line-height:1;
position: absolute;

top:20%;
left:0;
right:0;
margin:0 auto;

z-index: 1;

   -moz-user-select: none;
   -khtml-user-select: none;
   -webkit-user-select: none;

}


text:
Q: Host a Blazor WASM app inside a Visual Studio Extension Is it possible to create a Visual Studio Extension that has a host window (that I can dock etc inside VS like code tabs do) that I can show the contents of a #Blazor WASM app inside?
I've not written a VS extension before, and have no idea where to start.


text:
Q: How to cite more than 14 papers in overleaf? I am writing a dissertation on overleaf.
I make more than 14 citations in my dissertation.
I received an error that overleaf cannot compile.
Here is my lataxmkrc:
$latex = 'uplatex';
$bibtex = 'upbibtex';
$dvipdf = 'dvipdfmx %O -o %D %S';
$makeindex = 'mendex -U %O -o %D %S';
$pdf_mode = 3;
$ENV{TZ} = 'Asia/Tokyo';
$ENV{OPENTYPEFONTS} = '/usr/share/fonts//:';
$ENV{TTFONTS} = '/usr/share/fonts//:';

I got this error bellow.
Timed out. Sorry, your compile took too long to run and timed out. This may be due to a LaTeX error, or a large number of high-res images or complicated diagrams. Learn how to fix compile timeoutsthis is what I got

I will cite more papers in the paper.
How can I cite more than 14 papers in overleaf?


text:
Q: How to get notification email every time an IP address of a website (dynamic DNS) gets changed? My weekly task is to monitor the IP address from a list of my company's site with different port, the IP address is stored in txt file, for example:
http://name1.domain.net:port
http://name2.domain.net:port2
http://name4.domain.net:port4

I used to use chrome extension "IP Address and Domain Information" to get the IP address manually every 3 days and paste the change to another txt file but now my supervisor want to check those IP list every 12 hours.
This process take me a lot of time (around 40 address and getting more). Is there any program or bash code to make automatic this process and just send me the an email if some of those address has been down or getting another IP address? For example, the email content should look like this:
http://name4.domain.net:port4 - server "UP" - "New IPv4 address"
http://name1.domain.net:port4 - server "Down" - "IPv4 address"

A: Well.... it's school holidays for me, and I'm super bored today, so I decided to make a Python script that does what you need, and can automatically send you an email detailing the changes. It'll check the IPs of the sites you specify in urls every 12 hours. It should work.
This answer probably belongs on StackOverflow, but leave me alone >:(
I've added comments detailing what each thingo does
import requests, smtplib, time

# Put the urls of the servers you wanna check here (makes sure to specify http:// or https://)
urls = ['https://google.com', 'https://pigeonburger.xyz']
print("Checking websites:", str(urls))

def checkSites():
        while True:
            siteIPs = []

            # For each site in the list, get their IP and append it to another list for future checking. current_ips is what we'll be checking against.
            for site in urls:
                request = requests.get(site, stream=True)
                siteIPs.append([site, request.raw._connection.sock.getpeername()[0]])
                current_ips = siteIPs

            print("Current site IPs:", str(current_ips))

            # While the latest check of IPs is equal to the first check (i.e there has been no IP change). This loop will run every 12 hours (43200 seconds)
            while siteIPs == current_ips:
                print("No changes found. Checking the sites IPs again in 12 hours")
                time.sleep(43200)
                print("Checking sites IPs again......")
                siteIPs = []
                for site in urls:
                    request = requests.get(site, stream=True)
                    siteIPs.append([site, request.raw._connection.sock.getpeername()[0]])

            # Once the loop is broken, and a change is detected, find what site's IP was changed.
            print("An IP change(s) was detected! Locating the exact change now.....")
            def find_difference(x, y):
                list_difference = [i for i in x+y if i not in x]
                return list_difference

            site_diffs = find_difference(siteIPs, current_ips)

            # Generates a line to be included in the email detailing what the sites IP has changed to - a new line for each change.
            email_content = []
            for site_data in site_diffs:
                email_content.append(f"The IP of {site_data[0]} has changed to {site_data[1]}")
            print('\n'.join(email_content))

            # Send an email containing the info on the changes.
            print("Sending email containing the changes now......")
            sendMail('\n'.join(email_content))
            print("Email sent! Program will restart now.")

# This is the function that sends the email. Update the email addresses and SMTP server info to meet your needs.
def sendMail(content):
    sender = 'sender@google.com'
    receivers = ['receiver@example.com']

    message = f"""From: Server <sender@google.com>
    To: Your email <receiver@example.com>
    Subject: Site IP Updated

    {content}
    """

    smtpObj = smtplib.SMTP('smtp.example.com', port=587)
    smtpObj.connect("smtp.example.com", port=587)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.login("username", "password")
    smtpObj.sendmail(sender, receivers, message)

# Start
if __name__ == '__main__':
    checkSites()

To anyone reading this - let me know if there are any potential errors with the script or ways to make it more efficient. This isn't my best code lol


text:
Q: I cannot understand how a struct can substitute a typedef See this link: https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(C4503)&rd=true It suggests to write:
// C4503b.cpp
// compile with: /W1 /EHsc /c
#include <string>
#include <map>

class Field{};
struct Screen2 {
   std::map<std::string, Field> Element;
};

struct WebApp2 {
   std::map<std::string, Screen2> Element;
};

struct WebAppTest2 {
   std::map<std::string, WebApp2> Element;
};

struct Hello2 {
   std::map<std::string, WebAppTest2> Element;
};

Hello2 MyWAT2;

instead of
// C4503.cpp
// compile with: /W1 /EHsc /c
// C4503 expected
#include <string>
#include <map>

class Field{};

typedef std::map<std::string, Field> Screen;
typedef std::map<std::string, Screen> WebApp;
typedef std::map<std::string, WebApp> WebAppTest;
typedef std::map<std::string, WebAppTest> Hello;
Hello MyWAT;

But those codes are not equivalent as with the typedefs Hello is an std::map while with structs it is just a struct that has a field which is a map which means I cannot use them interchangeably. Could someone explain the trick?

A: You're right, you can't use them interchangeably. In fact, Microsoft advise you to do so in order to overcome a technical difficulty from their end: they can't (or have difficulty to) handle mangled names longer than 4096 bytes.
In most case, a typedef would be a better solution over aggregation, I believe.
But since your compiler is somewhat limited, you may be stuck with their hack.

A: If you want a solution which fulfills the goal of differentiating the (mangled, possibly truncated) names, but without the downside of an extra layer of naming, you can use inheritance:
class Screen : public std::map<std::string, Field>
{
    // forward constructors here
};

A: The workaround provided isn't to be meant as an equivalent replacement of the reproducer but rather as a possible way to reduce the decorated length of exported symbols.
You can verify with a simple objdump /symbols objfile.obj that the length of decorated symbols by using typedefs is incredibly longer than their similar counterparts split into structs (Microsoft compilers have historically used a proprietary name mangling scheme).

A: A typedef doesn't declare a new type, it just an alias. And if you forward-declare a typedef, when the compiler sees the typedef definition, it throws you an error:
// a.hpp
class Screen;

class any_class_using_screen {};

// a.cpp
#include "a.hpp"

typedef std::map<std::string, Field> Screen; // Error.

Using even simple inheritance allows you to use your custom names for other types:
class Screen : public std::map<std::string, Field>
{};

Remeber that simple inheritance without additional members doesn't cause any memory or time overhead. That is as efficient as a typedef, with the adventage that it is a new type.
Since std::map<...> hasn't virtual destructors, you cannot use the "pointer to base class" pattern as usual, of course. The owner of the Screen instance (the one who created a screen instance), if it lives in the heap and must be destructed, must be destructed from a pointer to the derived class:
template<class K, class V>
void f(std::map<K, V> const* map); // Do something

int main()
{
    Screen* s = new Screen;
    f(s); // Ok
    delete s; // OK, deleting from derivate class
}

@PeterA.Scheneider suggest that, as far as the derivate class hasn't additional members, nothing happens, and you can call the destructor from a pointer to the derived class. But, theoretically, without a virtual destructor, you are destructing the base class instance (only the base class life reachs to its end), and the derivate class instance is still alive with a dead base, having a corrupted object. From a practical point of view, I think the object is correctly destructed, but anyway I don't know if that can cause undefined behaviour.
The standard should be check to be sure.
Additionally, there could be alignment issues with that approach of destructing, from a base class pointer, a derivated object without extra members.
If a base class has no virtual destructor, do inheritance without "polymorphic intentions", and destruct always from the most derived class.


text:
Q: Finding out which log line triggered a logcheckd notification? We are using the logcheck package in Debian for log-monitoring.
If I understand it correctly, logcheck monitors the logs, filters out known (normal & unimportant) messages and triggers a mail if any message occurs which might indicate a problem.
Logcheck is sending me an excerpt of the log (System Events). But the log does not look suspicious. It contains messages like:
Jul 31 08:22:03 example pop3d: Connection, ip=[::ffff:123.456.789.123]

I think logcheck sends also the surrounding part of the log if there is a line that triggered the notification - but how can I find out, which exact line triggered this mail?

A: One way to check the status of the log-checking is to copy all your rules to a file, and then use egrep for the analysis:
# First of all:
cat /etc/logcheck/ignore.d.server/ > /tmp/logcheckrules

# color last 10 log lines. Darken matches (which would not trigger a warning)
tail -n10 /var/log/syslog | GREP_COLOR=30 egrep --color -f /tmp/lcd

# When you have a single line and what to check wether your regex is working:
tail n-10 /var/log/syslog | GREP_COLOR=32 egrep --color "singleRegExpGoesHere"

It turned out that in the end lots of those messages we received, triggered log check.
On the system there is a "courier-pop" file - but this matches for courierpop3login. So we simply copied this file and changed the string to pop3d.
The commands
cat /var/log/syslog|egrep -v -f /etc/logcheck/ignore.d.server/LOCAL

to show, what is not yet filtered in this file
cat /var/log/syslog|egrep -f /etc/logcheck/ignore.d.server/LOCAL

to show what matches the rules of a file, or even
cat /etc/logcheck/ignore.d.server/* | egrep -v -f /dev/stdin /var/log/syslog

to see what is not filtered by any rules,
are quite helpful for debugging.


text:
Q: Get string from array via property lookup, but insert a variable I want to use property look-up on an associative array of strings, but there's a catch - I need to be able to use a variable in the string. I came up with two solutions, but both seem hacky in PHP.
$foo = [
  'someProp' => 'Some value here: $$value$$.'
];
$myProp = 'someProp';
$value = 'some value';
$myString = $foo[$myProp];
$myString = str_replace('$$value$$', $value, $myString);
echo $myString;

In JavaScript, I would probably use functions instead of strings and return the string including the variable. I've heard that this is bad practice in PHP.
$foo = array(
  'someProp' => function($value) {
    return "Some value here: {$value}.";
  }
);
$myProp = 'someProp';
$value = 'some value';
$myString = $foo[$myProp]($value);
echo $myString;

To be sure this is not an X/Y problem, I will say that my goal is to abstract my error messages to one location in my code (the array mentioned here) and form what might be considered an error api for use throughout the application. For example:
try {
  something(); //throws "MyException('someProp', 'someValue');
}
catch (MyException $e) {
  $someClass->addError($e->getType(), $e->getValue());
  //this function will get the string based on $type and add $value to it, then add the message to an array
}

Are either of these two approaches the way to go? The answer I'm looking for would include a more optimum solution if there is one and mature thoughts on my two proposed solutions.

A: From your example, is there only a single variable per message string or it could be many variables?
If there's only single variable, instead of role out your old string interpolation, you could use sprinf for this. This is more flexible in my opinion since it allows you to do many formatting types e.g. int, decimal etc
$foo = [
   'someProp' => 'Some value here: %s.'
];
$myString = sprintf($myString, $value);


text:
Q: Layered Navigation has different Links to the main Navi in a shop we have the usual main Navigation, which outputs the url as a clean url-rewrite url, eg: /category-one/sub-category-one/
Now if I click into the first category /category-one and use the layered navigation in the sidebar to get to the sub-category, the URL Link is written as:
/category-one?cat=2 rather than the clean urls version from the main menu:
 /category-one/sub-category-one/
Why is this and how do I change this?
In the code the url is rendered using:
echo $this->getCategoryUrl($_category)
and in the main navi it is rendered with:
$child->getUrl()

A: It's because you aren't actually viewing that category, you are view category-one filtering the products by only products that are in sub-category-one. Whilst this might sound like a pedantic difference, there are multiple reasons they aren't the same thing. Layout handles applied will be those matching category-one not sub-category-one for example. The same applies for all settings/attributes that can be modified on a category level, such as theme. If sub-category-one wasn't a category with is_anchor enabled, then by your approach, clicking it would mean the layered navigation disappears, whereas it doesn't with the current implementation.
There is no core functionality to support what you are trying to achieve, however you could potentially modify the code if you are happy with the above effects. The simplest way would probably be to rewrite Mage_Catalog_Model_Layer_Filter_Item::getUrl and do something like:
if ($this->getFilter()->getRequestVar() === 'cat') {
    return Mage::getModel("catalog/category")->load($this->getValue())->getUrl();
}
return parent::getUrl();

Though I doubt this is massively efficient.


text:
Q: Plotly disable "band behavior" zoom selection Is it possible to disable the "band behavior" plotly displays when doing a selection zoom?
To illustrate, these first two pictures are examples of moving into "band mode" when I am selecting and move the mouse too negative in the y or x axis.

What I want is to enforce behavior where selection only allows you do this kind of selecting:

A: layout.xaxis.fixedrange: true
layout.yaxis.fixedrange: true

https://plotly.com/javascript/reference/#layout-xaxis-fixedrange


text:
Q: Are the decimal places in a CSS width respected? Something I've been wondering for a while whilst doing CSS design.
Are decimal places in CSS widths respected? Or are they rounded?
.percentage {
  width: 49.5%;
}

or
.pixel {
  width: 122.5px;
}

A: Elements have to paint to an integer number of pixels, and as the other answers covered, percentages are indeed respected.
An important note is that pixels in this case means css pixels, not screen pixels, so a 200px container with a 50.7499% child will be rounded to 101px css pixels, which then get rendered onto 202px on a retina screen, and not 400 * .507499 ~= 203px.
Screen density is ignored in this calculation, and there is no way to paint* an element to specific retina subpixel sizes. You can't have elements' backgrounds or borders rendered at less than 1 css pixel size, even though the actual element's size could be less than 1 css pixel as Sandy Gifford showed.
[*] You can use some techniques like 0.5 offset box-shadow, etc, but the actual box model properties will paint to a full CSS pixel.

A: Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.
I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.
Edge case, sure, but something to keep in mind.

A: Although fractional pixels may appear to round up on individual elements (as @SkillDrick demonstrates very well) it's important to know that the fractional pixels are actually respected in the actual box model.
This can best be seen when elements are stacked next to (or on top of) each other; in other words, if I were to place 400 0.5 pixel divs side by side, they would have the same width as a single 200 pixel div.  If they all actually rounded up to 1px (as looking at individual elements would imply) we'd expect the 200px div to be half as long.
This can be seen in this runnable code snippet:

body {
  color:            white;
  font-family:      sans-serif;
  font-weight:      bold;
  background-color: #334;
}

.div_house div {
  height:           10px;
  background-color: orange;
  display:          inline-block;
}

div#small_divs div {
  width:            0.5px;
}

div#large_div div {
  width:            200px;
}

0.5px div x 400

200px div x 1

A: If it's a percentage width, then yes, it is respected:

#outer {
    width: 200px;
}

#first {
    width: 50%;
    height: 20px;
    background-color: red;
}

#second {
    width: 50.5%;
    height: 20px;
    background-color:green;
}

#third {
    width: 51%;
    height: 20px;
    background-color:blue;
}

As Martin pointed out, things break down when you get to fractional pixels, but if your percentage values yield integer pixel value (e.g. 50.5% of 200px in the example) you'll get sensible, expected behaviour.
Edit: I've updated the example to show what happens to fractional pixels (in Chrome the values are truncated, so 50, 50.5 and 50.6 all show the same width.)

#percentage {
    width: 200px;
    color: white;
}

#percentage .first {
    width: 50%;
    height: 20px;
    background-color: red;
}

#percentage .second {
    width: 50.5%;
    height: 20px;
    background-color:green;
}

#percentage .third {
    width: 51%;
    height: 20px;
    background-color:blue;
}

#pixels {
    color: white;
}

#pixels .first {
    width: 50px;
    height: 20px;
    background-color: red;
}

#pixels .second {
    width: 50.5px;
    height: 20px;
    background-color:green;
}

#pixels .third {
    width: 50.6px;
    height: 20px;
    background-color:blue;
}

#pixels .fourth {
    width: 51px;
    height: 20px;
    background-color:red;
}

50%=100px

50.5%=101px

51%=102px

50px

50.5px

50.6px

51px

A: The width will be rounded to an integer number of pixels.
I don't know if every browser will round it the same way though. They all seem to have a different strategy when rounding sub-pixel percentages. If you're interested in the details of sub-pixel rounding in different browsers, there's an excellent article on ElastiCSS.
edit: I tested @Skilldrick's demo in some browsers for the sake of curiosity. When using fractional pixel values (not percentages, they work as suggested in the article I linked) IE9p7 and FF4b7 seem to round to the nearest pixel, while Opera 11b, Chrome 9.0.587.0 and Safari 5.0.3 truncate the decimal places. Not that I hoped that they had something in common after all...

A: They seem to round up the values to the closest integer; but Iam seeing inconsistency in chrome,safari and firefox.
For e.g if 33.3% converts to 420.945px
chrome and firexfox show it as 421px.
while
safari shows its as 420px.
This seems like chrome and firefox follow the floor and ceil logic while safari doesn't.
This page seems to discuss the same problem
http://ejohn.org/blog/sub-pixel-problems-in-css/


text:
Q: Fullcalendar substring date returns Uncaught TypeError: info.event.end.substring is not a function I have a fullcalendar in which i'm using a jquery timepicker.
On event click i need to take the start properties (example: "Wed May 04 2022 11:30:00 GMT+0200 (Ora legale dell'Europa centrale)") but using the substring to only have HH:MM.
I tried doing: "var x= info.event.end.substring(16, 21);" but when i click an event this error occure: "Uncaught TypeError: info.event.end.substring is not a function"
How can i fix this?

A: end is a Date object, and substring only works on String objects. Add .toString() and you'll be able to progress.
var x= info.event.end.toString().substring(16, 21);


text:
Q: How can I search within listview How can I search within (listview) displays data So when he finds the item is indicated by the blue color inside the (listview)
 private void butsearch_Click(object sender, EventArgs e)
 {
      SqlConnection cn = new SqlConnection(Class1.x);

      DataSet mydata = new DataSet();
      mydata.Clear();
      SqlDataAdapter db = new SqlDataAdapter("SELECT * FROM okk WHERE username LIKE '%" + textBox4.Text + "%'", cn);
      db.Fill(mydata, "uspas");
      textBox4.DataBindings.Clear();
      textBox4.DataBindings.Add("text", mydata, "uspas.okk");
      listView1.SelectedItems.data....// I could not be completed because I do not know
 }

A: Look this example, this is the way you can add new elements to a ListView, what I see is that the action for button3 is to search and to add, so this must be your problem, if not what do you want to do.
private void LoadList()
{
    // Get the table from the data set
    DataTable dtable = _DataSet.Tables["Titles"];

    // Clear the ListView control
    listView1.Items.Clear();

    // Display items in the ListView control
    for (int i = 0; i < dtable.Rows.Count; i++)
    {
        DataRow drow = dtable.Rows[i];

        // Only row that have not been deleted
        if (drow.RowState != DataRowState.Deleted)
        {
            // Define the list items
            ListViewItem lvi = new ListViewItem(drow["title"].ToString());
            lvi.SubItems.Add (drow["title_id"].ToString());
            lvi.SubItems.Add (drow["price"].ToString());
            lvi.SubItems.Add (drow["pubdate"].ToString());

            // Add the list items to the ListView
            listView1.Items.Add(lvi);
        }
    }
}

If you want to delete selected items, you would do like this:
foreach(System.Windows.Forms.ListViewItem eachItem in
this.listView1.SelectedItems)
{

}


text:
Q: How to use more than one custom javascript css carousel on same page? I am using an image carousel which is working perfectly. Except that I can't use 2nd, 3rd carousel on same page. If I use more than one carousel on same page than the 2nd and 3rd are not working only the 1st. I am not expert and need some help if it possbile to change the code and have more than one carousel on same page? Here is the code:
Style:
/** img-carousel **/
#imgages-carousel {
    display: grid;
    align-items: center;
    justify-items: center;
    padding: 40px 0px;
}
.img-carousel-container {
    width: 800px;
    position: relative;
}
.img-carousel {
    display: flex;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scroll-snap-type: x mandatory;
    scroll-behavior: smooth;
    padding-bottom: 5px;
}
.img-carousel div {
    flex: none;
    scroll-snap-align: start;
    width: 800px;
    position: relative;
}
.img-carousel div img {
    display: block;
    width: 100%;
    object-fit: cover;
}
.img-carousel div p {
    position: absolute;
    top: 0;
    right: 10px;
    background: rgba(0,0,0,0.5);
    color: #fff;
    padding: 5px;
    border-radius: 10px;
}

.img-carousel-container button {
    position: absolute;
    top: calc(50% - 15px);
    transform: translateY(-50%);
    border: none;
    background-color: rgba(255, 193, 7, 0.7);
    color: #000;
    cursor: pointer;
    padding: 10px 15px;
    border-radius: 50%;
    outline: none;
    opacity: 0;
    transition: all ease-in-out 0.5s;
}
#prev {
    left: 10px;
}
#next {
    right: 10px;
}
.img-carousel-container:hover button {
    opacity: 1;
}
.img-carousel-container button:hover {
    background-color: #ffc107;
}

/** custom scrollbar **/
.img-carousel::-webkit-scrollbar {
    width: 10px;
    height: 10px;
}
.img-carousel::-webkit-scrollbar-thumb {
    background: #ffc107;
    border-radius: 10px;

}
.img-carousel::-webkit-scrollbar-track {
    background: transparent;
}
.img-carousel-container:hover .img-carousel::-webkit-scrollbar-thumb {
    visibility: visible;
}

@media screen and (max-width: 800px) {
    .img-carousel-container {
        width: 100%;
    }
    .img-carousel div  {
        width: 100%;
    }
}

Script:
const carousel = document.querySelector('.img-carousel');
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
let carsouselImages = document.querySelectorAll('.img-carousel div');

//Next Carousel
const nextCarousel = () => {
    if(carsouselImages[carsouselImages.length - 1]) {
      carousel.scrollTo(0, 0);
    }
      carousel.scrollBy(300, 0);
};

nextBtn.addEventListener('click', e => {
  nextCarousel();
});

//Prev Carousel
const prevCarousel = () => {
   if(carsouselImages[0]) {
    carousel.scrollTo(4800,0);
   }
    carousel.scrollBy(-300, 0);
};

prevBtn.addEventListener('click', e => {
   prevCarousel();
});

// Auto carousel
const auto = true; // Auto scroll
const intervalTime = 5000;
let sliderInterval;

if (auto) {
  sliderInterval = setInterval(nextCarousel, intervalTime);
};

carousel.addEventListener('mouseover', (stopInterval) => {
  clearInterval(sliderInterval);
});

carousel.addEventListener('mouseleave', (startInterval) => {
  if (auto) {
    sliderInterval = setInterval(nextCarousel, intervalTime);
  }
});

//for mobile events
carousel.addEventListener('touchstart', (stopIntervalT) => {
    clearInterval(sliderInterval);
});
carousel.addEventListener('touchend', (startIntervalT) => {
   if (auto) {
    sliderInterval = setInterval(nextCarousel, intervalTime);
  }
});

//Debounce
var previousCall;
window.addEventListener('resize', () => {
    if (previousCall >= 0) {
        clearTimeout(previousCall);
    }
    previousCall = setTimeout(() => {
      carousel.scrollBy(-300, 0);
    }, 200);
});

Html:

1/6

2/6

3/6

4/6

5/6

6/6

                   <button id="prev"></button>
                   <button id="next"></button>

A: Here is a solution looping through the carousels. All you need to do is to make sure your styles are added. There are styles based on the id of the carousels - that needs to be added for all of them or made universal.
Here is little bit revised answer, no need to declare the functions and variables several times inside the forLoop like it was before.
What this code does it selects all carousels with the class .img-carousel and loops through them. Adding functionality to each carousel and relative buttons (based on index). The core functionality is the same only now it is added dynamically.

const carousels = document.querySelectorAll('.img-carousel');
const prevBtn = document.querySelectorAll('.prev');
const nextBtn = document.querySelectorAll('.next');
let carsouselImages = document.querySelectorAll('.img-carousel div');

//Next Carousel
const nextCarousel = (carousel) => {
    if(carsouselImages[carsouselImages.length - 1]) {
      carousel.scrollTo(0, 0);
    }
      carousel.scrollBy(300, 0);
};
//Prev Carousel
const prevCarousel = (carousel) => {
   if(carsouselImages[0]) {
    carousel.scrollTo(4800,0);
   }
    carousel.scrollBy(-300, 0);
};

// Auto carousel

carousels.forEach((carousel, index)=>{
nextBtn[index].addEventListener('click', e => {
  nextCarousel(carousel);
});
prevBtn[index].addEventListener('click', e => {
   prevCarousel(carousel);
});
// Auto carousel
const auto = true; // Auto scroll
const intervalTime = 5000;
let sliderInterval;
let previousCall;

if (auto) {
  sliderInterval = setInterval(()=>nextCarousel(carousel), intervalTime);
};

carousel.addEventListener('mouseover', (stopInterval) => {
  clearInterval(sliderInterval);
});

carousel.addEventListener('mouseleave', (startInterval) => {
  if (auto) {
    sliderInterval = setInterval(()=>nextCarousel(carousel), intervalTime);
  }
});

//for mobile events
carousel.addEventListener('touchstart', (stopIntervalT) => {
    clearInterval(sliderInterval);
});
carousel.addEventListener('touchend', (startIntervalT) => {
   if (auto) {
    sliderInterval = setInterval(()=>nextCarousel(carousel), intervalTime);
  }
});

//Debounce
window.addEventListener('resize', () => {
    if (previousCall >= 0) {
        clearTimeout(previousCall);
    }
    previousCall = setTimeout(() => {
      carousel.scrollBy(-300, 0);
    }, 200);
});
});
/** img-carousel **/
#imgages-carousel {
    display: grid;
    align-items: center;
    justify-items: center;
    padding: 40px 0px;
}
#imgages-carousel1 {
    display: grid;
    align-items: center;
    justify-items: center;
    padding: 40px 0px;
}
.img-carousel-container {
    width: 800px;
    position: relative;
}
.img-carousel {
    display: flex;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scroll-snap-type: x mandatory;
    scroll-behavior: smooth;
    padding-bottom: 5px;
}
.img-carousel div {
    flex: none;
    scroll-snap-align: start;
    width: 800px;
    position: relative;
}
.img-carousel div img {
    display: block;
    width: 100%;
    object-fit: cover;
}
.img-carousel div p {
    position: absolute;
    top: 0;
    right: 10px;
    background: rgba(0,0,0,0.5);
    color: #fff;
    padding: 5px;
    border-radius: 10px;
}

.img-carousel-container button {
    position: absolute;
    top: calc(50% - 15px);
    transform: translateY(-50%);
    border: none;
    background-color: rgba(255, 193, 7, 0.7);
    color: #000;
    cursor: pointer;
    padding: 10px 15px;
    border-radius: 50%;
    outline: none;
    opacity: 0;
    transition: all ease-in-out 0.5s;
}
.prev {
    left: 10px;
}
.next {
    right: 10px;
}
.img-carousel-container:hover button {
    opacity: 1;
}
.img-carousel-container button:hover {
    background-color: #ffc107;
}

/** custom scrollbar **/
.img-carousel::-webkit-scrollbar {
    width: 10px;
    height: 10px;
}
.img-carousel::-webkit-scrollbar-thumb {
    background: #ffc107;
    border-radius: 10px;

}
.img-carousel::-webkit-scrollbar-track {
    background: transparent;
}
.img-carousel-container:hover .img-carousel::-webkit-scrollbar-thumb {
    visibility: visible;
}

@media screen and (max-width: 800px) {
    .img-carousel-container {
        width: 100%;
    }
    .img-carousel div  {
        width: 100%;
    }
}

1/6

2/6

3/6

4/6

5/6

6/6

    <button class="prev"></button>
    <button class="next"></button>

1/6

2/6

3/6

4/6

5/6

6/6

    <button class="prev"></button>
    <button class="next"></button>


text:
Q: Why do subsequent reads of a multi-gigabyte file run faster? I have some algorithm test software running on a Windows 7 machine which, when run the first time on any given data file, runs ~3-5x slower than on subsequent runs. Our algorithm simply reads the file a few hundred bytes at a time and writes one result back for every ~50 reads operations.
Is there some inherent caching somewhere in Windows (seems unlikely with a 3GB file?) or something else? Is there any way I can speed up that first run?

A:
Is there some inherent caching somewhere in Windows (seems unlikely with a 3GB file?)

Yes, Windows does have a cache that could be responsible for this.
According to the linked MSDN article you can disable caching for a certain file with the flag FILE_FLAG_NO_BUFFERING in the CreateFile call. If you can't change the code, you can instead use the SysInternals RAMMap app to reset the cache between benchmark runs.
See this related posting on SO for details.


text:
Q: httpClient post request call does not succeed in windows.unload event angular I want to send post request from my client to server while user close tab or browser window i am using  'windows.unload'or 'windows.beforeunload' event when i invoke my call in this event it does't succeeded, windows closed before getting response how do i do this, i have tried some thing here is my code
This is 'onbeforeUnload' event
window.onbeforeunload = ()=>{

  this.store.dispatch<any>(this.mystore.UnLock());
}

this is my function in Store
UnLock() {
    return (dispatch, getState) => {
      dispatch(this.resetTimer());
      return this.dataService.Locks('/unlock').subscribe(
        (data: any) => {},
        (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
            dispatch(this.errormsg('Client-side error occured.'));
            console.log('Client-side error occured.');
          }
        }
      );
    };
  }

Here is my data service function
Locks(url: string): Observable<any> {
    return this.httpclient.post(url, {
      headers: _headers
    });
  }

my browser window is closed before getting response from server, i am stuck in this issue how do i resolve this issue.

A: Try like this
-put this code in bootstrap component
export class AppComponent {
  constructor() {
    window.onbeforeunload = (e)=> {
        this.store.dispatch<any>(this.mystore.UnLock());
    };
  }
}

A: If you are using Angular, then use Angular guards to implement it.
For this scenario you have to use

canDeactive

guard in angular.


text:
Q: Accurate angle sensor in humid, bouncy environment I'm working on a midi controller to use while boating. I want to use a hinge for a midi control. This means I want to take the angle inside the hinge and convert it to a value between 0 and 127. The physical range of motion is 0-180 degrees. This means I need an angular position that has less than 180/127/2 or +/-0.7 degrees of error. This hinge could have an arbitrary angle with gravity.
There are numerous angular sensors but none seem to fit the bill entirely. Potentiometers are not accurate. Rotary encoders are prone to errors in high-humidity environments, like boating. IMU's don't work well when the waves are causing regular movement in the device.
I understand that there may not be a perfect solution, but before I go empirically testing each solution and trying to filter out imperfections, I thought I would ask for the advice of those more experienced. Any help you can give would be appreciated.

A: There are magnetic rotary encoders that use a permanent magnet mounted on the rotating shaft combined with two/four fixed magnetic sensors (GMR or Hall elements) for measuring the magnetic field in x- and y-direction with integrated signal conditioning in one IC.
I.e. there is no mechanical contact between rotating shaft and sensor. Sensor and electronics can be encapsulated and hermetically sealed.

(Image taken from https://www.magcam.com/application/2-pole-rotary-encoder-magnets)
E.g. this one. Resolution is 14 bits, i.e. much more than what you required.


text:
Q: What is the probability that there is a re-election If there are $n$ voters and $k$ contestants ($n>k$) in an election. What is the probability that there is a re-election?
Re-election will happened only if two or more lead contestants have got equal number of votes. It is also assumed that any number of voters ($0$ to $n$) may appear on election day for voting or you may assume number of valid votes may vary between $0$ to $n$.
My approach: Any voters may vote any of the contestants or he may not appear for voting or he may cast an invalid vote. In this case, number of ways $n$ voters may cast their votes is $(k+1)^n$. This way I can calculate the total number of events in the sample space,
$$n(S) = (k+1)^n$$
But I don't know how can I calculate the number of favorable outcomes, $n(E).$

A: Let $A_m$ denote the event that $m$ votes are valid and let $A$ denote the event that there is NO re-election. Then
$$  P(A) = \sum_{m=0}^n P(A|A_m)P(A_m) $$
where $P(A_m) = \binom{n}{m}p^m(1-p)^{n-m}$ assuming that votes are independent and their valid with probability $p$.
Now let us look at $P(A|A_m)$ for fixed $m$. If $m=0$, then $P(A|A_m) = 1$ trivially, hence we can assume $m\ge 1$. Counting the number of favorable outcomes boils down to basically writing $m=a_1 + a_2 + \ldots + a_k$, where $a_j\ge0$ denotes the number of votes on candidate $j$, and the maximal value is unique. The number of ways of writing $m$ as the sum of $k$ nonnegative integers is actually a number theoretic question, there is no closed expression known even for the case when $k$ can vary.
Although for some concrete fixed values of $n$ and $k$ one can write a program to count all the cases...

A: This is just a partial answer, but I can't conveniently fit it in a comment box.  I will do the problem for the case $n=1000,\ k=3$ that the OP mentioned in a comment.
We are to assume that there are $4^{1000}$ equally likely outcomes, so we just have to count the number of outcomes that result in a tie.
First, there is the possibility of a three-way tie, where each candidate gets $v$ votes, and $1000-3v$ members do not vote, for $0\leq v\leq333.$  The number of ways this can happen is $$\sum_{v=0}^{333}\binom{1000}{v,v,v,1000-3v}\tag1$$
For the two-way ties, there are three ways to determine which two candidates tie for the lead.  This time, each gets $v$ votes, where $1\leq v\leq500$.  The third candidate gets $w$ votes, where $0\leq w\leq \min\{v-1,1000-2v\}$ and $1000-v-w$ members don't vote.  This gives $$3\sum_{v=1}^{500}\sum_w\binom{1000}{v,v,w,1000-2v-w}\tag2$$
where the inner sum is over all $w$ with $0\leq w <=\min\{v-1,1000-2v\}$
Offhand, I don't know of any convenient way of computing the numbers in $(1)$ and $(2)$, although one can do it with a computer program of course. If you try to do this for general $k$, you'll get a $(k-1)$-fold sum at the end, and it will take someone smarter than me to deal with it.
EDIT
I forgot to bound $w$ by $1000-2v$ in $(2)$.  Corrected.
I wrote a python script to compute this, and amazingly there's a substantial probability, although the assumptions aren't very realistic.  I got a probability of $0.00904$.  Here's the script:
from math import factorial

def choose(n, *args):
    if len(args)==1:
        m =  args[0]
        if m>n: return 0
        args += (n-m,)
    assert sum(args) == n
    answer = factorial(n)
    for m in args:
        answer //= factorial(m)
    return answer

a = sum(choose(1000,v,v,v,1000-3*v) for v in range(334))
b = sum(choose(1000, v,v,w,1000-2*v-w)
      for v in range(1,501)
      for w in range(min(v,1001-2*v) ))
print((a+b)/4**1000)


text:
Q: BufferedReader `is.ready()` method not working properyly try {
        Scanner inConsole = new Scanner(System.in);
        String CONNECT_TO_WHOM = "";
        Socket clientEndPoint = new Socket("localhost", 9000);
        PrintWriter out = new PrintWriter(clientEndPoint.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientEndPoint.getInputStream()));

        MessageFromServerThread messageFromServer = new MessageFromServerThread(in);
        messageFromServer.start();

        // Giving Client Details To whom To Connect
        if(!in.ready())
        CONNECT_TO_WHOM = inConsole.nextLine();

        //System.out.println("You are Connecting To This " + CONNECT_TO_WHOM);
        out.println(CONNECT_TO_WHOM);
        //break;

        System.out.println("To quit press q");
        //inConsole.nextLine();
        while(!clientMessage.equals("q")) {
                out.println(clientMessage = inConsole.nextLine());
                //System.out.println(in.readLine());
        }
        System.out.println("Check in chatClient");
    } catch(Exception e) {
        e.printStackTrace();
    }

The code working flow:
Whenever client gets connected it the server, server will inform the client about all the other available clients, Then the from the client, server expects to which client to connect.
Here, there is a possibility that the client can be connected to another client before he wants to communicate with others. In that case the server informs that you are connected to Client X. I want to check this incident occurrence, via the if(!in.ready()).
I do understand that the in buffer could very well be empty. any way to effectively do this checking.

A:
The java.io.BufferedReader.ready() method informs whether the stream
  is ready to be read. A buffered character stream is only ready when
  the buffer is not empty or if the underlying stream is ready.

So your buffer should be empty to make it return false condition


text:
Q: React - Formik - Field Arrays - implementing repeatable form fields I am trying to follow the Formik documentation on using FieldArrays so that I can add repeatable form elements to my form.
I've also seen this Medium post setting out an example.
I'm slow to learn and can't join the dots between the documentation and the implementation.
I want to have a button in my main form that says:  "Add a request for data".
If that button is selected, then a nested form setting out the data profile is displayed, along with "add another data request" and "remove" buttons.
I have made the nested form in another component in my application, but I'm struggling to figure out how to use the example from the medium post to incorporate the nested form (as a repeatable element - ie someone might want 5 data requests).
Are there any examples of how to implement this?
In my code, I have basically followed the medium post, but tried to link the Data Request form component inside the index
<button
      type="button"
      onClick={() => arrayHelpers.insert(index, <DataRequestForm />)}>
      Add a data request
</button>

This is plainly incorrect, but I can't get a handle on how to do this.
Taking Nithin's answer, I've tried to modify the embedded form so that I can use react-select, as follows, but I'm getting an error which says:

TypeError: Cannot read property 'values' of undefined

import React from "react";
import { Formik, Form, Field, FieldArray, ErrorMessage, withFormik } from "formik";
import Select from "react-select";

import {
  Button,
  Col,
  FormControl,
  FormGroup,
  FormLabel,
  InputGroup,
  Table,
  Row,
  Container
} from "react-bootstrap";

const initialValues = {
  dataType: "",
  title: "",
  description: '',
  source: '',

}

class DataRequests extends React.Component {

  render() {
    const dataTypes = [
      { value: "primary", label: "Primary (raw) data sought" },
      { value: "secondary", label: "Secondary data sought"},
      { value: "either", label: "Either primary or secondary data sought"},
      { value: "both", label: "Both primary and secondary data sought"}
    ]

    return(
      <Formik
          initialValues={initialValues}
          render={({
            form,
            remove,
            push,
            errors,
            status,
            touched,
            setFieldValue,
            setFieldTouched,
            handleSubmit,
            isSubmitting,
            dirty,
            values
          }) => {
          return (

                {form.values.dataRequests.map((_notneeded, index) => {
                return (

                              Title
                              <Field
                                name={`dataRequests.${index}.title`}
                                placeholder="Add a title"
                                className={"form-control"}
                              >
                              </Field>

                                Description
                                  <Field
                                    name={`dataRequests.${index}.description`}
                                    component="textarea"
                                    rows="10"
                                    placeholder="Describe the data you're looking to use"
                                    className={
                                      "form-control"}
                                  >
                                  </Field>

                              Do you know who or what sort of entity may have this data?
                                <Field
                                  name={`dataRequests.${index}.source`}
                                  component="textarea"
                                  rows="10"
                                  placeholder="Leave blank and skip ahead if you don't"
                                  className={
                                    "form-control"}
                                >
                                </Field>

                              Are you looking for primary (raw) data or secondary data?

                              <Select
                              key={`my_unique_select_keydataType`}
                              name={`dataRequests.${index}.source`}
                              className={
                                  "react-select-container"
                              }
                              classNamePrefix="react-select"
                              value={values.dataTypes}
                              onChange={selectedOptions => {
                                  // Setting field value - name of the field and values chosen.
                                  setFieldValue("dataType", selectedOptions)}
                                  }
                              onBlur={setFieldTouched}
                              options={dataTypes}
                              />

                          <Button variant='outline-primary' size="sm" onClick={() => remove(index)}>
                            Remove
                          </Button>

                );
              })}
              <Button
                variant='primary' size="sm"
                onClick={() => push({ requestField1: "", requestField2: "" })}
              >
                Add Data Request
              </Button>

          )
          }
          }
      />
    );
  };
};

export default DataRequests;

A: You cannot add nested forms inside a form element.
Please refer the below post for mode details.
Can you nest html forms?
If you are looking to nest multiple fields with a nested structure, inside a main form, you can achieve it using FieldArrays.
You can structure the form like.
{
    firstName: "",
    lastName: "",
    dataRequests: []
  }

Here firstName and lastName are top level form fields and dataRequests can be an array where each element follows the structure
{
  requestField1: "",
  requestField2: ""
}

Since dataRequests is an array, for rendering each item of FieldArray you need a map function.
form.values.dataRequests.map( render function() )

And for each rendered item, the change handlers should target their index to update the correct item in FieldArray.

            <Field
              name={`dataRequests.${index}.requestField1`}
              placeholder="requestField1"
            ></Field>
            <Field
              name={`dataRequests.${index}.requestField2`}
              placeholder="requestField2"
            ></Field>
            <button type="button" onClick={() => remove(index)}>
              Remove
            </button>

In the above snippet name={dataRequests.${index}.requestField1} asks formik to update the key requestField1 of nth element of dataRequests array with the value of the input field.
Finally your <DataRequest /> component might look something like below.
import React from "react";
import { Field } from "formik";

export default ({ form, remove, push }) => {
  return (

      {form.values.dataRequests.map((_notneeded, index) => {
        return (

            <Field
              name={`dataRequests.${index}.requestField1`}
              placeholder="requestField1"
            ></Field>
            <Field
              name={`dataRequests.${index}.requestField2`}
              placeholder="requestField2"
            ></Field>
            <button type="button" onClick={() => remove(index)}>
              Remove
            </button>

        );
      })}
      <button
        type="button"
        onClick={() => push({ requestField1: "", requestField2: "" })}
      >
        Add Data Request
      </button>

  );
};

And using <FieldArray /> you can connect <DataRequest /> to the main form.
You can try out the below sample SO snippet

function DataRequests({ form, remove, push }){
  return (

      {form.values.dataRequests.map((_notneeded, index) => {
        return (

            <Formik.Field
              name={`dataRequests.${index}.requestField1`}
              placeholder="requestField1"
            ></Formik.Field>
            <Formik.Field
              name={`dataRequests.${index}.requestField2`}
              placeholder="requestField2"
            ></Formik.Field>
            <button type="button" onClick={() => remove(index)}>
              Remove
            </button>

        );
      })}
      <button
        type="button"
        onClick={() => push({ requestField1: "", requestField2: "" })}
      >
        Add Data Request
      </button>

  );
};

class Home extends React.Component {
  initialValues = {
    firstName: "",
    lastName: "",
    dataRequests: []
  };
  state = {};
  render() {
    return (

        <Formik.Formik
          initialValues={this.initialValues}
          onSubmit={values => {
            this.setState({ formData: values });
          }}
        >
          {() => {
            return (
              <Formik.Form>

                  <Formik.Field
                    name="firstName"
                    placeholder="First Name"
                  ></Formik.Field>

                  <Formik.Field
                    name="lastName"
                    placeholder="Last Name"
                  ></Formik.Field>

                <Formik.FieldArray name="dataRequests" component={DataRequests} />
                <button type="submit">Submit</button>
              </Formik.Form>
            );
          }}
        </Formik.Formik>
        {this.state.formData ? (
          {JSON.stringify(this.state.formData, null, 4)}
        ) : null}

    );
  }
}

ReactDOM.render(<Home />, document.getElementById("root"))

A: For anyone looking to learn from this post, the answer to this question from nithin is clearly motivated by good intentions, but it isn't a correct deployment of formik. You can check out a code sandbox here: https://codesandbox.io/embed/goofy-glade-lx65p?fontsize=14 for the current attempt at solving this problem (still not fixed) but a better step toward a solution. Thanks just the same for the helpful intentions behind the answer to this question.


text:
Q: Action when form is closed How to make as by pressing to the close button, make so that the form was not closed, and it was turned off?
private void Form1_Closed(object sender, EventArgs e)
{
    Form1.Hide();
}

So the form is all the same closed.

A: You should do it on FormClosing not FormClosed event like this:
private void Form1_FormClosing(object sender, EventArgs e) {
    Form1.Hide();
    e.Cancel = true;
}

FormClosed means the form is already closed.

A: You want to interrupt the form closing event and cancel it, for example to minimize:
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
   e.Cancel = true;
   this.WindowState = FormWindowState.Minimized;
}

A: see Form.Closing Event
Here is the sample. you have several options
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
  // this.Hide();
  // e.Cancel = true;
  this.Close();

}

to remove a form both from the
  display, and from memory, it is
  necessary to Close rather than Hide it

A: Use the FormClosing event, and set e.Cancel to true.


text:
Q: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type MVC 5 I know these question(s) has been asked

*

*Cannot convert lambda expression to type 'string' because it is not a delegate type

*Entity Framework - Cannot convert lambda expression to type 'string' because it is not a delegate type
But none of them has helped me to find the problem that i am facing
i have tried to use this solution

     @Html.LabelFor(model => model.Postcode_area_name, htmlAttributes: new { @class = "control-label col-md-2" })

 @Html.TextBox(model => model.Postcode_area_name, new { disabled = "disabled", @readonly = "readonly" })

to make one edit field read only, but i do get an error of
Cannot convert lambda expression to type 'Delegate' because it is not a delegate type
i do use entity frame work and these using
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CRM2.Models;

the suggestion on other questions are that using
using System.Data.Entity;
using System.Linq;

should fix the problem but it does not work for me
I am using MVC 5
i have fixed the issue by using this solution
@Html.DisplayFor(model => model.Postcode_area_name)
@Html.HiddenFor(model => model.Postcode_area_name)

but because i am new on MVC and entity frame work i want learn why the other way throw an error
Sorry for English "mistake"
Thank you

A: So your original code:

     @Html.LabelFor(model => model.Postcode_area_name, htmlAttributes: new { @class = "control-label col-md-2" })

         @Html.TextBox(model => model.Postcode_area_name, new { disabled = "disabled", @readonly = "readonly" })

You should change it to:

     @Html.LabelFor(model => model.Postcode_area_name, htmlAttributes: new { @class = "control-label col-md-2" })

         @Html.TextBoxFor(model => model.Postcode_area_name, new { @readonly = "readonly" })

Note, the addition of For on the TextBox and the removal of disabled = "disabled"
The reason for removing disabled as per @StephenMuecke

disabled controls do not submit a value

The reason for adding For is that it's extension method signature has the first parameter of an expression

A:

 @Html.LabelFor(model => model.Postcode_area_name, htmlAttributes: new { @class = "control-label col-md-2" })

 @Html.TextBoxFor(model => model.Postcode_area_name, new { @readonly = "readonly" })

As you are using tightly bound entities


text:
Q: CRM Find Records 'Not In' a Marketing List I am trying to find all contacts that are not in a given marketing list. It seems like a simple request but is proving impossibly hard to execute. There does not seem to be a way to do this in Advanced Find. Ideally, the following query would work but I understand why it does not;

Has anyone ever needed to do this, and how have they gone about it? The only way I can see is to create a SQL query to retrieve the data and then add an SSRS report to the system.
Any pointers would be greatly appreciated!

A: There is no direct way to get Not In query in Advanced Find at the moment. You already mentioned SSRS option. Another one possible solution is usage of Marketing lists. Here are steps you have to apply to get the result:

*

*Create Marketing list with Contact type.

*Add all contacts inside.

*Remove contacts from the list using Advanced Find Query like "Get contacts that belong to Marketing List Training".

You can find step-by-step instruction here - http://www.powerobjects.com/2012/10/16/searching-for-accounts-contacts-without-opportunities/


text:
Q: Laravel - multiple parameters in the URL I have a simple foreach loop that loops through the current week dates in Y-m-d format:
@foreach($dates as $date)
    date('Y-m-d', strtotime($date))]))}}">{{date('l', strtotime($date))}}
@endforeach

With above, I can simply click on the anchor link, and the specific date will be appended:
example.org/consols?date=2020-03-04

Now I use this to filter a specific SQL query and I wish to be able to filter for multiple dates. For example:
example.org/consols?date=2020-03-04&date=2020-03-05&date=2020-03-06

Where in above example, I wish to send 3 dates as query parameters.
If I simply append another &date= to the already present ?date, it will only select the last date= in the query string.
How can I, with PHP, send multiple variables in my URL with the same parameter name?

A: Add an integer $i
['date'.$i => date('Y-m-d'

You will have date1= &date2= & date3=

A: You can add your date as array i.e. date[].
Your URL would look like:
example.org/consols?date[]=2020-03-04&date[]=2020-03-05&date[]=2020-03-06

When you console your query it will give you
{ date: [ '2020-03-04', '2020-03-05', '2020-03-06' ] }

A: I ended up looking at the link CodyKL linked to, and from there saw that I could actually use http_build_query.
This is my solution:

$url = [];
$dates = isset($_GET['date']) ? $_GET['date'] : null;
if($dates){

  foreach($dates as $date){
     $url['date'][] = date('Y-m-d', strtotime($date));
  }

}

$query = http_build_query($url);

Then I can simply just redirect to $query.


text:
Q: Microsoft.Reporting.* vs XML/XSLT I would like to add reporting capabilities to a .NET application. My data source is just the data model of the application, i.e. a bunch of objects that may have been generated or loaded from anything (not necessarily from a database).
The initial plan was to generate a report data XML file from these objects, and then use XSLT to transform this into an XHTML report file. The report can then be shown in the application with a browser control.
However, I've noticed that there exist Microsoft.Reporting.* namespaces and from what I've tried, it seems that the classes and controls in there can also take care of my reporting. Would it be a good idea to use this instead? Will it save work compared to the XML/XSLT approach? What limitations (if any) of the Microsoft Reporting framework am I likely to run into?

A: A couple of things to consider.
1) Reporting Services are part of Sql Server, so you may have an extra license issue if you go that route.
2) Reporting Services can serve up web pages, or be used in WinForms with full paging, sorting, sub reports, totals etc etc - that's really hard in XSL. It will also play nicely with printers.
3) Reporting services comes with a WYSIWYG editor to build reports. It's not perfect by any means, but a lot easier than hand crafting.
4) Using XSL to create XHTML can be real performance hit. XSL works on an entire XML Dom, and that maybe a big document if you're dealing with a multipage report. I'd expect Reporting Services to work a lot faster.
5) Reporting Services can leverage the whole of .Net, so you can get a lot of other functionality for free.
Taking all that on board, using Reporting Services will save you time, unless your reporting requirements are very simple. It is less fun though.

A: Agree with most of MrTelly's comments with the following exceptions and additions:

*

*Unless you're dumb about your XSLT and your reporting data is HUGE (100+ MB -- bare in mind I'm talking about the data that feeds the report and NOT the source data), performance isn't likely to be a significant problem.  We've built an XML/XSLT reporting system that takes .NET datasets and transforms them to reports on the fly and with properly written XSLT, performance is mostly subsecond (for large datasets it can be longer, but nothing horrible for a web app).

*Report Layout with an XML/XSLT solution is essentially unlimited, with Reporting Services, you are restricted to the constructs within RDL (Microsoft's Report Definition Language).  If you need something more complicated than standard reporting structures, Reporting Services will be frustrating.

A: Data Dynamics Reports and ActiveReports (and other third party .NET tools) can also report directly off of objects and have a developer-friendly licensing policy.

A: seems you could also generate the xml from your objects and then create your native ReportViewer Report from that XMl as well
Building Reports from XML Documents using ReportViewer
http://www.c-sharpcorner.com/UploadFile/mahesh/XmlReports04182007115639AM/XmlReports.aspx