text:
Q: Construction of equivariant Steenrod algebra I am reading through the calculations in Hu-Kriz "Real-oriented homotopy theory and an analogue of the Adams-Novikov spectral sequence" and I've got a small problem in understanding the computations of coefficients of the "first version" of $C_2$-equivariant Steenrod algebra.
Notation:

*

*$H$ is a $C_2$-spectrum constructed as follows: we take the naive Eilenberg-MacLane spectrum associated to the constant Mackey functor $\underline{\mathbb{Z}/2}$ and extend it to a complete universe.

*$A_\star=(H\wedge H)_\star$ is a dual Steenrod algebra associated to $H$ ($RO(C_2)$-graded) and $A_\ast$ is its part graded over the integers.

*$H^f_\star=(H\wedge EQ_+)_\star$ - the coefficients of homotopy orbits.

Now in Proposition 6.6 the authors compute $A_\star$ by smashing $H\wedge H$ with the isotropy separation sequence. This yields the exact sequence
$$
\ldots\to (H\wedge H\wedge EC_{2+})_\star\to A_\star\to (H\wedge H\wedge\widetilde{EC_2})\to\ldots.
$$
The authors claim that $(H\wedge H\wedge EC_{2+})_\star\cong A_\ast\otimes H^f_\star$. I cannot see why this is true; I suppose it might come from applying homotopy orbits spectral sequence, but it seems quite complicated to me.


text:
Q: PrimeNG datatable cols with nested json object I've a directive for creating table using PrimeNG p-datatable:

                ...

Inside service a create an entity like this:
        header = new MyTableHeaders();
        header.header = "Col Head"
        header.field = "field";
        header.sortable = false;
...

The is when I've a nested object to pass in, like this:
name: "name",
address: {
   city: "city",
   street: "street",
   ...

I tried to pass:
header = new MyTableHeaders();
header.header = "Col Head"
header.field = "address.city";
header.sortable = false;

or
header = new MyTableHeaders();
header.header = "Col Head"
header.field = "address[city]";
header.sortable = false;

but no value appears in col. Can you help me?
Thanks

A: I think you have to change your p-column to include a ng-template...
Have a look at

    <ng-template let-col let-sessions="rowData" let-ri="rowIndex" pTemplate="body">

{{sessions.Sessions[0].StartDateTime | date: 'd,MMM,yyyy'}}

    </ng-template>

for an example. See also here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Manage distribution of container threads to avoid session timeout I have a webApp deployed on a Gateway server which is actually a reverse proxy for an upstream server. The gateway receives HTTP requests from clients and also from the upstream server.The upstream server keeps sending requests periodically. The requests of client are serialized and written in the response  to upstream server. The gateway server is Apache tomcat and has 200 threads by default. An HTTP session is created for the upstream server, at the gateway. If client sends 200 requests, all threads of the gateway are occupied and the requests of upstream server get rejected. The session times out and client receives error response - HTTP 503.
I do not wish to change the default server thread pool size.
I can either reject client requests after they reach some specified max count, or I can use two  different thread pools by creating two different ports (connectors in case of tomcat). Is there anything else I can do?
thanks in advance.


text:
Q: hibernate createCriteria From Hibernate source, in Criteria.class, we have:
List cats = session.createCriteria(Cat.class)
  .createCriteria("kittens")
      .add( Restrictions.like("name", "Iz%") )
  .list();

What is 'kittens' here? The name of a column? Are not column names specified by using a ProjectionList?
Thanks

A: Here is the complete example from the Hibernate docs:

16.4. Associations
By navigating associations using createCriteria() you can specify constraints upon related entities:

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "F%") )
    .createCriteria("kittens")
      .add( Restrictions.like("name", "F%") )
    .list();

The second createCriteria() returns a new instance of Criteria that refers to the elements of the kittens collection.

So, "kittens" is a collection-type property for your Cat entity, for which a nested criterion is created, which constrains the kittens to only have names starting with F.
I think this means that you will only get Cats named starting with F with at least one kitten named starting with F.
List cats = session.createCriteria(Cat.class)
 .createCriteria("kittens")
   .add( Restrictions.like("name", "Iz%") )
 .list();

In your example, it returns all Cats with at least one kitten named starting with Iz.
I find this syntax kind of confusing, since the nesting is flattened. A Java source code formatter will also take away the helpful indentation.

Are not column names specified by using a ProjectionList?

This is not a projection. You are still getting all "columns". This is selection (a WHERE clause in SQL terms).

A: Kittens is a collection belonging to Cat. This query will return a List of Cat objects whose kittens collections contain only Cats starting with "Iz".
Edit: see Thilo's answer.


text:
Q: cannot retrieve object of TreeViewItem I have a tree view in silver light which i am creating dynamically from my code behind on the load event of my .xaml page. My treeview contains numerous treeviewitems.The header of my treeviewitem contains a stack panel. My stackpanel contains a check box as child. I have created an event handler for Unchecked event of the check box.

Now here is my problem.
When the unchecked event of my check box is triggered i want to retrieve the object of treeviewitem that is consuming the check box.
Here is the code snippet that shows how i am creating my treeviewitem
    objTreeviewItem = new TreeViewItem();
    objStackPanel = new StackPanel();
 objStackPanel.Orientation = Orientation.Horizontal;
objCheckBox = new CheckBox();
   objCheckBox.Content = "Checkbox1";
   objCheckBox.Unchecked += new RoutedEventHandler(objCheckBox_Unchecked);
   objStackPanel.Children.Add(objCheckBox);
   objTreeviewItem.Header = objStackPanel;

Here is the code snippet for unchecked event of the checkbox
void objCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {

                   TreeViewItem objItem = (((e.OriginalSource) as CheckBox).Parent as StackPanel).Parent as TreeViewItem;

            }
            catch (Exception ex)
            {

            }
        }

The above statement in the try block is returning me a null value. Hence i am not able to retrieve the treeviewitem which is consuming the check box on which event has been triggered.
So is there any other Property or method(other then the parent property) which can help me get the treeviewitem.
Please any kind of help will be appreciated

A: The OriginalSource property does not return your CheckBox but whatever control on which the event started which may be a TextBlock inside the CheckBox, cast the sender instead, it will always be the control the event is associated with.


text:
Q: How does the magnetic field of an inductor affect the operation of a DC circuit? I was reading about the operation of inductors in DC circuits on the website All About Circuits, and I'm a bit confused on how an inductor operates in a DC circuit.
So far, I understood that any current flowing through a conductor will produce a magnetic field force and, consequently, a magnetic field flux, which is perpendicular to the conductor. And by making the conductor coil-shaped, the magnetic field flux will increase because it gets concentrated.
So far this is kinda clear.
But then two sentences confused me:

*

*
Whereas an electric field flux between two conductors allows for an accumulation of free electron charge within those conductors, a magnetic field flux allows for a certain "inertia" to accumulate in the flow of electrons through the conductor producing the field.

What do they mean by inertia accumulating in the flow of electrons?
What I understood from this sentence is that eventually the magnetic field force will become so high that it will prevent any more current from flowing. However, I know that magnetic field flux is perpendicular to the conductor, so I don't see how it can prevent the current from flowing. This is why I'm confused and why I think they mean something else by inertia.

*
As the electric current produces a concentrated magnetic field around the coil, this field flux equates to a storage of energy representing the kinetic motion of the electrons through the coil.

From this sentence I understood that magnetic field flux is the equivalent of energy in the inductor. And of course this energy was taken from the circuit's voltage source, so if this energy becomes equal to the energy supplied by the voltage source, shouldn't it, eventually, prevent any more current from flowing through the circuit?
I'm really confused in here...

A: Unfortunately, your source does not have a good understanding of physics, so has chosen some bad analogies. 'Inertia of electron flow' is harking back to the water flowing through pipes analogy, which is OK for voltage, current and resistors, but gets stretched too far when it comes to inductors.
Current flowing in the wires of an inductor create a magnetic field in the inductor core, which is at right angles to the wire.
Energy is stored in the magnetic core of the inductor. This energy has come from the power supply's energy source. Energy is stored as the magnetic field, and has nothing to do with kinetic energy. It's stored in the field, just as an electric field stores energy between two conductors at different voltages. What the field is is best left to quantum physics. You can think of a field as stretchy rubber sheet if you like. It isn't, but it helps some people.
It's this stored energy that drives the 'unusual' behaviour of capacitors and inductors. Capacitors store energy as the square of the voltage. Inductors store energy as the square of the current. If you try to change their voltage or current (respectively), you have to change the stored energy. If you try to do this quickly, then it requires (or generates) a high power (energy change per time). If you've ever short-circuited a big capacitor, or open-circuited a big inductor, you'll know what a spark you get.
There are two limits to how much current can usefully be pushed into an inductor, but neither has to do with the magnetic field interacting with the wires.
The first is heat. The current generates heat in the resistance of the wire, and the first thing to fail as the temperature rises is usually the wire insulation. So as long as it's limited to a very short time, very large currents can be applied, before the temperature rises too far.
The second is magnetic saturation. At a certain current, the core reaches its maximum field, and its permeability drops. Higher current (up to the thermal limit) will not damage the inductor, but its inductance value will have dropped radically, and little more energy can be stored. It's the practical limit for operation. If the inductance value is being relied on to limit a changing current, onset of saturation is a bad thing and usually results in a further sudden increase of current.

A: A useful mental model of a inductor for the purpose of designing circuits is that inductors impart inertia to current.  This is false and non-sensical at the physics level, but a useful abstraction when trying to picture what a inductor does in a circuit.
Consider current running thru a piece of wire.  There is always some unavoidable inductance, but for individual wires it's usually so small we can ignore it.  Let's say you connected this wire to a 5 V source with 5 Ω in series across the ends of the wire.  As soon as you connect it, 1 A will flow instantly.  When you disconnect it, the current stops flowing instantly and goes to 0 A.
Now replace that wire with a inductor.  When you first connect it, the current will ramp up, not jump to the final value instantly.  Actually, the current is a exponential that asymptotically approaches the steady state value of 1 A.  The larger the inductor, the larger the time constant.
One way to mentally picture this (again, don't try to think of the physics this way) is that the inductor gives inertia to the current.  When you first connect the "push" (the voltage), the current starts going up.
Now think of what happens when the circuit is opened.  The current thru the inductor doesn't want to stop suddenly, just like a car going down the road can't stop suddenly.  It takes a sustained force over some time to stop the car.
Likewise, it takes a sustained reverse voltage over some time to stop the current.  But I can hear you thinking, we just opened the circuit, so there can't be any current.  The problem is that this is a case where the approximation of all components being ideal breaks down.  Somewhere there is a switch that has to open to stop the current flowing.  That could be a transistor or a mechanical contact.
Let's look at what happens as a mechanical contact opens.  It can't instantly jump from connected to far apart.  At some point, it just starts to open, and there is a very small air gap between the contacts.  Due to the "inertia" of the current, the current can't change instantaneously.  Immediately after the contacts open, the voltage goes high enough to arc across the little air gap, which continues to allow current to flow.  That does cause some voltage across the switch, which applies reverse voltage across the inductor, which cause the current to decrease.  Eventually the current goes to 0, and everything is back to the open-circuit steady state.
You may have a problem imagining how this inductor can make a high voltage.  Think of the car being slowed down.  When it is slowed down normally, the brakes cause a reverse force, which causes the speed to go down until it eventually gets to 0.  However, trying to open the circuit quickly with a mechanical switch is like the car hitting a solid wall.  The reverse force gets very high.  Due to being so high, it stops the car quickly (and in this case destructively).
In the case of a inductor and mechanical switch opening, it's the switch that gives a bit, unlike the car hitting a wall where the car gives instead of the wall.
Go back to the basic equation of what a inductor does, and you can see this behavior described mathematically:
    dI = V dt / L
A voltage (V) applied for some time (dt) cause a current increment (dI) inversely proportional to the inductance (L).  In common units:
    dA = V ds / H
dA is the current increase in Amperes, V the voltage, ds the seconds the voltage is applied, and H the inductance in Henries.
For example, if you apply 5 V to 100 mH for 30 ms, the current rise in the inductor will be (5 V)(30 ms)/(100 mH) = 1.5 A.
This ability of a inductor to make a high voltage when you try to stop the current thru it quickly is the basis for how boost converters work.

First, the inductor is "charged up" by connecting it between the input supply and ground.  This is done by closing the switch.  That causes the current thru it to rise linearly.
When the current gets to a nice level, the switch is opened.  The inductor current can't stop instantaneously.  The inductor makes whatever voltage it takes to keep the current flowing in the short term.  The current therefore flows thru the diode, charging the output capacitor.  This puts reverse voltage across the inductor, reducing its current over time.
This switch is then closed again.  That stops current from flowing to the output, but builds up current in the inductor.  This process repeats rapidly to deliver lots of little shots of current to the output.

A: You asked how an inductor affects the operation of a DC circuit. Strictly speaking, a DC circuit has a constant current, which means that an ideal inductor behaves exactly like a short-circuit. There is a zero voltage drop across it and it neither helps nor hinders the flow of the constant current.
The only time the inductor has any effect is when there is a change in current, like when you open or close a switch in the circuit. When that happens, the inductor resists any change in current; it tries to keep the current the same as before. This is the "inertia" that the "All About Circuits" website describes.
The magnetic flux is like a heavy flywheel that tends to keep the current flowing at the same rate. To change the current, you have to apply a force to the flywheel to speed it up or slow it down. The bigger and heavier the flywheel, the bigger the inductance, and the harder it is to change the current.
The following website (which I wrote) might help you understand the concept better:
http://ataridogdaze.com/science/hydraulic/index.html
Click the "Inductor" link to watch the video or read about the analogy between an inductor and a flywheel.


text:
Q: Spring properties and idempotentKey in uri of a File endpoint I'm using a file endpoint to monitor changes on a file.

*

*I need to be notified whenever the file is edited (i.e., the last-modified time changes)

*I should specify the path of the file from properties, using Spring property placeholders

Everything works fine if I write:
<camelContext>
  <route>
    <from uri="file:/my/path?fileName=myFilename.txt&noop=true&idempotentKey=${file:name}-${file:modified}" />
    <log message="Received file: ${header.CamelFilePath} (${header.CamelFileLastModified})" />
    <to uri="direct:result" />
  </route>
</camelContext>

But if I change the code to use Spring properties, therefore creating an <endpoint>, it doesn't work anymore.
<camelContext>
  <endpoint id="fileEndpoint"
  uri="file://${ids.log.dir}?fileName=${ids.log.file}&noop=true&idempotentKey=${file:name}-${file:modified}" />

  <route id="fileRoute">
    <from ref="fileEndpoint" />
    <log message="Received file: ${header.CamelFilePath} (${header.CamelFileLastModified})" />
    <to uri="direct:result" />
  </route>
</camelContext>

I guess there is an issue with the ${} notation and the ${file:...} placeholders being expanded too early.
How can I resolve this issue? (I shall use Spring properties, not Camel's.) Is there any way to escape the $?

A: Camel property placeholders is using {{ and }} style. See more details at

*

*http://camel.apache.org/using-propertyplaceholder.html
And this FAQ:

*

*http://camel.apache.org/how-do-i-use-spring-property-placeholder-with-camel-xml.html


text:
Q: Conformal harmonic maps in high dimensions are scaled isometries It is well-known that conformal maps between $2$-dimensional Riemannian manifolds are harmonic.
I discovered lately that in dimension $d>2$, conformal harmonic maps must be scaled isometries (The conformal factor is constant).
This is a "rigidity phenomena"- in stark contrast to the $2$D case, in higher dimensions the set of conformal and harmonic maps is very "small".
I am quite sure this should be already known, but couldn't find a reference.
Any help?

A: After posting in MO, it turns out that:
Indeed, the result can be found in the book Harmonic morphisms between Riemannian manifolds, by Paul Baird, John C. Wood.
The relevant statement is Corollary 3.5.2.


text:
Q: Scala and @Inject annotation I know that the best way to deal with dependency injection in Scala is using tools that were built specifically for the language, but I working on a project that must integrate some Scala and Java code.
Then, I am using Google Guice, that implements specification JSR-330. Fortunatly, I found no problem during integration of Guice and Scala. I am using constructor injection, because I have to deal with immutability.
My question is, why in Scala we have to use the notation @Inject() in front of the constructor parameter? Why the () paranthesis? It follows an example:
class MyClass @Inject() (val another: AnotherClass) {
  // Body of the class
}

A: It is all about the syntax of annotating a constructor. Scala requires a constructor annotation to have one (and exactly one) parameter list (even if it is empty)
class Bar @Fooable() ( val i : Int) {

}

What would the i parameter belong to below: The annotation or the Bar class?
class Bar @Fooable( val i : Int) {

}

A: Otherwise, how could you tell if (val another: AnotherClass) is constructor parameter list or arguments to @Inject?


text:
Q: Creating an executable file with an icon from another assembly I'm looking for a way to take an icon from an executable, and create a new executable (using CSharpCodeProvider) that uses this icon.
The first part is easy, I do it using:
Icon icon = Icon.ExtractAssociatedIcon(path);

The problems come when I want to "attach" the icon. I tried using:
compilerParameters.CompilerOptions = @"/win32icon:"

But this solution requires the icon to be written in a file and I'd like to avoid that (one of the reason being it's such a mess to save an icon with more than 16 colors...).
Is it possible to use the System.Drawing.Icon object in memory directly?
EDIT: Just to be clear, I'm trying to obtain a code that can compile C# code into an executable. This executable will have an icon that is only hold in memory (as an Icon object) and not in a file (as a .ico file).

A: Use the IconLibrary to save Icon
Icon icon = Icon.ExtractAssociatedIcon(@"C:\Windows\System32\notepad.exe");
MultiIcon mIcon = new MultiIcon();
SingleIcon sIcon = mIcon.Add("notepad");
sIcon.CreateFrom(icon.ToBitmap(), IconOutputFormat.Vista);
sIcon.Save(@"c:\notepad.ico");

And use that for CompilerOptions
More information
https://msdn.microsoft.com/en-us/library/2aaxe43f.aspx

A: Solution :
In case anyone is looking to do the same thing, here is a method that brought the expected result (icon extracting with correct graphic quality).
I use Tsuda Kageyu IconExtractor in order to get the icon I want and convert it to Bitmap with the transparency.
Then I use the IconLibrary suggested by @mohsen to write in icon as a .ico file and then embed it with the CompilerOptions.


text:
Q: How get Live Connect(Hotmail) Calendar Object ID.? I want to sync Hotmail Calendar with my Java web Application.(Not Android app).
Live Connect Dev suggests REST using below syntax.
GET https://apis.live.net/v5.0/calendar.611afb17fa9448f28cdb8277e8ffeb77?access_token=ACCESS_TOKEN
where calendar.611afb17fa9448f28cdb8277e8ffeb77 is calendar's ID.
Can anyone tell me how to get calendar's ID.?
Thanks,
Ram

A: I don't know is this question still valid or not, but i think will be good for documentation purposes.
before you call the detail of the calendar, you should list all calendar object first, by using
https://apis.live.net/v5.0/me/calendars?access_token=ACCESS_TOKEN

there then you'll get the list of calendar data.
but don't be confused with CALENDAR or EVENTS
you can get all list of events by using:
https://apis.live.net/v5.0/me/events?start_time=2012-10-01T00:00:00Z
     &end_time=2012-10-03T00:00:00Z&access_token=ACCESS_TOKEN

good luck


text:
Q: changes subView frame when rotate i add subView(backgroundView) in uiview in my base view controller its working well in potratate but when i change orientation from potraite to landscape its frame size is same as potrait i want to change size of subview when rotate.
UIView *activityView = [[UIView alloc] initWithFrame:self.view.bounds];
CGRect frame = activityView.frame;
activityView.frame = frame;
activityView.backgroundColor = [UIColor clearColor];
activityView.alpha = 0.0f;
[self.view addSubview:activityView];
self.activityView = activityView;
UIView *backgroundView = [[UIView alloc]initWithFrame:activityView.bounds];
backgroundView.alpha = 0.0f;
[backgroundView setBackgroundColor:[UIColor lightGrayColor]];
[self.activityView backgroundView];
UIActivityIndicatorView *spinning = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.activityView spinning];
spinning.center = activityView.center;
self.activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[spinning setColor:[UIColor lightGrayColor]];
[spinning startAnimating];

A: To do this you must add constraints to your view (AutoLayout).
For example :
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView
                                                      attribute:NSLayoutAttributeTop
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeTop
                                                     multiplier:1.0
                                                       constant:0.0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView
                                                      attribute:NSLayoutAttributeLeading
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeLeading
                                                     multiplier:1.0
                                                       constant:0.0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView
                                                      attribute:NSLayoutAttributeBottom
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeBottom
                                                     multiplier:1.0
                                                       constant:0.0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView
                                                      attribute:NSLayoutAttributeTrailing
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeTrailing
                                                     multiplier:1.0
                                                       constant:0.0]];

Edit :
Don't forget to set translatesAutoresizingMaskIntoConstraints property to NO on views.
(Replace self.view and containerView with your views).


text:
Q: Turn off EPMD listening port (4369) in Ubuntu / RabbitMQ I'm trying to secure an install of RabbitMQ, and am not sure how to secure the Erlang EPMD port.  I only have one machine running anything, so I'd like to make it listen only on the loopback device.  Per the docs, I've added:
ERL_EPMD_ADDRESS=127.0.0.1

to /etc/rabbitmq/rabbitmq-env.conf, but this has no effect, as the port still shows open in nmap from a remote system.
Is there a way to lock down this port that I won't be using?

A: This port is already secure. Access to this port is controlled by a Cookie, which is basically a developer key that is unique to this particular server and is created at install time. It is probably located in /var/lib/rabbitmq/.erlang.cookie although it is possible for a distro to change that location. You will note that the cookie file is only readable by root.
If a remote node (another server) or a local node (another Erlang instance on this server) wants to communicate with your RabbitMQ server, they must present the cookie when communicating via EPMD or the requests will be ignored.
If you are following RabbitMQ best practices then you will have RabbitMQ running on its own server, and there will be two or three other RabbitMQ servers that are clustered with it. In this context "clustered" means sharing the same cookie and communicating via the same EPMD port. Blocking this port is a bad thing.
However, it is generally a good thing to have a perimeter around the cluster, which is managed by a firewall so that the EPMD port can only be used from inside the perimeter. This implies that the blocking is on a firewall device, or a server acting as a firewall, or an EC2 firewall or similar.


text:
Q: trying to get Apache 2.4 to conditionally server .webp via mod_rewrite, need another view I have Apache 2.2.15 configured on the test bed server to serve .webp in lieu of .jpg and .png if available.  This works successfully.  However, the same configuration does not seem to work on the outward-facing server running Apache 2.4.51.
These are the applicable lines from /etc/httpd/conf/httpd.conf:
<IfModule mime_module>
    ...
    AddType image/webp .webp
    ...
    </IfModule>

<IfModule  rewrite_module>
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} Chrome [OR]
RewriteCond %{HTTP_USER_AGENT} Edg    [OR]
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1\.webp -f
RewriteRule (.+)\.(?:jpe?g|png)$ $1.webp [NC,T=image/webp,E=webp,L]
<IfModule headers_module>
    <FilesMatch "(?i)\.(jpe?g|png)$">
        Header append Vary Accept env=REDIRECT_webp
    </FilesMatch>
</IfModule>

The only difference between the two configuration files is a) use of the module names (so as to be consistent with the rest of the configuration files) versus the source-file name, and b) the AddType for image/webp is inside the IfModule mime_module block.
I have checked ( httpd -M ) that mod_mime, mod_rewrite and mod_headers.so are all loaded so that isn't the issue (?). Tested with both Chrome and Edge as clients.  Verified that the webp images did get there with release make via find(1). but...
Environmentally, the inward facing test bed serves via http, the outward facing production serves via https, but for the life of me I dont know how that would have any affect???
Anyway, I would appreciate a new set of eyeballs on this. [On the test bed, this knocked off about 40% of the page load, so its a rather  big deal .]


text:
Q: Line number of the matched characters in JS/node.js Is it possible to find the line number of the regex matched characters for multiline inputs (such as files) in Javascript or node.js?

A: Yes, with a semi-awkward work around.
http://jsfiddle.net/tylermwashburn/rbbqn/
var string = "This\nstring\nhas\nmultiple\nlines.",
    astring = string.split('\n'),
    match = /has/, foundon;

Array.each(astring, function (line, number) {
    if (match.exec(line))
        foundon = number + 1;
});

A: how to get the line number by string index
function lineNumberByIndex(index,string){
    // RegExp
    var line = 0,
        match,
        re = /(^)[\S\s]/gm;
    while (match = re.exec(string)) {
        if(match.index > index)
            break;
        line++;
    }
    return line;
}

how that's useful
create a function that returns the line number for the first match
function lineNumber(needle,haystack){
    return lineNumberByIndex(haystack.indexOf(needle),haystack);
}

create a function that returns the line numbers for every match
function lineNumbers(needle,haystack){
    if(needle !== ""){
        var i = 0,a=[],index=-1;
        while((index=haystack.indexOf(needle, index+1)) != -1){
            a.push(lineNumberByIndex(index,haystack));
        }
        return a;
    }
}

Fiddle

A: Thank you @Shanimal
I changed your code to also add the column position:

function lineNumberByIndex(index, string) {
  const re = /^[\S\s]/gm;
  let line = 0,
    match;
  let lastRowIndex = 0;
  while ((match = re.exec(string))) {
    if (match.index > index) break;
    lastRowIndex = match.index;
    line++;
  }
  return [Math.max(line - 1, 0), lastRowIndex];
}

const findOccurrences = (needle, haystack) => {
  let match;
  const result = [];
  while ((match = needle.exec(haystack))) {
    const pos = lineNumberByIndex(needle.lastIndex, haystack);
    result.push({
      match,
      lineNumber: pos[0],
      column: needle.lastIndex - pos[1] - match[0].length
    });
  }
  return result;
};

const text = `Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.`;
findOccurrences(/dolor/gim, text).forEach(result =>
  console.log(
    `Found: ${result.match[0]} at ${result.lineNumber}:${result.column}`
  )
);

A: It may be a good idea to use a parser generator. Zach Carter's jison reports line numbers. Here's an example of a small utility that uses jison to parse JSON and report errors with line numbers. It may be a good starting point.
https://github.com/zaach/jsonlint
For a minimal solution, I might try getting the index from a regex using the exec method (/myregex/.exec(mystring).index), taking the substring (mystring.substring(0, index)), splitting it on newlines, and counting the number of elements in the array.

A: I would do it the opposite way
I think it will have better performance because of only one regexp
var text="aaaaaaaaaaaaaaaaaaaaa\naaaaaaaabaaaaaaaaaa\naaaaaaaaaaaaaaaaaaa";
var RE=/b/g
var until=text.split(RE)
if (until.length>1){//found
   var linenumber=until[0].split(/\n/g).length
}

A: The match object has both the match index and the original text, so you can efficiently just count the line breaks using only the match.

/**
 * Return the line number of the match, or -1 if there is no match.
 */
function matchLineNumber(m) {
  if (!m) {
    return -1
  }
  let line = 1
  for (let i = 0; i < m.index; i++) {
    if (m.input[i] == '\n') {
      line++;
    }
  }
  return line
}

const rx = /foo/
const ex1 = `foo`
const ex2 = `
hello
foo
`
const ex3 = `
hello
`

console.log(matchLineNumber(rx.exec(ex1)))
console.log(matchLineNumber(rx.exec(ex2)))
console.log(matchLineNumber(rx.exec(ex3)))

A: Updated from 2015 answer with more modern javascript and a code snippet.
const lineNumbers = (needle, haystack) => haystack
    .split(/^/gm)
    .map((v, i) => v.match(needle) ? i + 1 : 0)
    .filter(a => a);

Notes

*

*one line number could have multiple matches

*adds one to index to get actual line number

*each match could also return an object with stats, line text, index
of matches etc.

Try it

const input = `Pommy ipsum shortbread bent as a nine bob note bossy britches numbskull you 'avin a laugh tallywhacker, had a barney with the inlaws stiff upper lip jolly good they can sod off yorkshire pudding Victoria sponge cake knackered a tenner, houlligan a total jessie in a pickle 'tis I'm off to Bedfordshire oopsy-daisies. Fish fingers and custard ended up brown bread chap one would like knackered owt, a diamond geezer lass a reet bobbydazzler chips ey up duck half-inch it, bossy britches lass The Doctor gosh. Driving a mini The Hounds of Baskerville real ale Dr. Watson a right toff naff, wind up cockney off the hook.
At the boozer bossy britches got his end away teacakes, chuffed. Lost her marbles Sherlock doolally muck about shepherd's pie lost her marbles, toad in the whole bog off knee high to a grasshopper i'll be a monkey's uncle one would be honoured to. Have a butcher's at this wedding tackle balderdash off the hook bargain Betty utter shambles bovver boots collywobbles nuthouse throw a paddy bloody mary, made a pig's ear of it tip-top scrubber posh nosh muck about tally-ho bit of a div. Off the hook nuthouse bowler hat air one's dirty linen tally-ho gosh, in a pickle chaps ask your mother if a cuppa up North splendid, gallivanting around squirrel cornish pasty shepherd's pie.
Scrumpy scouser knackered fish fingers and custard twiglets a reet bobbydazzler scatterbrained we'll be 'avin less of that porky-pies tosser, willy scally biscuits nuthouse brilliant baffled in the goolies bloke. Macca a bottle of plonk ridicule apple and pears ask your mother if challenge you to a duel, slappers yorkshire pudding and thus well chuffed. What a mug slap-head we'll be 'avin less of that anorak loo, naff wedding tackle balderdash. God save the queen corgi bottled it one would be honoured to quid, her Majesty's pleasure a cracking nicked bent as a nine bob note, pigeons in Trafalgar Square scally accordingly.
A fiver lass pork scratchings scrote down the local and rambunctious ey up knee high to a grasshopper i'll be a monkey's uncle, by 'eck love fancy a cuppa numbskull what a load of guff a fiver on his bill lost the plot. Slappers fork out rather wellies pulled out the eating irons had a barney with the inlaws, jolly hockey sticks Queen Elizabeth blimey a fiver. Pigeons in Trafalgar Square unhand me sir bowler hat gobsmacked pikey scrubber odds and sods taking the mick spiffing, golly scouser jolly have a kip rambunctious guinness man and his whippet naff lad, mush chin up ended up brown bread good old fashioned knees up conked him one on the nose fancied a flutter Kate and Will.
Tallywhacker unhand me sir blighty absolute upper class stop arsing around quid, down the local chinwag off t'shop tip-top blighty. Geordie spiffing clock round the earhole on his bill ever so utter shambles manky a week on Sunday bow ties are cool, tip-top off with her head bobby 10 pence mix chippy devonshire cream tea bread and butter pudding, beefeater challenge you to a duel lost her marbles sling one's hook upper class fried toast on his tod. Lad wellies see a man about a dog oopsy-daisies supper copped a bollocking up North and we all like figgy pudding, ended up brown bread jolly good absolute naff on a stag do nose rag oopsy-daisies what a mug, willy sling one's hook come hither oo ecky thump hard cheese old boy doing my head in.`;

const lineNumbers = (needle, haystack) => haystack
    .split(/^/gm)
    .map((v, i) => v.match(needle) ? i + 1 : 0)
    .filter(a => a);

console.log(lineNumbers('honoured', input));


text:
Q: Problemas para executar áudios em aplicações javascript com nw.js Estou trabalhando com uma aplicação javascript que precisa ser executada offline em um ambiente desktop. Utilizei o Node Webkit para empacotar minha aplicação e gerar um arquivo executável.  Porém, após criar esse pacote, os áudios pararam de tocar. Através do app.exe consigo analisar o console e verificar se  está ocorrendo algum erro, mas nada acontece.
Vocês conhecem alguma solução para transformar um projeto web javascript para rodar via desktop funcionando os audios corretamente?


text:
Q: C# How to send a file to webhook and get sent file's link? Hello im trying upload file to a link and i tried this:
`private void buttonInput_Click(object sender, EventArgs e)
    {
        try
        {
            using (WebClient client = new WebClient())
            {
                var resStr = client.UploadFile(@"https://anonfiles.com", @"C:\Users\sadettin\desktop\test.txt");
                var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr));
                var linkToFile = jObjResult["link"];
            }
        }
        catch(Exception err)
        {
            MessageBox.Show(err.Message);
        }
    }`

But Im taking 404 error.
Now i want to send any txt file to my discord webhook address and take sent file's link.
How can i do?

A: Despite your claims, using the correct end-point and a non-zero bytes file does lead to an uploaded file:
using (WebClient client = new WebClient())
{
      var resStr = client.UploadFile(@"https://api.anonfiles.com/upload", @"C:\tmp\test.txt");
      var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr));
      var linkToFile = jObjResult["data"]["file"]["url"]["full"].ToString();
      MessageBox.Show(linkToFile);
}

Do note that the JSON structure that is returned is different then you seem to handle. The url is found in an attribute full under this path /data/file/url hence this line in my code example:
var linkToFile = jObjResult["data"]["file"]["url"]["full"];

Here is one of the full urls that the service returned to me with my test file

https://anonfiles.com/nai0Z3S0x5/test_txt

It is 106 bytes in total.


text:
Q: Spring Data MongoDB com.mongodb.MongoWaitQueueFullException I'm trying to insert data into MongoDB in multiple threads using Spring Data MongoDB framework. But unfortunately I get following error:
Caused by: com.mongodb.MongoWaitQueueFullException: Too many threads are already waiting for a connection. Max number of threads (maxWaitQueueSize) of 50 has been exceeded.
at com.mongodb.PooledConnectionProvider.get(PooledConnectionProvider.java:70)
at com.mongodb.DefaultServer.getConnection(DefaultServer.java:60)
at com.mongodb.BaseCluster$WrappedServer.getConnection(BaseCluster.java:216)
at com.mongodb.DBTCPConnector$MyPort.getConnection(DBTCPConnector.java:503)
at com.mongodb.DBTCPConnector$MyPort.get(DBTCPConnector.java:451)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:286)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:271)
at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:84)
at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:66)
at com.mongodb.DBCursor._check(DBCursor.java:458)
at com.mongodb.DBCursor._hasNext(DBCursor.java:546)
at com.mongodb.DBCursor.hasNext(DBCursor.java:571)
at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1782)
... 22 more

I'm using following configuration for Spring:
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mongo="http://www.springframework.org/schema/data/mongo"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/data/mongo
    http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

<context:annotation-config/>

<context:property-placeholder location="classpath:database.properties"/>

<mongo:mongo host="${mongo.db.host}" port="${mongo.db.port}"/>
<mongo:db-factory id="mongoDbFactory" dbname="${mongo.db.name}"/>

<mongo:repositories base-package="com.test.app.mongodb.dao"/>
<mongo:template db-factory-ref="mongoDbFactory" converter-ref="mappingConverter" write-concern="ACKNOWLEDGED"/>
<mongo:mapping-converter id="mappingConverter" db-factory-ref="mongoDbFactory" type-mapper-ref="defaultMongoTypeMapper"
                         mapping-context-ref="mappingContext"/>

<bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
    <constructor-arg name="typeKey">
        <null/>
    </constructor-arg>
</bean>

<bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext"/>

As I understood from documentation there are a few properties which are responsible for allowed connections number (default combination of them allow 50 connections per node). They could be configured with Spring: connections-per-host and threads-allowed-to-block-for-connection-multiplier. I tried to use first one as shown below:
<mongo:mongo host="${mongo.db.host}" port="${mongo.db.port}">
    <mongo:options connections-per-host="100"/>
</mongo:mongo>

But result is the same. I still get that exception about 50 allowed connections.
I would be very grateful if somebody could explain what I did wrong. Has anyone encountered this problem?


text:
Q: Anyone seen a native Android push notification example now that push notification is on general release, is there a sample native android app that demonstrates it?
I thought I had the code right when an entry appeared i the "Mobile Push Registrations" page, but when I used the test page to send a JSON string to my app, and set a breakpoint in the interface function, the code never got to the function.
Then I refreshed the "Mobile Push Registrations" page and the entry had disappeared.
My OnCreate code is pretty much a copy and paste from the documentation:
static public ReceivePushNotification rp = new ReceivePushNotification ();;

@Override
public void onCreate() {
  super.onCreate();
  SalesforceSDKManager.initNative(getApplicationContext(), new KeyImpl(), MainActivity.class);
  SalesforceSDKManager.getInstance().setPushNotificationReceiver(rp);
}

and then in the ReceivePushNotification.java file:
public class ReceivePushNotification extends Activity implements PushNotificationInterface {

    @Override
    public void onPushMessageReceived(Bundle message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
        builder.setTitle("Pushed");
        AlertDialog chooseFault = builder.create();
        chooseFault.show();
    }

}

But it never gets into OnPushMessageReceived!


text:
Q: Interface and exposing class as property I am looking at this code from a peer of mine and am a little confused as to how this makes sense:
public class CA
{
    public CurrType CT {get; set;}
}

public interface ICharge
{
    CA a {get; set;}
    CurrType CT {get; set;}
}

public enum CurrType {X=0, Y=1}
public class Ch : ICharge
{
    public CA a {get; set;}
    public CurrType CT {get; set;}
}

I understand that interfaces contain properties but cant make any sense of the above code specifically:
1) Can the interface ICharge contain a class as a property?
2) Isnt some circular reference going on?

A:
Isnt some circular reference going on?

No, there is no circular reference going on.

Can the interface ICharge contain a class as a property?

It sure can - why did you think it couldn't? This is perfectly normal usage - the interface is specifying that that property will contain an instance of that class (i.e. an object of that type). Why a class? Because classes are everywhere - even a lot of the basic .Net types are classes. A string is a class. You can't do everything with primitive value types :)
I can't answer why there is two different usages of CurrType in Ch (one at the root level, one in the CA instance), that's for you to figure out.


text:
Q: Get Javascript variable inside json I have a json file that has about twenty objects like this:
{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "http://www.example.com/wp-content/themes/mytheme/images/profile/user1.jpg",
"contact": {
     "email" : "user1@example.com"
      }
}

I have a javascript code to display images/description from these objects to a page. I want this site to be uploaded in more than one place. So it doesn't make sense for me to use absolute url in this json file. I overcame the issue in js by passing a variable templateUrl from header.php file and calling it inside the javascript file.
<script type="text/javascript">
    var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>

And in javascript:$.getJSON(templateUrl+"/scripts/file.json", function(file){....}
I want a way to pass this templateUrl variable to json file too. So I can have image path set to just images/profile/user1.jpg, and I can prepend the url to this depending on where the site is uploaded.

A: #json.php
{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "<?= $_GET['var']; ?>/images/profile/user1.jpg",
"contact": {
     "email" : "user1@example.com"
      }
}

#main page
<script type="text/javascript">
var templateUrl = encodeURI("http://example.com");

$(function(){
    $.getJSON(
        'json.php?var=' + templateUrl,

        function(data){
            $.each(data, function(key, val){
                console.log(key + ": " + val);
            });
        }
    );
});

</script>

Output:
firstName: User1
lastName: UserLname
title: Human
description: Something Facinating
photoURL: http://example.com/images/profile/user1.jpg
contact: [object Object]


text:
Q: Asymptotic expansion of modified Bessel function $K_\alpha$ An integral representation for the Bessel function $K_\alpha$ for real $x>0$ is given by $$K_\alpha(x)=\frac{1}{2}\int_{-\infty}^{\infty}e^{\alpha h(t)}dt$$ where $h(\alpha)=t-(\frac{x}{\alpha})\cosh t$

Do you know any reference where its shown that using some generalization of Laplace method  $$K_\alpha(x)\sim(\frac{\pi}{2\alpha})^{\frac{1}{2}}(\frac{2\alpha}{ex})^\alpha$$ as $\alpha\rightarrow\infty$ ?

I have difficulties doing the calculation myself, first we cann see that the integrand has a maximum at $$t=\sinh^{-1}(\alpha/x)\sim\log(2\alpha/x)$$ which rises the idea using the substitution $t=\log(2\alpha/x)+c$ but I it does not help me.

A: abbreviate $t_0={\rm arsinh}(\alpha/x),\;\;x_0=x\sqrt{1+\alpha^2/x^2}>0$
expand the exponent around the saddle point, to second order:
$$\alpha[t-(x/\alpha)\cosh t]=-x_0+\alpha t_0-\tfrac{1}{2}x_0(t-t_0)^2+{\rm order}(t-t_0)^3$$
carry out the Gaussian integration:
$$\int_{-\infty}^{\infty}\tfrac{1}{2}\exp\left(-x_0+\alpha t_0-\tfrac{1}{2}x_0(t-t_0)^2\right)dt=\sqrt{\frac{\pi}{2x_0}}\exp(-x_0+\alpha t_0)$$
take the limit $\alpha\rightarrow\infty$ and you're done: $x_0\rightarrow\alpha$, $t_0\rightarrow\ln(2\alpha/x)$, so
$$K_\alpha(x)\rightarrow\sqrt{\frac{\pi}{2\alpha}}e^{-\alpha}(2\alpha/x)^\alpha$$


text:
Q: Can't get the 4th root using Newton-Raphson method I need to find the roots of the given equation using the N-R method. I am getting 3 of the 4 roots, but don't know why I am not able to get the last one. This is my code:
x = 1.5
for i in range(0,100):
    foX= ((6435)*x**8 - (12012)*x**6 + (6930)*x**4 - (1260)*x**2 + 35)/128
    devoX= ((6435*8)*x**7 - (12012*6)*x**5 + (6930*4)*x**3 - (1260*2)*x)/128

    delta = foX/devoX
    y = x - delta
    #print(y)
    error = abs(delta/x)
    if error<0.00000001:
        #print(y)
        print("{:.8f}".format(y))
        #break
        x=x-1/6
        continue
    x=y

Output:
0.96028986
0.79666648
0.52553241
-0.96028986
-0.96028986
-0.96028986
-0.96028986
-0.96028986
-0.96028986
-0.96028986
-0.96028986
-0.96028986

The actual roots are :
0.9602898564975, 0.7966664774136, 0.5255324099163, 0.1834346424957

If I change my initial condition from x=1.5 to x=1/6, I get only the 0.1834346424957 root and not others.
I need a program that gives me all the 4(or 8) roots.


text:
Q: Numpy indexing: Set values of an array given by conditions in different array I want to set all values of an array to 0 that have values that are not in a different array.
Easy if it's only one condition:
a = np.array([[1,2],[2,4],[5,6]])
cond = 1
a[a!=cond] = 0

What about if I have a list of conditions, e.g.
cond = np.array([1,2,6])

I can write it out like this
a[(a!=1) & (a!=2) & (a!=6)]=0

but I can't figure out the general way of doing this, something like this
a[a!=cond] = 0

when cond is an array. I also looked at np.select but that doesn't seem to do what I need.

A: Crux of the solution is :
NOT( option1) & NOT(option2) & NOT(option3) would be an equivalent of
NOT (option1 | option2 | option3 ).
Now, to get the mask for option1 | option2 | option3, we have a built-in np.in1d. So, basically the solution would be somewhat like ~np.in1d(a,cond). Since np.in1d works on 1D array, we need to reshape it afterwards before using the mask on the input array for setting values as zeros.
Thus, the implementation would look something like this -
a[~np.in1d(a,cond).reshape(a.shape)] = 0

A: Well, there's the function np.in1d which tests if the first array
contains any of the items from the second array.
But since this works on 1d arrays, and you need to test on a 2d array
the solution is a bit tricky, using the fact that ravel() returns a view:
a = np.array([[1,2],[2,4],[5,6]])
a.ravel()[~np.in1d(a.ravel(), [1, 2, 6])] = 0
print(a)

And then you get the output:
[[1 2]
 [2 0]
 [0 6]]


text:
Q: custom font iphone I am trying to add a custom font in my app, searched the web, there are many posts but i am getting error
InfoPlist.strings:0: error: validation failed: The data couldn't be read because it has been corrupted.

i dont get what's the issue, i added a new file of font in my project and added this code in plist, i never used plist before
<key>UIAppFonts</key>
<array>
<string>CloisterBlack.ttf
</string>
</array>

A: Add font in plist, then check the name of your font, by double clicking the font file in finder, like in my case the name of the font is Abduction for the font file name "CloisterBlack.ttf"
then access it like
[UIFont fontWithName:@"Abduction" size:20.0];

A: I think your font file has been corrupted. Add it again and then try.
This link will help you Add Custom Font in your app.
Make sure your file should be .ttf . Do you have any .ttf file or not ? If YES then add it to you project folder and then make little changes in your info.plist file.
If you dont have any .ttf file then download it first. It is your font file.

A: just use this class for custome fonts

A: I think adding the extension will fix it, my plist files look the same.
<key>UIAppFonts</key>
<array>
<string>CloisterBlack.ttf</string>
</array>


text:
Q: Google Kickstart 2020 round D- Record Breaker Question is my solution is working Fine for all test cases.
this is google kickstart 2020 round d question.
for 4 test cases my output is correct.
Time Complexity is also O(n).
#include <iostream>
using namespace std;

int main(){
    int n;
    cin>>n;
    int a[n+1];
    a[n]  = -1;
    for(int i = 0; i < n; i++){
        cin>>a[i];
    }
    int max = 0;
    int ans = 0;
    if(a[1] < a[max]){
        ans = 1;
    }
    for(int i = 1; i < n; i++){
        if(a[i] > a[max]){
            if(a[i] > a[i+1]){
                max = i;
                ans++;
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

A: The problem should be:
Record Breaker - Kick Start
Your code is wrong because it outputs 1 for input
3
1 2 2

while the answer should be 0.

*

*The first day is not record breaking because it is not the last day and the number is not strictly larger than one on the following day.

*The second day is not record breaking because it is not the last day and the number is not strictly larger than one on the following day.

*The third day is not record breaking because the number is not strictly larger than one on the second day.

What is wrong is that you are updating the maximum value only if the number on a day is larger than the next day.


text:
Q: Laravel 8, how to upload more than one image at a time I want to upload more than one image at a time through an  in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes

id
nombre
id_coche

01
name.jpg
0004

...
...
...

My Code
Blade with the Form

                   @foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
                            <form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
                                @csrf

                                                ID

                                            <input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>

                                        <input type="file" class="form-control" name="imagen" required multiple/>

                                        <button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>

                            </form>
                        @endforeach

Controller
"To upload only one image"

    public function añadirImagen(Request $request){

        $validated = $request->validate([
            'id_coche' => 'required',
            'nombre.*' => 'mimes:image'
        ]);

        $data = $request->input();

        $id_coche = $data['id_coche'];

        $Imagenes= new Imagenes;

        $Imagenes->id_coche = $id_coche;

        if($request->file("imagen")!=null){
            $nombre = $request->file('imagen');
                $nombreFoto = $nombre->getClientOriginalName();
                $nombre->move('img/Coches/', $nombreFoto);
                $Imagenes->nombre = $nombreFoto;
        }

        $Imagenes->save();

        return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
    }
}

"My attempt to upload more than one"
public function añadirImagen(Request $request){

        $validated = $request->validate([
            'id_coche' => 'required',
            'imagen.*' => 'mimes:image'
        ]);

        $data = $request->input();

        $id_coche = $data['id_coche'];

        $Imagenes= new Imagenes;

        $Imagenes->id_coche = $id_coche;

        if($request->hasfile("imagen")){
            $nombre_img = $request->file('imagen');
            foreach($nombre_img as $nombre) {
                $nombreFoto = $nombre->getClientOriginalName();
                $nombre->move('img/Coches/', $nombreFoto);

                $Imagenes->nombre = $nombreFoto;
            }
        }

        $Imagenes->save();

When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.

A: You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
     foreach($request->file('imagen') as $file)
        {
            ...
        }
}


text:
Q: Expressing $\displaystyle\int_1^x S(u) \mathrm{d}u$ in terms of elementary function Let's suppose we have the following series
$$S(x)=\sum_{n=1}^{\infty}(-1)^n\frac{x^{2n}}{n+1}$$
then I need to express $\displaystyle\int_1^x S(u) \mathrm{d}u$ in terms of elementary function. Some hints, suggestions ?
Thanks!!!
Sis.

A: We have
$$\log(1+x)=\sum_{n=1}^\infty(-1)^{n+1}\frac{x^n}{n},$$
so we find
$$x^2S(x)=\sum_{n=1}^\infty(-1)^n\frac{(x^2)^{n+1}}{n+1}=\sum_{n=1}^\infty(-1)^{n+1}\frac{(x^2)^n}{n}-x^2=\log(1+x^2)-x^2.$$
Now, we inegrate by parts, we find
\begin{align}\int_1^xS(u)du&=\int_1^x(\frac{\log(1+u^2)}{u^2}-1)du\\&=\frac{-1}{2x}(2\log(x^2+1)-(2-\pi+2\log2)x-4x\arctan x+2x^2)\end{align}

A: There are two elementary approaches, recognize and integrate, or integrate and recognize.  We take the second path.
Your sum goes from $n=1$ to infinity, but if it is a good little mathematical sum, it probably really wants to start at $n=0$. If it stubbornly insists on $n=1$, we can subtract appropriately at the end.  When we integrate
$$\sum_0^\infty (-1)^n \frac{x^{2n}}{n+1}$$
term by term, we get
$$\sum_0^\infty (-1)^n \frac{x^{2n+1}}{(n+1)(2n+1)},$$
or equivalently (partial fractions)
$$\sum_0^\infty 2(-1)^n\frac{x^{2n+1}}{2n+1} - \sum_0^\infty (-1)^n \frac{x^{2n+1}}{n+1}.$$
The first sum is $2\arctan x$.  The second sum (for $x\ne 0$) can be rewritten as
$\dfrac{1}{x}\displaystyle\sum_0^\infty (-1)^n \dfrac{(x^2)^{n+1}}{n+1}$. This is $\dfrac{1}{x}\log(1+x^2)$.


text:
Q: Merge XSL with include I must merge two xsl files into one:
The include element replaced by the content on the XSL file.
Do you know a software(or code) to do this?
Thanks

A: Not sure why you would want to do this, but you could simly transform your xslt stylesheet with a stylesheet that resolves the include.
Like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="xsl:include">
    <xsl:apply-templates select="document(@href)/*/*"/>
</xsl:template>

</xsl:stylesheet>


text:
Q: Encapsulation and generalization function def mult_tasks(str_numbers) in python The Question:
Without altering mult_tasks, write a definition for mult_tasks_line so that the
doctests pass.
So:
print mult_tasks("3469")  will produce:
(3*3) (3*4) (3*6) (3*9)
(4*3) (4*4) (4*6) (4*9)
(6*3) (6*4) (6*6) (6*9)
(9*3) (9*4) (9*6) (9*8)

def mult_tasks_line(first_num, str_numbers):

    """
    >>> mult_tasks_line("4", "3469")
    '(4*3) (4*4) (4*6) (4*9) '
    """
    #Add your code here

def mult_tasks(str_numbers):

    """
    >>> mult_tasks("246")
    '(2*2) (2*4) (2*6) \\n(4*2) (4*4) (4*6) \\n(6*2) (6*4) (6*6) \\n'
    >>> mult_tasks("1234")
    '(1*1) (1*2) (1*3) (1*4) \\n(2*1) (2*2) (2*3) (2*4) \\n(3*1) (3*2) (3*3) (3*4) \\n(4*1) (4*2) (4*3) (4*4) \\n'
    """

    #Do not alter any code in this function
    result_tasks = ""
    for ch in str_numbers:
        result_tasks += mult_tasks_line(ch, str_numbers) + "\n"
    return result_tasks

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose = True)

I have already tried doing this:
def mult_tasks_line(first_num, str_numbers):
    digits=0
    for num in str_numbers:
        while digits<len(str_numbers):
            print "("+first_num+"*"+str_numbers[digits]+")",
            digits=digits+1

def mult_tasks(str_numbers):
    result_tasks = ""
    for ch in str_numbers:
        result_tasks += mult_tasks_line(ch, str_numbers),"\n"
    return result_tasks

This is what I tried, the first function works pretty close, but it does not have the single quote. when run
mult_tasks_line("4", "3469")
it comes out (4*3) (4*4) (4*6) (4*9).
But the second function seems totally wrong.
this is the result for the second function :
mult_tasks("246")
(2*2) (2*4) (2*6)

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module> mult_tasks("246")
File "/Users/HuesFile/Downloads/Mastery Test/2.py", line 25, in mult_tasks
result_tasks += mult_tasks_line(ch, str_numbers),"\n"
TypeError: cannot concatenate 'str' and 'tuple' objects

A: From what I understood, you want to print the matrix of ordered tuples from a string of number-characters,
while the seperator
def mult_tasks_line(first_num, str_numbers):
    return ''.join(
        ['({n1}*{n2}) '.format(n1 = first_num, n2 = n2 ) for n2 in str_numbers])

def mult_tasks(str_numbers):
    result_tasks = ""
    for ch in str_numbers:
        result_tasks += mult_tasks_line(ch, str_numbers) + "\n"
    return result_tasks

Then
print mult_tasks("3469")

gives
(3*3) (3*4) (3*6) (3*9)
(4*3) (4*4) (4*6) (4*9)
(6*3) (6*4) (6*6) (6*9)
(9*3) (9*4) (9*6) (9*9)

as desired. The result scales, in the sense that it works for an arbitrary string.
Do you wish the multiplications to be computed?

A: Obviously mult_tasks contains an incorrect line
result_tasks += mult_tasks_line(ch, str_numbers),"\n"

result_tasks is a string and here it is concatenated with a tuple (They are constructed by commas with or without parentheses) mult_tasks_line(ch, str_numbers), "\n" which leads to exception.
You need to modify this line to
result_tasks += mult_tasks_line(ch, str_numbers) + "\n"

Another problem in your code, is that mult_tasks_line doesn't return value, but simply prints it. You want to do something like this
def mult_tasks_line(first_num, str_numbers):
    result = []
    for ch in str_numbers:
        result.append('({}*{})'.format(first_num, ch))
    return ' '.join(result)


text:
Q: How do I include fragments of HTML within layouts? What's a simple way for me to write HTML files that have several "includes" that pull other HTML files into certain DIVs (which can in turn pull HTML files into certain of their DIVs, i.e. nesting)?
I would certainly want a CLI tool where I say "compile these files into plain old HTML" and it just works.

A: Lots of templating languages. Freemarker, google closure templates (soy), but if you want something simple and fast without lots of setup, try "Server Side Includes".
Wikipedia Article On SSI


text:
Q: How should I parse a file in Ruby on Rails to store in a database? I want to create a simple form for users to upload a file, which will be stored in a database.  I also want to display all the submitted files in the database with their name and a link to download the file. Schematically, what's the best way to do this in Rails/how should I store the file in table (which fields should my table have? etc). Thanks!

A: i would use paperclip gem with the upload to s3 instead of file system
https://github.com/thoughtbot/paperclip
checkout the README, most of the examples are for an image, but works with non-image files as well

A: use paperclip to upload file, you can store images/file in your database as well as in s3 (AWS)
See below link how to use paperclip in rails with example
Here is the steps how to upload file using paperclip in rails
http://patshaughnessy.net/2009/4/30/paperclip-sample-app

for github
https://github.com/thoughtbot/paperclip
https://github.com/websymphony/Rails3-Paperclip-Uploadify


text:
Q: Matlab Iteratively remove a row of matrix, except for first iteration I have a matrix that I use to solve a system of equation using ode45. I am iteratively removing one row in a while loop. However, I want the first iteration to 'continue' and not remove any arrow, so that I can compare all my results where one array is removed with the result using initial matrix.
It would look like:
while smtg
    A(pos,:)=0 % Do not compute this line the first iteration
    pop=ode45(involving A)
end

My real code:
countrow=0;
A=randi([0 1], 5, 5);
distrib=sum(A,1);
while sum(distrib)>5
    countrow=countrow+1;
    A(pos,:)=0; % remove one row
    options = odeset('RelTol', 1e-4);
    [t, pop]=ode45(@Diff,[0 MaxTime],[E I],options,n,m, A);
    nbtot =sum(pop(:,n+1:2*n),2);
end

I tried to use
if countrow==1 % (the first iteration),
    continue;
end

but it skips until the second end and not compute nbtot so I'm out of ideas... Any help?

A: If you don't want A(pos,:)=0; % remove one row to occur on the first iteration then put it inside an if statement like
countrow = countrow + 1;
if countrow ~= 1
    A(pos,:)=0; % remove one row
end

The ~= symbol in MATLAB is "not equal to". The line A(pos,:)=0; % remove one row will now only execute when countrow is not equal to 1 but all of the other statements within the loop will execute as normal.

The keyword continue will stop the execution of the current loop iteration and proceed to the next loop iteration. All of the statements after a continue within a loop will not be executed.

A: Or you can go with :
A(pos,:)=A(pos,:)*(countrow==1);


text:
Q: What is the difference between Java CPU and PSU Releases, eg JDK SE 8u101 and JDK SE 8u102 I'm installing JDK SE 8u101 on my mac for Android Studio.  Is there any reason I should pick 8u102 vs. 8u101?  Are there any noticeable differences in them? Looks like they were released at the same time.

A: Are there any noticeable differences in them?

*

*8u101 contains security updates. This is a Critical Patch Update (CPU).

*8u102 contains the security updates and new features. This is a Patch Set Update (PSU). There is also a known bug in 8u101 which is resolved in 8u102.
Release notes:

*

*8u101 Update Release Notes

*8u102 Update Release Notes

Java CPU and PSU Releases Explained
Which Java version should I choose: the CPU or the PSU?

Oracle strongly recommends that all Java SE users upgrade to the latest CPU release available for a release family. Most users should choose the CPU release.
Users should only use the corresponding PSU release if they are being impacted by one of the additional bugs fixed in that version as noted in the release notes.
The subsequent CPU release will contain all of the fixes from the current PSU. For this reason, organizations should test the current PSU in their environment in anticipation of these fixes being included in the next CPU.

What is the difference between a Java CPU and PSU release?

Java SE Critical Patch Updates (CPU) contain fixes to security vulnerabilities and critical bug fixes. Oracle strongly recommends that all Java SE users upgrade to the latest CPU releases as they are made available. Java SE CPU releases are odd numbered versions (i.e. 7u71, 7u65 – see more on Java SE version numbering schemes here).
Java SE Patch Set Updates (PSU) contain all of fixes in the corresponding CPU, as well as additional non-critical fixes. Java PSU releases should only be used if you are being impacted by one of the additional bugs fixed in that version. The release notes call out the additional fixes available in Java SE PSU releases.

Source Java CPU and PSU Releases Explained


text:
Q: file stop read when line reached I have the code below to begin read the rest of the file after I have found the line containing the string "start"
   foreach line clines [
      if find [%start] line [
      print line
     ]
   ]

I can't figure it out from the documentation.. what's going on here? seems logical to me.

A: You have always to read the file before you can search in the content of the file.
Maybe you are looking for something like
clines: read/lines %myfile
found: false
foreach line clines [
    if any [
        found
        found:  find line "start"
    ]  [
        print line
    ]
]

an other way would be
cfile: read %myfile
print all [
    cfile: find cfile "start"
    find/tail cfile lf
]


text:
Q: How to get the server URL using a cron scheduled thread? I have a thread running using @Scheduled in a Java web app, which needs the current URL of the server on which it is running:
@Scheduled(cron = "0 0/5 * 1/1 * *")
public void processTask() {
   // 1) Get the server URL.
   // 2) Do some other work.
}

Is it possible to do this without getting the URL from the properties file (or other files)?

A: There are many ways to work around this issue of attempting to get the hostname however to get the port name is something I am not sure of (without the property file approach):

*

*Use the InetAddress.getLocalHost() but this might return the loopback.

*Iterate through the network interfaces as in NetworkInterface.getNetworkInterfaces() but this would return all the network interfaces.

*Since this is a webapp, you could get the hostname from servletrequest.getServerName and store that in a Singleton or any helper class to be used in your cron job. So you store it once for use later.

*Get the hostname from the OS. I would demonstrate this approach. It is rough code but it would suffice to demonstrate.

String hostname = new BufferedReader
         (new InputStreamReader
         (   Runtime.getRuntime().exec("hostname").getInputStream())).readLine();
      System.out.println("Hostname: " +  hostname);

Now create a socket to that host.
Socket socket = new Socket (hostname, [some well known port that is always up as in port 22 in linux]);
InetSocketAddress inetSock = (InetSocketAddress) socket.getRemoteSocketAddress();
System.out.println ("Socket address: " + inetSock.getAddress().getHostAddress() );

On my mac prints:
Hostname: khannas-macbook-pro.local
Socket address: 192.xxx.xx.xx

Hope this helps.


text:
Q: understand df.isnull.mean() in python I have a dataframe df. Code is written in such a manner
df.isnull().mean().sort_values(ascending = False)
Here is the some part of the output-
inq_fi                                 1.0
sec_app_fico_range_low                 1.0

I want to understand how it is working?
if we use, df.isnull() only it will return us True or False for each and every cell. How mean() is going to give us right output. My objective is to find percentage of null values in all columns. Above output represents inq_fi and sec_app_fico_range_low has all missing values.
Also we are not passing by in sort_values?

A: Breakdown would look like this:
df.isnull()
#Mask all values that are NaN as True
df.isnull().mean()
#compute the mean of Boolean mask (True evaluates as 1 and False as 0)
df.isnull().mean().sort_values(ascending = False)
#sort the resulting series by column names descending

That being said a column that has values:
[np.nan, 2, 3, 4]

is evaluated as:
[True, False, False, False]

interpreted as:
[1, 0, 0, 0]

Resulting in:
0.25


text:
Q: No data is getting into a table built over a stream from ksql binary, it get's there if I do the same with ksql prompt? I'm trying to create a table over a stream using ksql binary. The table gets created and starts running but when I query it there is no data inside the table. When I create the same using ksql prompt the table gets created I'm also able to query the data.
PS: I am setting this property  SET 'auto.offset.reset'='earliest'; to query the data form beginning.
I tried both methods. It works when I create table using ksql prompt. Same command does not work when try to do the same with ksql binary.
sudo echo "CREATE TABLE movie_table AS SELECT title, count(*) AS appearance FROM test WHERE year > 1988 GROUP BY title;" | sh /home/binary/ksql http://devopsksql.default.svc.cluster.local:8088

ksql> CREATE TABLE movie_table AS SELECT title, count(*)

 Message
---------------------------
 Table created and running
---------------------------

ksql> select * from MOVIE_TABLE;
^CQuery terminated

Same when I run with ksql prompt open it works as is.
I am expecting a way to create a table and query it without using the ksql prompt.

A: You need to set SET 'auto.offset.reset'='earliest'; before your CREATE query.
If you want to interact with KSQL from a script I'd suggest using the REST API (e.g. via curl) than trying to pipe to the ksql binary.


text:
Q: Video stop randomly (ffmpeg) Does anyone know why a video stops playing? It breaks randomly. Not always at the same time.
Build a video wall of 3x3 monitors. Each one has a raspberry pi that receives the video and cuts it to be displayed. The project is https://piwall.co.uk/
Thanks
ffmpeg -re -i /home/pi/Videos/videowall-edit80.mp4 -vcodec copy -f avi -an udp://239.0.1.23:1234?buffer_size=327680B

frame=  471 fps= 30 q=-1.0 size=   15983kB time=00:00:15.69 bitrate=8340.1kbits/frame=  484 fps= 30 q=-1.0 Lsize=   16507kB time=00:00:16.13 bitrate=8382.2kbits/s speed=   1x
video:16498kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.055688%
Exiting normally, received signal 15.


text:
Q: Read NFC tag from Xamarin I'm new to Xamarin cross-platform app development, and I'm trying to implement on Android version of my app an external NFC tag reading.
When a tag is scanned, I would like my application to open and read the text inside the tag and finally perform some specific actions based on what was read.
I've this implementation on MainActivity.cs, but it doesn't work because it seems that I can't get the intent:
using Android.Content;
using System;
using System.Text;
using System.Diagnostics;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
using Android.Content.Res;
using FFImageLoading.Forms.Platform;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
using Plugin.CurrentActivity;
using Android.Nfc;
using Android.Nfc.Tech;
using Poz1.NFCForms.Abstract;
using Poz1.NFCForms.Droid;

namespace Kibelis.Droid
{
    [Activity(Label = "Kibelis", Icon = "@drawable/icon", Theme = "@style/MainTheme", LaunchMode = LaunchMode.SingleTop, MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {

        private NfcAdapter _nfcAdapter;

        public object NFCUtil { get; private set; }

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
            CachedImageRenderer.Init(true);
            base.OnCreate(savedInstanceState);
            CrossCurrentActivity.Current.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            _nfcAdapter = NfcAdapter.GetDefaultAdapter(this);
            System.Diagnostics.Debug.WriteLine("CREATE");

            // is attached.
            LoadApplication(new App());
        }

        protected override void OnResume()
        {
            base.OnResume();

            if (_nfcAdapter == null)
            {
                System.Diagnostics.Debug.WriteLine("NFC UNAVIABLE");
            }
            else
            {
                var tagDetected = new IntentFilter(NfcAdapter.ActionNdefDiscovered);
                var filters = new[] { tagDetected };

                var intent = new Intent(this, this.GetType()).AddFlags(ActivityFlags.SingleTop);

                var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);

                _nfcAdapter.EnableForegroundDispatch(this, pendingIntent, filters, null);

                System.Diagnostics.Debug.WriteLine("FOREGRAUND DISPATCH");
            }
        }

        protected override void OnPause()
        {
            base.OnPause();
        }

        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);

            System.Diagnostics.Debug.WriteLine("NEW INTENT");

            if (intent.Extras.IsEmpty)
            {
                System.Diagnostics.Debug.WriteLine("empty");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Not empty");
            }

            //For start reading
            if (intent.Action == NfcAdapter.ActionTagDiscovered || intent.Action == NfcAdapter.ActionNdefDiscovered || intent.Action == NfcAdapter.ActionAdapterStateChanged
                || intent.Action == NfcAdapter.ActionTransactionDetected || intent.Action == NfcAdapter.ExtraNdefMessages || intent.Action == NfcAdapter.ExtraNdefMessages)
            {
                System.Diagnostics.Debug.WriteLine("DISCOVERD");
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
                if (tag != null)
                {
                    System.Diagnostics.Debug.WriteLine("TAG");
                    // First get all the NdefMessage
                    var rawMessages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
                    if (rawMessages != null)
                    {
                        var msg = (NdefMessage)rawMessages[0];
                        System.Diagnostics.Debug.WriteLine("MESSAGE");
                        // Get NdefRecord which contains the actual data
                        var record = msg.GetRecords()[0];
                        if (record != null)
                        {
                            if (record.Tnf == NdefRecord.TnfWellKnown)
                            {
                                // Get the transfered data
                                var data = Encoding.ASCII.GetString(record.GetPayload());
                                System.Diagnostics.Debug.WriteLine("RECORD");
                            }
                        }
                    }
                }
            }
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
        {
            PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

Can you help me?

A: You are registering the foreground dispatch for the ActionNdefDiscovered intent. However, this intent filter also requires a specific data type (to be present on the tag and to be registered for the intent). If that's what you want, you need to add that data type (MIME type or URI) to the intent filter (variable tagDetected).
If, instead, you want to just listen for all tags, you want to use the ActionTagDiscovered intent instead. In fact, you can simply skip the intnent filter all together from the call to EnableForegroundDispatch:
_nfcAdapter.EnableForegroundDispatch(this, pendingIntent, null, null);


text:
Q: Add dynamic FormControl Validators without removing old ones I have a form like below
this.personForm = new FormGroup({
            title: new FormControl(this.person.salutation, Validators.compose([
            Validators.minLength(2)
        ])),
            firstName: new FormControl(this.person.firstName, Validators.compose([
            Validators.minLength(4)
        ])),
});

Based on a configuration from an API call I want to make them dynamically required or not. I  know I can use formControl.setValidators([Validators.required]) but that will clear existing Validators.
I was hoping to achieve it in one of the following ways

*

*A function for just adding (Exp: addValidators([]))

*OR a function that would give me the list of Validators a formControl already has, so that I can join them with what I want to add. (Exp: getValidators())

Unfortunately(as for as I know) none of above 2 functions exist. So how can one add a new Validation to a formControl without having to know already existing ones?

A: I supouse you can use a customValidator that depends of one variable, In the example, a button make a variable "yet" true or false. depending the form is valid or not
@Component({
  selector: 'my-app',
  template:`
  <form [formGroup]="personForm">
     <input formControlName="title"/>
     <input formControlName="firstName"/>
  </form>
  <button (click)="addValidator()">click</button>
  <hr/>
  {{personForm?.errors|json}}
  {{personForm?.valid}}`
})
export class AppComponent implements OnInit {
  yet: boolean;
  personForm: FormGroup;
  person = { salutation: "", firstName: "" }
  ngOnInit() {
    this.personForm = new FormGroup({
      title: new FormControl(this.person.salutation, Validators.compose([
        Validators.maxLength(2)
      ])),
      firstName: new FormControl(this.person.firstName, Validators.compose([
        Validators.minLength(4)
      ])),
    }, this.customValidator())
  }
  addValidator() {
    this.yet = !this.yet;
    this.personForm.updateValueAndValidity();
  }
  customValidator() {
    return (group: FormGroup) => {
      if (!this.yet)
        return null;
      if (group.get('title').value == '')
        return { title: 'required' }
    }
  }

see stackblitz


text:
Q: What font is this document? can anyone tell me the name of this font used in this document? thanks in advance. ?

A: This fragment should prove without any doubt that the document used
\usepackage[upright]{fourier}

Here's a sample code.
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[french]{babel}

\usepackage[upright]{fourier}

\usepackage{amsmath}

\begin{document}

Si $z_0\in\mathbb{C}$, on a succéssivement
\[
z_0\in\mathcal{H}(f)\Longleftrightarrow
\exists\theta\in[0,2\pi\mathclose{[}
\quad
\exists\varepsilon_1,\varepsilon_2\in\mathbb{U}
\qquad
z_0=\begin{bmatrix}
\overline{\varepsilon_1}\cos\theta\\
\overline{\varepsilon_2}\sin\theta
\end{bmatrix}
\cdot
\left(
  \begin{bmatrix}
  1 & 0 \\
  0 & 1
  \end{bmatrix}
  \begin{bmatrix}
  \varepsilon_1\cos\theta \\
  \varepsilon_2\sin\theta
  \end{bmatrix}
\right)
\]

\end{document}

A: There are several fonts in the image. An approximation:
\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{upgreek}
\usepackage[sans]{dsfont}
\begin{document}
\textbf{1.3.}\quad Si $z_0 \in \mathds{C}$, on a successivement
\begin{gather*}
  \overline{\upepsilon_1} \cos\uptheta,
  \exists\uptheta \in [0; 2\uppi[\\
  \mathds{C}, \mathds{U}\\
  \mathcal{H}(f) \cdot \mathcal{L}_{\text{E}}\\
  \Longleftrightarrow \boxed{\left\{ 0 \leqslant \frac{1}{2}\right\}}
\end{gather*}
\end{document}

The set symbols by \mathds of package dsfont are close, but the result of \mathcal is quite different.


text:
Q: Check whether a tree is a binary search tree using inorder int* inorder(node* root)
{
    //Dynamically Created array as we are required to pass array into main function
    int* arr=new int[100];
    int i=0;
    if(root==NULL)
    return 0;
    inorder(root->left);
    arr[i]=root->data;
    i++;
    inorder(root->right);
    return arr;
}

We are required to check whether the tree is Bst or not using Inorder traversal.If the data present in the array are sorted then it is Bst.After passing the array in main() we will check whether the array is sorted or not but when i checked the content of the array it comes out to be a garbage value
and tree always comes out to be not a Bst for input tree that is bst
int main()
{
    node* root= newNode(6);
    root->left= newNode(4);
    root->right= newNode(8);
    root->left->left= newNode(3);
    root->left->right= newNode(5);
    root->right->left= newNode(7);
    root->right->right= newNode(9);
    int* ptr=inorder(root);
    if(is_sorted(ptr,ptr+7))
    cout<<"Tree is Binary search tree: "<<endl;
    else
    cout<<"Tree is not a binary search tree: "<<endl;
}

A: Using a vector is unnecessary here. Determining whether a tree is a binary search tree does not require any extra memory apart from the stack for the recursive calls.
If you define a separate inorder tree traversal algorithm that makes the implementation almost trivial:
#include <utility>
#include <functional>

template<class T>
struct Node {
    T value;
    Node *left, *right;
};

template<class T, class F>
bool traverse_inorder(Node<T> const* tree, F&& f) {
    return !tree || (
           traverse_inorder(tree->left, std::forward<F>(f))
        && f(tree->value)
        && traverse_inorder(tree->right, std::forward<F>(f))
        );
}

template<class T, class Pred>
bool is_bst(Node<T> const* tree, Pred&& pred) {
    T const* p = 0;
    return traverse_inorder(tree, [&p, &pred](T const& next) {
        T const* prev = p;
        p = &next;
        return !prev || !pred(next, *prev);
    });
}

template<class T>
bool is_bst(Node<T> const* tree) {
    return is_bst(tree, std::less<T>{});
}

int main() {
    // bst tree:
    //       33
    //   20      35
    // 10  30
    Node<int> n1{10}, n3{30}, n2{20, &n1, &n3}, n5{35}, n4{33, &n2, &n5};
    auto tree = &n4;

    std::cout << is_bst(tree) << '\n'; // Outputs 1.

    // Break bst property.
    n4.value = 25;
    std::cout << is_bst(tree) << '\n'; // Outputs 0.
}

To convert a tree into a vector using inorder traversal you can use the following function:
template<class T>
std::vector<T> inorder_to_vector(Node<T> const* tree) {
    std::vector<T> v;
    traverse_inorder(tree, [&v](T const& t) {
        v.push_back(t);
        return true;
    });
    return v;
}


text:
Q: Cannot convert from 'System.Windows.Forms.DataGridViewRow' to 'int' When I try to do this:
var row = datagrid.CurrentRow;
 name.RemoveAt(row);
(name is a list of strings)
This error appears "Cannot convert from 'System.Windows.Forms.DataGridViewRow' to 'int'"
I need to convert the row to int so I can delete it.

A: A DataGridViewRow is not an integer but you can get the Index of the row:
name.RemoveAt(row.Index);


text:
Q: Returning view with model and query string I am trying to return to view from a controller that has both querystring and model
return View("BillingReport.aspx/?report=" + fc["report_selector"], bilDet);

but this gives me a runtime error of page not found as it appends .aspx etc at the end of the url.
RedirectToAction() doesnt have an option to do it.
Is there a way to do it or does mvc3 limit us to using either a query string or a model

A: MVC does not support what you are looking for,
But I dont understand why do you want to Redirect To a URL with ModelValues.
Any redirection is a GET request, so you can construct the model and return View from that action.
View() expects a view name and model associated with it.
Redirect() or RedirectToAction() are used to redirect the url to another controller/action. So you can not pass a model.Even if you will try to pass model it will append model properties as querystring parameters.

A: Here is a reason why you would want use the model and the querystring: the querystring allows you to give user way to save URL with state information.  The model allows you to pass a lot of non-flattened data around. So here is I think how to do this in MVC 5 (maybe does not work for older versions, but probably does):
Use 2 actions rather than 1 for the view. use first one to set querystring via RedirectToAction. Use second action to return model to the view.  And you pass the model from the first action to the second action via session state. Here is example code:
public ActionResult Index(string email){
    Session["stuff"]=Load(email);
    return RedirectToAction("View1action", new { email = email, color = "red" });
}

public ActionResult View1action(string email){
    return View("View1",(StuffClass)Session["stuff"]);
}

A: I agree with Manas's answer and if I were you I would consider changing the design if possible.  As a side note, the following technique is possible:
TempData["bilDet"] = bilDet;
return RedirectToAction(....);   // your controller, action etc.

On the action you can then retrieve your TempData.  TempData will automatically be removed.
But also check out: ASP.NET MVC - TempData - Good or bad practice


text:
Q: Return first and last words in a person name - postgres I have a list of names and I want to separate the first and last words in a person's name.
I was trying to use the "trim" function without success.
Can someone explain how could I do it?
table:
Names
Mary Johnson Angel Smith
Dinah Robertson Donald
Paul Blank Power Silver

Then I want to have as a result:
Names
Mary Smith
Dinah Donald
Paul Silver

Thanks,

A: You can do it simply with regular expressions, like:
substring(trim(name) FROM '^([^ ]+)') || ' ' || substring(trim(name) FROM '([^ ]+)$')

Of course it would only work you are 100% there is always supplied at least a first and a last name. I'm not 100% sure it is the case for everybody in the World. For instance: would that work for names in Chinese? I'm not sure and I avoid doing any assumption about people names. The best is to simply ask the user two fields, one for the "name" and another for "How would you like to be called?".

A: Another approach, which takes advantage of Postgres string processing built-in functions:
SELECT split_part(name, ' ', 1) as first_token,
split_part(name, ' ', array_length(regexp_split_to_array(name, ' '), 1)) as last_token
FROM mytable

A: Here's how I extracted full names from emails with a dot in them, eg Jeremy.Thompson@abc.com
SELECT split_part(email, '.', 1) || ' ' || replace(split_part(email, '.',  2), '@abc','')
FROM people

Result:

Jeremy     |     Thompson

You can easily replace the dot with a space:
SELECT split_part(email, ' ', 1) || ' ' || replace(split_part(email, ' ',  2), '@abc','')
FROM people


text:
Q: Change only when compatible with a single word If the words in the text are compatible with the words in the Array, the words are class adding.
$searchArray = array('settings all','print', 'sum', 'industry', ...); // total 50K words

function sanitize($string) {
    global $searchArray;
    $repl = array_map("dashReplace", $searchArray);
    $string = str_replace($searchArray, $repl, $string);

    return $string;
}

function dashReplace($str) {
    return "" . $str . "";
}

echo sanitize($text);

Result:

Lorem Ipsum is simply dummy text of the printing and typesettings all
  industry.

HTML Format:
Lorem Ipsum is simply dummy text of the printing and typesettings all industry.
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If there is a match in the word it changes but I don't want it to change. For example;
HTML Format:
Lorem Ipsum is simply dummy text of the printing and typesettings all industry.
                                                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

What do I need to do to change it if it is compatible with a single word? (not compatibility for words)

A: This issue is occurring because it's matching a substring as well. To avoid this, you can use preg_replace() to replace all patterns(as in words in regex format from $searchArray) with your $repl array on $string as the subject.
<?php

$searchArray = array('settings all','print', 'sum', 'industry'); // total 50K words

function sanitize($string,$searchArray) {
    $repl = array_map("dashReplace", $searchArray);
    $pattern = array_map("insertWordBoundaries", $searchArray);
    $string = preg_replace($pattern,$repl,$string);
    return $string;
}

function dashReplace($str) {
    return "" . $str . "";
}

function insertWordBoundaries($str){
    return "/\b". preg_quote($str,"/") ."\b/";
}

$text = 'Lorem Ipsum is simply dummy text of the printing and typesettings all industry.';
echo sanitize($text,$searchArray);

Demo: https://3v4l.org/2gved
Update #1:
Also, using global variables inside method definitions are bad, especially in the OOP context. Your style is procedural, but I would still recommend passing $searchArray as an extra parameter, so it's like a perfectly reusable piece. Otherwise, we are making it static to only use global $searchArray always.
Update #2:
We perform a regex match on each word by adding a word boundary \b on both sides of a string.
Quoting from Regex tutorials

The metacharacter \b is an anchor like the caret and the dollar sign.
  It matches at a position that is called a "word boundary". This match
  is zero-length.
There are three different positions that qualify as word boundaries:

*

*Before the first character in the string, if the first character is a word character.

*After the last character in the string, if the last character is a word character.

*Between two characters in the string, where one is a word character and the other is not a word character.


text:
Q: How can I split a single string into two different columns sql I have two columns and I want to create a splitting function that will accept a single string and put every two consecutive numbers into my columns.
for example:
If my string was
(1,5,2,20,3,9).
The result should be:
size   quantity
 1   |  5
 2   |  20
 3   |  9

Here is the code that I have been trying with it:
create FUNCTION [dbo].[getSizesAndQuantity1](@input AS Varchar(4000) )
RETURNS
  @Result TABLE(Size BIGINT, Quantity BIGINT)
AS
BEGIN
  DECLARE @str int
  DECLARE @strQ int
  DECLARE @ind Int
  IF(@input is not null)
  BEGIN
        SET @ind = CharIndex(',',@input)
        WHILE @ind > 0
        BEGIN
              SET @str = SUBSTRING(@input,1,@ind-1)
              SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
              SET @strQ = SUBSTRING(@input,1,@ind-1)
              SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
              INSERT INTO @Result(Size,Quantity) values (@str,@strQ)
              SET @ind = CharIndex(',',@input)
        END

  END
  RETURN
END

I appreciate the help.

A: Using DelimitedSplit8K
select  size = max(case when ItemNumber % 2 = 1 then Item end),
    quantity = max(case when ItemNumber % 2 = 0 then Item end)
from    DelimitedSplit8K('1,5,2,20,3,9', ',')
group by (ItemNumber - 1) / 2

A: see may following would hepl you
DECLARE @Result TABLE
(
  Size BIGINT ,
  Quantity BIGINT
)

DECLARE @str INT ,
@input VARCHAR(MAX) = '1,20,2,10,3,15,5,20'
DECLARE @strQ INT
DECLARE @ind INT
IF ( @input IS NOT NULL )
BEGIN
    SET @ind = CHARINDEX(',', @input)
    WHILE @ind > 0
        BEGIN
            SET @str = SUBSTRING(@input, 1, @ind - 1)
            SET @input = SUBSTRING(@input, @ind + 1, LEN(@input))
            SET @ind = CHARINDEX(',', @input)
            IF ( @ind > 0 )
                BEGIN
                    SET @strQ = SUBSTRING(@input, 1, @ind - 1)
                    SET @input = SUBSTRING(@input, @ind + 1, LEN(@input))
                END
            ELSE
                BEGIN
                    SET @strQ = @input
                END

            INSERT  INTO @Result
                    ( Size, Quantity )
            VALUES  ( @str, @strQ )
            SET @ind = CHARINDEX(',', @input)
            SET @str = NULL
            SET @strQ = NULL
        END
END

SELECT    *
FROM      @Result

A: Another way with XML and recursive CTE:
DECLARE @string nvarchar(max) = N'1,5,2,20,3,9',
        @xml xml

;WITH cte AS (
    SELECT STUFF(@string,CHARINDEX(',',@string),1,'')  s, 1 as LEV
    UNION ALL
    SELECT CASE WHEN LEV % 2 = 0 THEN STUFF(s,CHARINDEX(',',s),1,'')
                ELSE STUFF(s,CHARINDEX(',',s),1,'</s><s>') END, LEV + 1
    FROM cte
    WHERE LEV < (LEN(@string) - LEN(REPLACE(@string,',','')))
)
SELECT TOP 1 @xml = CAST('<s>' + s + '</s>' as xml)
FROM cte
ORDER BY LEV DESC

SELECT  t.v.value('a[1]', 'int') as size,
        t.v.value('b[1]', 'int') as quantity
FROM @xml.nodes('/s') as t(v)

We get XML like:
<s>
  1
  5
</s>
<s>
  2
  20
</s>
<s>
  3
  9
</s>

Output:
size    quantity
1       5
2       20
3       9


text:
Q: How to run sql script in mysql on Ubuntu? I am new to sql. I know I can run script with absolute path:
mysql> source /absolute_path/file.sql;

Is there a way to use just relative path? Or to simplify the absolute path via some variable?

A: If you use a relative path, then it will be relative to the current working directory you were in when you ran the mysql client.
In other words, the following would work:
$ cd /absolute_path
$ mysql
mysql> source file.sql

I don't think you can use expressions or variables in the source command. It's a builtin command to the mysql client, and that has a simpler parser than the MySQL Server's SQL parser. Builtin commands don't support expressions or variables.
Here's a link to the code that parses the source command: https://github.com/mysql/mysql-server/blob/8.0/client/mysql.cc#L4187-L4197


text:
Q: Is it possible to use EC2 and AWS Certificate Manager only? I have my websites deployed on ec2 instance and was planning to use SSL/TLS certificate using AWS Certificate Manager. I found this link saying I may have to use Load Balancer to use the SSL from ACM. https://docs.aws.amazon.com/acm/latest/userguide/acm-services.html. Is it possible to just use EC2 and ACM not including the Load Balancer.
I know I can buy a certificate from other sites and install the ssl through EC2 instead. But I was just thinking if I can have it all on AWS.
Any pointers is much appreciated.

A: No I don't think its possible, because the certificate itself is stored in AWS Infrastructure and only referenced via ARN, besides AWS takes care of rotating the certificate and that cannot be achieved via a manual process.

A: Unfortuntely No there is no direct way to use it on EC2 Instance.
But it can achieved if you put EC2(Single Instance also) Behind Load Balancer and attach Certificate to LB then you will get https.
Thanks